All of lore.kernel.org
 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 9/9] greybus: Add Rust UART node driver
Date: Fri, 04 Dec 2026 11:18:30 +0000	[thread overview]
Message-ID: <sashiko-outbox-249666@kernel.org> (raw)
In-Reply-To: <20261204-gb-uart-transport-v6-9-668b333ae71d@beagleboard.org>

Thank you for your contribution! Sashiko AI review found 11 potential
issues to consider:
- [High] greybus: gb_uart_node: infinite write_all() timeout hangs
  unbind and UAFs op
- [High] greybus: gb_uart_node: Module teardown in Drop crashes or
  stalls UART RX
- [High] greybus: refcount and active-count underflow in
  gb_operation_request_send()
- [Medium] greybus: gb_uart_node: TX buffer undersized for HDLC
  byte-stuffing
- [Medium] greybus: gb_uart_node: premature Module::new() before rx_buf
  allocation
- [Medium] greybus: MTU mismatch between gb-softsvc and GbNode::write()
- [Medium] greybus: un-ratelimited dev_warn() flood under SpinLock in
  HdlcRx::rx()
- [Medium] greybus: GbUartNode::init() does not enable optional
  vbat-supply regulator
- [Medium] greybus: unsound Device::as_bound() in GbNode::write() on
  remove failure
- [Low] greybus: HdlcRx::rx() fails to discard HDLC abort sequences
- [Low] greybus: per-byte out-of-line crc_ccitt() calls in
  GbNode::fill_buf()
--

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

greybus: Add Rust UART node driver

This commit adds the gb_uart_node serdev driver for Greybus nodes
connected over a UART using HDLC framing, registering each node with the
gb-softsvc software SVC.

> diff --git a/drivers/greybus/gb_uart_node.rs b/drivers/greybus/gb_uart_node.rs
> new file mode 100644
> index 0000000000000..b38e776c3e850
> --- /dev/null
> +++ b/drivers/greybus/gb_uart_node.rs
> @@ -0,0 +1,270 @@

[ ... ]

> +struct HdlcRx {
> +    rx_buf: KVec<u8>,
> +    rx_in_esc: bool,
> +    rx_overflow: bool,
> +    sdev: ARef<serdev::Device>,
> +    node: gb_softsvc::Module,
> +}

[Severity: High]
Can storing gb_softsvc::Module inside HdlcRx without implementing
serdev::Driver::unbind() crash or stall UART RX during unbind?

Registration::post_unbind_callback() calls drvdata_obtain(), clearing
dev->driver_data to NULL before PrivateData::drop() runs
assume_init_drop() and before serdev_device_close() stops UART RX:

CPU0                              CPU1
----                              ----
post_unbind_callback()
  drvdata_obtain()
    dev->driver_data = NULL
  PrivateData::drop()
    lock(self.active)
    assume_init_drop()
      Module::drop()
        hd.svc_flush()            receive_buf_callback()
                                    drvdata_borrow()  <-- NULL deref
  serdev_device_close()

Even without the NULL dereference, PrivateData::drop() holds
self.active.lock() across hd.svc_flush(), blocking receive_buf_callback()
from delivering replies to synchronous control requests on svc->wq (such
as gb_control_bundle_resume() during gb_module_del()), which stalls
teardown until 1000ms timeouts expire.  Tearing down gb_softsvc::Module
in serdev::Driver::unbind() (stored outside the rx spinlock) runs before
drvdata is cleared and without holding self.active.

Separately, GbNode::write() invokes AsBusDevice::from_device(), which
rust/kernel/device.rs documents as internal and not for driver use, and
continues sending UART frames during post_unbind_callback() after
unbind() has completed.

[ ... ]

> +    fn frame_finish(&self) -> Result<()> {
> +        if self.rx_buf.len() < 4 {
> +            return Err(code::EFAULT);
> +        }
> +
> +        let crc = crc_ccitt(0xffff, &self.rx_buf);
> +        if crc != HDLC_EXPECTED_CRC {
> +            dev_warn!(self.sdev.as_ref(), "CRC failed {}", crc);
> +            return Ok(());
> +        }

[ ... ]

> +    fn rx(&mut self, data: &[u8]) -> usize {
> +        for i in data.iter() {
> +            match *i {
> +                HDLC_FRAME => {
> +                    if !self.rx_buf.is_empty() {
> +                        if let Err(e) = self.frame_finish() {
> +                            dev_warn!(self.sdev.as_ref(), "bad frame: {e:?}\n");
> +                        }
> +                    }
> +
> +                    self.rx_buf.clear();
> +                    self.rx_in_esc = false;
> +                    self.rx_overflow = false;
> +                }
> +                HDLC_ESC => self.rx_in_esc = true,

[Severity: Low]
Should HDLC_FRAME discard the buffer when self.rx_in_esc is true?

An HDLC_ESC (0x7D) immediately followed by HDLC_FRAME (0x7E) is an RFC
1662 abort sequence, so calling frame_finish() without checking
!self.rx_in_esc emits spurious warnings on every abort and risks
delivering truncated data on a 16-bit CRC collision.

> +                // Skip data if buffer has overflown.
> +                _ if self.rx_overflow => {}
> +                _ => {
> +                    let c = if self.rx_in_esc { *i ^ HDLC_XOR } else { *i };
> +                    self.rx_in_esc = false;
> +
> +                    if self.rx_buf.push_within_capacity(c).is_err() {
> +                        dev_warn!(self.sdev.as_ref(), "buffer overflow. Dropping frame");
> +
> +                        self.rx_overflow = true;
> +                        self.rx_buf.clear();
> +                    }
> +                }

[Severity: Medium]
Can a noisy or baudrate-mismatched serial peer flood dmesg while
preemption is disabled here?

GbUartNode::receive() holds SpinLock<HdlcRx> across guard.rx(data), and
the dev_warn! calls in HdlcRx::frame_finish() and HdlcRx::rx() are not
ratelimited, so continuous framing errors can stall the serial console
and spike scheduling latency.

In addition, short frames in frame_finish() return code::EFAULT instead
of code::EINVAL or code::EBADMSG, and the CRC and overflow dev_warn!
calls omit trailing newlines.

[ ... ]

> +    fn fill_buf(mut crc: u16, data: &[u8], buf: &mut KVec<u8>) -> Result<u16> {
> +        for i in data {
> +            crc = crc_ccitt(crc, &[*i]);
> +            if *i == HDLC_ESC || *i == HDLC_FRAME {
> +                buf.push_within_capacity(HDLC_ESC)
> +                    .map_err(|_| code::E2BIG)?;
> +                buf.push_within_capacity(i ^ HDLC_XOR)
> +                    .map_err(|_| code::E2BIG)?;
> +            } else {
> +                buf.push_within_capacity(*i).map_err(|_| code::E2BIG)?;
> +            }
> +        }
> +
> +        Ok(crc)
> +    }

[Severity: Low]
Can fill_buf() call crc_ccitt(crc, data) once per slice instead of once
per byte?

crc_ccitt() is an out-of-line exported C function, so this loop makes up
to 510 cross-FFI calls per frame, and GbNode::write() also redundantly
computes crc_ccitt() over the two appended CRC bytes only to discard the
result.

[ ... ]

> +impl gb_softsvc::InterfaceOps for GbNode {
> +    fn write(&self, data: &[u8], cport: u16, gfp_mask: Flags) -> Result<()> {
> +        // SAFETY: `GbNode` only exists while its serdev driver is bound, so the device is in the
> +        // `Bound` state for the duration of this call.
> +        let bound: &serdev::Device<Bound> =
> +            unsafe { serdev::Device::from_device(self.sdev.as_ref().as_bound()) };

[Severity: Medium]
Does this Device::as_bound() assumption hold if GB_SVC_TYPE_MODULE_REMOVED
fails during unbind?

GbHdDriver::message_send() clones Arc<dyn InterfaceOps> out of intf_map
and drops the lock before calling intf.write().  On unbind,
Svc::module_remove() ignores send_request() errors and cannot detect
silent drops from a GFP_ATOMIC allocation failure in
gb_operation_create_incoming() or kmalloc_obj() failure in
gb_svc_queue_deferred_request():

CPU0                              CPU1
----                              ----
                                  GbHdDriver::message_send()
                                    intf = intf_by_id()
PrivateData::drop()
  Module::drop()
    send_request(MODULE_REMOVED)
      (alloc fails, not queued)
    hd.svc_flush()
    map_remove()
                                  GbNode::write()
                                    ttyport_write_buf()
                                      test_bit(SERPORT_ACTIVE) == 1
  serdev_device_close()
    ttyport_close()
      tty_release_struct(tty)
      serport->tty = NULL
                                      tty->ops->write(tty, ...)  <-- UAF

If SERPORT_ACTIVE is already cleared before ttyport_write_buf() checks
it, ttyport_write_buf() returns 0 and serdev_device_write(..., 0) sleeps
forever holding serdev->write_lock.

> +        // Drop messages which are bigger than what is supported.
> +        if data.len() > HDLC_MAX_MSG_LEN {
> +            return Err(code::E2BIG);
> +        }

[Severity: Medium]
Does this 504-byte limit mismatch the MTU advertised by gb-softsvc?

GreybusSoftSvc::init() registers the host device with
GB_OPERATION_SIZE_MAX (65535 bytes), which protocol drivers such as
gb_uart_probe() query via gb_operation_get_payload_size_max().  Any
protocol transfer larger than 504 bytes will therefore fail at runtime
with -E2BIG instead of being segmented to the transport MTU.

> +        let mut buf = KVec::with_capacity(HDLC_MAX_FRAME_LEN, gfp_mask)?;

[Severity: Medium]
Is buf undersized for HDLC byte-stuffing?

HDLC_MAX_MSG_LEN is 504 unescaped bytes, but fill_buf() doubles every
0x7D and 0x7E byte in the header, CPort ID, payload, and CRC, requiring
up to 2 + 2 * (6 + data.len()) bytes (1020 bytes for a 504-byte
message).  Valid messages up to HDLC_MAX_MSG_LEN will fail spuriously
with -E2BIG whenever byte-stuffing pushes the wire frame past 512
bytes, while small messages always allocate 512 bytes instead of sizing
to the worst-case escaped length for data.len() as hdlc_encoded_length()
in drivers/greybus/gb-beagleplay.c does.

[ ... ]

> +        // A short count means the wait was interrupted by a signal after part of the frame was
> +        // accepted. The rest is never sent; the receiver drops the truncated frame on the next
> +        // flag, but the message itself was not sent.
> +        if bound.write_all(&buf, 0)? != buf.len() {
> +            return Err(code::EINTR);
> +        }

[Severity: High]
Can passing timeout 0 to bound.write_all() hang unbind permanently if
the UART stops draining?

serdev_device_write() converts timeout 0 to MAX_SCHEDULE_TIMEOUT while
holding serdev->write_lock, and GbHdDriver::message_cancel() is a no-op.
Because Greybus sends messages from signal-less kernel workqueues
(svc->wq, connection->wq), a stalled UART blocks serdev_device_write()
indefinitely, so unbind deadlocks forever in gb_operation_cancel()
waiting for operation->active to drop before serdev_device_close() can
run.  Holding serdev->write_lock synchronously also serializes
concurrent asynchronous Greybus operations.

[Severity: High]
Can bound.write_all(&buf, 0) sleeping interruptibly inside
gb_message_send() cause an active-count underflow and use-after-free in
gb_operation_request_send()?

gb_operation_request_send() takes two active counts and two references
and arms operation->timer before calling gb_message_send():

CPU0                              CPU1
----                              ----
gb_operation_request_send()
  gb_operation_get() x2
  __gb_operation_get_active(2)
  add_timer(&operation->timer)
  gb_message_send()
    GbNode::write()
      bound.write_all(&buf, 0)    gb_operation_timeout()
        (sleeps interruptibly)      queue gb_operation_work()
                                      gb_operation_put_active()
                                      gb_operation_put()
      (signal -> -EINTR)
err_put_active:
  gb_operation_put_active() x2    <-- active underflows to -1
  gb_operation_put() x2           <-- extra put / use-after-free

The same three-puts-for-two-gets underflow occurs if
gb_operation_cancel() queues gb_operation_work() while write_all() is
blocked and later returns an error, leaving operation->active non-zero
(hanging gb_operation_cancel()) and dropping an extra reference on
struct gb_operation.

[ ... ]

> +impl GbUartNode {
> +    fn init(sdev: &serdev::Device<Core<'_>>) -> Result<HdlcRx> {
> +        if sdev
> +            .set_baudrate(
> +                sdev.as_ref()
> +                    .fwnode()
> +                    .and_then(|fwnode| fwnode.property_read(c"current-speed").optional())
> +                    .unwrap_or(115200),
> +            )
> +            .is_err()
> +        {
> +            return Err(EINVAL);
> +        }
> +        sdev.set_flow_control(false);
> +        sdev.set_parity(serdev::Parity::None)?;

[Severity: Medium]
Should GbUartNode::init() enable the optional vbat-supply regulator?

Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
declares vbat-supply for beagle,beagleconnect-freedom.  Without enabling
it (for example via kernel::regulator::devm_enable_optional()), boards
with a controllable vbat-supply rail not marked regulator-always-on can
leave the MCU unpowered or have the rail disabled at
regulator_init_complete(), and -EPROBE_DEFER will not be honored.

> +        let node = gb_softsvc::Module::new(&[Arc::new(GbNode::new(sdev.into()), GFP_KERNEL)?])?;
> +
> +        HdlcRx::new(sdev.into(), node)

[Severity: Medium]
Should rx_buf be allocated before calling gb_softsvc::Module::new()?

Adapter::probe_callback() holds private_data.active.lock() across probe,
blocking UART RX delivery.  If KVec::with_capacity() fails with -ENOMEM
in HdlcRx::new(), dropping node calls hd.svc_flush() while the queued
GB_SVC_TYPE_MODULE_INSERTED work transiently publishes the module and
waits for UART control replies that cannot be delivered, stalling probe
error unwinding until the 1000ms Greybus timeout expires.

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

      reply	other threads:[~2026-12-04 11:18 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
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 [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=sashiko-outbox-249666@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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.