Rust for Linux List
 help / color / mirror / Atom feed
From: "Gary Guo" <gary@garyguo.net>
To: "Alexandre Courbot" <acourbot@nvidia.com>, "Zhi Wang" <zhiw@nvidia.com>
Cc: <rust-for-linux@vger.kernel.org>, <linux-kernel@vger.kernel.org>,
	<dakr@kernel.org>, <jgg@nvidia.com>, <dave.jiang@intel.com>,
	<saeedm@nvidia.com>, <jic23@kernel.org>, <gary@garyguo.net>,
	<joelagnelf@nvidia.com>, <aliceryhl@google.com>,
	<kwilczynski@kernel.org>, <ojeda@kernel.org>,
	<alex.gaynor@gmail.com>, <boqun.feng@gmail.com>,
	<bjorn3_gh@protonmail.com>, <lossin@kernel.org>,
	<a.hindborg@kernel.org>, <tmgross@umich.edu>, <cjia@nvidia.com>,
	<smitra@nvidia.com>, <ankita@nvidia.com>, <aniketa@nvidia.com>,
	<kwankhede@nvidia.com>, <targupta@nvidia.com>, <kjaju@nvidia.com>,
	<alkumar@nvidia.com>, <jhubbard@nvidia.com>, <zhiwang@kernel.org>,
	<daniel.almeida@collabora.com>
Subject: Re: [PATCH v6 1/1] rust: introduce abstractions for fwctl
Date: Mon, 06 Jul 2026 13:00:42 +0100	[thread overview]
Message-ID: <DJRH022OWTTK.1KPQDQHKG7CTF@garyguo.net> (raw)
In-Reply-To: <DJR76RV8NEKN.2MP5M9Z66U4TY@nvidia.com>

On Mon Jul 6, 2026 at 5:19 AM BST, Alexandre Courbot wrote:
> Hi Zhi,
>
> This is looking pretty good to me overall, a few remarks/questions
> below. None of these should require big changes.
>
> On Tue Jun 30, 2026 at 12:01 AM JST, Zhi Wang wrote:
> <...>
>> +/// A fwctl device.
>> +///
>> +/// `#[repr(C)]` with the `fwctl_device` at offset 0, matching the C `fwctl_alloc_device()` layout
>> +/// convention. Contains a pointer to the [`Registration`]'s data, set at registration time and
>> +/// cleared on unregistration.
>> +///
>> +/// # Invariants
>> +///
>> +/// - `dev` is embedded at offset 0 and is initialised by fwctl.
>> +/// - The fwctl refcount owns the allocation lifetime.
>> +/// - `registration_data` is either `NonNull::dangling()` (before registration / after
>> +///   unregistration) or points to valid data owned by the [`Registration`].
>> +#[repr(C)]
>> +pub struct Device<T: Operations> {
>> +    dev: Opaque<bindings::fwctl_device>,
>> +    registration_data: UnsafeCell<NonNull<T::RegistrationData<'static>>>,
>> +}
>> +
>> +impl<T: Operations> Device<T> {
>> +    /// Allocate a new fwctl device.
>> +    ///
>> +    /// Returns an [`ARef`] that can be passed to [`Registration::new()`]
>> +    /// to make the device visible to userspace.
>> +    pub fn new(parent: &device::Device<device::Bound>) -> Result<ARef<Self>> {
>> +        const_assert!(
>> +            core::mem::offset_of!(Self, dev) == 0,
>> +            "struct fwctl_device must be at offset 0"
>> +        );
>> +
>> +        let ops = core::ptr::from_ref::<bindings::fwctl_ops>(&VTable::<T>::VTABLE).cast_mut();
>> +
>> +        // SAFETY: `ops` is static, `parent` is bound, and `size` covers the full `Device<T>`.
>> +        let raw = unsafe {
>> +            bindings::_fwctl_alloc_device(parent.as_raw(), ops, core::mem::size_of::<Self>())
>> +        };
>> +
>> +        if raw.is_null() {
>> +            return Err(ENOMEM);
>> +        }
>> +
>> +        let this = raw.cast::<Self>();
>> +
>> +        // INVARIANT: Set `registration_data` to dangling (no registration yet).
>> +        // SAFETY: `this` points to the allocation just returned by fwctl.
>> +        unsafe {
>> +            core::ptr::addr_of_mut!((*this).registration_data)
>> +                .write(UnsafeCell::new(NonNull::dangling()));
>> +        };
>> +
>> +        // SAFETY: `raw` owns the initial reference.
>> +        Ok(unsafe { ARef::from_raw(NonNull::new_unchecked(this)) })
>
> How about replacing from `if raw.is_null() ...` with something more
> functional-style:
>
>     NonNull::new(raw.cast::<Self>())
>         .map(|this| {
>             // INVARIANT: Set `registration_data` to dangling (no registration yet).
>             // SAFETY: `this` points to the allocation just returned by fwctl.
>             unsafe {
>                 (&raw mut (*this.as_ptr()).registration_data)
>                     .write(UnsafeCell::new(NonNull::dangling()))
>             };
>             // SAFETY: `this` owns the initial reference.
>             unsafe { ARef::from_raw(this) }
>         })
>         .ok_or(ENOMEM)

I would rather do

    let this = NonNull::new(raw.cast::<Self>()).ok_or(ENOMEM);
    // use this

for a more linear style. Map shouldn't be needed.

Best,
Gary

>
> It's not just cosmetic: it removes one call to an unsafe method
> (`NonNull::new_unchecked`), carries the fact that `this` is not NULL in
> the type system from the get-go (instead of relying on an explicit
> check), and makes the transition steps from the raw pointer to the
> `ARef` more explicit.


      parent reply	other threads:[~2026-07-06 12:00 UTC|newest]

Thread overview: 6+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-06-29 15:01 [PATCH v6 0/1] rust: introduce abstractions for fwctl Zhi Wang
2026-06-29 15:01 ` [PATCH v6 1/1] " Zhi Wang
2026-07-04 19:42   ` Danilo Krummrich
2026-07-06  4:19   ` Alexandre Courbot
2026-07-06 11:30     ` Danilo Krummrich
2026-07-06 12:00     ` Gary Guo [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=DJRH022OWTTK.1KPQDQHKG7CTF@garyguo.net \
    --to=gary@garyguo.net \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=alex.gaynor@gmail.com \
    --cc=aliceryhl@google.com \
    --cc=alkumar@nvidia.com \
    --cc=aniketa@nvidia.com \
    --cc=ankita@nvidia.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=cjia@nvidia.com \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=dave.jiang@intel.com \
    --cc=jgg@nvidia.com \
    --cc=jhubbard@nvidia.com \
    --cc=jic23@kernel.org \
    --cc=joelagnelf@nvidia.com \
    --cc=kjaju@nvidia.com \
    --cc=kwankhede@nvidia.com \
    --cc=kwilczynski@kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=saeedm@nvidia.com \
    --cc=smitra@nvidia.com \
    --cc=targupta@nvidia.com \
    --cc=tmgross@umich.edu \
    --cc=zhiw@nvidia.com \
    --cc=zhiwang@kernel.org \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox