The following has been changed:
- introduce a new C serdev API to fix race conditions and simplify rust
code. Should also be useful on the C side.
- fix race conditions
- simplify rust code
- add rust function to provide mutable references to driver's private
data
- provide mutable references in callbacks to avoid the need for a
SpinLock in the greybus patch series [1]
[1]
https://lore.kernel.org/rust-for-linux/20260827-gb-uart-transport-v2-7-a03b…
Signed-off-by: Markus Probst <markus.probst(a)posteo.de>
---
Markus Probst (5):
tty: serdev: Export functions to pause receive_buf callback calls
rust: serdev: Replace `active` mutex with receive pause
rust: serdev: Simplify callbacks
rust: Add `Device::drvdata_borrow_mut`
rust: serdev: Pause receive callback before calling unbind
drivers/tty/serdev/core.c | 50 +++++++++-
drivers/tty/serdev/serdev-ttyport.c | 32 ++++++
include/linux/serdev.h | 6 ++
rust/kernel/device.rs | 24 +++++
rust/kernel/serdev.rs | 189 +++++++++++++-----------------------
samples/rust/rust_driver_serdev.rs | 2 +-
6 files changed, 180 insertions(+), 123 deletions(-)
---
base-commit: e5e04726cdd043e309677071ab1b65a4b18f422b
change-id: 20260905-rust_serdev_probe_refactor-0e2b044354a7
A Greybus network needs an SVC (Supervisory Controller) to bring
interfaces up, assign device IDs and connect CPorts to the AP. On a
UniPro network the SVC is a real entity on the bus. On transports that
merely carry Greybus messages - a UART, an I2C bus, a network link -
nothing on the wire plays that role, so the SVC has to be emulated
somewhere: in a user-space bridge (gbridge), in coprocessor firmware
(cc1352p7 in gb-beagleplay), or open-coded inside the host driver itself.
This series moves the emulation into the kernel and makes it shared.
This was discussed in a prior RFC as well [2], but to keep things short,
removing the need for an external SVC greatly simplifies the greybus
network setup when nodes are directly connected over common transports
such as UART, I2C etc.
gb-uart-node gb-softsvc greybus core
(transport, serdev) <-> (SVC + host device) <-> (bundles, protocols)
NodeOps module_insert()
submit_message() module_remove()
gb-softsvc registers itself as a Greybus host device and answers the
SVC-side operations the core expects during interface bring-up and
teardown. A host driver implements the NodeOps trait to push data
towards its node, calls module_insert() to announce a new node,
submit_message() to hand incoming Greybus messages back to the core,
and module_remove() on disconnect.
The first user is gb-uart-node, a driver for Greybus nodes attached over
a plain serial port. Framing is HDLC, with a one-byte address (0x01 for
Greybus) and control byte, followed by the 16-bit CPort ID and the
Greybus message. No SVC firmware is required on the far end, so the node
can be a bare microcontroller speaking Greybus - a BeagleConnect Freedom
over its serial link, in this case. The testing is performed with
greybus-zephyr [0] implementation.
Both drivers are written in Rust, which is why the middle of the series
is abstractions rather than drivers. Only the APIs these two drivers
need are covered: protocols.rs abstracts the SVC-facing parts of
greybus_protocols.h, and types such as Greybus Interface do not
implement AlwaysRefCounted yet. The intent is to grow this as more Rust
host drivers appear rather than to abstract the whole subsystem up
front.
Patches 1 and 2 are small C-side preparations to the Greybus core:
exporting gb_connection_get()/gb_connection_put() and adding
gb_connection_hd_find_by_intf(), a lookup by remote interface and CPort
id for callers that only know the far end of a connection. Patch 3 adds
a CRC-CCITT abstraction, needed for HDLC frame checks. Patch 4 adds the
Greybus abstractions, patches 5 and 6 the two drivers, and patch 7 the
device tree binding for BeagleConnect Freedom.
Open questions
***************
- gb-uart-node imports types from gb-softsvc, so the series carries the
Rust-to-Rust cross-module calling setup from nova-core [1]:
gb_softsvc_exports.c plus the Makefile plumbing that emits crate
metadata and generates the export list. This is a workaround for the
build system not supporting Rust cross-module dependencies natively,
and it should go away once that lands.
- Connection create/destroy and interface activate/resume in gb-softsvc
currently just acknowledge the request. Callbacks into NodeOps can be
added when a transport actually needs to act on them; I did not want
to invent an interface without a user.
- Zerocopy is currently not being used in grebeybus/protocols.rs. They
cannot be derived yet since types generated by bindgen do not have
them, and it seems explicitly forbindden to manually impl the traits.
So using old traits from transmute.
- The bindings are supposed to be created for actual device, but any MCU
that supports Zephyr, can run the greybus-zephyr firmware with UART
transport. So not sure if adding a beagle,beagleconnect-freedom
compatible is the correct choice here.
- The individual patches can be spun off into independent patch series
if required. The reason for this single patch series is to provide a
complete picture of usage.
- Since gb-softsvc currently is not being used from a C driver, no C API
is provided. However, if required, it can be added.
- Writing to UART from gb-uart-node is currently a bit broken. I am not
quite sure what the safe way is to go from a non-bound device to a
bound device. Any suggestions on this front are welcome.
- I am not sure if Rust abstractions should have a seperate entry in
MAINTAINERS with me as the maintainer, or if they should just be added
to the respective subsystem entries.
[0]: https://github.com/beagleboard/greybus-zephyr
[1]: https://lore.kernel.org/all/20260622-nova-exports-v5-0-6191773fc977@nvidia.…
[2]: https://lore.kernel.org/all/ecca8eb2-8e5a-4770-bcf6-3fb49773088b@beagleboar…
Signed-off-by: Ayush Singh <ayush(a)beagleboard.org>
---
Changes in v2:
- Fix possible null pointer dereference in
gb_connection_hd_find_by_intf. Flagged by sashiko-bot.
- Remove prompt CONFIG_RUST_CRC_CCITT_ABSTRACTIONS Kconfig symbol.
- Add CONFIG_RUST_GREYBUS_ABSTRACTIONS to ensure that greybus is
built-in for rust abstractions to work.
- Use gfp_mask in message_send callback.
- Only provide a Message reference in message_cancel callback.
- Add invariant comment for Registration.
- Call Registration->add directly in new, before constructing
Registration.
- Add Send and Sync bounds to T in Registration<T>
- Set endo_id as 0. Is not used anywhere.
- Fix module_insert intf_count. Was hardcoded to 1 by mistake. Flagged by
sashiko-bot.
- Check for empty intfs slice in Module::new.
- Remove module in serdev::Driver::unbind instead of on drop.
- Make gb_uart_node write atomic. Using temp buffer to build frame.
- Fix import style.
- Reorder beagleconnect-freedom dtbinding patch to be before gb_uart_node.
- Add vbat-supply and reg properties to beagleconnect-freedom dtbinding.
- Reference spi-peripheral-props in beagleconnect-freedom dtbinding.
- Link to v1: https://lore.kernel.org/r/20260820-gb-uart-transport-v1-0-282da14ab7b7@beag…
---
Ayush Singh (7):
greybus: connection: Export gb_connection_get() and gb_connection_put()
greybus: connection: Add gb_connection_hd_find_by_intf()
rust: crc_ccitt: add CRC-CCITT abstraction
rust: kernel: Add greybus abstractions
drivers: greybus: Add software SVC implementation
dt-bindings: beagle: Add BeagleConnect Freedom
greybus: Add Rust UART node driver
.../beagle/beagle,beagleconnect-freedom.yaml | 39 ++
MAINTAINERS | 15 +
drivers/greybus/.gitignore | 1 +
drivers/greybus/Kconfig | 34 ++
drivers/greybus/Makefile | 50 ++
drivers/greybus/connection.c | 29 +-
drivers/greybus/gb_softsvc.rs | 504 +++++++++++++++++++++
drivers/greybus/gb_softsvc_exports.c | 15 +
drivers/greybus/gb_uart_node.rs | 245 ++++++++++
include/linux/greybus/connection.h | 6 +
lib/crc/Kconfig | 7 +
rust/bindings/bindings_helper.h | 2 +
rust/kernel/alloc.rs | 5 +
rust/kernel/crc_ccitt.rs | 26 ++
rust/kernel/greybus/hd.rs | 333 ++++++++++++++
rust/kernel/greybus/mod.rs | 232 ++++++++++
rust/kernel/greybus/protocols.rs | 392 ++++++++++++++++
rust/kernel/lib.rs | 4 +
18 files changed, 1937 insertions(+), 2 deletions(-)
---
base-commit: 6b8c8af514d739d0335f5579b585e02babe8a727
change-id: 20260810-gb-uart-transport-9255d6557c4c
Best regards,
--
Ayush Singh <ayush(a)beagleboard.org>
Correct "registerd" to "registered", reported by scripts/checkpatch.pl
using the misspelling list in scripts/spelling.txt. Only touches comments,
no code changes.
Assisted-by: Cursor:claude-opus-5
Signed-off-by: Hemanth Selam <hemanth.selam(a)gmail.com>
---
drivers/greybus/greybus_trace.h | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/drivers/greybus/greybus_trace.h b/drivers/greybus/greybus_trace.h
index 616a3bd61aa6..3c331e09ea83 100644
--- a/drivers/greybus/greybus_trace.h
+++ b/drivers/greybus/greybus_trace.h
@@ -339,7 +339,7 @@ DEFINE_INTERFACE_EVENT(gb_interface_create);
DEFINE_INTERFACE_EVENT(gb_interface_release);
/*
- * Occurs after an interface been registerd.
+ * Occurs after an interface been registered.
*/
DEFINE_INTERFACE_EVENT(gb_interface_add);
--
2.48.1
The incoming message size from the device header (header.size) is
trusted without checking that it is at least the size of the message
header itself, but a value smaller than sizeof(struct gb_operation_msg_hdr)
underflows request_size in gb_operation_create_incoming(), wraps around
in gb_operation_message_alloc(), and results in a tiny buffer that is
then written past its end in gb_operation_message_init().
Reject undersized messages before parsing the message header.
Fixes: 87d208feb74f ("greybus: embed message buffer into message structure")
Reported-by: syzbot+2fd6aefc361af86911d5(a)syzkaller.appspotmail.com
Link: https://syzkaller.appspot.com/bug?extid=2fd6aefc361af86911d5
Cc: stable(a)vger.kernel.org
Assisted-by: opencode:deepseek v4 pro
Signed-off-by: Adriano Cordova <adrianox(a)gmail.com>
---
v2: point the Fixes tag at the proper commit (87d208feb74f), and add an
Assisted-by tag.
drivers/greybus/operation.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/drivers/greybus/operation.c b/drivers/greybus/operation.c
index 7e12ffb2dd..df6daee4fb 100644
--- a/drivers/greybus/operation.c
+++ b/drivers/greybus/operation.c
@@ -1047,6 +1047,14 @@ void gb_connection_recv(struct gb_connection *connection,
/* Use memcpy as data may be unaligned */
memcpy(&header, data, sizeof(header));
msg_size = le16_to_cpu(header.size);
+ if (msg_size < sizeof(header)) {
+ dev_err_ratelimited(dev,
+ "%s: malformed message 0x%04x of type 0x%02x received (%zu < %zu)\n",
+ connection->name,
+ le16_to_cpu(header.operation_id),
+ header.type, msg_size, sizeof(header));
+ return;
+ }
if (size < msg_size) {
dev_err_ratelimited(dev,
"%s: incomplete message 0x%04x of type 0x%02x received (%zu < %zu)\n",
--
2.51.0
On Fri, Sep 04, 2026 at 04:08:20PM +0800, Yang Zi wrote:
> gb_connection_recv() accepts a received message whose advertised size is
> smaller than struct gb_operation_msg_hdr. In particular, a header with a
> size of zero passes the incomplete-message check and reaches
> gb_operation_create_incoming().
>
> The subtraction used to derive the request payload size then underflows.
> When gb_operation_message_alloc() adds the header size, the result wraps
> to zero, bypassing the maximum-buffer-size check. kzalloc(0) returns
> ZERO_SIZE_PTR and gb_operation_message_init() subsequently dereferences
> it.
>
> Reject advertised sizes smaller than the message header. Also check the
> payload size before adding the header size, so that the size calculation
> cannot wrap and bypass the buffer-size limit.
>
> This issue was found using a locally modified syzkaller. The
> analysis and fix were assisted by GPT-5.6.
>
> Fixes: d90c25b0a279 ("greybus: let operation layer examine incoming data")
This one should also be backported:
Cc: stable(a)vger.kernel.org
> Assisted-by: Codex:gpt-5.6
> Signed-off-by: Yang Zi <2959243019(a)qq.com>
> ---
You should put a short change log here (after ---) when revising
patches.
No need to resend this time, but keep in mind for the future.
Reviewed-by: Johan Hovold <johan(a)kernel.org>
Johan
Hello,
I am reporting an unbounded memcpy in the Greybus CAP driver.
Product: Linux kernel
File: drivers/staging/greybus/authentication.c
Header: drivers/staging/greybus/greybus_authentication.h
include/linux/greybus/greybus_protocols.h
Tree: torvalds/linux 8ab1afb
Observed
========
cap_get_ims_certificate() and cap_authenticate() do:
*size = op->response->payload_size - sizeof(*response);
memcpy(dest, src, *size);
The response buffer is allocated with gb_operation_get_payload_size_max()
and GB_OPERATION_FLAG_SHORT_RESPONSE.
The ioctl destinations are fixed:
certificate[CAP_CERTIFICATE_MAX_SIZE] /* 1600 */
signature[CAP_SIGNATURE_MAX_SIZE] /* 320 */
There is no check that payload_size >= sizeof(*response)
and no cap to 1600 / 320.
A 2048-byte payload therefore copies:
IMS: 2048 - 1 = 2047 bytes into certificate[1600]
AUTH: 2048 - 65 = 1983 bytes into signature[320]
A payload shorter than the response header wraps the unsigned subtract and
memcpy uses a huge length.
Expected
========
Reject payload_size < sizeof(*response) (-EMSGSIZE).
Reject copy length > CAP_CERTIFICATE_MAX_SIZE /
CAP_SIGNATURE_MAX_SIZE (-E2BIG).
Reproduce (no Greybus hardware)
===============================
git clone --depth 1 https://github.com/torvalds/linux.git
# tree used: 8ab1afb
gcc -fsanitize=address -g -O0 -fno-builtin -U_FORTIFY_SOURCE \
-I gb-poc \
-I linux/drivers/staging/greybus \
-I linux/include/linux/greybus \
gb-poc/poc_cap_headers.c -o poc_cap_headers
./poc_cap_headers
./poc_cap_headers auth
ASan excerpt (IMS)
==================
CAP_CERTIFICATE_MAX_SIZE=1600 CAP_SIGNATURE_MAX_SIZE=320
[IMS] payload=2048 dest=1600 mode=ims
=================================================================
ERROR: AddressSanitizer: stack-buffer-overflow
WRITE of size 2047
#0 memcpy
#1 cap_get_ims_certificate poc_cap_headers.c:18
#2 main poc_cap_headers.c:61
Address is located in stack of thread T0
This frame has 2 object(s):
[48, 481) 'a'
[560, 2173) 'ims' <== overflows certificate[1600]
SUMMARY: AddressSanitizer: stack-buffer-overflow in memcpy
ABORTING
ASan excerpt (AUTH)
===================
CAP_CERTIFICATE_MAX_SIZE=1600 CAP_SIGNATURE_MAX_SIZE=320
[AUTH] payload=2048 dest=320
=================================================================
ERROR: AddressSanitizer: stack-buffer-overflow
WRITE of size 1983
#0 memcpy
#1 cap_authenticate poc_cap_headers.c:26
#2 main poc_cap_headers.c:54
Address is located in stack of thread T0
This frame has 2 object(s):
[48, 481) 'a' <== overflows signature[320]
[560, 2173) 'ims'
SUMMARY: AddressSanitizer: stack-buffer-overflow in memcpy
ABORTING
The PoC includes greybus_authentication.h and
greybus_protocols.h from this tree. It is not a live
CAP_IOC_* ioctl and there is no in-kernel KASAN frame.
Impact
======
Local overflow in the CAP ioctl path if a CAP connection exists and a
module answers GET_IMS_CERTIFICATE or AUTHENTICATE with an oversized or
truncated payload.
Not unauthenticated remote RCE. Same trust model as a malicious or buggy
Greybus module.
Files in the attached zip
=========================
poc_cap_headers.c
ktypes.h
asan_ims.txt
asan_auth.txt
Regards,
Suraj Theekshana
The receive callback and unbind callback now have exclusive access to
the drivers private data. Provide mutable references in callbacks to
avoid the need for locks in the private data. Remove the Sync
requirement.
Signed-off-by: Markus Probst <markus.probst(a)posteo.de>
---
This patch avoids the need for a SpinLock in the patch series
https://lore.kernel.org/rust-for-linux/20260827-gb-uart-transport-v2-7-a03b…
.
---
rust/kernel/serdev.rs | 51 ++++++++++++++++++++++----------------
samples/rust/rust_driver_serdev.rs | 2 +-
2 files changed, 31 insertions(+), 22 deletions(-)
diff --git a/rust/kernel/serdev.rs b/rust/kernel/serdev.rs
index 17ca504b7f8d..44f029ed93fd 100644
--- a/rust/kernel/serdev.rs
+++ b/rust/kernel/serdev.rs
@@ -106,7 +106,7 @@ pub struct PrivateData<'bound, T: Driver> {
/// Whether `receive_buf_callback` is allowed to call `Driver::receive`.
///
/// If locked, the receive_buf_callback will be blocked on data reception.
- /// This is the case while the driver is being probed or while [`PrivateData`] is being dropped.
+ /// This is the case while the driver is being probed or removed.
/// This is necessary, because we need to open the serdev device before the driver has been
/// probed in order to allow it to be configured, which allows `receive_buf_callback` to be
/// called. Thus we need to block data until probe completes and the driver data becomes
@@ -127,16 +127,6 @@ pub struct PrivateData<'bound, T: Driver> {
#[pinned_drop]
impl<T: Driver> PinnedDrop for PrivateData<'_, T> {
fn drop(self: Pin<&mut Self>) {
- let mut active = self.active.lock();
- if *active {
- // SAFETY:
- // - We have exclusive access to `self.driver`.
- // - `self.driver` is guaranteed to be initialized.
- unsafe { (*self.driver.get()).assume_init_drop() };
- *active = false;
- }
- drop(active);
-
// SAFETY: We have exclusive access to `self.open`.
if unsafe { *self.open.get() } {
// SAFETY: `self.sdev.as_raw()` is guaranteed to be a pointer to a valid
@@ -176,7 +166,20 @@ extern "C" fn probe_callback(sdev: *mut bindings::serdev_device) -> kernel::ffi:
let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
let private_data = ScopeGuard::new_with_data(private_data, |_| {
// SAFETY: We just set drvdata to `PrivateData<'_, T>`.
- drop(unsafe { sdev.as_ref().drvdata_obtain::<PrivateData<'_, T>>() });
+ let private_data = unsafe {
+ sdev.as_ref()
+ .drvdata_obtain::<PrivateData<'_, T>>()
+ .unwrap_unchecked()
+ };
+
+ let mut active = private_data.active.lock();
+ if *active {
+ // SAFETY:
+ // - We have exclusive access to `private_data.driver`.
+ // - `private_data.driver` is guaranteed to be initialized.
+ unsafe { (*private_data.driver.get()).assume_init_drop() };
+ *active = false;
+ }
});
let mut active = private_data.active.lock();
@@ -222,15 +225,21 @@ extern "C" fn remove_callback(sdev: *mut bindings::serdev_device) {
// and stored a `Pin<KBox<PrivateData<'_, T>>>`.
let private_data = unsafe { sdev.as_ref().drvdata_borrow::<PrivateData<'_, T>>() };
- // SAFETY: No one has exclusive access to `private_data.driver`.
- let data = unsafe { &*private_data.driver.get() };
+ let mut active = private_data.active.lock();
+
+ // SAFETY: We have exclusive access to `private_data.driver`.
+ let data = unsafe { &mut *private_data.driver.get() };
// SAFETY:
// - `private_data.driver` is pinned.
// - `remove_callback` is only ever called after a successful call to `probe_callback`,
// hence it's guaranteed that `private_data.driver` was initialized.
- let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+ let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_mut()) };
T::unbind(sdev, data_pinned);
+
+ // SAFETY: We already established that `data` is guaranteed to be initialized.
+ unsafe { data.assume_init_drop() };
+ *active = false;
}
extern "C" fn receive_buf_callback(
@@ -254,13 +263,13 @@ extern "C" fn receive_buf_callback(
return length;
}
- // SAFETY: No one has exclusive access to `private_data.driver`.
- let data = unsafe { &*private_data.driver.get() };
+ // SAFETY: We have exclusive access to `private_data.driver`.
+ let data = unsafe { &mut *private_data.driver.get() };
// SAFETY:
// - `private_data.driver` is pinned.
// - `receive_buf_callback` is only ever called after a successful call to `probe_callback`,
// hence it's guaranteed that `private_data.driver` was initialized.
- let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_ref()) };
+ let data_pinned = unsafe { Pin::new_unchecked(data.assume_init_mut()) };
// SAFETY: `buf` is guaranteed to be non-null and has the size of `length`.
let buf = unsafe { core::slice::from_raw_parts(buf, length) };
@@ -365,7 +374,7 @@ pub trait Driver {
type IdInfo: 'static;
/// The type of the driver's bus device private data.
- type Data<'bound>: Send + Sync + 'bound;
+ type Data<'bound>: Send + 'bound;
/// The table of OF device ids supported by the driver.
const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = None;
@@ -391,7 +400,7 @@ fn probe<'bound>(
/// `&Device<Core>` or `&Device<Bound>` reference. For instance.
///
/// Otherwise, release operations for driver resources should be performed in `Drop`.
- fn unbind<'bound>(sdev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<'bound>>) {
+ fn unbind<'bound>(sdev: &'bound Device<device::Core<'_>>, this: Pin<&mut Self::Data<'bound>>) {
let _ = (sdev, this);
}
@@ -402,7 +411,7 @@ fn unbind<'bound>(sdev: &'bound Device<device::Core<'_>>, this: Pin<&Self::Data<
/// Returns the number of bytes accepted.
fn receive<'bound>(
sdev: &'bound Device<device::Bound>,
- this: Pin<&Self::Data<'bound>>,
+ this: Pin<&mut Self::Data<'bound>>,
data: &[u8],
) -> usize {
let _ = (sdev, this, data);
diff --git a/samples/rust/rust_driver_serdev.rs b/samples/rust/rust_driver_serdev.rs
index 51b4898cd855..d00d547234c8 100644
--- a/samples/rust/rust_driver_serdev.rs
+++ b/samples/rust/rust_driver_serdev.rs
@@ -63,7 +63,7 @@ fn probe<'bound>(
fn receive<'bound>(
sdev: &'bound serdev::Device<Bound>,
- _this: Pin<&Self>,
+ _this: Pin<&mut Self>,
data: &[u8],
) -> usize {
sdev.write(data).unwrap_or_default() as usize
---
base-commit: e5e04726cdd043e309677071ab1b65a4b18f422b
change-id: 20260903-rust_serdev_ref_mut-4d2285776ae1