//! One publisher, three readers, an immutable publication, and an acknowledged //! lifetime. Release/acquire orders both publication and subsequent overwrite. use core::{cell::UnsafeCell,mem::MaybeUninit,sync::atomic::{AtomicU64,Ordering}}; #[repr(u64)]#[derive(Clone,Copy,Debug,PartialEq,Eq)] pub enum Error{Configuration=1,AlreadyBound,Context,NotReady,Busy,Closed,Stale,Exhausted} #[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} /// Returns actual CPU/root/IRQ state; clients cannot choose their own context. pub unsafe trait Context{fn execution(&self)->Execution;} #[repr(C)]pub struct Publication{issued:u64,sequence:AtomicU64,acknowledged:[AtomicU64;3],closed:AtomicU64,value:UnsafeCell>} // The publisher is unique and mutably borrowed for publication. A reader owns // a non-cloneable guard until its release acknowledgement. The next write/drop // requires acquire acknowledgements from all three readers. T is shared only // immutably; transferring it to/from the publisher requires Send. unsafe impl Sync for Publication{} impl Publication{ pub const fn new()->Self{Self{issued:0,sequence:AtomicU64::new(0),acknowledged:[const{AtomicU64::new(0)};3],closed:AtomicU64::new(0),value:UnsafeCell::new(MaybeUninit::uninit())}} /// Caller pins these exact online bindings through reader retirement and /// assigns a unique publication issuer. One exclusive borrow issues endpoints. pub unsafe fn bind(&mut self,issuer:u64,root:u64,bindings:[Binding;3])->Result<(Publisher<'_,T>,[Reader<'_,T>;3]),Error>{ if self.issued!=0{return Err(Error::AlreadyBound)} if issuer==0||root==0||root&4095!=0||root>>48!=0||bindings.iter().enumerate().any(|(i,b)|b.cpu!=i as u64+1||b.generation==0||b.issuer==0||b.epoch==0||b.issuer!=bindings[0].issuer||b.epoch!=bindings[0].epoch){return Err(Error::Configuration)} self.issued=1;Ok((Publisher{channel:self,issuer,root},core::array::from_fn(|i|Reader{channel:self,issuer,root,binding:bindings[i],completed:0}))) } } #[repr(C)]pub struct Publisher<'a,T>{channel:&'a Publication,issuer:u64,root:u64} #[repr(C)]pub struct Reader<'a,T>{channel:&'a Publication,issuer:u64,root:u64,binding:Binding,completed:u64} #[repr(C)]pub struct Reading<'a,T>{reader:Reader<'a,T>,sequence:u64} fn context(c:&impl Context,cpu:u64,root:u64)->Result<(),Error>{let e=c.execution();if e.cpu!=cpu||e.root!=root||!e.masked{return Err(Error::Context)}Ok(())} impl Publisher<'_,T>{ fn reusable(&self,c:&impl Context)->Result{context(c,0,self.root)?;if self.channel.closed.load(Ordering::Acquire)!=0{return Err(Error::Closed)}let sequence=self.channel.sequence.load(Ordering::Relaxed);if self.channel.acknowledged.iter().any(|a|a.load(Ordering::Acquire)!=sequence){return Err(Error::Busy)}Ok(sequence)} pub fn publish(&mut self,c:&impl Context,value:T)->Result{let sequence=match self.reusable(c){Ok(v)=>v,Err(e)=>return Err((e,value))};let Some(next)=sequence.checked_add(1)else{return Err((Error::Exhausted,value))}; // All readers' release acknowledgements are acquired before this overwrite. unsafe{if sequence!=0{(*self.channel.value.get()).assume_init_drop();}(*self.channel.value.get()).write(value);} self.channel.sequence.store(next,Ordering::Release);Ok(next) } pub fn close(self,c:&impl Context)->Result,(Error,Self)>{let sequence=match self.reusable(c){Ok(v)=>v,Err(e)=>return Err((e,self))};self.channel.closed.store(1,Ordering::Release);Ok(if sequence==0{None}else{Some(unsafe{(*self.channel.value.get()).assume_init_read()})})} pub fn sequence(&self)->u64{self.channel.sequence.load(Ordering::Acquire)} pub fn acknowledged(&self)->[u64;3]{core::array::from_fn(|i|self.channel.acknowledged[i].load(Ordering::Acquire))} } impl<'a,T> Reader<'a,T>{ pub fn acquire(self,c:&impl Context)->Result,(Error,Self)>{if let Err(e)=context(c,self.binding.cpu,self.root){return Err((e,self))}if self.channel.closed.load(Ordering::Acquire)!=0{return Err((Error::Closed,self))}let sequence=self.channel.sequence.load(Ordering::Acquire);if sequence==self.completed{return Err((Error::NotReady,self))}if self.completed.checked_add(1)!=Some(sequence){return Err((Error::Stale,self))}Ok(Reading{reader:self,sequence})} pub fn retire(self,c:&impl Context)->Result{if let Err(e)=context(c,self.binding.cpu,self.root){return Err((e,self))}if self.channel.closed.load(Ordering::Acquire)!=1{return Err((Error::Busy,self))}if self.channel.sequence.load(Ordering::Acquire)!=self.completed{return Err((Error::Stale,self))}Ok(self.binding)} pub fn completed(&self)->u64{self.completed}pub fn binding(&self)->Binding{self.binding} } impl<'a,T> Reading<'a,T>{ pub fn data(&self,c:&impl Context)->Result<&T,Error>{context(c,self.reader.binding.cpu,self.reader.root)?;Ok(unsafe{(*self.reader.channel.value.get()).assume_init_ref()})} pub fn sequence(&self)->u64{self.sequence} pub fn binding(&self)->Binding{self.reader.binding} pub fn complete(mut self,c:&impl Context)->Result,(Error,Self)>{if let Err(e)=context(c,self.reader.binding.cpu,self.reader.root){return Err((e,self))} self.reader.completed=self.sequence; // Consuming the read guard ends all safe payload borrows before release. self.reader.channel.acknowledged[self.reader.binding.cpu as usize-1].store(self.sequence,Ordering::Release);Ok(self.reader) } } // Dropping endpoints or a Reading does not acknowledge, drop, or return the // payload. An abandoned read therefore keeps overwrite and close blocked. pub const fn os_k2080_layout()->[u64;25]{use core::mem::{size_of,offset_of};[(size_of::>())as u64,(offset_of!(Publication,issued))as u64,(offset_of!(Publication,sequence))as u64,(offset_of!(Publication,acknowledged))as u64,(offset_of!(Publication,closed))as u64,(offset_of!(Publication,value))as u64,(size_of::>())as u64,(offset_of!(Publisher,channel))as u64,(offset_of!(Publisher,issuer))as u64,(offset_of!(Publisher,root))as u64,(size_of::>())as u64,(offset_of!(Reader,channel))as u64,(offset_of!(Reader,issuer))as u64,(offset_of!(Reader,root))as u64,(offset_of!(Reader,binding))as u64,(offset_of!(Reader,completed))as u64,(size_of::>())as u64,(offset_of!(Reading,reader))as u64,(offset_of!(Reading,sequence))as u64,(size_of::())as u64,(offset_of!(Binding,issuer))as u64,(offset_of!(Binding,epoch))as u64,(offset_of!(Binding,generation))as u64,(offset_of!(Binding,cpu))as u64,(size_of::())as u64] }