//! Bounded CPU0 allocation service for three pinned online CPU clients. //! The backend retains the unique central allocator borrow. No client obtains //! a mutable allocator reference; only owned, generation-bound leases move. use core::mem::MaybeUninit; #[repr(u64)]#[derive(Clone,Copy,Debug,PartialEq,Eq)] pub enum Error{Context=1,Configuration,Busy,Closed,Foreign,Stale,Quota,Exhausted,Backend,Protocol,Live} #[repr(C)]#[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Binding{pub issuer:u64,pub epoch:u64,pub generation:u64,pub cpu:u64} #[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Execution{pub cpu:u64,pub root:u64,pub masked:bool} /// Implementations observe the actual executing CPU/root/IRQ mask. pub unsafe trait Context{fn execution(&self)->Execution;} #[repr(C)]#[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Page{pub address:u64,pub generation:u64} /// Owns or exclusively borrows one live central allocator. Allocation returns /// a valid, exclusive, zeroed 4096-byte lease. Release validates and zeroes it /// before returning it to that same allocator. Every failure retains custody. pub unsafe trait Backend:Context{ type Lease; fn allocate(&mut self)->Result; fn page(&self,lease:&Self::Lease)->Result; fn release(&mut self,lease:Self::Lease)->Result<(),(Error,Self::Lease)>; } #[repr(C)]pub struct Owned{value:MaybeUninit,live:u64} impl Owned{ pub const fn empty()->Self{Self{value:MaybeUninit::uninit(),live:0}} fn one(value:T)->Self{Self{value:MaybeUninit::new(value),live:1}} pub fn is_live(&self)->bool{self.live==1} pub fn get(&self)->Option<&T>{if self.live==1{Some(unsafe{self.value.assume_init_ref()})}else{None}} pub fn take(&mut self)->Option{if self.live!=1{return None}self.live=0;Some(unsafe{self.value.assume_init_read()})} } #[repr(C)]pub struct Frame{service:u64,binding:Binding,serial:u64,page:Page,lease:L} impl Frame{pub fn page(&self)->Page{self.page}pub fn serial(&self)->u64{self.serial}pub fn binding(&self)->Binding{self.binding}} #[repr(C)]#[derive(Clone,Copy,Debug,PartialEq,Eq)] pub struct Header{pub service:u64,pub binding:Binding,pub sequence:u64,pub operation:u64} pub const ALLOCATE:u64=1;pub const RETURN:u64=2;pub const CLOSE:u64=3; #[repr(C)]pub struct Request{header:Header,frame:Owned>} #[repr(C)]pub struct Reply{header:Header,status:u64,frame:Owned>} impl Request{pub fn header(&self)->Header{self.header}} impl Reply{pub fn header(&self)->Header{self.header}pub fn status(&self)->u64{self.status}} #[repr(C)]pub struct Client{service:u64,root:u64,binding:Binding,sequence:u64,pending:u64,closed:u64} impl Client{ fn context(&self,c:&impl Context)->Result<(),Error>{let e=c.execution();if e.cpu!=self.binding.cpu||e.root!=self.root||!e.masked{return Err(Error::Context)}Ok(())} fn request(&mut self,c:&impl Context,operation:u64,frame:Owned>)->Result,(Error,Owned>)>{ let result=(||{self.context(c)?;if self.closed!=0{return Err(Error::Closed)}if self.pending!=0{return Err(Error::Busy)}self.sequence.checked_add(1).ok_or(Error::Exhausted)})(); let next=match result{Ok(v)=>v,Err(e)=>return Err((e,frame))}; self.sequence=next;self.pending=operation;Ok(Request{header:Header{service:self.service,binding:self.binding,sequence:next,operation},frame}) } pub fn allocate(&mut self,c:&impl Context)->Result,Error>{self.request(c,ALLOCATE,Owned::empty()).map_err(|(e,_)|e)} pub fn close(&mut self,c:&impl Context)->Result,Error>{self.request(c,CLOSE,Owned::empty()).map_err(|(e,_)|e)} pub fn release(&mut self,c:&impl Context,frame:Frame)->Result,(Error,Frame)>{ if frame.service!=self.service||frame.binding!=self.binding{return Err((Error::Foreign,frame))} self.request(c,RETURN,Owned::one(frame)).map_err(|(e,mut f)|(e,f.take().unwrap())) } pub fn receive(&mut self,c:&impl Context,reply:Reply)->Result,(Error,Reply)>{ if let Err(e)=self.context(c){return Err((e,reply))} let expected=Header{service:self.service,binding:self.binding,sequence:self.sequence,operation:self.pending}; if self.pending==0||reply.header!=expected{return Err((Error::Stale,reply))} let want_frame=(reply.status==0&&self.pending==ALLOCATE)||(reply.status!=0&&self.pending==RETURN); if reply.frame.is_live()!=want_frame{return Err((Error::Protocol,reply))} if let Some(f)=reply.frame.get(){if f.service!=self.service||f.binding!=self.binding||f.serial==0{return Err((Error::Foreign,reply))}} if self.pending==CLOSE&&reply.status==0{self.closed=1}self.pending=0;Ok(reply) } pub fn pending(&self)->u64{self.pending}pub fn is_closed(&self)->bool{self.closed==1}pub fn binding(&self)->Binding{self.binding} } impl Reply{pub fn take_frame(&mut self)->Option>{self.frame.take()}} #[repr(C)]#[derive(Clone,Copy,Debug,PartialEq,Eq)] struct Entry{serial:u64,page:Page} const EMPTY:Entry=Entry{serial:0,page:Page{address:0,generation:0}}; #[repr(C)]pub struct Service{backend:B,issuer:u64,root:u64,targets:[Binding;3],completed:[u64;3],closed:[u64;3],entries:[Entry;3],serial:u64,quarantine:Owned>} impl Service{ /// Caller supplies a unique service issuer and pins the three actual online /// generations until all clients close. The backend's borrow is exclusive. pub unsafe fn open(backend:B,issuer:u64,root:u64,targets:[Binding;3])->Result<(Self,[Client;3]),(Error,B)>{ if issuer==0||root==0||root&4095!=0||root>>48!=0||targets.iter().enumerate().any(|(i,b)|b.cpu!=i as u64+1||b.generation==0||b.issuer==0||b.epoch==0||b.issuer!=targets[0].issuer||b.epoch!=targets[0].epoch){return Err((Error::Configuration,backend))} let e=backend.execution();if e.cpu!=0||e.root!=root||!e.masked{return Err((Error::Context,backend))} let clients=core::array::from_fn(|i|Client{service:issuer,root,binding:targets[i],sequence:0,pending:0,closed:0}); Ok((Self{backend,issuer,root,targets,completed:[0;3],closed:[0;3],entries:[EMPTY;3],serial:0,quarantine:Owned::empty()},clients)) } fn context(&self)->Result<(),Error>{let e=self.backend.execution();if e.cpu!=0||e.root!=self.root||!e.masked{return Err(Error::Context)}Ok(())} pub fn serve(&mut self,port:usize,request:Request)->Result,(Error,Request)>{ let validation=(||{self.context()?;if self.quarantine.is_live(){return Err(Error::Backend)}if port>=3||request.header.service!=self.issuer||request.header.binding!=self.targets[port]{return Err(Error::Foreign)}if self.closed[port]!=0{return Err(Error::Closed)}if self.completed[port].checked_add(1)!=Some(request.header.sequence){return Err(Error::Stale)}if ![ALLOCATE,RETURN,CLOSE].contains(&request.header.operation)||request.frame.is_live()!=(request.header.operation==RETURN){return Err(Error::Protocol)}Ok(())})(); if let Err(e)=validation{return Err((e,request))} let Request{header,mut frame}=request; let result=match header.operation{ ALLOCATE=>{ if self.entries[port].serial!=0{Err(Error::Quota)}else if let Some(next)=self.serial.checked_add(1){ match self.backend.allocate(){Err(e)=>Err(e),Ok(lease)=>{ // Backend contract guarantees a valid descriptor for every live lease. // If it breaks that contract, quarantine custody and refuse further use. match self.backend.page(&lease){Ok(page) if page.address!=0&&page.address&4095==0&&page.generation!=0&&!self.entries.iter().any(|e|e.serial!=0&&e.page.address==page.address)=>{ self.serial=next;self.entries[port]=Entry{serial:next,page};frame=Owned::one(Frame{service:self.issuer,binding:self.targets[port],serial:next,page,lease});Ok(()) },_=>{self.quarantine=Owned::one(Frame{service:self.issuer,binding:self.targets[port],serial:next,page:Page{address:0,generation:0},lease});Err(Error::Backend)}} }} }else{Err(Error::Exhausted)} }, RETURN=>{ let f=frame.get().unwrap();let expected=self.entries[port]; if f.service!=self.issuer||f.binding!=self.targets[port]{Err(Error::Foreign)}else if expected.serial==0||f.serial!=expected.serial||f.page!=expected.page{Err(Error::Stale)}else if self.backend.page(&f.lease)!=Ok(f.page){Err(Error::Backend)}else{ let Frame{service,binding,serial,page,lease}=frame.take().unwrap();match self.backend.release(lease){Ok(())=>{self.entries[port]=EMPTY;Ok(())},Err((e,lease))=>{frame=Owned::one(Frame{service,binding,serial,page,lease});Err(e)}} } }, CLOSE=>if self.entries[port].serial!=0{Err(Error::Live)}else{self.closed[port]=1;Ok(())}, _=>unreachable!() }; self.completed[port]=header.sequence;Ok(Reply{header,status:result.err().map(|e|e as u64).unwrap_or(0),frame}) } pub fn live(&self)->usize{self.entries.iter().filter(|e|e.serial!=0).count()+usize::from(self.quarantine.is_live())} pub fn completed(&self)->[u64;3]{self.completed} pub fn closed(&self)->[u64;3]{self.closed} pub fn finish(self)->Result{if let Err(e)=self.context(){return Err((e,self))}if self.live()!=0||self.closed!=[1;3]{return Err((Error::Live,self))}Ok(self.backend)} }