// Included as a child of the duration worker module. All non-atomic state is // protected by the existing Shared custody, including the single wake receipt. use super::*; use turkos_kernel::runtime::smp_workload as workload; use workload::Context as _; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKLOAD_BINDINGS:[[u64;4];4]=[[0;4];4]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKLOAD_PROGRESS:[[u64;6];4]=[[0;6];4]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKLOAD_STALE:[u64;24]=[0;24]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKLOAD_SUMMARY:[u64;32]=[0;32]; #[unsafe(no_mangle)]pub static mut OS_K2100_WORKLOAD_MONITOR:core::mem::MaybeUninit=core::mem::MaybeUninit::uninit(); #[unsafe(no_mangle)]pub static mut OS_K2100_HOST_DURATION_CONTROL:u64=0; static mut BASELINE:Option=None; static mut RESOURCES:Option=None; static mut PENDING_WAKE:Option=None; struct Clock; unsafe impl workload::Context for Clock{ fn execution(&self)->workload::Execution{ let h=os_k1120_registers();let mpidr:u64;unsafe{asm!("mrs {v},MPIDR_EL1",v=out(reg)mpidr,options(nomem,nostack,preserves_flags));} workload::Execution{cpu:mpidr&0xff00ffffff,root:h.ttbr,masked:h.daif==0x3c0&&h.current_el==4&&h.spsel==1,counter:counter()} } } fn gate()->Result<(),&'static str>{let e=Clock.execution();if e.cpu!=0||!e.masked{return Err("k2100-duration-context")}Ok(())} fn monitor()->&'static mut workload::Monitor{unsafe{&mut*core::ptr::addr_of_mut!(OS_K2100_WORKLOAD_MONITOR).cast::()}} fn summary(i:usize,v:u64){put(core::ptr::addr_of_mut!(OS_K2100_WORKLOAD_SUMMARY).cast(),i,v)} pub fn bind_secondary(q:&backend::Local<'_>,cpu:usize)->Result<(),&'static str>{ q.audit().map_err(|_|"k2100-duration-bind-owner")?;let b=q.binding(); if cpu==0||cpu>=profile_cpu_count()||b.cpu!=cpu as u32||!b.online||b.generation==0{return Err("k2100-duration-binding")} unsafe{core::ptr::addr_of_mut!(OS_K2100_WORKLOAD_BINDINGS).cast::<[u64;4]>().add(cpu).write([b.issuer,b.epoch,b.cpu as u64,b.generation]);}Ok(()) } fn resources(shared:&backend::Shared<'_>,boot:&life::BootOnline)->Result<(workload::Resources,os_k720_frame::Audit),&'static str>{ gate()?; let(audit,snapshot,binding)=shared.with_state(|s|Ok::<_,&'static str>((s.allocator.os_authority().audit().map_err(|_|"k2100-duration-audit")?,s.lifecycle.snapshot(),s.lifecycle.boot_binding(boot).map_err(|_|"k2100-duration-boot-owner")?)))?; let all=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_WORKLOAD_BINDINGS))};let count=profile_cpu_count(); if snapshot.state.count!=count as u64||snapshot.state.phase!=1||binding!=all[0]{return Err("k2100-duration-lifecycle")} for cpu in 0..count{ let b=all[cpu];let r=snapshot.records[cpu]; if b!=[snapshot.state.issuer,snapshot.state.epoch,cpu as u64,r.generation]||r.phase!=4||r.generation==0{return Err("k2100-duration-generation")} } if all[count..].iter().any(|r|*r!=[0;4]){return Err("k2100-duration-inactive-owner")} // Count the retained primary guard and the private running worker guards. let guard=core::ptr::addr_of!(OS_K2045_PRIMARY_STACK)as u64; if !shared.tables.task_stack_guard_unmapped(guard)||unsafe{read_volatile((guard+4096)as*const u64)}!=0x20455052494d4c4f||unsafe{read_volatile((guard+69624)as*const u64)}!=0x20455052494d4849{return Err("k2100-duration-primary-canary")} for cpu in 1..count{ // These ownership fields are immutable after the release ACK121. Other row // fields continue changing, so never form a shared reference to the array. let row=unsafe{core::ptr::addr_of!(OS_K2100_WORKER_RECORDS).cast::().add(cpu*32)}; let base=unsafe{read_volatile(row.add(6))};let bytes=unsafe{read_volatile(row.add(7))};let pte=unsafe{read_volatile(row.add(23))}; if bytes!=16384||base%4096!=0||pte==0||unsafe{read_volatile(pte as*const u64)}!=0||unsafe{read_volatile(base as*const u64)}!=th::LOW_CANARY||unsafe{read_volatile((base+bytes-8)as*const u64)}!=th::HIGH_CANARY{return Err("k2100-duration-worker-canary")} } // Authorized pages are the conserved ledger total. In addition, the COMPLETE // actual Audit (including live/free/reserved) must match at every window. Ok((workload::Resources{pages:audit.authorized_pages,owners:count as u64,guarded_stacks:count as u64},audit)) } fn observation(r:workload::Resources)->workload::Observation{ let bindings=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_WORKLOAD_BINDINGS))};let done=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_WORKLOAD_PROGRESS))}; workload::Observation{counter:counter(),resources:r,canary_failures:0,cpus:core::array::from_fn(|cpu|{ let b=bindings[cpu];workload::CpuProgress{binding:workload::Binding{issuer:b[0],epoch:b[1],cpu:b[2],generation:b[3]},completed:done[cpu]} })} } pub fn start(shared:&backend::Shared<'_>,boot:&life::BootOnline)->Result<(),&'static str>{ gate()?;let binding=shared.with_state(|s|s.lifecycle.boot_binding(boot)).map_err(|_|"k2100-duration-boot-binding")?; unsafe{core::ptr::addr_of_mut!(OS_K2100_WORKLOAD_BINDINGS).cast::<[u64;4]>().write(binding);} let(r,audit)=resources(shared,boot)?;let first=observation(r);let frequency=frequency(); let m=unsafe{workload::Monitor::bind(shared.tables.root,frequency,profile_cpu_count()as u64,first)}.map_err(|_|"k2100-duration-bind")?; unsafe{core::ptr::addr_of_mut!(BASELINE).write(Some(audit));core::ptr::addr_of_mut!(RESOURCES).write(Some(r));core::ptr::addr_of_mut!(OS_K2100_WORKLOAD_MONITOR).write(core::mem::MaybeUninit::new(m));} for(i,v)in[(0,2100),(1,profile_cpu_count()as u64),(2,first.counter),(3,frequency),(4,first.counter+frequency*workload::MIN_SECONDS),(5,core::ptr::addr_of!(OS_K2100_WORKLOAD_MONITOR)as u64),(6,core::mem::size_of::()as u64)]{summary(i,v)}Ok(()) } /// Called ONLY after actual Stale and complete before/after owner checks in the /// real process wake path. It never synthesizes a Wait or grants wake authority. pub unsafe fn stale(old:k2100_process::ProcessId,current:k2100_process::ProcessId,thread:k2100_threads::ThreadId,epoch:u64,audit:os_k720_frame::Audit)->Result<(),&'static str>{ let h=os_k1120_registers();if h.cpu!=os_k2100_process_cpu()||h.cpu>=profile_cpu_count()as u64||h.daif!=0x3c0||h.current_el!=4{return Err("k2100-duration-stale-context")} if unsafe{(&*core::ptr::addr_of!(PENDING_WAKE)).is_some()}{return Err("k2100-duration-wake-pending")} let r=unsafe{read_volatile(core::ptr::addr_of!(RESOURCES))}.ok_or("k2100-duration-resources-missing")?; if r.pages!=audit.authorized_pages{return Err("k2100-duration-stale-pages")} let old_id=workload::ProcessIdentity{table:old.table(),slot:old.slot()as u64,generation:old.generation()};let current_id=workload::ProcessIdentity{table:current.table(),slot:current.slot()as u64,generation:current.generation()};let now=counter(); let receipt=unsafe{workload::RejectedWake::from_kernel(old_id,current_id,now,r,true)}; unsafe{core::ptr::addr_of_mut!(PENDING_WAKE).write(Some(receipt));core::ptr::addr_of_mut!(OS_K2100_WORKLOAD_STALE).write([2100,h.cpu,old.table(),old.slot()as u64,old.generation(),current.generation(),now,audit.authorized_pages,audit.live_pages,audit.reserved_pages,audit.free_pages,r.owners,r.guarded_stacks,1,thread.table(),thread.slot()as u64,thread.generation(),epoch,0,0,0,0,0,0]);}Ok(()) } pub fn service_done(cpu:usize)->Result<(),&'static str>{ let h=os_k1120_registers();if h.cpu!=cpu as u64||h.cpu!=os_k2100_process_cpu(){return Err("k2100-duration-service-cpu")} let p=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_PROCESS_EVIDENCE))};let s=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_SERVICE_EVIDENCE))};let e=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_EL0_EVIDENCE))};let n=unsafe{read_volatile(core::ptr::addr_of!(k2100_network::OS_K2100_NETWORK_EVIDENCE))}; let timer=if cpu==0{unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_TIMER_EVIDENCE))}}else{unsafe{read_volatile(core::ptr::addr_of!(secondary_timer::OS_K2100_SECONDARY_TIMERS).cast::().add(cpu*128+64).cast::<[u64;48]>())}}; if p[0]!=2100||p[16]!=cpu as u64||s[17]!=cpu as u64||e[20]!=cpu as u64||e[2]!=5||e[19]!=1||n[39]!=cpu as u64||n[38]!=1||timer[0]!=2100||timer[1]!=1||timer[22]!=30||timer[23]!=0||timer[24]!=0{return Err("k2100-duration-service-evidence")} let values=[p[14]+s[13],s[8],s[10],timer[13],s[9],n[38]];if values!=[3,2,1,1,1,1]{return Err("k2100-duration-service-units")} let ptr=unsafe{core::ptr::addr_of_mut!(OS_K2100_WORKLOAD_PROGRESS).cast::<[u64;6]>().add(cpu)};let mut prior=unsafe{read_volatile(ptr)}; for i in 0..6{prior[i]=prior[i].checked_add(values[i]).ok_or("k2100-duration-progress-overflow")?}unsafe{write_volatile(ptr,prior)}Ok(()) } pub fn take_wake()->Result<(),&'static str>{ gate()?;let wake=unsafe{(&mut*core::ptr::addr_of_mut!(PENDING_WAKE)).take()}.ok_or("k2100-duration-no-wake")?; let row=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_WORKLOAD_STALE))};let s=core::ptr::addr_of!(OS_K2100_WORKLOAD_SUMMARY).cast::(); let deadline=unsafe{read_volatile(s.add(4))};let late=unsafe{read_volatile(s.add(8))}; // Once a late refusal is accepted, require another whole service window. // New receipts are consumed but cannot move that boundary forward forever. if late==0{ if let Err((_,wake))=monitor().rejected_wake(wake,&Clock){unsafe{core::ptr::addr_of_mut!(PENDING_WAKE).write(Some(wake));}return Err("k2100-duration-refusal")} if row[6]>=deadline{summary(8,monitor().windows()+1);summary(9,row[6]);} } summary(10,monitor().stale_refusals());Ok(()) } pub fn window(shared:&backend::Shared<'_>,boot:&life::BootOnline)->Result<(),&'static str>{ let(r,audit)=resources(shared,boot)?;if unsafe{read_volatile(core::ptr::addr_of!(BASELINE))}!=Some(audit){return Err("k2100-duration-window-leak")} let next=observation(r);unsafe{monitor().observe(next,&Clock)}.map_err(|_|"k2100-duration-window")?;summary(7,monitor().windows());summary(11,next.counter);Ok(()) } pub fn may_stop()->Result{ gate()?;let control=load(core::ptr::addr_of!(OS_K2100_HOST_DURATION_CONTROL));if control>2{return Err("k2100-duration-host-control")} if control==2&&monitor().windows()>=3{ if monitor().close(&Clock)!=Err(workload::Error::Pending){return Err("k2100-duration-short-not-pending")} summary(12,2);return Ok(true) } let late=unsafe{read_volatile(core::ptr::addr_of!(OS_K2100_WORKLOAD_SUMMARY).cast::().add(8))}; if control==1&&late>0&&monitor().windows()>late{monitor().close(&Clock).map_err(|_|"k2100-duration-close")?;summary(12,1);return Ok(true)}Ok(false) } #[unsafe(no_mangle)]pub static mut OS_K2100_WORKLOAD_WINDOW_ACK:u64=0; pub fn await_window_ack(window:u64)->Result<(),&'static str>{gate()?;loop{let ack=load(core::ptr::addr_of!(OS_K2100_WORKLOAD_WINDOW_ACK));if ack==window{return Ok(())}if ack>window{return Err("k2100-duration-future-ack")}core::hint::spin_loop()}}