Skip to content

Commit

Permalink
rust: make SharedState::try_new() return a pinned Arc
Browse files Browse the repository at this point in the history
Pinning the Arc immediately guarantees no way to obtain a
Arc<SharedState>, but only a Pin<Arc<SharedState>>

Signed-off-by: Ayaan Zaidi <zaidi.ayaan@gmail.com>
  • Loading branch information
obviyus committed May 23, 2021
1 parent 45d79fc commit 6ad8ebc
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions samples/rust/rust_miscdev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,16 @@ struct SharedState {
}

impl SharedState {
fn try_new() -> Result<Arc<Self>> {
let state = Arc::try_new(Self {
// SAFETY: `condvar_init!` is called below.
state_changed: unsafe { CondVar::new() },
// SAFETY: `mutex_init!` is called below.
inner: unsafe { Mutex::new(SharedStateInner { token_count: 0 }) },
})?;
fn try_new() -> Result<Pin<Arc<Self>>> {
// SAFETY: Immediately pin the Arc
let state = unsafe {
Pin::new_unchecked(Arc::try_new(Self {
// SAFETY: `condvar_init!` is called below.
state_changed: CondVar::new(),
// SAFETY: `mutex_init!` is called below.
inner: Mutex::new(SharedStateInner { token_count: 0 }),
})?)
};
// SAFETY: `state_changed` is pinned behind `Arc`.
let state_changed = unsafe { Pin::new_unchecked(&state.state_changed) };
kernel::condvar_init!(state_changed, "SharedState::state_changed");
Expand All @@ -56,11 +59,11 @@ impl SharedState {
}

struct Token {
shared: Arc<SharedState>,
shared: Pin<Arc<SharedState>>,
}

impl FileOpener<Arc<SharedState>> for Token {
fn open(shared: &Arc<SharedState>) -> Result<Self::Wrapper> {
impl FileOpener<Pin<Arc<SharedState>>> for Token {
fn open(shared: &Pin<Arc<SharedState>>) -> Result<Self::Wrapper> {
Ok(Box::try_new(Self {
shared: shared.clone(),
})?)
Expand Down Expand Up @@ -122,7 +125,7 @@ impl FileOperations for Token {
}

struct RustMiscdev {
_dev: Pin<Box<miscdev::Registration<Arc<SharedState>>>>,
_dev: Pin<Box<miscdev::Registration<Pin<Arc<SharedState>>>>>,
}

impl KernelModule for RustMiscdev {
Expand Down

0 comments on commit 6ad8ebc

Please sign in to comment.