use core::array; #[repr(C)] #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Principal { pub table:u64,pub slot:u64,pub generation:u64 } #[repr(C)] #[derive(Clone,Copy,Debug,Default,PartialEq,Eq)] pub struct Usage { pub pages:u64,pub tasks:u64,pub channels:u64 } impl Usage { fn add(self,b:Self)->Option{Some(Self{pages:self.pages.checked_add(b.pages)?,tasks:self.tasks.checked_add(b.tasks)?,channels:self.channels.checked_add(b.channels)?})} fn within(self,b:Self)->bool{self.pages<=b.pages&&self.tasks<=b.tasks&&self.channels<=b.channels} } #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub enum Kind { Spawn,Channel } #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub enum Error { Configuration,Principal,Quota,Capacity,State,Backend,Clock,Receipt,Resource } #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Observation {pub principal:Principal,pub kind:Kind,pub object:u64,pub generation:u64,pub usage:Usage} /// A kernel-owned backend retains the real address spaces, task identities and /// nonclone resource tokens. Caller identity never comes from a user request. /// Baseline/cost/observe include all physical backing, and acquisition errors /// are inert. Tokens retain ownership on every rejected operation. A successful /// release zeroes backing and consumes exactly the supplied token; failure /// returns it unchanged. Channel I/O validates ownership and bounded storage. /// # Safety /// Every observation must derive from the retained real resources. Changing /// caller is permitted only at a trusted kernel dispatch boundary. No owner /// reference may outlive that boundary or span an unmasked interrupt. pub unsafe trait Backend { type Token; fn caller(&self)->Result; fn baseline(&self,principal:Principal)->Result; fn cost(&self,kind:Kind)->Usage; fn acquire(&mut self,principal:Principal,kind:Kind)->Result; fn observe(&self,token:&Self::Token)->Observation; fn exchange(&mut self,token:&Self::Token,value:u64)->Result; fn release(&mut self,token:Self::Token)->Result<(),Self::Token>; } #[repr(C)] #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Account {pub principal:Principal,pub baseline:Usage,pub used:Usage,pub limit:Usage,pub cpu_ticks:u64,pub cpu_used:u64,pub slices:u64,pub expired:u64} struct Resource{token:Option,observation:Option,generation:u64} #[derive(Debug,PartialEq,Eq)] pub struct Handle{slot:usize,generation:u64,principal:Principal} #[derive(Debug,PartialEq,Eq)] pub struct Slice {principal:Principal,nonce:u64,start:u64,deadline:u64} impl Slice {pub fn deadline(&self)->u64{self.deadline}pub fn principal(&self)->Principal{self.principal}} #[repr(C)] #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct TimerReceipt {principal:Principal,nonce:u64,start:u64,deadline:u64,end:u64,irq:u64} impl TimerReceipt { /// # Safety /// The trusted dispatcher records these values from the exclusively owned /// physical timer and saved exception frame. irq=true requires an actual /// acknowledged and completed timer interrupt from this EL0 execution. An /// ordinary user return must be stopped by the kernel before its deadline. pub unsafe fn from_kernel(slice:&Slice,end:u64,irq:bool)->Self{Self{principal:slice.principal,nonce:slice.nonce,start:slice.start,deadline:slice.deadline,end,irq:irq as u64}} } pub struct Controller{backend:B,accounts:[Account;2],resources:[Resource;4],active:Option<(Principal,u64,u64,u64)>,nonce:u64,fault:bool} impl Controller{ pub fn new(backend:B,principals:[Principal;2],limits:[Usage;2],cpu_ticks:[u64;2])->Result{ if principals[0]==principals[1]||principals.iter().any(|p|p.table==0||p.generation==0)||cpu_ticks.contains(&0){return Err(backend)} let a=match backend.baseline(principals[0]){Ok(v)=>v,Err(_)=>return Err(backend)}; let b=match backend.baseline(principals[1]){Ok(v)=>v,Err(_)=>return Err(backend)}; if !a.within(limits[0])||!b.within(limits[1]){return Err(backend)} let accounts=array::from_fn(|i|Account{principal:principals[i],baseline:[a,b][i],used:[a,b][i],limit:limits[i],cpu_ticks:cpu_ticks[i],cpu_used:0,slices:0,expired:0}); Ok(Self{backend,accounts,resources:array::from_fn(|_|Resource{token:None,observation:None,generation:0}),active:None,nonce:0,fault:false}) } fn current(&self)->Result{if self.fault{return Err(Error::State)}let p=self.backend.caller()?;self.accounts.iter().position(|a|a.principal==p).ok_or(Error::Principal)} pub fn accounts(&self)->[Account;2]{self.accounts} pub fn acquire(&mut self,kind:Kind)->Result{ let i=self.current()?;if self.active.is_some(){return Err(Error::State)}let p=self.accounts[i].principal; let cost=self.backend.cost(kind);if cost.pages==0||match kind{Kind::Spawn=>cost.tasks!=1||cost.channels!=0,Kind::Channel=>cost.tasks!=0||cost.channels!=1}{return Err(Error::Resource)} let next=self.accounts[i].used.add(cost).ok_or(Error::Quota)?; if !next.within(self.accounts[i].limit){return Err(Error::Quota)} let slot=self.resources.iter().position(|r|r.token.is_none()).ok_or(Error::Capacity)?; let generation=self.resources[slot].generation.checked_add(1).ok_or(Error::Capacity)?; let token=self.backend.acquire(p,kind)?;let observed=self.backend.observe(&token); self.resources[slot]=Resource{token:Some(token),observation:Some(observed),generation}; if observed.principal!=p||observed.kind!=kind||observed.usage!=cost||observed.object==0||observed.generation==0{self.fault=true;return Err(Error::Resource)} self.accounts[i].used=next;Ok(Handle{slot,generation,principal:p}) } fn resource(&self,handle:&Handle)->Result{let i=self.current()?;if handle.principal!=self.accounts[i].principal{return Err(Error::Principal)}let r=self.resources.get(handle.slot).ok_or(Error::Resource)?;if r.generation!=handle.generation||r.token.is_none(){return Err(Error::Resource)}if Some(self.backend.observe(r.token.as_ref().unwrap()))!=r.observation{return Err(Error::Resource)}Ok(i)} pub fn exchange(&mut self,h:&Handle,value:u64)->Result{self.resource(h)?;let r=&self.resources[h.slot];if r.observation.unwrap().kind!=Kind::Channel{return Err(Error::Resource)}self.backend.exchange(r.token.as_ref().unwrap(),value)} pub fn close(&mut self,h:Handle)->Result<(),(Error,Handle)>{ let i=match self.resource(&h){Ok(i)=>i,Err(e)=>return Err((e,h))};if self.active.is_some(){return Err((Error::State,h))} let r=&mut self.resources[h.slot];let used=r.observation.unwrap().usage;let token=r.token.take().unwrap(); if let Err(token)=self.backend.release(token){r.token=Some(token);return Err((Error::Backend,h))} r.observation=None;self.accounts[i].used.pages-=used.pages;self.accounts[i].used.tasks-=used.tasks;self.accounts[i].used.channels-=used.channels;Ok(()) } pub fn begin_slice(&mut self,start:u64,maximum:u64)->Result{ let i=self.current()?;if self.active.is_some(){return Err(Error::State)}let a=self.accounts[i]; if maximum==0||a.cpu_used>=a.cpu_ticks{return Err(Error::Quota)} let amount=maximum.min(a.cpu_ticks-a.cpu_used);let deadline=start.checked_add(amount).ok_or(Error::Clock)?;let nonce=self.nonce.checked_add(1).ok_or(Error::Clock)?; self.nonce=nonce;self.active=Some((a.principal,nonce,start,deadline));Ok(Slice{principal:a.principal,nonce,start,deadline}) } pub fn finish_slice(&mut self,slice:Slice,r:TimerReceipt)->Result<(),(Error,Slice)>{ let i=match self.current(){Ok(i)=>i,Err(e)=>return Err((e,slice))}; if slice.principal!=self.accounts[i].principal||self.active!=Some((slice.principal,slice.nonce,slice.start,slice.deadline))||r.principal!=slice.principal||r.nonce!=slice.nonce||r.start!=slice.start||r.deadline!=slice.deadline||r.end1||(r.irq==1&&r.end=r.deadline){return Err((Error::Receipt,slice))} let charged=if r.irq==1{r.deadline-r.start}else{r.end-r.start}; let a=&mut self.accounts[i];a.cpu_used+=charged;a.slices+=1;a.expired+=r.irq;self.active=None;Ok(()) } pub fn into_backend(self)->Result{if self.fault||self.active.is_some()||self.resources.iter().any(|r|r.token.is_some()){Err(self)}else{Ok(self.backend)}} }