// Three real secondary threads retain private, guarded stacks. The primary // keeps the allocator loan while workers access only their own retained leases. // Setup and teardown use the existing exclusive Shared custody protocol. use super::*; use turkos_kernel::runtime::thread_migration as mv; use th::Backend as _; core::arch::global_asm!(include_str!("k2100-smp-workers.S")); #[unsafe(no_mangle)]pub static mut OS_K2100_WORKER_STACKS:[mv::Slot;3]=[const{mv::Slot::new()};3]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKER_ACK:[u64;3]=[0;3]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKER_RECORDS:[[u64;32];4]=[[0;32];4]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKER_EVIDENCE:[u64;32]=[0;32]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKER_GO:u64=0; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKER_FINISH:u64=0; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKER_CAPTURE_GATE:u8=0; #[unsafe(no_mangle)]pub static OS_K2100_WORKER_THREAD_LAYOUT:[u64;28]=th::os_k2045_layout::(); #[unsafe(no_mangle)]pub static OS_K2100_WORKER_PROGRESS:[AtomicU64;3]=[const{AtomicU64::new(0)};3]; #[unsafe(no_mangle)]pub static mut OS_K2100_OVERLAP_EVIDENCE:[u64;32]=[0;32]; const ROUNDS:u64=32; fn checkpoint(active:bool){ unsafe{write_volatile(core::ptr::addr_of_mut!(OS_K2100_WORKER_CAPTURE_GATE),0)} write_line(if active{"TURKOS/OS/K2100-SMP-WORKERS: CAPTURE ACTIVE"}else{"TURKOS/OS/K2100-SMP-WORKERS: CAPTURE RETURNED"}); while unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_WORKER_CAPTURE_GATE))}!=1{core::hint::spin_loop()} } struct PrivateBackend<'a>{inner:backend::ThreadBackend<'a>} impl PrivateBackend<'_>{ fn retained(&self,s:&backend::Stack)->Result{ let e=backend::execution();let l=s.layout(); if e.cpu!=self.inner.cpu||s.cpu!=e.cpu||e.daif!=0x3c0||e.root!=self.inner.shared.tables.root{return Err(th::Error::Context)} if s.leases.iter().enumerate().any(|(i,p)|p.address()!=l.guard()+i as u64*4096){return Err(th::Error::Layout)} Ok(l) } } // Only this Table owns the non-Clone Stack/Lease/guard values. No prepare, // release, remap or allocator access occurs during the concurrent interval. unsafe impl th::Backend for PrivateBackend<'_>{ type Stack=backend::Stack; fn execution(&self)->th::Execution{self.inner.execution()} fn layout(&self,s:&backend::Stack)->Result{self.retained(s)} fn entry_executable(&self,pc:u64)->bool{self.inner.entry_executable(pc)} fn prepare(&mut self,s:&mut backend::Stack)->Result<(),th::Error>{self.inner.prepare(s)} fn observe(&self,s:&backend::Stack)->Result{ let l=self.retained(s)?;let g=s.guard.as_ref().ok_or(th::Error::Guard)?; let descriptor=self.inner.shared.tables.os_k1020_stack_guard_descriptor(g).map_err(|_|th::Error::Guard)?; Ok(th::StackObservation{layout:l,guard_descriptor:descriptor, low_canary:unsafe{read_volatile(l.base as*const u64)},high_canary:unsafe{read_volatile((l.base+l.bytes-8)as*const u64)}, initially_zeroed:(1..l.bytes/8-1).all(|i|unsafe{read_volatile((l.base as*const u64).add(i as usize))}==0)}) } fn release(&mut self,s:backend::Stack)->Result<(),(th::Error,backend::Stack)>{self.inner.release(s)} } type Table<'a>=th::Table,1>; struct Call<'a>{table:*mut Table<'a>,id:th::ThreadId,cpu:usize,gicr:u64,shared:&'a backend::Shared<'a>,online:*const backend::Local<'a>,command:*const u64,error:Option<&'static str>} fn ack(cpu:usize,n:u64){store(unsafe{core::ptr::addr_of_mut!(OS_K2100_WORKER_ACK).cast::().add(cpu-1)},n)} fn record(cpu:usize,i:usize,n:u64){put(unsafe{core::ptr::addr_of_mut!(OS_K2100_WORKER_RECORDS).cast::().add(cpu*32)},i,n)} fn wait(cpu:usize,n:u64)->Result<(),&'static str>{ let deadline=counter()+(if n==125{60}else{10})*frequency();loop{ if load(unsafe{core::ptr::addr_of!(OS_K2100_WORKER_ACK).cast::().add(cpu-1)})==n{return Ok(())} if load(unsafe{core::ptr::addr_of!(OS_K2045_RECEIPTS).cast::().add((cpu-1)*64)})==99{return Err("k2100-worker-secondary")} if counter()>deadline{return Err("k2100-worker-timeout")}core::hint::spin_loop() } } fn service(cpu:usize,round:u64)->Result<(),&'static str>{ let words=turkos_os_shell_words::Words::<32,4>::parse("echo 'smp-load'").map_err(|_|"k2100-worker-parse")?; let d=turkos_os_shell_dispatch::decide(&words).map_err(|_|"k2100-worker-route")?; if d.route!=turkos_os_shell_dispatch::Route::External("echo")||d.argc!=1{return Err("k2100-worker-command")} let payload=words.get(1).ok_or("k2100-worker-arg")?.as_bytes();let owner=cpu as u64+1; let mut fs=os_vfs_tmpfs::Tmpfs::new(0x210000+owner*256+round,32).map_err(|_|"k2100-worker-fs")?; let file=fs.create(owner,b"message").map_err(|_|"k2100-worker-create")?; if fs.write_at(owner,file,0,payload)!=Ok(8){return Err("k2100-worker-write")} let mut bytes=[0u8;32];let n=fs.read_at(owner,file,0,&mut bytes).map_err(|_|"k2100-worker-read")?; if n!=8||&bytes[..n]!=b"smp-load"||fs.used()!=8{return Err("k2100-worker-data")} fs.unlink(owner,b"message").map_err(|_|"k2100-worker-unlink")?; if fs.used()!=0{return Err("k2100-worker-leak")}Ok(()) } fn body(c:&mut Call<'_>)->Result<(),&'static str>{ let table=unsafe{&mut*c.table};table.activate(c.id).map_err(|_|"k2100-worker-activate")?; let r=table.record(c.id).map_err(|_|"k2100-worker-running-record")?;let e=backend::execution(); if r.state!=th::State::Running||e.spr.layout.usable_top(){return Err("k2100-worker-real-stack")} for(i,v)in[(0,2100),(1,c.cpu as u64),(2,c.id.table()),(3,c.id.slot()as u64),(4,c.id.generation()),(5,r.layout.guard()),(6,r.layout.base),(7,r.layout.bytes),(8,e.sp),(9,e.root),(10,e.daif),(11,counter())]{record(c.cpu,i,v)} let stack_ptr=table.os_k2045_stack_address(c.id).map_err(|_|"k2100-worker-stack-pointer")?; let stack=unsafe{&*(stack_ptr as*const backend::Stack)};let guard=stack.guard.as_ref().ok_or("k2100-worker-guard-pointer")?; for(i,v)in[(20,c.table as u64),(21,core::mem::size_of::()as u64),(22,stack_ptr),(23,guard.descriptor_address()),(24,guard.original_descriptor())]{record(c.cpu,i,v)} ack(c.cpu,121);while load(core::ptr::addr_of!(OS_K2100_WORKER_GO))==0{core::hint::spin_loop()} record(c.cpu,12,counter()); secondary_timer::wait(c.cpu,c.gicr,e.root,r.layout.base,r.layout.base+r.layout.bytes)?;record(c.cpu,25,1); wait_command(c.command,125); if c.shared.os_k2090_owner()!=c.cpu as u64||os_k2100_process_cpu()!=c.cpu as u64{return Err("k2100-worker-process-custody")} let online=unsafe{&*c.online};online.audit().map_err(|_|"k2100-worker-process-online")?;let binding=online.binding(); if binding.cpu!=c.cpu as u32||!binding.online{return Err("k2100-worker-process-binding")} let boot=OS_K2100_PROCESS_BOOT.load(Ordering::Acquire);if boot==0{return Err("k2100-worker-process-boot")} c.shared.with_state(|state|os_k2100_secondary_process(c.cpu,unsafe{&*(boot as*const BootData)},state.allocator,c.shared.tables))?; online.audit().map_err(|_|"k2100-worker-process-owner-after")?;if online.binding()!=binding{return Err("k2100-worker-process-binding-drift")} for(i,v)in [(26,1),(27,3),(28,2),(29,1),(30,5),(31,1)]{record(c.cpu,i,v)} c.shared.handoff(0);ack(c.cpu,125); let mut completed=0u64; loop{ service(c.cpu,completed)?;completed=completed.checked_add(1).ok_or("k2100-worker-progress-overflow")?; record(c.cpu,13,completed);record(c.cpu,14,completed); OS_K2100_WORKER_PROGRESS[c.cpu-1].store(completed,Ordering::Release); if completed>=ROUNDS&&load(core::ptr::addr_of!(OS_K2100_WORKER_FINISH))==1{break} } record(c.cpu,15,counter()); table.exit_current(c.id).map_err(|_|"k2100-worker-exit")?;record(c.cpu,16,counter());record(c.cpu,17,1);Ok(()) } #[unsafe(no_mangle)]pub extern "C" fn __os_k2100_worker_body(p:*mut Call<'_>)->u64{ let c=unsafe{&mut*p};match body(c){Ok(())=>0,Err(e)=>{c.error=Some(e);1}} } pub fn cycle<'a>(q:&backend::Local<'a>,shared:&'a backend::Shared<'a>,c:*const u64)->Result<(),&'static str>{ let cpu=backend::execution().cpu as usize;if load(c)!=120{return Err("k2100-worker-entry-command")} q.audit().map_err(|_|"k2100-worker-online-owner")?; let stack=unsafe{(&mut (*core::ptr::addr_of_mut!(OS_K2100_WORKER_STACKS))[cpu-1]).take()}.ok_or("k2100-worker-stack")?; let mut table=Table::new(PrivateBackend{inner:backend::ThreadBackend{shared,cpu:cpu as u32}}).map_err(|_|"k2100-worker-table")?; let id=table.create(stack,__os_k2100_worker_body as*const()as u64,cpu as u64).map_err(|_|"k2100-worker-create-thread")?; let context=table.ready_context(id).map_err(|_|"k2100-worker-ready-context")?; shared.handoff(0);ack(cpu,120);wait_command(c,121); let gicr=unsafe{read_volatile(core::ptr::addr_of!(OS_K2045_LAUNCH).cast::().add((cpu-1)*32+13))}; let mut call=Call{table:&mut table,id,cpu,gicr,shared,online:q as*const _,command:c,error:None}; unsafe extern "C"{fn __os_k2100_worker_call(p:*mut Call<'_>,sp:u64)->u64;} if unsafe{__os_k2100_worker_call(&mut call,context.initial_sp)}!=0{return Err(call.error.unwrap_or("k2100-worker-body"))} if table.record(id).map(|r|r.state)!=Ok(th::State::Dead){return Err("k2100-worker-not-dead")} record(cpu,18,backend::execution().sp);ack(cpu,123);wait_command(c,122); q.audit().map_err(|_|"k2100-worker-retained-owner")?; table.reap(id).map_err(|_|"k2100-worker-reap")?; let s=table.snapshot();if s.live!=0{return Err("k2100-worker-table-live")} table.into_backend().map_err(|_|"k2100-worker-close")?;record(cpu,19,1); shared.handoff(0);ack(cpu,124);wait_command(c,3);Ok(()) } pub fn drive(boot:&BootData,shared:&backend::Shared)->Result<(),&'static str>{ OS_K2100_PROCESS_BOOT.store(boot as*const BootData as u64,Ordering::Release); let before=shared.with_state(|s|s.allocator.os_authority().audit().map_err(|_|"k2100-worker-before"))?; let e=core::ptr::addr_of_mut!(OS_K2100_WORKER_EVIDENCE).cast::();put(e,0,2100);put(e,1,before.live_pages);put(e,2,counter());put(e,13,core::ptr::addr_of!(OS_K2100_WORKER_THREAD_LAYOUT)as u64);put(e,14,224); for cpu in 1..profile_cpu_count(){ let stack=shared.with_state(|s|{let at=guard_candidate(s.allocator,shared.tables)?;Ok::<_,&'static str>(backend::Stack{leases:allocate::<5>(s.allocator,at)?,guard:None,cpu:cpu as u32})})?; unsafe{(&mut (*core::ptr::addr_of_mut!(OS_K2100_WORKER_STACKS))[cpu-1]).put(stack)}.map_err(|_|"k2100-worker-publish-stack")?; shared.handoff(cpu as u64);command(cpu-1,120);wait(cpu,120)?; } let during=shared.with_state(|s|s.allocator.os_authority().audit().map_err(|_|"k2100-worker-during"))?; let mut expected=before;expected.live_pages=expected.live_pages.checked_add(5*(profile_cpu_count()-1)as u64).ok_or("k2100-worker-retired-count")?;expected.free_pages=expected.free_pages.checked_sub(5*(profile_cpu_count()-1)as u64).ok_or("k2100-worker-retired-free")?;if during!=expected{return Err("k2100-worker-page-count")}put(e,3,during.live_pages); for cpu in 1..profile_cpu_count(){command(cpu-1,121)}for cpu in 1..profile_cpu_count(){wait(cpu,121)?} let hw=backend::execution();for(i,v)in[(0,2100),(1,0),(8,hw.sp),(9,hw.root),(10,hw.daif),(11,counter())]{record(0,i,v)} checkpoint(true);put(e,4,counter());store(core::ptr::addr_of_mut!(OS_K2100_WORKER_GO),1);record(0,12,counter()); for cpu in 1..profile_cpu_count(){ OS_K2100_PROCESS_OWNER.store(cpu as u64,Ordering::Release);shared.handoff(cpu as u64);command(cpu-1,125);wait(cpu,125)?; if shared.os_k2090_owner()!=0{return Err("k2100-primary-process-custody-return")} } OS_K2100_PROCESS_OWNER.store(0,Ordering::Release); for round in 0..ROUNDS{service(0,round)?;record(0,13,round+1);record(0,14,round+1)}record(0,15,counter()); os_k2100_timer_bind(boot,shared.tables)?; let o=core::ptr::addr_of_mut!(OS_K2100_OVERLAP_EVIDENCE).cast::();put(o,0,2100);put(o,1,counter()); for cpu in 0..profile_cpu_count()-1{put(o,2+cpu,OS_K2100_WORKER_PROGRESS[cpu].load(Ordering::Acquire));} shared.with_state(|state|os_k2100_repeat(boot,shared.tables,state.allocator))?; put(o,5,counter()); for cpu in 0..profile_cpu_count()-1{let count=OS_K2100_WORKER_PROGRESS[cpu].load(Ordering::Acquire);put(o,6+cpu,count);if count<=unsafe{read_volatile(o.add(2+cpu))}{return Err("k2100-worker-no-overlap-progress")}} put(o,9,3);put(o,10,1); put(e,5,counter());store(core::ptr::addr_of_mut!(OS_K2100_WORKER_FINISH),1);record(0,16,counter()); for cpu in 1..profile_cpu_count(){wait(cpu,123)?}checkpoint(false); for cpu in 1..profile_cpu_count(){shared.handoff(cpu as u64);command(cpu-1,122);wait(cpu,124)?;} let after=shared.with_state(|s|s.allocator.os_authority().audit().map_err(|_|"k2100-worker-after"))?; expected.live_pages=expected.live_pages.checked_sub(5*(profile_cpu_count()-1)as u64).ok_or("k2100-worker-final-count")?;expected.free_pages=expected.free_pages.checked_add(5*(profile_cpu_count()-1)as u64).ok_or("k2100-worker-final-free")?;if expected!=after{return Err("k2100-worker-accounting")} for(i,v)in[(6,after.live_pages),(7,counter()),(8,(profile_cpu_count()-1)as u64),(9,ROUNDS+OS_K2100_WORKER_PROGRESS.iter().map(|p|p.load(Ordering::Acquire)).sum::()),(10,ROUNDS+OS_K2100_WORKER_PROGRESS.iter().map(|p|p.load(Ordering::Acquire)).sum::()),(11,5*(profile_cpu_count()-1)as u64),(12,1)]{put(e,i,v)} write_line("TURKOS/OS/K2100-PROFILE-WORKERS: ALL_ONLINE_CPUS_SERVICED=1 RESOURCES_RETURNED=1");Ok(()) } #[path="k2100-secondary-timer.rs"]mod secondary_timer;