On Tue, Nov 19, 2024 at 12:24 PM Abdiel Janulgue <abdiel.janulgue@xxxxxxxxx> wrote: > > Ensure pages returned by the constructor are always reference counted. > This requires that we replace the page pointer wrapper with Opaque instead > of NonNull to make it possible to cast to a Page pointer from a raw struct > page pointer which is needed to create an ARef instance. > > Signed-off-by: Abdiel Janulgue <abdiel.janulgue@xxxxxxxxx> > -/// A pointer to a page that owns the page allocation. > +/// A pointer to a reference-counted page. > /// > /// # Invariants > /// > -/// The pointer is valid, and has ownership over the page. > +/// The pointer is valid. > +#[repr(transparent)] > pub struct Page { > - page: NonNull<bindings::page>, > + page: Opaque<bindings::page>, With this change, Page is no longer a pointer, nor does it contain a pointer. The documentation should be updated to reflect this. > // SAFETY: Pages have no logic that relies on them staying on a given thread, so moving them across > @@ -71,19 +73,23 @@ impl Page { > /// let page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; > /// # Ok(()) } > /// ``` > - pub fn alloc_page(flags: Flags) -> Result<Self, AllocError> { > + pub fn alloc_page(flags: Flags) -> Result<ARef<Self>, AllocError> { > // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it > // is always safe to call this method. > let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) }; > - let page = NonNull::new(page).ok_or(AllocError)?; > - // INVARIANT: We just successfully allocated a page, so we now have ownership of the newly > - // allocated page. We transfer that ownership to the new `Page` object. > - Ok(Self { page }) > + if page.is_null() { > + return Err(AllocError); > + } > + // CAST: Self` is a `repr(transparent)` wrapper around `bindings::page`. > + let ptr = page.cast::<Self>(); > + // INVARIANT: We just successfully allocated a page, ptr points to the new `Page` object. > + // SAFETY: According to invariant above ptr is valid. > + Ok(unsafe { ARef::from_raw(NonNull::new_unchecked(ptr)) }) Why did you change the null check? You should be able to avoid changing anything but the last line. Alice