Re: [PATCH v3 1/2] rust: page: use the page's reference count to decide when to free the allocation

From: Abdiel Janulgue
Date: Tue Nov 19 2024 - 07:06:43 EST



On 19/11/2024 13:45, Alice Ryhl wrote:
+ 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.

Changing only the line, it complains:

86 | Ok(unsafe { ARef::from_raw(page) })
| -------------- ^^^^ expected `NonNull<Page>`, found `NonNull<page>`

Unless this is what you mean?

let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) };
let page = page.cast::<Self>();
let page = NonNull::new(page).ok_or(AllocError)?;
Ok(unsafe { ARef::from_raw(page) })

But what if alloc_pages returns null in the place? Would that be a valid cast still?

Regards,
Abdiel