Linux cryptographic layer development
 help / color / mirror / Atom feed
From: sashiko-bot@kernel.org
To: "Ayush Singh" <ayush@beagleboard.org>,
	"Jason Kridner" <jkridner@beagleboard.org>,
	robertcnelson@gmail.com, "Johan Hovold" <johan@kernel.org>,
	"Alex Elder" <elder@kernel.org>,
	"Greg Kroah-Hartman" <gregkh@linuxfoundation.org>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	"Eric Biggers" <ebiggers@kernel.org>,
	"Ard Biesheuvel" <ardb@kernel.org>,
	"Ayush Singh" <ayush@beagleboard.com>,
	"Rob Herring" <robh@kernel.org>,
	"Krzysztof Kozlowski" <krzk+dt@kernel.org>,
	"Conor Dooley" <conor+dt@kernel.org>,
	"Lorenzo Stoakes" <ljs@kernel.org>,
	"Vlastimil Babka" <vbabka@kernel.org>,
	"Liam R. Howlett" <liam@infradead.org>,
	"Uladzislau Rezki" <urezki@gmail.com>,
	"Markus Probst" <markus.probst@posteo.de>
Cc: linux-crypto@vger.kernel.org, devicetree@vger.kernel.org
Subject: Re: [PATCH v6 6/9] rust: kernel: Add greybus abstractions
Date: Fri, 04 Dec 2026 11:06:35 +0000	[thread overview]
Message-ID: <sashiko-outbox-249655@kernel.org> (raw)
In-Reply-To: <20261204-gb-uart-transport-v6-6-668b333ae71d@beagleboard.org>

Thank you for your contribution! Sashiko AI review found 9 potential
issues to consider:
- [High] greybus: double-drop in gb_operation_request_send() on send
  failure
- [High] rust: greybus: data_rcvd() exposes gb_connection_recv() size
  underflow
- [Medium] rust: greybus: UAF of HdDriverVTable in gb_hd_release() after
  module unload
- [Medium] rust: greybus: Message::sent() holds references across
  potential free
- [Low] rust: alloc: missing inline attribute on Flags::new()
- [Low] rust: greybus: missing calling-context docs on
  HdDriver::message_send()
- [Low] rust: greybus: hd::Device missing DeviceContext bound and SAFETY
  comment
- [Low] rust: greybus: doc mismatches in Message::payload() and
  data_rcvd()
- [Low] rust: greybus: HdDriver::message_cancel() lacks &Self and
  default no-op impl
--

commit 0aa91303eac5e1c6fd892a4ecdeb192bf9f8230f
Author: Ayush Singh <ayush@beagleboard.org>

rust: kernel: Add greybus abstractions

This commit adds Rust abstractions for the Greybus core, covering host
device registration and driver callbacks, message/operation/connection
wrappers, and SVC protocol wire-format definitions.

> diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs
> index 6cd29ca35244d..e38bfe6e85728 100644
> --- a/rust/kernel/alloc.rs
> +++ b/rust/kernel/alloc.rs
> @@ -41,6 +41,12 @@
>  pub struct Flags(u32);
>  
>  impl Flags {
> +    /// Creates [`Flags`] from a raw `gfp_t`.
> +    #[cfg_attr(not(CONFIG_RUST_GREYBUS_ABSTRACTIONS), expect(dead_code))]
> +    pub(crate) fn new(v: bindings::gfp_t) -> Self {
> +        Self(v)
> +    }
> +
>      /// Get the raw representation of this flag.
>      pub(crate) fn as_raw(self) -> u32 {
>          self.0

[Severity: Low]
Should Flags::new() be marked #[inline] to match the convention for small
wrappers in the kernel crate?

> diff --git a/rust/kernel/greybus/hd.rs b/rust/kernel/greybus/hd.rs
> new file mode 100644
> index 0000000000000..24913c054f6a5
> --- /dev/null
> +++ b/rust/kernel/greybus/hd.rs
> @@ -0,0 +1,391 @@

[ ... ]

> +    /// Transmits `msg` to `dest_cport_id`.
> +    ///
> +    /// The message is only borrowed for the duration of this call: copy what is needed out of it,
> +    /// do not stash the reference. Returning `Ok(())` reports the message as sent to the core.
> +    ///
> +    /// `hd` is the host device the message is sent on. It is only guaranteed to be alive for the
> +    /// duration of this call.
> +    fn message_send(
> +        data: &Self,
> +        hd: &Device,
> +        dest_cport_id: u16,
> +        msg: &Message,
> +        gfp_mask: Flags,
> +    ) -> Result;

[Severity: Low]
Should HdDriver::message_send() document its calling context and sleeping
constraints?  gb_operation_request_send() is exported and forwards its
caller-supplied gfp_t directly to message_send(), so callers can invoke it
from atomic context with GFP_ATOMIC where sleeping or taking a mutex is
forbidden.  Unlike message_cancel(), which documents process context,
message_send() leaves this unspecified.

> +    /// Aborts the transmission of a message previously handed to [`HdDriver::message_send`].
> +    ///
> +    /// Always called in process context.
> +    fn message_cancel(msg: &Message);

[Severity: Low]
Should HdDriver::message_cancel() take data: &Self and hd: &Device, and
provide a default empty implementation?  Unlike C drivers, which can follow
message->operation->connection->hd to reach driver private data, the Rust
wrappers are opaque so drivers cannot access per-device state here.

gb_message_cancel() already dereferences message->operation->connection->hd
before invoking the callback, so HdDriverVTable::message_cancel() can borrow
hd and data without changing the C API.  Also, because
HdDriverVTable::message_send() synchronously calls msg.sent(hd, 0) on
Ok(()), synchronous transports have nothing to cancel and currently have to
define empty stubs.

[ ... ]

> +        match T::message_send(&data, hd_normal, dest_cport_id, msg, Flags::new(gfp_mask)) {
> +            Ok(()) => {
> +                // SAFETY: `msg` is still valid since `sent` is not called anywhere else.
> +                unsafe { msg.sent(hd, 0) };
> +                0
> +            }
> +            Err(e) => e.to_errno(),
> +        }

[Severity: High]
Can returning Err(e) from HdDriver::message_send() trigger a use-after-free
and refcount underflow in gb_operation_request_send()?

gb_operation_request_send() acquires two active counts and two references,
arms operation->timer, and then calls gb_message_send().  If the timer fires
or another thread calls gb_operation_cancel() while T::message_send() is
running, gb_operation_work() is queued and takes ownership of one active
count and one reference.  When T::message_send() then returns an error, the
err_put_active path calls timer_delete_sync() (which does not flush
operation->work) and unconditionally drops both active counts and both
references:

CPU0                              CPU1
gb_operation_request_send()
  __gb_operation_get_active(..., 2)
  add_timer(&operation->timer)
  gb_message_send()
    T::message_send()
                                  gb_operation_timeout()
                                    gb_operation_result_set(..., -ETIMEDOUT)
                                    queue_work(..., &operation->work)
    return Err(e)
  err_put_active:
  timer_delete_sync()
  gb_operation_put_active() x2
  gb_operation_put() x2
                                  gb_operation_work()
                                    operation->callback(...) <-- use-after-free
                                    gb_operation_put_active() <-- underflow
                                    gb_operation_put()

That drops three active counts and three references for the two acquired,
freeing operation while gb_operation_work() is still queued or running and
underflowing operation->active to -1.

[ ... ]

> +#[repr(transparent)]
> +pub struct Device<Ctx = device::Normal>(Opaque<bindings::gb_host_device>, PhantomData<Ctx>);
> +
> +// SAFETY: `gb_host_device` is reference counted through its embedded `struct device`, which may be
> +// used from any thread.
> +unsafe impl Send for Device {}
> +
> +// SAFETY: `gb_host_device` has its own internal locking, so it is safe to share references to it
> +// across threads.
> +unsafe impl Sync for Device {}
> +
> +kernel::impl_device_context_deref!(unsafe { Device });

[Severity: Low]
Should Device<Ctx = device::Normal> (and impl<Ctx> Device<Ctx>) carry a
Ctx: device::DeviceContext bound like other bus device wrappers, and should
impl_device_context_deref!(unsafe { Device }) have a // SAFETY: comment
explaining that Device is #[repr(transparent)] with layout independent of
Ctx?

Also, in HdDriverVTable::message_send(),
Device::<device::Normal>::from_raw(hd.as_raw()) is an unnecessary unsafe
cast because hd already deref-coerces to &Device<device::Normal> via
impl_device_context_deref!.

[ ... ]

> +    /// Hands a message received on `hd_cport_id` to the Greybus core.
> +    #[inline]
> +    pub fn data_rcvd(&self, cport_id: u16, msg: &[u8]) {
> +        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> +        // `struct gb_host_device`. `msg` is valid for reads of ``msg.len()` bytes for the duration
> +        // of the call, and the core only reads through the pointer — it copies the payload into
> +        // the operation before returning — so handing it a `*mut` derived from a shared reference
> +        // is sound.
> +        //
> +        // TODO: The C signature of this function should be changed to take const pointer for msg.
> +        unsafe {
> +            bindings::greybus_data_rcvd(self.as_raw(), cport_id, msg.as_ptr().cast_mut(), msg.len())
> +        }
> +    }
> +
> +    /// Hands `msg`, received from CPort `cport` of interface `intf_id`, to the Greybus core.
> +    ///
> +    /// Fails with `EINVAL` if no connection is bound to that pair.
> +    #[inline]
> +    pub fn data_rcvd_by_intf(&self, intf_id: u8, cport: u16, msg: &[u8]) -> Result {
> +        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> +        // `struct gb_host_device`. `msg` is valid for reads of `msg.len()` bytes for the duration
> +        // of the call, and the core only reads through the pointer — it copies the payload into
> +        // the operation before returning — so handing it a `*mut` derived from a shared reference
> +        // is sound.
> +        //
> +        // TODO: The C signature of this function should be changed to take const pointer for msg.
> +        to_result(unsafe {
> +            bindings::greybus_data_rcvd_by_intf(
> +                self.as_raw(),
> +                intf_id,
> +                cport,
> +                msg.as_ptr().cast_mut(),
> +                msg.len(),
> +            )
> +        })
> +    }

[Severity: High]
Can passing a message with header.size < sizeof(gb_operation_msg_hdr) to
Device::data_rcvd() or Device::data_rcvd_by_intf() cause a slab
out-of-bounds write or ZERO_SIZE_PTR dereference?

Both safe methods forward arbitrary &[u8] slices to gb_connection_recv(),
which checks size >= sizeof(header) and size >= msg_size, but never checks
msg_size >= sizeof(header).  For a slice of at least 8 bytes with
header.size in 0..7, gb_operation_create_incoming() underflows
request_size = size - sizeof(struct gb_operation_msg_hdr), and
gb_operation_message_alloc() adds sizeof(*header) back so message_size wraps
to 0..7 and bypasses hd->buffer_size_max.

kzalloc() then returns ZERO_SIZE_PTR (for 0) or a 1..7-byte buffer, and
gb_operation_message_init() writes the 8-byte header out of bounds or faults
on ZERO_SIZE_PTR.  On the response path with GB_OPERATION_FLAG_SHORT_RESPONSE,
gb_connection_recv_response() similarly underflows message->payload_size.
Rejecting msg_size < sizeof(header) in gb_connection_recv() (or validating
msg in the Rust wrappers) would close both the C underflow and the Rust
soundness hole.

[ ... ]

> +        // SAFETY: `parent` is a valid device, and the driver table is `'static`. The core only
> +        // ever reads through the driver pointer, so casting away `const` is fine.
> +        let hd = from_err_ptr(unsafe {
> +            bindings::gb_hd_create(
> +                core::ptr::from_ref(HdDriverVTable::<T>::build()).cast_mut(),
> +                parent.as_raw(),
> +                buffer_size_max,
> +                num_cports,
> +            )
> +        })?;

[ ... ]

> +    fn drop<'a>(&'a mut self) {
> +        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> +        // `struct gb_host_device`.
> +        unsafe { bindings::gb_hd_del(self.as_raw()) }
> +
> +        {
> +            // SAFETY: `hd` is a valid pointer to `gb_host_device`.
> +            let hd_dev = unsafe { Device::<device::CoreInternal<'_>>::from_raw(self.as_raw()) };
> +            // SAFETY: The driver data was set to a `T` in `Registration::new()` and has not been
> +            // taken since, and this is the only place that takes it.
> +            drop(unsafe { hd_dev.as_ref().drvdata_obtain::<T>() });
> +        }
> +
> +        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
> +        // `struct gb_host_device`.
> +        unsafe { bindings::gb_hd_put(self.as_raw()) };
> +    }

[Severity: Medium]
Can gb_hd_release() dereference HdDriverVTable::<T>::DRIVER after a loadable
host driver module is unloaded?

Registration::new() passes &HdDriverVTable::<T>::DRIVER, which lives in the
driver module's .rodata, to gb_hd_create() without pinning the module.
Because hd::Device implements AlwaysRefCounted and gb_hd_add() exposes
hd->dev in sysfs, an external reference can keep hd->dev alive past
Registration::drop() and module unload.  When the final reference is later
dropped, gb_hd_release() -> gb_svc_put() -> gb_svc_release() ->
gb_connection_destroy(svc->connection) -> gb_hd_cport_release() reads
hd->driver->cport_release from unmapped module memory.

Pinning the module for the lifetime of gb_host_device or repointing
hd->driver to a kernel-crate-resident table before gb_hd_put() would avoid
the use-after-free.

> diff --git a/rust/kernel/greybus/mod.rs b/rust/kernel/greybus/mod.rs
> new file mode 100644
> index 0000000000000..908356af08e67
> --- /dev/null
> +++ b/rust/kernel/greybus/mod.rs
> @@ -0,0 +1,200 @@

[ ... ]

> +    /// # Safety
> +    ///
> +    /// `Message` is not valid after this call.
> +    #[inline]
> +    pub(crate) unsafe fn sent<Ctx>(&self, hd: &hd::Device<Ctx>, status: i32) {
> +        // SAFETY: By the type invariant the message is valid and still owned by the transport,
> +        // and its connection and host device are alive for as long as it is.
> +        unsafe {
> +            bindings::greybus_message_sent(hd.as_raw(), self.0.get(), status);
> +        }
> +    }

[Severity: Medium]
Does Message::sent() hold &self and hd: &hd::Device<Ctx> across a call that
can free both objects?

greybus_message_sent() calls gb_operation_put_active(operation) followed by
gb_operation_put(operation).  Dropping operation->active to zero can wake a
concurrent Registration::drop() -> gb_hd_del() -> gb_hd_put() -> kfree(hd),
and gb_operation_put() can synchronously destroy operation and free message
before greybus_message_sent() returns.  Ending the borrows in
HdDriverVTable::message_send() and passing raw *mut pointers to
bindings::greybus_message_sent() avoids holding references across
deallocation.

[ ... ]

> +    /// Interprets the message payload as a `T`.
> +    ///
> +    /// Returns `None` if the payload is too short or misaligned for `T`.
> +    #[inline]
> +    pub fn payload<T: FromBytes>(&self) -> Option<&T> {
> +        T::from_bytes(self.payload_bytes())
> +    }

[Severity: Low]
This isn't a bug, but the doc comment on Message::payload() says it returns
None if the payload is too short or misaligned for T, whereas
FromBytes::from_bytes() requires an exact length match and also returns None
when the payload is longer than size_of::<T>().  Separately, in
rust/kernel/greybus/hd.rs, the doc comment on Device::data_rcvd() refers to
hd_cport_id instead of the parameter name cport_id.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261204-gb-uart-transport-v6-0-668b333ae71d@beagleboard.org?part=6

  reply	other threads:[~2026-12-04 11:06 UTC|newest]

Thread overview: 18+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
2026-12-04 10:30 ` [PATCH v6 1/9] greybus: operation: keep request active across message_send Ayush Singh
2026-12-04 10:55   ` sashiko-bot
2026-12-04 10:30 ` [PATCH v6 2/9] greybus: operation: arm request timeout before sending Ayush Singh
2026-12-04 10:52   ` sashiko-bot
2026-12-04 10:30 ` [PATCH v6 3/9] greybus: svc: add gb_svc_flush() Ayush Singh
2026-12-04 10:43   ` sashiko-bot
2026-12-04 10:30 ` [PATCH v6 4/9] greybus: connection: Add greybus_data_rcvd_by_intf() Ayush Singh
2026-12-04 10:52   ` sashiko-bot
2026-12-04 10:30 ` [PATCH v6 5/9] rust: crc_ccitt: add CRC-CCITT abstraction Ayush Singh
2026-12-04 10:30 ` [PATCH v6 6/9] rust: kernel: Add greybus abstractions Ayush Singh
2026-12-04 11:06   ` sashiko-bot [this message]
2026-12-04 10:30 ` [PATCH v6 7/9] drivers: greybus: Add software SVC implementation Ayush Singh
2026-12-04 11:07   ` sashiko-bot
2026-12-04 10:30 ` [PATCH v6 8/9] dt-bindings: beagle: Add BeagleConnect Freedom Ayush Singh
2026-12-04 11:03   ` sashiko-bot
2026-12-04 10:30 ` [PATCH v6 9/9] greybus: Add Rust UART node driver Ayush Singh
2026-12-04 11:18   ` sashiko-bot

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=sashiko-outbox-249655@kernel.org \
    --to=sashiko-bot@kernel.org \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=ardb@kernel.org \
    --cc=ayush@beagleboard.com \
    --cc=ayush@beagleboard.org \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=conor+dt@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=devicetree@vger.kernel.org \
    --cc=ebiggers@kernel.org \
    --cc=elder@kernel.org \
    --cc=gary@garyguo.net \
    --cc=gregkh@linuxfoundation.org \
    --cc=jkridner@beagleboard.org \
    --cc=johan@kernel.org \
    --cc=krzk+dt@kernel.org \
    --cc=liam@infradead.org \
    --cc=linux-crypto@vger.kernel.org \
    --cc=ljs@kernel.org \
    --cc=lossin@kernel.org \
    --cc=markus.probst@posteo.de \
    --cc=ojeda@kernel.org \
    --cc=robertcnelson@gmail.com \
    --cc=robh@kernel.org \
    --cc=sashiko-reviews@lists.linux.dev \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=urezki@gmail.com \
    --cc=vbabka@kernel.org \
    --cc=work@onurozkan.dev \
    /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