Linux cryptographic layer development
 help / color / mirror / Atom feed
* [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers
@ 2026-12-04 10:30 Ayush Singh
  2026-12-04 10:30 ` [PATCH v6 1/9] greybus: operation: keep request active across message_send Ayush Singh
                   ` (8 more replies)
  0 siblings, 9 replies; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh, Conor Dooley

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. As mentioned by Miguel Ojeda
  [3], this is upto greybus maintainers. So waiting on their inputs. I
  am available to be maintainer for the Rust abstractions for greybus
  if required.

[0]: https://github.com/beagleboard/greybus-zephyr
[1]: https://lore.kernel.org/all/20260622-nova-exports-v5-0-6191773fc977@nvidia.com/
[2]: https://lore.kernel.org/all/ecca8eb2-8e5a-4770-bcf6-3fb49773088b@beagleboard.org/
[3]: https://lore.kernel.org/all/CANiq72mA6pTmPJUk8g7y3Z=wetFMXdzHLiPEPChpY4OTg3OHiw@mail.gmail.com/

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
Changes in v6:
- Rework patch 1 from last series. Now updating the active count in a
  single lock.
- Fix sashiko-bot flagged problems.
- Handle case when responses to SVC arrive with a non-success code.
- Link to v5: https://lore.kernel.org/r/20261103-gb-uart-transport-v5-0-f8e326d6561f@beagleboard.org

Changes in v5:
- Remove AlwaysRefCounted impl from Interface. No longer required.
- Fix invalid comments.
- Fix interface drop in spinlock.
- Impl AlwaysRefCounted for hd::Device only in normal context.
- Match the bus device struct defination in device.rs docs.
- Return GB_OP_PROTOCOL_BAD instead of ENOTSUP when encountering an
  unknown message.
- Fix possible race condition in SVC module removed. Flagged by
  sashiko-bot. Involved, ensuring that operation_cancel cannot drop an
  in-flight message.
- Fix timer leak in a greybus operation.
- Check write_all return.
- Return E2BIG when frame lenght is exceeded in uart node driver.
- Link to v4: https://lore.kernel.org/r/20261021-gb-uart-transport-v4-0-c308ce821d45@beagleboard.org

Changes in v4:
- Remove gb_uard_node::GbUartNode::unbind. Suggested by Markus Probst,
  since write is still valid after unbind.
- Add inline attribute where suggested.
- Remove patch 1. No longer required with modifications to the old patch
  2.
- Increse hdlc max buffer size to 512 bytes.
- Send module_removed request before removing from map.
- Also do not hold lock across interface drop.
- Link to v3: https://lore.kernel.org/r/20261013-gb-uart-transport-v3-0-81d0a8a1acf7@beagleboard.org

Changes in v3:
- Fix incorrect email in MAINTAINERS.
- Make CONFIG_RUST_GREYBUS_ABSTRACTIONS depend on sysfs like
  CONFIG_GREYBUS.
- Fix cleanup in hd::Registration::new in case of errors.
- Fix comments.
- Fix Msg AsBytes impl as suggested by sashiko-bot.
- Use SpinLock for intf_map. This should be fine since we need locking
  only for getting the interface. We do not hold locks across operations.
- Properly drop message in case of buffer overflow in gb_uart_node.
- Link to v2: https://lore.kernel.org/r/20260827-gb-uart-transport-v2-0-a03bb1f5fbd1@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@beagleboard.org

---
Ayush Singh (9):
      greybus: operation: keep request active across message_send
      greybus: operation: arm request timeout before sending
      greybus: svc: add gb_svc_flush()
      greybus: connection: Add greybus_data_rcvd_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       |  62 +++
 MAINTAINERS                                        |  15 +
 drivers/greybus/.gitignore                         |   1 +
 drivers/greybus/Kconfig                            |  35 ++
 drivers/greybus/Makefile                           |  50 ++
 drivers/greybus/connection.c                       |  47 ++
 drivers/greybus/gb_softsvc.rs                      | 570 +++++++++++++++++++++
 drivers/greybus/gb_softsvc_exports.c               |  15 +
 drivers/greybus/gb_uart_node.rs                    | 270 ++++++++++
 drivers/greybus/operation.c                        |  74 ++-
 drivers/greybus/svc.c                              |  14 +
 include/linux/greybus/connection.h                 |   2 +
 include/linux/greybus/svc.h                        |   1 +
 lib/crc/Kconfig                                    |   7 +
 rust/bindings/bindings_helper.h                    |   2 +
 rust/kernel/alloc.rs                               |   6 +
 rust/kernel/crc_ccitt.rs                           |  26 +
 rust/kernel/greybus/hd.rs                          | 391 ++++++++++++++
 rust/kernel/greybus/mod.rs                         | 200 ++++++++
 rust/kernel/greybus/protocols.rs                   | 454 ++++++++++++++++
 rust/kernel/lib.rs                                 |   4 +
 21 files changed, 2224 insertions(+), 22 deletions(-)
---
base-commit: d138596e9f822033490b2e577ec2ea64f2aa246c
change-id: 20260810-gb-uart-transport-9255d6557c4c

Best regards,
-- 
Ayush Singh <ayush@beagleboard.org>


^ permalink raw reply	[flat|nested] 18+ messages in thread

* [PATCH v6 1/9] greybus: operation: keep request active across message_send
  2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
@ 2026-12-04 10:30 ` 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
                   ` (7 subsequent siblings)
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

gb_operation_request_send() takes a single active count, and completion
drops it. This would be fine normally, but in case of cancellation (in
gb_softsvc context, this would happen in module_removed), completion
(gb_operation_work), can drop the active count, while message_send is
running.
The core does call message_cancel before dropping the active count,
but in most normal circumstances, cancelling an operation that is
already writing over a protocol (UART) is not really possible. So we
are only left with making the core wait for the said write to complete
instead of making active count 0 while message_send is in progress.
The patch takes a second reference and active count before the send
and drop them once it returns. If the connection starts tearing down
between the two calls, return 0 and let the cancel complete the
operation.
Since it took at least me a while to truely understand what the initial
sashiko-bot report meant, here is an example:
       Thread A                     Thread B + worker                  active
       ------------------------     ------------------------------     ------
  1    get_active()                                                      1
  2    gb_message_send()
  3      GbNode::write() ...
  4      ... blocked                state = DISCONNECTING
  5      ... blocked                gb_operation_cancel()
  6      ... blocked                  result_set(-ESHUTDOWN)
  7      ... blocked                  queue_work(completion)
  8      ... blocked                  wait_event(!active)  [sleeps]
  9      ... blocked                [worker] gb_operation_work()
 10      ... blocked                [worker]   put_active()   [:292]     0
 11      ... blocked                  wait_event wakes, returns       <- too early
 12      ... blocked                gb_module_del() returns
 13      ... blocked                [softsvc] Module::drop finishes
 14      ... blocked                serdev port closed, unbind done   <- bad
 15      write() returns
 16    return to caller

This patch simply takes an extra active count when calling
gb_message_send. in core. It also treats both requests and response
the same, i.e. clear an active count when gb_message_sent() is
called. Earlier, this was only being done for responses.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 drivers/greybus/operation.c | 61 ++++++++++++++++++++++++++++++++-------------
 1 file changed, 43 insertions(+), 18 deletions(-)

diff --git a/drivers/greybus/operation.c b/drivers/greybus/operation.c
index 7e12ffb2dd60..a9eada39ec79 100644
--- a/drivers/greybus/operation.c
+++ b/drivers/greybus/operation.c
@@ -37,42 +37,55 @@ static int gb_operation_response_send(struct gb_operation *operation,
  * Increment operation active count and add to connection list unless the
  * connection is going away.
  *
- * Caller holds operation reference.
+ * Caller holds operation reference and connection->lock
  */
-static int gb_operation_get_active(struct gb_operation *operation)
+static int __gb_operation_get_active(struct gb_operation *operation, int count)
+	__must_hold(&operation->connection->lock)
 {
 	struct gb_connection *connection = operation->connection;
-	unsigned long flags;
 
-	spin_lock_irqsave(&connection->lock, flags);
 	switch (connection->state) {
 	case GB_CONNECTION_STATE_ENABLED:
 		break;
 	case GB_CONNECTION_STATE_ENABLED_TX:
 		if (gb_operation_is_incoming(operation))
-			goto err_unlock;
+			return -ENOTCONN;
 		break;
 	case GB_CONNECTION_STATE_DISCONNECTING:
 		if (!gb_operation_is_core(operation))
-			goto err_unlock;
+			return -ENOTCONN;
 		break;
 	default:
-		goto err_unlock;
+		return -ENOTCONN;
 	}
 
-	if (operation->active++ == 0)
+	if (operation->active == 0)
 		list_add_tail(&operation->links, &connection->operations);
 
-	trace_gb_operation_get_active(operation);
+	operation->active += count;
 
-	spin_unlock_irqrestore(&connection->lock, flags);
+	trace_gb_operation_get_active(operation);
 
 	return 0;
+}
+
+/*
+ * Increment operation active count and add to connection list unless the
+ * connection is going away.
+ *
+ * Caller holds operation reference.
+ */
+static int gb_operation_get_active(struct gb_operation *operation)
+{
+	struct gb_connection *connection = operation->connection;
+	unsigned long flags;
+	int ret;
 
-err_unlock:
+	spin_lock_irqsave(&connection->lock, flags);
+	ret = __gb_operation_get_active(operation, 1);
 	spin_unlock_irqrestore(&connection->lock, flags);
 
-	return -ENOTCONN;
+	return ret;
 }
 
 /* Caller holds operation reference. */
@@ -726,6 +739,7 @@ int gb_operation_request_send(struct gb_operation *operation,
 	struct gb_connection *connection = operation->connection;
 	struct gb_operation_msg_hdr *header;
 	unsigned int cycle;
+	unsigned long flags;
 	int ret;
 
 	if (gb_connection_is_offloaded(connection))
@@ -758,11 +772,17 @@ int gb_operation_request_send(struct gb_operation *operation,
 	gb_operation_result_set(operation, -EINPROGRESS);
 
 	/*
-	 * Get an extra reference on the operation. It'll be dropped when the
-	 * operation completes.
+	 * Take two references and active counts. One is dropped when the
+	 * operation completes, the other when the host driver is done with the
+	 * request, so that cancelling the operation waits for both. Take both
+	 * counts under one lock, so the operation can't be cancelled in between.
 	 */
 	gb_operation_get(operation);
-	ret = gb_operation_get_active(operation);
+	gb_operation_get(operation);
+
+	spin_lock_irqsave(&connection->lock, flags);
+	ret = __gb_operation_get_active(operation, 2);
+	spin_unlock_irqrestore(&connection->lock, flags);
 	if (ret)
 		goto err_put;
 
@@ -779,8 +799,10 @@ int gb_operation_request_send(struct gb_operation *operation,
 
 err_put_active:
 	gb_operation_put_active(operation);
+	gb_operation_put_active(operation);
 err_put:
 	gb_operation_put(operation);
+	gb_operation_put(operation);
 
 	return ret;
 }
@@ -880,6 +902,9 @@ void greybus_message_sent(struct gb_host_device *hd,
 	 * reference to the operation.  If an error occurred, report
 	 * it.
 	 *
+	 * The host driver is done with the message, so drop the reference and
+	 * active count taken when it was sent. If a response failed, report it.
+	 *
 	 * For requests, if there's no error and the operation in not
 	 * unidirectional, there's nothing more to do until the response
 	 * arrives. If an error occurred attempting to send it, or if the
@@ -892,15 +917,15 @@ void greybus_message_sent(struct gb_host_device *hd,
 				"%s: error sending response 0x%02x: %d\n",
 				connection->name, operation->type, status);
 		}
-
-		gb_operation_put_active(operation);
-		gb_operation_put(operation);
 	} else if (status || gb_operation_is_unidirectional(operation)) {
 		if (gb_operation_result_set(operation, status)) {
 			queue_work(gb_operation_completion_wq,
 				   &operation->work);
 		}
 	}
+
+	gb_operation_put_active(operation);
+	gb_operation_put(operation);
 }
 EXPORT_SYMBOL_GPL(greybus_message_sent);
 

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 2/9] greybus: operation: arm request timeout before sending
  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:30 ` 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
                   ` (6 subsequent siblings)
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

The host driver can complete a request before add_timer is called. The
main case for this is softsvc, although, depending on which transport
is used, there is a possibility that response arrives much faster than
expected.

By populating timer earilier, we prevent the starting a timer on
already completed request (which would then leak an active timer on cleanup).

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 drivers/greybus/operation.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)

diff --git a/drivers/greybus/operation.c b/drivers/greybus/operation.c
index a9eada39ec79..cac3b0abf62b 100644
--- a/drivers/greybus/operation.c
+++ b/drivers/greybus/operation.c
@@ -786,18 +786,23 @@ int gb_operation_request_send(struct gb_operation *operation,
 	if (ret)
 		goto err_put;
 
-	ret = gb_message_send(operation->request, gfp);
-	if (ret)
-		goto err_put_active;
-
+	/*
+	 * Arm the timeout before sending: the response can arrive, and the
+	 * operation complete, before the host driver returns.
+	 */
 	if (timeout) {
 		operation->timer.expires = jiffies + msecs_to_jiffies(timeout);
 		add_timer(&operation->timer);
 	}
 
+	ret = gb_message_send(operation->request, gfp);
+	if (ret)
+		goto err_put_active;
+
 	return 0;
 
 err_put_active:
+	timer_delete_sync(&operation->timer);
 	gb_operation_put_active(operation);
 	gb_operation_put_active(operation);
 err_put:

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 3/9] greybus: svc: add gb_svc_flush()
  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:30 ` [PATCH v6 2/9] greybus: operation: arm request timeout before sending Ayush Singh
@ 2026-12-04 10:30 ` 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
                   ` (5 subsequent siblings)
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

A host driver that is its own SVC, such as a software SVC, injects
requests like MODULE_REMOVED through greybus_data_rcvd(). The core acts
on them asynchronously: the request handler runs on the connection
workqueue and queues the actual work on svc->wq. The response is sent
before that work runs, so it cannot tell the driver that the module is
gone.

Add gb_svc_flush() to wait until every request received so far has been
fully processed. It flushes the connection workqueue, then svc->wq.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 drivers/greybus/svc.c       | 14 ++++++++++++++
 include/linux/greybus/svc.h |  1 +
 2 files changed, 15 insertions(+)

diff --git a/drivers/greybus/svc.c b/drivers/greybus/svc.c
index 490577731a19..788d95b4b87b 100644
--- a/drivers/greybus/svc.c
+++ b/drivers/greybus/svc.c
@@ -1381,6 +1381,20 @@ static void gb_svc_remove_modules(struct gb_svc *svc)
 	}
 }
 
+/**
+ * gb_svc_flush - wait for received SVC requests to be processed
+ * @svc: the SVC
+ *
+ * Requests pass through the connection workqueue on their way to svc->wq, so
+ * both have to be flushed, in this order.
+ */
+void gb_svc_flush(struct gb_svc *svc)
+{
+	flush_workqueue(svc->connection->wq);
+	flush_workqueue(svc->wq);
+}
+EXPORT_SYMBOL_GPL(gb_svc_flush);
+
 void gb_svc_del(struct gb_svc *svc)
 {
 	gb_connection_disable_rx(svc->connection);
diff --git a/include/linux/greybus/svc.h b/include/linux/greybus/svc.h
index da547fb9071b..ced5fc3a9c6b 100644
--- a/include/linux/greybus/svc.h
+++ b/include/linux/greybus/svc.h
@@ -63,6 +63,7 @@ struct gb_svc *gb_svc_create(struct gb_host_device *hd);
 int gb_svc_add(struct gb_svc *svc);
 void gb_svc_del(struct gb_svc *svc);
 void gb_svc_put(struct gb_svc *svc);
+void gb_svc_flush(struct gb_svc *svc);
 
 int gb_svc_pwrmon_intf_sample_get(struct gb_svc *svc, u8 intf_id,
 				  u8 measurement_type, u32 *value);

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 4/9] greybus: connection: Add greybus_data_rcvd_by_intf()
  2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
                   ` (2 preceding siblings ...)
  2026-12-04 10:30 ` [PATCH v6 3/9] greybus: svc: add gb_svc_flush() Ayush Singh
@ 2026-12-04 10:30 ` 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
                   ` (4 subsequent siblings)
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

greybus_data_rcvd() finds the receiving connection by its host-side
CPort id. A host driver such as a software SVC sees only the remote end
of a connection, the interface id and the interface CPort id, and cannot
deliver data that way.

Add greybus_data_rcvd_by_intf(), which looks the connection up by
interface id and interface CPort id and passes the data to it.
It returns -EINVAL if no such connection exists. The first user is the
gb-softsvc driver, added later in this series.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 drivers/greybus/connection.c       | 47 ++++++++++++++++++++++++++++++++++++++
 include/linux/greybus/connection.h |  2 ++
 2 files changed, 49 insertions(+)

diff --git a/drivers/greybus/connection.c b/drivers/greybus/connection.c
index bd04485decb3..ce8646299ce8 100644
--- a/drivers/greybus/connection.c
+++ b/drivers/greybus/connection.c
@@ -69,6 +69,32 @@ gb_connection_hd_find(struct gb_host_device *hd, u16 cport_id)
 	return connection;
 }
 
+/*
+ * Returns a reference-counted pointer to the connection if found.
+ */
+static struct gb_connection *
+gb_connection_hd_find_by_intf(struct gb_host_device *hd, u8 intf_id,
+			      u16 intf_cport)
+{
+	struct gb_connection *connection;
+	unsigned long flags;
+
+	spin_lock_irqsave(&gb_connections_lock, flags);
+	list_for_each_entry(connection, &hd->connections, hd_links) {
+		if (connection->intf &&
+		    connection->intf->interface_id == intf_id &&
+		    connection->intf_cport_id == intf_cport) {
+			gb_connection_get(connection);
+			goto found;
+		}
+	}
+	connection = NULL;
+found:
+	spin_unlock_irqrestore(&gb_connections_lock, flags);
+
+	return connection;
+}
+
 /*
  * Callback from the host driver to let us know that data has been
  * received on the bundle.
@@ -91,6 +117,27 @@ void greybus_data_rcvd(struct gb_host_device *hd, u16 cport_id,
 }
 EXPORT_SYMBOL_GPL(greybus_data_rcvd);
 
+/*
+ * Callback from a host driver that only knows the remote end of a connection
+ * (interface id and interface CPort id), such as a software SVC.
+ */
+int greybus_data_rcvd_by_intf(struct gb_host_device *hd, u8 intf_id,
+			      u16 intf_cport, u8 *data, size_t length)
+{
+	struct gb_connection *connection;
+
+	trace_gb_hd_in(hd);
+
+	connection = gb_connection_hd_find_by_intf(hd, intf_id, intf_cport);
+	if (!connection)
+		return -EINVAL;
+	gb_connection_recv(connection, data, length);
+	gb_connection_put(connection);
+
+	return 0;
+}
+EXPORT_SYMBOL_GPL(greybus_data_rcvd_by_intf);
+
 static void gb_connection_kref_release(struct kref *kref)
 {
 	struct gb_connection *connection;
diff --git a/include/linux/greybus/connection.h b/include/linux/greybus/connection.h
index d59b7fc1de3e..e8be67a936a6 100644
--- a/include/linux/greybus/connection.h
+++ b/include/linux/greybus/connection.h
@@ -92,6 +92,8 @@ void gb_connection_mode_switch_complete(struct gb_connection *connection);
 
 void greybus_data_rcvd(struct gb_host_device *hd, u16 cport_id,
 		       u8 *data, size_t length);
+int greybus_data_rcvd_by_intf(struct gb_host_device *hd, u8 intf_id,
+			      u16 intf_cport, u8 *data, size_t length);
 
 void gb_connection_latency_tag_enable(struct gb_connection *connection);
 void gb_connection_latency_tag_disable(struct gb_connection *connection);

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 5/9] rust: crc_ccitt: add CRC-CCITT abstraction
  2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
                   ` (3 preceding siblings ...)
  2026-12-04 10:30 ` [PATCH v6 4/9] greybus: connection: Add greybus_data_rcvd_by_intf() Ayush Singh
@ 2026-12-04 10:30 ` Ayush Singh
  2026-12-04 10:30 ` [PATCH v6 6/9] rust: kernel: Add greybus abstractions Ayush Singh
                   ` (3 subsequent siblings)
  8 siblings, 0 replies; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

The module is gated behind the new RUST_CRC_CCITT_ABSTRACTIONS Kconfig
symbol, which selects CRC_CCITT, so the C library is only built when a
Rust user actually needs it.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 MAINTAINERS                     |  1 +
 lib/crc/Kconfig                 |  7 +++++++
 rust/bindings/bindings_helper.h |  1 +
 rust/kernel/crc_ccitt.rs        | 26 ++++++++++++++++++++++++++
 rust/kernel/lib.rs              |  2 ++
 5 files changed, 37 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 857ad039c997..f6d0a4fecc41 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -7210,6 +7210,7 @@ T:	git https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/linux.git crc-ne
 F:	Documentation/staging/crc*
 F:	include/linux/crc*
 F:	lib/crc/
+F:	rust/kernel/crc*
 F:	scripts/gen-crc-consts.py
 
 CREATIVE SB0540
diff --git a/lib/crc/Kconfig b/lib/crc/Kconfig
index 927fc6a6b2b9..628da2d30fc8 100644
--- a/lib/crc/Kconfig
+++ b/lib/crc/Kconfig
@@ -32,6 +32,13 @@ config CRC_CCITT
 	  The CRC-CCITT library functions.  Select this if your module uses any
 	  of the functions from <linux/crc-ccitt.h>.
 
+config RUST_CRC_CCITT_ABSTRACTIONS
+	bool
+	depends on RUST
+	select CRC_CCITT
+	help
+	  This enables the Rust abstraction for the CRC-CCITT API.
+
 config CRC_ITU_T
 	tristate
 	help
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index cc41dc946757..f2206f6e1833 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -49,6 +49,7 @@
 #include <linux/cpu.h>
 #include <linux/cpufreq.h>
 #include <linux/cpumask.h>
+#include <linux/crc-ccitt.h>
 #include <linux/cred.h>
 #include <linux/debugfs.h>
 #include <linux/device/faux.h>
diff --git a/rust/kernel/crc_ccitt.rs b/rust/kernel/crc_ccitt.rs
new file mode 100644
index 000000000000..6042ada16967
--- /dev/null
+++ b/rust/kernel/crc_ccitt.rs
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! CRC-CCITT computation.
+//!
+//! C header: [`include/linux/crc-ccitt.h`](srctree/include/linux/crc-ccitt.h)
+
+/// Computes the CRC-CCITT of `data`, starting from the seed value `crc`.
+///
+/// Pass the result back in as `crc` to compute the checksum of a buffer
+/// incrementally.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::crc_ccitt::crc_ccitt;
+///
+/// let one_shot = crc_ccitt(0xffff, b"hello world");
+/// let split = crc_ccitt(crc_ccitt(0xffff, b"hello "), b"world");
+/// assert_eq!(one_shot, split);
+/// ```
+#[inline]
+pub fn crc_ccitt(crc: u16, data: &[u8]) -> u16 {
+    // SAFETY: `data.as_ptr()` is valid for reads of `data.len()` bytes for the
+    // duration of the call, since it is derived from a live shared slice.
+    unsafe { bindings::crc_ccitt(crc, data.as_ptr(), data.len()) }
+}
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index db238655c700..5aa46a1982df 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -64,6 +64,8 @@
 #[cfg(CONFIG_CPU_FREQ)]
 pub mod cpufreq;
 pub mod cpumask;
+#[cfg(CONFIG_RUST_CRC_CCITT_ABSTRACTIONS)]
+pub mod crc_ccitt;
 pub mod cred;
 pub mod debugfs;
 pub mod device;

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 6/9] rust: kernel: Add greybus abstractions
  2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
                   ` (4 preceding siblings ...)
  2026-12-04 10:30 ` [PATCH v6 5/9] rust: crc_ccitt: add CRC-CCITT abstraction Ayush Singh
@ 2026-12-04 10:30 ` 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
                   ` (2 subsequent siblings)
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

Add Rust abstractions for the Greybus core, enough to implement a
Greybus host driver in Rust.

The abstractions are split into 3 modules:

- Top level mod.rs: Basic abstractions greybus structures.
- hd.rs: Greybus Host Device specific abstractions.
- protocols.rs: Abstractions for greybus_protocols.h, i.e. greybus
  protocol types and constants.

Only the APIs used by gb-softsvc and gb-uart-node driver are covered.
As such, protocols.rs also only contains abstractions for greybus
structures that are used by SVC and some types such as Greybus Interface
do not implement AlwaysRefCounted at the moment.

HdDriver Note
**************

- In C message_send callback, it is possible for the caller to defer
  calling gb_message_sent. This is used in es2 driver. However, looking at
  the internals, it does not seem like the message owenership is actually
  transferred to the caller in real terms. Instead, it is more like the
  caller is shared ownership. This is evident by the fact that
  message_cancel can be called at any point, and depending on wheather the
  message is request or response, the message can become invalid after the
  message_cancel callback. Thus the driver is expected to ensure that no
  dangling references to that message exist.

  Since gb_message is not an internally ref counted structure in true
  terms (it does seem to use the ref counting in the internal operation),
  and since double calls to gb_message_sent are not really allowed, I have
  made the decision to call gb_message_sent on a message in the
  abstractions rather than making the driver call it. This means the
  driver only gets a reference to the message, and never owns it. This
  does prevent a driver to use it in the way es2 currently does, but seems
  much less of a footgun.

  Another possibility would be to implement AlwaysRefCounted on Message
  and pass the calls to gb_operation_get/put, but I have not gone through
  the internals enough to figure out if this is correct in all cases.

- At the moment, nothing in-tree calls message_send from an atomic
  context. However, since it does have gfp_mask in param, and an
  exported function, it is possible to call it from atomic context. So
  not sure if the doc comment should specific non-sleep requirement.

- message_cancel does not directly provide access to driver data. This
  was flagged by sashiko-bot. It actually is possible for the Rust
  abstractions to provide the driver data though. This is because we can
  do gb_message->operation->connection->host_device->priv_data. However,
  not sure if we should do this just in Rust abstractions. Maybe it
  would be preferable to change the C API itself instead.

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 MAINTAINERS                      |   1 +
 drivers/greybus/Kconfig          |   8 +
 rust/bindings/bindings_helper.h  |   1 +
 rust/kernel/alloc.rs             |   6 +
 rust/kernel/greybus/hd.rs        | 391 +++++++++++++++++++++++++++++++++
 rust/kernel/greybus/mod.rs       | 200 +++++++++++++++++
 rust/kernel/greybus/protocols.rs | 454 +++++++++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs               |   2 +
 8 files changed, 1063 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index f6d0a4fecc41..6791104ed3ee 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -11700,6 +11700,7 @@ F:	drivers/greybus/
 F:	drivers/staging/greybus/
 F:	include/linux/greybus.h
 F:	include/linux/greybus/
+F:	rust/kernel/greybus/
 
 GREYBUS UART PROTOCOLS DRIVERS
 M:	David Lin <dtwlin@gmail.com>
diff --git a/drivers/greybus/Kconfig b/drivers/greybus/Kconfig
index c3f056d28b01..d9f52024d1c2 100644
--- a/drivers/greybus/Kconfig
+++ b/drivers/greybus/Kconfig
@@ -15,6 +15,14 @@ menuconfig GREYBUS
 	  To compile this code as a module, choose M here: the module
 	  will be called greybus.ko
 
+config RUST_GREYBUS_ABSTRACTIONS
+	bool "Rust greybus abstractions"
+	depends on RUST
+	depends on SYSFS
+	select GREYBUS
+	help
+	  This enables the Rust abstraction for the Greybus API.
+
 if GREYBUS
 
 config GREYBUS_BEAGLEPLAY
diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index f2206f6e1833..14029d2fb44d 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -64,6 +64,7 @@
 #include <linux/firmware.h>
 #include <linux/fwctl.h>
 #include <linux/fs.h>
+#include <linux/greybus.h>
 #include <linux/i2c.h>
 #include <linux/interrupt.h>
 #include <linux/io-pgtable.h>
diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs
index 6cd29ca35244..e38bfe6e8572 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
diff --git a/rust/kernel/greybus/hd.rs b/rust/kernel/greybus/hd.rs
new file mode 100644
index 000000000000..24913c054f6a
--- /dev/null
+++ b/rust/kernel/greybus/hd.rs
@@ -0,0 +1,391 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Greybus host device abstractions.
+//!
+//! A driver implements the transmit path through [`HdDriver`] and feeds received data back into
+//! the core with [`Device::data_rcvd`].
+//!
+//! A host device is created, populated with driver private data and added to the Greybus bus by
+//! constructing a [`Registration`], which owns the underlying `struct gb_host_device`. Dropping
+//! the registration drops the private data and removes the device from the bus, so it is normally
+//! stored in the driver data of the parent device and torn down implicitly when that device goes
+//! away.
+//!
+//! Individual references to a live host device are represented by
+//! [`ARef<Device>`](crate::sync::aref::ARef), which keeps the embedded `struct device` reference
+//! count balanced.
+//!
+//! C header: [`include/linux/greybus/hd.h`](srctree/include/linux/greybus/hd.h)
+//!
+//! # Examples
+//!
+//! ```ignore
+//! use kernel::{
+//!     alloc::Flags,
+//!     device,
+//!     greybus::{
+//!         hd::{
+//!             Device,
+//!             HdDriver,
+//!             Registration, //
+//!         },
+//!         Message, //
+//!     },
+//!     prelude::*, //
+//! };
+//!
+//! struct MyHd {
+//!     // transport state
+//! }
+//!
+//! #[vtable]
+//! impl HdDriver for MyHd {
+//!     fn message_send(
+//!         data: &Self,
+//!         hd: &Device,
+//!         dest_cport_id: u16,
+//!         msg: &Message,
+//!         gfp_mask: Flags,
+//!     ) -> Result {
+//!         // Copy what is needed out of `msg` and queue it, allocating with `gfp_mask`.
+//!         // Returning `Ok(())` reports the message as sent to the core.
+//!         Ok(())
+//!     }
+//!
+//!     fn message_cancel(_msg: &Message) {}
+//! }
+//!
+//! fn probe(parent: &device::Device) -> Result<Registration<MyHd>> {
+//!     Registration::new(parent, BUFFER_SIZE_MAX, NUM_CPORTS, try_pin_init!(MyHd {}))
+//! }
+//! ```
+
+use core::{
+    marker::PhantomData,
+    ptr::{
+        addr_of_mut,
+        NonNull, //
+    },
+};
+
+use crate::{
+    alloc::Flags,
+    device,
+    error::{
+        code,
+        from_err_ptr,
+        to_result, //
+    },
+    greybus::Message,
+    prelude::*,
+    sync::aref::AlwaysRefCounted,
+    types::Opaque,
+};
+
+/// The set of callbacks a Greybus host driver can provide.
+#[vtable]
+pub trait HdDriver: Send + Sync + Sized + 'static {
+    /// 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;
+
+    /// Aborts the transmission of a message previously handed to [`HdDriver::message_send`].
+    ///
+    /// Always called in process context.
+    fn message_cancel(msg: &Message);
+}
+
+/// Builds the C callback table for a [`HdDriver`] implementation.
+struct HdDriverVTable<T: HdDriver>(PhantomData<T>);
+
+impl<T: HdDriver> HdDriverVTable<T> {
+    const DRIVER: bindings::gb_hd_driver = bindings::gb_hd_driver {
+        // Both are mandatory, hence no `HAS_*` check. See [`HdDriver`].
+        message_send: Some(Self::message_send),
+        message_cancel: Some(Self::message_cancel),
+        // Every other callback is left `NULL`, which the Greybus core takes as "use the default
+        // behaviour".
+        ..pin_init::zeroed()
+    };
+
+    const fn build() -> &'static bindings::gb_hd_driver {
+        &Self::DRIVER
+    }
+
+    /// # Safety
+    ///
+    /// `hd` must point at a registered host device whose private area holds a pointer to a live
+    /// `T`, and `msg` must point at a valid message.
+    unsafe extern "C" fn message_send(
+        hd: *mut bindings::gb_host_device,
+        dest_cport_id: u16,
+        msg: *mut bindings::gb_message,
+        gfp_mask: bindings::gfp_t,
+    ) -> c_int {
+        // SAFETY: `gb_host_device` and `Device` have the same layout.
+        let hd = unsafe { Device::<device::CoreInternal<'_>>::from_raw(hd) };
+        // SAFETY: `message_send` is only ever called after a successful call to
+        // `gb_hd_add`, hence it's guaranteed that `Device::set_drvdata()` has been called
+        // and stored a `Pin<KBox<T>>`.
+        let data = unsafe { hd.as_ref().drvdata_borrow() };
+        // SAFETY: The caller guarantees `msg` is valid for the duration of this call.
+        let msg = unsafe { Message::from_raw(msg) };
+
+        // SAFETY: The caller guarantees `hd` is a registered host device, alive for the duration
+        // of this call.
+        let hd_normal = unsafe { Device::<device::Normal>::from_raw(hd.as_raw()) };
+
+        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(),
+        }
+    }
+
+    /// # Safety
+    ///
+    /// `msg` must point at a valid message of a registered host device of this driver.
+    unsafe extern "C" fn message_cancel(msg: *mut bindings::gb_message) {
+        // SAFETY: The caller guarantees `msg` is valid for the duration of this call.
+        let msg = unsafe { Message::from_raw(msg) };
+        T::message_cancel(msg);
+    }
+}
+
+/// A Greybus host device.
+///
+/// # Invariants
+///
+/// The wrapped value is a valid `struct gb_host_device` created by `gb_hd_create()`, and every
+/// [`ARef<Device>`](crate::sync::aref::ARef) owns an increment on its reference count.
+#[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 });
+kernel::impl_device_context_into_aref!(Device);
+
+// SAFETY: The embedded `struct device` carries the reference count, and `gb_hd_put()` is just
+// `put_device()` on it, so the object stays alive for as long as increments are outstanding.
+unsafe impl AlwaysRefCounted for Device {
+    #[inline]
+    fn inc_ref(&self) {
+        // SAFETY: By the type invariant there is a live reference to the host device, and `dev` is
+        // its embedded `struct device`.
+        unsafe { bindings::get_device(&raw mut (*self.0.get()).dev) };
+    }
+
+    #[inline]
+    unsafe fn dec_ref(obj: NonNull<Self>) {
+        // SAFETY: The caller guarantees it owns an increment on the reference count.
+        unsafe { bindings::gb_hd_put(obj.as_ptr().cast()) }
+    }
+}
+
+impl<Ctx> Device<Ctx> {
+    /// # Safety
+    ///
+    /// `ptr` must be a valid pointer to a `struct gb_host_device`.
+    #[inline]
+    pub(crate) const unsafe fn from_raw<'a>(ptr: *mut bindings::gb_host_device) -> &'a Self {
+        // SAFETY: `Device` is a transparent wrapper of `Opaque<bindings::gb_host_device>`.
+        unsafe { &*ptr.cast() }
+    }
+
+    #[inline]
+    pub(crate) fn as_raw(&self) -> *mut bindings::gb_host_device {
+        self.0.get()
+    }
+
+    /// 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(),
+            )
+        })
+    }
+
+    /// Waits until the SVC has processed every request handed to [`Device::data_rcvd`] so far.
+    ///
+    /// This may sleep.
+    #[inline]
+    pub fn svc_flush(&self) {
+        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
+        // `struct gb_host_device`. Its SVC is created with it and only freed when it is released,
+        // so `svc` is valid for as long as `self` is.
+        unsafe { bindings::gb_svc_flush((*self.as_raw()).svc) }
+    }
+}
+
+impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {
+    #[inline]
+    fn as_ref(&self) -> &device::Device<Ctx> {
+        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
+        // `struct gb_host_device`. `dev` points to a valid `struct device`.
+        unsafe { device::Device::from_raw(addr_of_mut!((*self.as_raw()).dev)) }
+    }
+}
+
+/// A host device owned by its driver, together with the driver's private data `T`.
+///
+/// Created and added to the Greybus bus on construction, removed on drop.
+///
+/// # Invariants
+///
+/// `ptr` points at a valid `struct gb_host_device` obtained from `gb_hd_create()`, whose driver
+/// data holds a live `T`
+#[repr(transparent)]
+pub struct Registration<T> {
+    ptr: NonNull<bindings::gb_host_device>,
+    _data: PhantomData<T>,
+}
+
+impl<T: HdDriver> Registration<T> {
+    /// Creates a host device under `parent` and adds it to the Greybus bus.
+    ///
+    /// `buffer_size_max` is the largest message the transport can carry in one go, header
+    /// included. `num_cports` is the number of cports that the greybus host device can connect to.
+    ///
+    /// `data` is initialised in place before the device is added, so callbacks may run against it
+    /// from the moment `gb_hd_add()` succeeds.
+    pub fn new(
+        parent: &device::Device,
+        buffer_size_max: usize,
+        num_cports: usize,
+        data: impl PinInit<T, Error>,
+    ) -> Result<Self> {
+        // 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,
+            )
+        })?;
+
+        // SAFETY: `hd` is a valid pointer to `gb_host_device`.
+        let hd_dev: &Device<device::CoreInternal<'_>> = unsafe { Device::from_raw(hd) };
+        if let Err(e) = hd_dev.as_ref().set_drvdata(data) {
+            // SAFETY: `hd` is a pointer to a valid `struct gb_host_device`.
+            unsafe { bindings::gb_hd_put(hd) };
+
+            return Err(e);
+        }
+
+        // SAFETY: By the type invariant the host device is valid, and it has not been added yet.
+        let res = to_result(unsafe { bindings::gb_hd_add(hd) });
+        if let Err(e) = res {
+            // SAFETY: The driver data was set to a `T` above and has not been taken since.
+            drop(unsafe { hd_dev.as_ref().drvdata_obtain::<T>() });
+            // SAFETY: `hd` is a pointer to a valid `struct gb_host_device`.
+            unsafe { bindings::gb_hd_put(hd) };
+
+            return Err(e);
+        }
+
+        // INVARIANT: `gb_hd_create()` returns a valid `gb_host_device` on success,
+        // and we own the reference it returns until `Drop`.
+        Ok(Self {
+            ptr: NonNull::new(hd).ok_or(code::ENOMEM)?,
+            _data: PhantomData,
+        })
+    }
+}
+
+impl<T> Registration<T> {
+    #[inline]
+    fn as_raw(&self) -> *mut bindings::gb_host_device {
+        self.ptr.as_ptr()
+    }
+}
+
+impl<T> AsRef<Device> for Registration<T> {
+    #[inline]
+    fn as_ref(&self) -> &Device {
+        // SAFETY: By the type invariant the host device is valid.
+        unsafe { Device::from_raw(self.as_raw()) }
+    }
+}
+
+impl<T> Drop for Registration<T> {
+    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()) };
+    }
+}
+
+// SAFETY: The greybus host device API is thread-safe as guaranteed by the device core, as long as
+// gb_hd_del() is guaranteed to only be called once - which is guaranteed by our type not
+// having Copy/Clone.
+unsafe impl<T: Send> Send for Registration<T> {}
+
+// SAFETY: The greybus device API is thread-safe as guaranteed by the device core, as long as
+// gb_hd_del() is guaranteed to only be called once - which is guaranteed by our type not
+// having Copy/Clone.
+unsafe impl<T: Sync> Sync for Registration<T> {}
diff --git a/rust/kernel/greybus/mod.rs b/rust/kernel/greybus/mod.rs
new file mode 100644
index 000000000000..908356af08e6
--- /dev/null
+++ b/rust/kernel/greybus/mod.rs
@@ -0,0 +1,200 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Abstractions for the Greybus core.
+//!
+//! C header: [`include/linux/greybus.h`](srctree/include/linux/greybus.h)
+//!
+//! Greybus host drivers ("host devices") bridge the Greybus core to whatever transport actually
+//! carries the traffic. A host driver registers an [`hd::Device`] through an [`hd::Registration`],
+//! and implements [`hd::HdDriver`] to transmit the messages the core hands it.
+
+use core::ptr::NonNull;
+
+use crate::{
+    transmute::FromBytes,
+    types::Opaque, //
+};
+
+pub mod hd;
+pub mod protocols;
+
+/// The largest Greybus message, header included.
+///
+/// Bounded by the 16-bit `size` field in the operation header.
+pub const GB_OPERATION_SIZE_MAX: usize = u16::MAX as usize;
+
+/// The largest valid CPort id.
+///
+/// Ids above this are reserved by the protocol; a host device's `num_cports` cannot exceed
+/// `CPORT_ID_MAX + 1`.
+pub const CPORT_ID_MAX: usize = bindings::CPORT_ID_MAX as usize;
+
+/// A Greybus message handed to a host driver for transmission.
+///
+/// # Invariants
+///
+/// The shared reference is only ever handed out for the duration of a [`hd::HdDriver`] callback,
+/// during which the Greybus core guarantees the message and its buffer stay alive.
+#[repr(transparent)]
+pub struct Message(Opaque<bindings::gb_message>);
+
+impl Message {
+    /// # Safety
+    ///
+    /// `ptr` must be non-null and point at a valid `struct gb_message` which outlives the
+    /// returned `Self`.
+    #[inline]
+    pub(crate) const unsafe fn from_raw<'a>(ptr: *mut bindings::gb_message) -> &'a Self {
+        // SAFETY: `Message` is a transparent wrapper of `Opaque<bindings::gb_message>`.
+        unsafe { &*ptr.cast() }
+    }
+
+    /// Returns the operation header at the start of the message.
+    #[inline]
+    pub const fn header(&self) -> &protocols::GbOperationMsgHdr {
+        // SAFETY: `header` points at a valid `gb_operation_msg_hdr` for as long as the message is
+        // alive, and `GbOperationMsgHdr` is a transparent wrapper of it.
+        unsafe { &*(*self.0.get()).header.cast() }
+    }
+
+    /// # 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);
+        }
+    }
+
+    /// Returns the payload, i.e. the message without its operation header.
+    #[inline]
+    pub const fn payload_bytes(&self) -> &[u8] {
+        // SAFETY: By the type invariant the message is valid.
+        let payload = unsafe { (*self.0.get()).payload };
+        // SAFETY: By the type invariant the message is valid.
+        let payload_size = unsafe { (*self.0.get()).payload_size };
+
+        if payload.is_null() || payload_size == 0 {
+            return &[];
+        }
+
+        // SAFETY: A non-null `payload` points at `payload_size` initialized bytes.
+        unsafe { core::slice::from_raw_parts(payload.cast::<u8>(), payload_size) }
+    }
+
+    /// 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())
+    }
+
+    /// Returns the operation this message belongs to.
+    #[inline]
+    pub const fn operation(&self) -> &Operation {
+        // SAFETY: By the type invariant the message is valid, and its `operation` is set for as
+        // long as the message is alive.
+        unsafe { Operation::from_raw((*self.0.get()).operation) }
+    }
+}
+
+/// A Greybus operation.
+///
+/// # Invariants
+///
+/// The wrapped value is a valid `struct gb_operation`.
+#[repr(transparent)]
+pub struct Operation(Opaque<bindings::gb_operation>);
+
+impl Operation {
+    /// # Safety
+    ///
+    /// `ptr` must be a valid pointer to a `struct gb_operation`.
+    #[inline]
+    pub(crate) const unsafe fn from_raw<'a>(ptr: *mut bindings::gb_operation) -> &'a Self {
+        // SAFETY: `Operation` is a transparent wrapper of `Opaque<bindings::gb_operation>`.
+        unsafe { &*ptr.cast() }
+    }
+
+    /// Returns the connection this operation travels on.
+    #[inline]
+    pub const fn connection(&self) -> &Connection {
+        // SAFETY: By the type invariant the operation is valid, and its `connection` is alive for
+        // as long as the operation is. The returned borrow is tied to `&self`, so it cannot
+        // outlive the host-device callback that handed out the operation, as `Connection`'s
+        // invariant requires.
+        unsafe { Connection::from_raw((*self.0.get()).connection) }
+    }
+}
+
+/// A Greybus connection.
+///
+/// # Invariants
+///
+/// The wrapped value is a valid `struct gb_connection`.
+///
+/// References to a `Connection` are only handed out for the duration of a host-device callback on
+/// a message travelling over it. During that time the connection is enabled, and its interface,
+/// if any, is alive: the core disables and destroys a bundle's connections before it tears down
+/// their interface.
+#[repr(transparent)]
+pub struct Connection(Opaque<bindings::gb_connection>);
+
+impl Connection {
+    /// # Safety
+    ///
+    /// `ptr` must be a valid pointer to a `struct gb_connection`.
+    #[inline]
+    pub(crate) const unsafe fn from_raw<'a>(ptr: *mut bindings::gb_connection) -> &'a Self {
+        // SAFETY: `Connection` is a transparent wrapper of `Opaque<bindings::gb_connection>`.
+        unsafe { &*ptr.cast() }
+    }
+
+    /// Returns the interface at the far end of the connection. In cases like SVC connection,
+    /// interface can be NULL.
+    #[inline]
+    pub fn interface(&self) -> Option<&Interface> {
+        // SAFETY: By the type invariant the connection is valid.
+        let intf_ptr = NonNull::new(unsafe { (*self.0.get()).intf })?;
+
+        // SAFETY: `intf_ptr` is non-NULL, and by the type invariant the interface is alive for as
+        // long as `&self` is. `Interface` is a transparent wrapper of
+        // `Opaque<bindings::gb_interface>`.
+        Some(unsafe { intf_ptr.cast().as_ref() })
+    }
+
+    /// Returns the CPort id this connection uses on the interface.
+    #[inline]
+    pub const fn intf_cport_id(&self) -> u16 {
+        // SAFETY: By the type invariant the connection is valid.
+        unsafe { (*self.0.get()).intf_cport_id }
+    }
+
+    /// Returns the CPort id this connection uses on the host device.
+    #[inline]
+    pub const fn hd_cport_id(&self) -> u16 {
+        // SAFETY: By the type invariant the connection is valid.
+        unsafe { (*self.0.get()).hd_cport_id }
+    }
+}
+
+/// A Greybus interface.
+///
+/// # Invariants
+///
+/// The wrapped value is a valid `struct gb_interface`.
+#[repr(transparent)]
+pub struct Interface(Opaque<bindings::gb_interface>);
+
+impl Interface {
+    /// Returns the interface id, unique within its host device.
+    #[inline]
+    pub const fn id(&self) -> u8 {
+        // SAFETY: By the type invariant the interface is valid.
+        unsafe { (*self.0.get()).interface_id }
+    }
+}
diff --git a/rust/kernel/greybus/protocols.rs b/rust/kernel/greybus/protocols.rs
new file mode 100644
index 000000000000..dcbc497092c5
--- /dev/null
+++ b/rust/kernel/greybus/protocols.rs
@@ -0,0 +1,454 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Greybus wire format definitions.
+//!
+//! Thin `repr(transparent)` wrappers over the generated bindings for the operation header and the
+//! SVC protocol messages, plus the constants that go in their type and result fields. The
+//! wrappers exist to keep the byte-order conversions in one place: constructors take native-endian
+//! values and store little-endian, accessors convert back.
+
+/// Set in the header type field to mark a message as a response to the operation of the same id.
+pub const MESSAGE_TYPE_RESPONSE: u8 = 0x80;
+
+/// Operation result: the operation succeeded.
+pub const GB_OP_SUCCESS: u8 = bindings::gb_operation_result_GB_OP_SUCCESS as u8;
+
+/// Operation result: the receiver does not support the request type.
+pub const GB_OP_PROTOCOL_BAD: u8 = bindings::gb_operation_result_GB_OP_PROTOCOL_BAD as u8;
+
+/// The CPort id reserved for the SVC connection on every host device.
+pub const GB_SVC_CPORT_ID: u16 = bindings::GB_SVC_CPORT_ID as u16;
+
+/// Defines `u8` constants from same-named `bindings` values.
+macro_rules! gb_u8_consts {
+    ($($name:ident),* $(,)?) => {
+        $(
+            #[allow(missing_docs)]
+            pub const $name: u8 = bindings::$name as u8;
+        )*
+    };
+}
+
+// SVC Operation Types
+gb_u8_consts! {
+    GB_SVC_TYPE_PROTOCOL_VERSION,
+    GB_SVC_TYPE_SVC_HELLO,
+    GB_SVC_TYPE_INTF_DEVICE_ID,
+    GB_SVC_TYPE_INTF_RESET,
+    GB_SVC_TYPE_CONN_CREATE,
+    GB_SVC_TYPE_CONN_DESTROY,
+    GB_SVC_TYPE_DME_PEER_GET,
+    GB_SVC_TYPE_DME_PEER_SET,
+    GB_SVC_TYPE_ROUTE_CREATE,
+    GB_SVC_TYPE_ROUTE_DESTROY,
+    GB_SVC_TYPE_TIMESYNC_ENABLE,
+    GB_SVC_TYPE_TIMESYNC_DISABLE,
+    GB_SVC_TYPE_TIMESYNC_AUTHORITATIVE,
+    GB_SVC_TYPE_INTF_SET_PWRM,
+    GB_SVC_TYPE_INTF_EJECT,
+    GB_SVC_TYPE_PING,
+    GB_SVC_TYPE_PWRMON_RAIL_COUNT_GET,
+    GB_SVC_TYPE_PWRMON_RAIL_NAMES_GET,
+    GB_SVC_TYPE_PWRMON_SAMPLE_GET,
+    GB_SVC_TYPE_PWRMON_INTF_SAMPLE_GET,
+    GB_SVC_TYPE_TIMESYNC_WAKE_PINS_ACQUIRE,
+    GB_SVC_TYPE_TIMESYNC_WAKE_PINS_RELEASE,
+    GB_SVC_TYPE_TIMESYNC_PING,
+    GB_SVC_TYPE_MODULE_INSERTED,
+    GB_SVC_TYPE_MODULE_REMOVED,
+    GB_SVC_TYPE_INTF_VSYS_ENABLE,
+    GB_SVC_TYPE_INTF_VSYS_DISABLE,
+    GB_SVC_TYPE_INTF_REFCLK_ENABLE,
+    GB_SVC_TYPE_INTF_REFCLK_DISABLE,
+    GB_SVC_TYPE_INTF_UNIPRO_ENABLE,
+    GB_SVC_TYPE_INTF_UNIPRO_DISABLE,
+    GB_SVC_TYPE_INTF_ACTIVATE,
+    GB_SVC_TYPE_INTF_RESUME,
+    GB_SVC_TYPE_INTF_MAILBOX_EVENT,
+    GB_SVC_TYPE_INTF_OOPS,
+}
+
+// UNIPRO modes
+gb_u8_consts! {
+    GB_SVC_UNIPRO_FAST_MODE,
+    GB_SVC_UNIPRO_SLOW_MODE,
+    GB_SVC_UNIPRO_FAST_AUTO_MODE,
+    GB_SVC_UNIPRO_SLOW_AUTO_MODE,
+    GB_SVC_UNIPRO_MODE_UNCHANGED,
+    GB_SVC_UNIPRO_HIBERNATE_MODE,
+    GB_SVC_UNIPRO_OFF_MODE,
+}
+
+// PWR States
+gb_u8_consts! {
+    GB_SVC_SETPWRM_PWR_OK,
+    GB_SVC_SETPWRM_PWR_LOCAL,
+    GB_SVC_SETPWRM_PWR_REMOTE,
+    GB_SVC_SETPWRM_PWR_BUSY,
+    GB_SVC_SETPWRM_PWR_ERROR_CAP,
+    GB_SVC_SETPWRM_PWR_FATAL_ERROR,
+}
+
+// Vsys Result
+gb_u8_consts! {
+    GB_SVC_INTF_VSYS_OK,
+    GB_SVC_INTF_VSYS_FAIL,
+}
+
+// Refclk Result
+gb_u8_consts! {
+    GB_SVC_INTF_REFCLK_OK,
+    GB_SVC_INTF_REFCLK_FAIL,
+}
+
+// Unipro Result
+gb_u8_consts! {
+    GB_SVC_INTF_UNIPRO_OK,
+    GB_SVC_INTF_UNIPRO_FAIL,
+    GB_SVC_INTF_UNIPRO_NOT_OFF,
+}
+
+// Op Codes
+gb_u8_consts! {
+    GB_SVC_OP_SUCCESS,
+    GB_SVC_OP_UNKNOWN_ERROR,
+    GB_SVC_INTF_NOT_DETECTED,
+    GB_SVC_INTF_NO_UPRO_LINK,
+    GB_SVC_INTF_UPRO_NOT_DOWN,
+    GB_SVC_INTF_UPRO_NOT_HIBERNATED,
+    GB_SVC_INTF_NO_V_SYS,
+    GB_SVC_INTF_V_CHG,
+    GB_SVC_INTF_WAKE_BUSY,
+    GB_SVC_INTF_NO_REFCLK,
+    GB_SVC_INTF_RELEASING,
+    GB_SVC_INTF_NO_ORDER,
+    GB_SVC_INTF_MBOX_SET,
+    GB_SVC_INTF_BAD_MBOX,
+    GB_SVC_INTF_OP_TIMEOUT,
+    GB_SVC_PWRMON_OP_NOT_PRESENT,
+}
+
+// Greybus Interface Types
+gb_u8_consts! {
+    GB_SVC_INTF_TYPE_UNKNOWN,
+    GB_SVC_INTF_TYPE_DUMMY,
+    GB_SVC_INTF_TYPE_UNIPRO,
+    GB_SVC_INTF_TYPE_GREYBUS,
+}
+
+/// The header every Greybus message starts with.
+///
+/// Its `size` field is the size of the whole message, this header included.
+#[repr(transparent)]
+pub struct GbOperationMsgHdr(bindings::gb_operation_msg_hdr);
+
+// SAFETY: `gb_operation_msg_hdr` is a POD type with no padding and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbOperationMsgHdr {}
+
+impl GbOperationMsgHdr {
+    /// Builds a header. `size` is the whole message, this header included.
+    #[inline]
+    pub const fn new(size: u16, operation_id: u16, type_: u8, result: u8) -> Self {
+        Self(bindings::gb_operation_msg_hdr {
+            size: size.to_le(),
+            operation_id: operation_id.to_le(),
+            type_,
+            result,
+            pad: [0u8; 2],
+        })
+    }
+
+    /// Returns the type field, response bit included.
+    #[inline]
+    pub const fn msg_type(&self) -> u8 {
+        self.0.type_
+    }
+
+    /// Returns whether this is a response rather than a request.
+    #[inline]
+    pub const fn is_response(&self) -> bool {
+        self.0.type_ & MESSAGE_TYPE_RESPONSE != 0
+    }
+
+    /// Returns the operation id pairing a response with its request. Zero for unidirectional
+    /// messages.
+    #[inline]
+    pub const fn operation_id(&self) -> u16 {
+        u16::from_le(self.0.operation_id)
+    }
+
+    /// Returns the type field with the response bit cleared.
+    #[inline]
+    pub const fn request_type(&self) -> u8 {
+        self.msg_type() & !MESSAGE_TYPE_RESPONSE
+    }
+
+    /// Returns the result field of a response. [`GB_OP_SUCCESS`] means success.
+    #[inline]
+    pub const fn result(&self) -> u8 {
+        self.0.result
+    }
+
+    /// Returns the whole message size, this header included.
+    #[inline]
+    pub const fn size(&self) -> u16 {
+        u16::from_le(self.0.size)
+    }
+}
+
+/// Request for [`GB_SVC_TYPE_PROTOCOL_VERSION`].
+#[repr(transparent)]
+pub struct GbSvcVersionRequest(bindings::gb_svc_version_request);
+
+// SAFETY: `gb_svc_version_request` is a packed struct of integer fields, so it has no padding and
+// no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcVersionRequest {}
+
+impl GbSvcVersionRequest {
+    /// Creates a request advertising SVC protocol version `major`.`minor`.
+    #[inline]
+    pub const fn new(major: u8, minor: u8) -> Self {
+        Self(bindings::gb_svc_version_request { major, minor })
+    }
+}
+
+/// Request for [`GB_SVC_TYPE_SVC_HELLO`].
+#[repr(transparent)]
+pub struct GbSvcHelloRequest(bindings::gb_svc_hello_request);
+
+// SAFETY: `gb_svc_hello_request` is a packed struct of integer fields, so it has no padding and
+// no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcHelloRequest {}
+
+impl GbSvcHelloRequest {
+    /// Creates a hello request identifying the endo as `endo_id` and the AP's own interface as
+    /// `interface_id`.
+    #[inline]
+    pub const fn new(endo_id: u16, interface_id: u8) -> Self {
+        Self(bindings::gb_svc_hello_request {
+            endo_id: endo_id.to_le(),
+            interface_id,
+        })
+    }
+}
+
+/// Request for [`GB_SVC_TYPE_INTF_SET_PWRM`].
+#[repr(transparent)]
+pub struct GbSvcIntfSetPwrmRequest(bindings::gb_svc_intf_set_pwrm_request);
+
+// SAFETY: `gb_svc_intf_set_pwrm_request` is a packed struct of sized fields, so every bit pattern
+// of its size is a valid instance.
+unsafe impl kernel::transmute::FromBytes for GbSvcIntfSetPwrmRequest {}
+
+impl GbSvcIntfSetPwrmRequest {
+    /// Returns the requested TX gear, one of the `GB_SVC_UNIPRO_*` modes.
+    #[inline]
+    pub const fn tx_mode(&self) -> u8 {
+        self.0.tx_mode
+    }
+
+    /// Returns the requested RX gear, one of the `GB_SVC_UNIPRO_*` modes.
+    #[inline]
+    pub const fn rx_mode(&self) -> u8 {
+        self.0.rx_mode
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_INTF_SET_PWRM`].
+#[repr(transparent)]
+pub struct GbSvcIntfSetPwrmResponse(bindings::gb_svc_intf_set_pwrm_response);
+
+// SAFETY: `gb_svc_intf_set_pwrm_response` is a packed struct of integer fields, so it has no
+// padding and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcIntfSetPwrmResponse {}
+
+impl GbSvcIntfSetPwrmResponse {
+    /// `result_code` is one of the `GB_SVC_SETPWRM_PWR_*` codes.
+    #[inline]
+    pub const fn new(result_code: u8) -> Self {
+        Self(bindings::gb_svc_intf_set_pwrm_response { result_code })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_DME_PEER_GET`].
+#[repr(transparent)]
+pub struct GbSvcDmePeerGetResponse(bindings::gb_svc_dme_peer_get_response);
+
+// SAFETY: `gb_svc_dme_peer_get_response` is a packed struct of integer fields, so it has no
+// padding and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcDmePeerGetResponse {}
+
+impl GbSvcDmePeerGetResponse {
+    /// `result_code` is the UniPro `ConfigResultCode`; `attr_value` is the UniPro attribute
+    /// value.
+    #[inline]
+    pub const fn new(result_code: u16, attr_value: u32) -> Self {
+        Self(bindings::gb_svc_dme_peer_get_response {
+            result_code: result_code.to_le(),
+            attr_value: attr_value.to_le(),
+        })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_DME_PEER_SET`].
+#[repr(transparent)]
+pub struct GbSvcDmePeerSetResponse(bindings::gb_svc_dme_peer_set_response);
+
+// SAFETY: `gb_svc_dme_peer_set_response` is a packed struct of integer fields, so it has no padding
+// and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcDmePeerSetResponse {}
+
+impl GbSvcDmePeerSetResponse {
+    /// `result_code` is the UniPro `ConfigResultCode`.
+    #[inline]
+    pub const fn new(result_code: u16) -> Self {
+        Self(bindings::gb_svc_dme_peer_set_response {
+            result_code: result_code.to_le(),
+        })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_PWRMON_RAIL_COUNT_GET`].
+#[repr(transparent)]
+pub struct GbSvcPwrmonRailCountGetResponse(bindings::gb_svc_pwrmon_rail_count_get_response);
+
+// SAFETY: `gb_svc_pwrmon_rail_count_get_response` is a packed struct of integer fields, so it has
+// no padding and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcPwrmonRailCountGetResponse {}
+
+impl GbSvcPwrmonRailCountGetResponse {
+    /// Creates a response reporting `rail_count` available rails.
+    #[inline]
+    pub const fn new(rail_count: u8) -> Self {
+        Self(bindings::gb_svc_pwrmon_rail_count_get_response { rail_count })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_INTF_VSYS_ENABLE`] and [`GB_SVC_TYPE_INTF_VSYS_DISABLE`].
+#[repr(transparent)]
+pub struct GbSvcIntfVsysResponse(bindings::gb_svc_intf_vsys_response);
+
+// SAFETY: `gb_svc_intf_vsys_response` is a packed struct of integer fields, so it has no padding
+// and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcIntfVsysResponse {}
+
+impl GbSvcIntfVsysResponse {
+    /// `result_code` is [`GB_SVC_INTF_VSYS_OK`] or [`GB_SVC_INTF_VSYS_FAIL`].
+    #[inline]
+    pub const fn new(result_code: u8) -> Self {
+        Self(bindings::gb_svc_intf_vsys_response { result_code })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_INTF_REFCLK_ENABLE`] and [`GB_SVC_TYPE_INTF_REFCLK_DISABLE`].
+#[repr(transparent)]
+pub struct GbSvcIntfRefclkResponse(bindings::gb_svc_intf_refclk_response);
+
+// SAFETY: `gb_svc_intf_refclk_response` is a packed struct of integer fields, so it has no padding
+// and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcIntfRefclkResponse {}
+
+impl GbSvcIntfRefclkResponse {
+    /// `result_code` is [`GB_SVC_INTF_REFCLK_OK`] or [`GB_SVC_INTF_REFCLK_FAIL`].
+    #[inline]
+    pub const fn new(result_code: u8) -> Self {
+        Self(bindings::gb_svc_intf_refclk_response { result_code })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_INTF_UNIPRO_ENABLE`] and [`GB_SVC_TYPE_INTF_UNIPRO_DISABLE`].
+#[repr(transparent)]
+pub struct GbSvcIntfUniproResponse(bindings::gb_svc_intf_unipro_response);
+
+// SAFETY: `gb_svc_intf_unipro_response` is a packed struct of integer fields, so it has no padding
+// and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcIntfUniproResponse {}
+
+impl GbSvcIntfUniproResponse {
+    /// `result_code` is one of the `GB_SVC_INTF_UNIPRO_*` codes.
+    #[inline]
+    pub const fn new(result_code: u8) -> Self {
+        Self(bindings::gb_svc_intf_unipro_response { result_code })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_INTF_ACTIVATE`].
+#[repr(transparent)]
+pub struct GbSvcIntfActivateResponse(bindings::gb_svc_intf_activate_response);
+
+// SAFETY: `gb_svc_intf_activate_response` is a packed struct of integer fields, so it has no
+// padding and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcIntfActivateResponse {}
+
+impl GbSvcIntfActivateResponse {
+    /// `status` is one of the `GB_SVC_OP_*` codes; `intf_type` is one of the
+    /// `GB_SVC_INTF_TYPE_*` values and is only meaningful when `status` is
+    /// [`GB_SVC_OP_SUCCESS`].
+    #[inline]
+    pub const fn new(status: u8, intf_type: u8) -> Self {
+        Self(bindings::gb_svc_intf_activate_response { status, intf_type })
+    }
+}
+
+/// Response to [`GB_SVC_TYPE_INTF_RESUME`].
+#[repr(transparent)]
+pub struct GbSvcIntfResumeResponse(bindings::gb_svc_intf_resume_response);
+
+// SAFETY: `gb_svc_intf_resume_response` is a packed struct of integer fields, so it has no padding
+// and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcIntfResumeResponse {}
+
+impl GbSvcIntfResumeResponse {
+    /// `status` is one of the `GB_SVC_OP_*` codes.
+    #[inline]
+    pub const fn new(status: u8) -> Self {
+        Self(bindings::gb_svc_intf_resume_response { status })
+    }
+}
+
+/// Request for [`GB_SVC_TYPE_MODULE_INSERTED`].
+#[repr(transparent)]
+pub struct GbSvcModuleInsertedRequest(bindings::gb_svc_module_inserted_request);
+
+// SAFETY: `gb_svc_module_inserted_request` is a packed struct of integer fields, so it has no
+// padding and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcModuleInsertedRequest {}
+
+impl GbSvcModuleInsertedRequest {
+    /// The module spans `intf_count` consecutive interfaces starting at `primary_intf_id`.
+    /// `flags` is a mask of `GB_SVC_MODULE_INSERTED_FLAG_*` values.
+    #[inline]
+    pub const fn new(primary_intf_id: u8, intf_count: u8, flags: u16) -> Self {
+        Self(bindings::gb_svc_module_inserted_request {
+            primary_intf_id,
+            intf_count,
+            flags: flags.to_le(),
+        })
+    }
+}
+
+/// Request for [`GB_SVC_TYPE_MODULE_REMOVED`].
+#[repr(transparent)]
+pub struct GbSvcModuleRemovedRequest(bindings::gb_svc_module_removed_request);
+
+// SAFETY: `gb_svc_module_removed_request` is a packed struct of integer fields, so it has no
+// padding and no interior mutability.
+unsafe impl kernel::transmute::AsBytes for GbSvcModuleRemovedRequest {}
+
+// SAFETY: `gb_svc_module_removed_request` is a struct of `u8` field, so every bit pattern of its
+// size is a valid instance.
+unsafe impl kernel::transmute::FromBytes for GbSvcModuleRemovedRequest {}
+
+impl GbSvcModuleRemovedRequest {
+    /// `primary_intf_id` identifies the module, and matches the one given when it was inserted.
+    #[inline]
+    pub const fn new(primary_intf_id: u8) -> Self {
+        Self(bindings::gb_svc_module_removed_request { primary_intf_id })
+    }
+
+    /// Returns the primary_intf_id field.
+    #[inline]
+    pub const fn primary_intf_id(&self) -> u8 {
+        self.0.primary_intf_id
+    }
+}
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 5aa46a1982df..d7627ca8cd11 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -87,6 +87,8 @@
 pub mod fwctl;
 #[cfg(CONFIG_GPU_BUDDY = "y")]
 pub mod gpu;
+#[cfg(CONFIG_RUST_GREYBUS_ABSTRACTIONS)]
+pub mod greybus;
 #[cfg(CONFIG_I2C = "y")]
 pub mod i2c;
 pub mod id_pool;

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 7/9] drivers: greybus: Add software SVC implementation
  2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
                   ` (5 preceding siblings ...)
  2026-12-04 10:30 ` [PATCH v6 6/9] rust: kernel: Add greybus abstractions Ayush Singh
@ 2026-12-04 10:30 ` 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 10:30 ` [PATCH v6 9/9] greybus: Add Rust UART node driver Ayush Singh
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

A Greybus network requires 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, but transports that
merely carry Greybus messages - a UART, an I2C bus, a network link -
have no such entity, so every host driver for those transports ends up
open-coding an SVC emulation of its own.

Add gb-softsvc, a Rust implementation of the SVC that lives in the
kernel and registers itself as a Greybus host device. It answers the
SVC-side operations the core expects during interface bring-up and
teardown.

Host drivers use it through a small in-kernel interface. A driver
implements the InterfaceOps trait to send data towards each of its
interfaces, and creates a Module from them with Module::new(), which
allocates the interface IDs and announces the module to the core.
Incoming Greybus messages are handed back with Module::submit_message(),
which takes the interface's index within the module. Dropping the Module
removes it from the core, and waits until no InterfaceOps method is
running any more.

Connection create/destroy and interface activate/resume currently just
acknowledge the request; callbacks into InterfaceOps can be added later
if transports need to act on them.

gb_softsvc_exports.c exports the Rust symbols for dependent modules, as
the build system does not yet support Rust cross-module dependencies
natively. This hack is taken from nova-core [0].

[0]: https://lore.kernel.org/all/20260622-nova-exports-v5-0-6191773fc977@nvidia.com/

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 MAINTAINERS                          |   6 +
 drivers/greybus/Kconfig              |  12 +
 drivers/greybus/Makefile             |  40 +++
 drivers/greybus/gb_softsvc.rs        | 570 +++++++++++++++++++++++++++++++++++
 drivers/greybus/gb_softsvc_exports.c |  15 +
 5 files changed, 643 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 6791104ed3ee..a5399350a59e 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -11690,6 +11690,12 @@ S:	Maintained
 F:	Documentation/devicetree/bindings/net/ti,cc1352p7.yaml
 F:	drivers/greybus/gb-beagleplay.c
 
+GREYBUS SOFTSVC DRIVERS
+M:	Ayush Singh <ayush@beagleboard.org>
+L:	greybus-dev@lists.linaro.org (moderated for non-subscribers)
+S:	Maintained
+F:	drivers/greybus/gb_softsvc.rs
+
 GREYBUS SUBSYSTEM
 M:	Johan Hovold <johan@kernel.org>
 M:	Alex Elder <elder@kernel.org>
diff --git a/drivers/greybus/Kconfig b/drivers/greybus/Kconfig
index d9f52024d1c2..709563f8c0ad 100644
--- a/drivers/greybus/Kconfig
+++ b/drivers/greybus/Kconfig
@@ -49,5 +49,17 @@ config GREYBUS_ES2
 	  To compile this code as a module, choose M here: the module
 	  will be called gb-es2.ko
 
+config GREYBUS_SOFTSVC
+	tristate "Greybus software SVC"
+	depends on RUST_GREYBUS_ABSTRACTIONS
+	help
+	  Select this option to enable a software implementation of the
+	  Greybus SVC (Supervisory Controller) running in the kernel. It can
+	  be used by host drivers that talk to a Greybus network which does
+	  not provide an SVC of its own.
+
+	  To compile this code as a module, choose M here: the module
+	  will be called gb-softsvc.ko
+
 endif	# GREYBUS
 
diff --git a/drivers/greybus/Makefile b/drivers/greybus/Makefile
index d986e94f8897..0fa802fdf6ca 100644
--- a/drivers/greybus/Makefile
+++ b/drivers/greybus/Makefile
@@ -25,4 +25,44 @@ gb-es2-y := es2.o
 
 obj-$(CONFIG_GREYBUS_ES2)	+= gb-es2.o
 
+obj-$(CONFIG_GREYBUS_SOFTSVC)	+= gb-softsvc.o
+gb-softsvc-y			+= gb_softsvc.o gb_softsvc_exports.o
 
+rust_needed_exports = \
+	{ $(if $(strip $(2)),$(NM) -u $(2);,) echo "__DEFINED_RUST_SYMBOLS__"; \
+	  $(NM) -p --defined-only $(1); } | \
+	awk -v fmt='$(3)' ' \
+		/^__DEFINED_RUST_SYMBOLS__$$/ { defs = 1; next } \
+		!defs { if ($$NF ~ /^_R/) needed[$$NF] = 1; next } \
+		defs && $$2 ~ /(T|R|D|B)/ && $$3 ~ /^_R/ && \
+			$$3 !~ /_(init|cleanup)_module$$/ && \
+			$$3 !~ /__(pfx|cfi|odr_asan)/ && \
+			$$3 in needed { printf fmt, $$3 } \
+	'
+
+quiet_cmd_exports = EXPORTS $@
+      cmd_exports = \
+	$(call rust_needed_exports,$<,$(gb-softsvc-export-deps),EXPORT_SYMBOL_RUST_GPL(%s);\n) > $@
+
+$(obj)/exports_gb_softsvc_generated.h: $(obj)/gb_softsvc.o $(gb-softsvc-export-deps) FORCE
+	$(call if_changed,exports)
+
+targets += exports_gb_softsvc_generated.h
+
+$(obj)/gb_softsvc_exports.o: $(obj)/exports_gb_softsvc_generated.h
+CFLAGS_gb_softsvc_exports.o := -I $(objtree)/$(obj)
+
+ifdef CONFIG_MODVERSIONS
+# The C export shim declares Rust symbols as `extern int`, so reuse its export
+# list but generate symbol CRCs from the Rust object instead of the shim's DWARF.
+$(obj)/gb_softsvc_exports.o: private cmd_gensymtypes_c = \
+	$(call getexportsymbols,\1) | \
+	$(objtree)/scripts/gendwarfksyms/gendwarfksyms \
+		$(if $(KBUILD_GENDWARFKSYMS_STABLE), --stable) \
+		$(if $(KBUILD_SYMTYPES), --symtypes $(@:.o=.symtypes),) \
+		$(obj)/gb_softsvc.o
+endif
+
+# Output gb_softsvc's crate metadata for use by gb_uart_node at compile time.
+RUSTFLAGS_gb_softsvc.o += \
+	--emit=metadata=$(objtree)/$(obj)/libgb_softsvc.rmeta
diff --git a/drivers/greybus/gb_softsvc.rs b/drivers/greybus/gb_softsvc.rs
new file mode 100644
index 000000000000..8fbcfe98e084
--- /dev/null
+++ b/drivers/greybus/gb_softsvc.rs
@@ -0,0 +1,570 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Greybus software SVC.
+//!
+//! A Greybus network needs an SVC to bring interfaces up and to connect their CPorts to the AP.
+//! Transports that carry Greybus without one - a UART or an I2C bus rather than a UniPro network -
+//! have to provide it themselves.
+//!
+//! This module implements that SVC in software.
+
+use kernel::{
+    alloc::Flags,
+    c_str,
+    error::code,
+    faux,
+    greybus::{
+        self,
+        hd,
+        protocols,
+        CPORT_ID_MAX,
+        GB_OPERATION_SIZE_MAX, //
+    },
+    id_pool::IdPool,
+    new_spinlock,
+    prelude::*,
+    sync::{
+        aref::ARef,
+        Arc,
+        Completion,
+        SpinLock, //
+    },
+    transmute::AsBytes,
+};
+use pin_init::init_array_from_fn;
+
+const SVC_VERSION_MAJOR: u8 = 0;
+const SVC_VERSION_MINOR: u8 = 1;
+
+const ENDO_ID: u16 = 0;
+const AP_INF_ID: u8 = 0;
+
+const TOSHIBA_DMID: u32 = 0x0126;
+
+const MAX_INTF_ID: u8 = u8::MAX;
+const INTF_ID_START: u8 = 1;
+const INTF_MAP_LEN: usize = (MAX_INTF_ID - INTF_ID_START) as usize;
+
+#[repr(C, packed)]
+struct Msg<P> {
+    hdr: protocols::GbOperationMsgHdr,
+    payload: P,
+}
+
+// SAFETY: `Msg` is `repr(C, packed)`, so it has no padding between its fields, and both fields
+// are `AsBytes`, so neither has uninitialized bytes of its own.
+unsafe impl<P: AsBytes> AsBytes for Msg<P> {}
+
+impl<P> Msg<P> {
+    const GB_SIZE: u16 = size_of::<Self>() as u16;
+
+    /// Builds a request of type `ty`.
+    ///
+    /// An `operation_id` of zero marks a unidirectional request, for which the AP sends no
+    /// response.
+    const fn request(operation_id: u16, ty: u8, payload: P) -> Self {
+        Self {
+            hdr: protocols::GbOperationMsgHdr::new(Self::GB_SIZE, operation_id, ty, 0),
+            payload,
+        }
+    }
+
+    /// Builds the response to `request`, carrying `result`.
+    const fn response(request: &protocols::GbOperationMsgHdr, result: u8, payload: P) -> Self {
+        Self {
+            hdr: protocols::GbOperationMsgHdr::new(
+                Self::GB_SIZE,
+                request.operation_id(),
+                request.msg_type() | protocols::MESSAGE_TYPE_RESPONSE,
+                result,
+            ),
+            payload,
+        }
+    }
+}
+
+const _: () = assert!(size_of::<Msg<()>>() == size_of::<protocols::GbOperationMsgHdr>());
+
+module! {
+    type: GreybusSoftSvc,
+    name: "gb_softsvc",
+    authors: ["Ayush Singh <ayush@beagleboard.org>"],
+    description: "Greybus software SVC implementation",
+    license: "GPL",
+}
+
+kernel::sync::global_lock! {
+    unsafe(uninit) static GLOBAL_STATE: Mutex<Option<GlobalState>> = None;
+}
+
+struct GlobalState {
+    svc: Arc<Svc>,
+    gb_hd: ARef<hd::Device>,
+}
+
+impl GlobalState {
+    fn new(svc: Arc<Svc>, gb_hd: ARef<hd::Device>) -> Self {
+        Self { svc, gb_hd }
+    }
+}
+
+#[pin_data]
+struct Svc {
+    #[pin]
+    svc_operation_id: SpinLock<IdPool>,
+    // Pos 0 = INTF_ID_START
+    #[pin]
+    intf_map: SpinLock<[Option<Arc<dyn InterfaceOps>>; INTF_MAP_LEN]>,
+    /// Completed when the SVC handshake has finished, successfully or not.
+    #[pin]
+    handshake: Completion,
+}
+
+impl Svc {
+    fn new() -> impl PinInit<Self, Error> {
+        pin_init!(Self {
+            intf_map <- new_spinlock!(init_array_from_fn(|_| None)),
+            handshake <- Completion::new(),
+            svc_operation_id <- new_spinlock!(IdPool::with_capacity(u16::MAX.into(), GFP_KERNEL)?)
+        }? Error)
+    }
+
+    fn new_operation_id(&self) -> Result<u16> {
+        let mut ida = self.svc_operation_id.lock();
+        let res = ida.find_unused_id(1).ok_or(code::EOVERFLOW)?.acquire() as u16;
+
+        Ok(res)
+    }
+
+    fn release_operation_id(&self, id: u16) {
+        let mut ida = self.svc_operation_id.lock();
+        ida.release_id(id as usize);
+    }
+
+    fn map_insert(&self, intfs: &[Arc<dyn InterfaceOps>]) -> Result<u8> {
+        fn find_empty_window(
+            intf_map: &[Option<Arc<dyn InterfaceOps>>; INTF_MAP_LEN],
+            count: usize,
+        ) -> Result<u8> {
+            for (id, window) in intf_map.windows(count).enumerate() {
+                if window.iter().all(|x| x.is_none()) {
+                    return Ok(id as u8);
+                }
+            }
+
+            Err(code::EOVERFLOW)
+        }
+
+        let mut guard = self.intf_map.lock();
+
+        let pos = find_empty_window(&guard, intfs.len())?;
+        for (i, intf) in intfs.iter().cloned().enumerate() {
+            guard[usize::from(pos) + i] = Some(intf);
+        }
+
+        Ok(pos + INTF_ID_START)
+    }
+
+    fn map_remove(&self, primary_id: u8, intf_count: u8, dev: &kernel::device::Device) {
+        let id = match primary_id.checked_sub(INTF_ID_START) {
+            Some(x) => x,
+            None => {
+                dev_warn!(dev, "Invalid interface id");
+                return;
+            }
+        };
+
+        for i in 0..intf_count {
+            // Drop outside the lock: this may be the last reference, and the node's `Drop` may
+            // sleep. `let _ =` would drop it before the guard, while the lock is still held.
+            let intf = self.intf_map.lock()[usize::from(id + i)].take();
+            drop(intf);
+        }
+    }
+
+    fn intf_by_id(&self, id: u8) -> Result<Arc<dyn InterfaceOps>> {
+        let id = id - INTF_ID_START;
+        let guard = self.intf_map.lock();
+
+        guard
+            .get(usize::from(id))
+            .ok_or(code::ENODEV)?
+            .as_ref()
+            .ok_or(code::ENODEV)
+            .cloned()
+    }
+
+    fn send_request<P: AsBytes>(&self, hd: &hd::Device, ty: u8, payload: P) -> Result<()> {
+        let msg = Msg::request(self.new_operation_id()?, ty, payload);
+        hd.data_rcvd(protocols::GB_SVC_CPORT_ID, msg.as_bytes());
+        Ok(())
+    }
+
+    fn module_insert(&self, hd: &hd::Device, intfs: &[Arc<dyn InterfaceOps>]) -> Result<u8> {
+        let intf_id = self.map_insert(intfs)?;
+        // map_insert already checks that intf len fits in u8
+        let intf_count = intfs.len() as u8;
+
+        let payload = protocols::GbSvcModuleInsertedRequest::new(intf_id, intf_count, 0);
+        let res = self.send_request(hd, protocols::GB_SVC_TYPE_MODULE_INSERTED, payload);
+
+        if res.is_err() {
+            self.map_remove(intf_id, intf_count, hd.as_ref());
+        }
+
+        res.map(|()| intf_id)
+    }
+
+    fn module_remove(&self, hd: &hd::Device, intf_id: u8, intf_count: u8) {
+        let payload = protocols::GbSvcModuleRemovedRequest::new(intf_id);
+        let res = self.send_request(hd, protocols::GB_SVC_TYPE_MODULE_REMOVED, payload);
+
+        if res.is_err() {
+            dev_warn!(
+                hd.as_ref(),
+                "Failed to send module_removed svc request for {}",
+                intf_id
+            );
+        }
+
+        // The ids stay taken until the core has removed the module, or a new module could be
+        // given them while the old connections still exist.
+        hd.svc_flush();
+
+        self.map_remove(intf_id, intf_count, hd.as_ref());
+    }
+
+    fn send_version(&self, hd: &hd::Device) -> Result<()> {
+        dev_info!(hd.as_ref(), "Sending SVC version request");
+
+        let payload = protocols::GbSvcVersionRequest::new(SVC_VERSION_MAJOR, SVC_VERSION_MINOR);
+        self.send_request(hd, protocols::GB_SVC_TYPE_PROTOCOL_VERSION, payload)?;
+
+        Ok(())
+    }
+
+    fn send_svc_hello(&self, hd: &hd::Device) -> Result<()> {
+        dev_info!(hd.as_ref(), "Sending SVC Hello request");
+
+        let payload = protocols::GbSvcHelloRequest::new(ENDO_ID, AP_INF_ID);
+        self.send_request(hd, protocols::GB_SVC_TYPE_SVC_HELLO, payload)?;
+
+        Ok(())
+    }
+
+    fn send_response<P: AsBytes>(
+        &self,
+        hd: &hd::Device,
+        msg: &protocols::GbOperationMsgHdr,
+        payload: P,
+    ) {
+        let msg = Msg::response(msg, 0, payload);
+        hd.data_rcvd(protocols::GB_SVC_CPORT_ID, msg.as_bytes());
+    }
+
+    fn intf_set_pwrm(&self, hd: &hd::Device, msg: &greybus::Message) -> Result<()> {
+        let req_msg: &protocols::GbSvcIntfSetPwrmRequest = msg.payload().ok_or(code::EINVAL)?;
+        let result_code = if req_msg.tx_mode() == protocols::GB_SVC_UNIPRO_HIBERNATE_MODE
+            && req_msg.rx_mode() == protocols::GB_SVC_UNIPRO_HIBERNATE_MODE
+        {
+            protocols::GB_SVC_SETPWRM_PWR_OK
+        } else {
+            protocols::GB_SVC_SETPWRM_PWR_LOCAL
+        };
+
+        let payload = protocols::GbSvcIntfSetPwrmResponse::new(result_code);
+        self.send_response(hd, msg.header(), payload);
+
+        Ok(())
+    }
+
+    fn dme_peer_get(&self, hd: &hd::Device, hdr: &protocols::GbOperationMsgHdr) {
+        let payload = protocols::GbSvcDmePeerGetResponse::new(0, TOSHIBA_DMID);
+        self.send_response(hd, hdr, payload);
+    }
+
+    fn dme_peer_set(&self, hd: &hd::Device, hdr: &protocols::GbOperationMsgHdr) {
+        let payload = protocols::GbSvcDmePeerSetResponse::new(0);
+        self.send_response(hd, hdr, payload);
+    }
+
+    fn pwrmon_rail_count_get(&self, hd: &hd::Device, hdr: &protocols::GbOperationMsgHdr) {
+        let payload = protocols::GbSvcPwrmonRailCountGetResponse::new(0);
+        self.send_response(hd, hdr, payload);
+    }
+
+    fn intf_vsys_enable_disable(&self, hd: &hd::Device, hdr: &protocols::GbOperationMsgHdr) {
+        let payload = protocols::GbSvcIntfVsysResponse::new(protocols::GB_SVC_INTF_VSYS_OK);
+        self.send_response(hd, hdr, payload);
+    }
+
+    fn intf_refclk_enable_disable(&self, hd: &hd::Device, hdr: &protocols::GbOperationMsgHdr) {
+        let payload = protocols::GbSvcIntfRefclkResponse::new(protocols::GB_SVC_INTF_REFCLK_OK);
+        self.send_response(hd, hdr, payload);
+    }
+
+    fn intf_unipro_enable_disable(&self, hd: &hd::Device, hdr: &protocols::GbOperationMsgHdr) {
+        let payload = protocols::GbSvcIntfUniproResponse::new(protocols::GB_SVC_INTF_UNIPRO_OK);
+        self.send_response(hd, hdr, payload);
+    }
+
+    fn intf_activate(&self, hd: &hd::Device, msg: &greybus::Message) {
+        let payload = protocols::GbSvcIntfActivateResponse::new(
+            protocols::GB_SVC_OP_SUCCESS,
+            protocols::GB_SVC_INTF_TYPE_GREYBUS,
+        );
+
+        // TODO: Maybe call a callback?
+
+        self.send_response(hd, msg.header(), payload);
+    }
+
+    fn intf_resume(&self, hd: &hd::Device, msg: &greybus::Message) {
+        let payload = protocols::GbSvcIntfResumeResponse::new(protocols::GB_SVC_OP_SUCCESS);
+
+        // TODO: Maybe call a callback?
+
+        self.send_response(hd, msg.header(), payload);
+    }
+
+    fn conn_create(&self, hd: &hd::Device, msg: &greybus::Message) -> Result<()> {
+        // TODO: Evaluate if we need to add callback to InterfaceOps
+        self.send_response(hd, msg.header(), ());
+
+        Ok(())
+    }
+
+    fn conn_destroy(&self, hd: &hd::Device, msg: &greybus::Message) -> Result<()> {
+        // TODO: Evaluate if we need to add callback to InterfaceOps
+        self.send_response(hd, msg.header(), ());
+
+        Ok(())
+    }
+}
+
+struct GbHdDriver(Arc<Svc>);
+
+impl GbHdDriver {
+    fn svc_handler(&self, hd: &hd::Device, msg: &greybus::Message) -> Result<()> {
+        let hdr = msg.header();
+
+        if hdr.is_response() {
+            self.0.release_operation_id(hdr.operation_id());
+        }
+
+        if hdr.is_response() && hdr.result() != protocols::GB_OP_SUCCESS {
+            dev_err!(
+                hd.as_ref(),
+                "SVC request 0x{:02x} failed: {}\n",
+                hdr.request_type(),
+                hdr.result()
+            );
+
+            if matches!(
+                hdr.request_type(),
+                protocols::GB_SVC_TYPE_PROTOCOL_VERSION | protocols::GB_SVC_TYPE_SVC_HELLO
+            ) {
+                self.0.handshake.complete_all();
+            }
+
+            return Ok(());
+        }
+
+        match (hdr.is_response(), hdr.request_type()) {
+            (
+                false,
+                protocols::GB_SVC_TYPE_INTF_DEVICE_ID
+                | protocols::GB_SVC_TYPE_ROUTE_CREATE
+                | protocols::GB_SVC_TYPE_ROUTE_DESTROY
+                | protocols::GB_SVC_TYPE_PING,
+            ) => self.0.send_response(hd, hdr, ()),
+            (false, protocols::GB_SVC_TYPE_CONN_CREATE) => self.0.conn_create(hd, msg)?,
+            (false, protocols::GB_SVC_TYPE_CONN_DESTROY) => self.0.conn_destroy(hd, msg)?,
+            (false, protocols::GB_SVC_TYPE_DME_PEER_GET) => self.0.dme_peer_get(hd, hdr),
+            (false, protocols::GB_SVC_TYPE_DME_PEER_SET) => self.0.dme_peer_set(hd, hdr),
+            (false, protocols::GB_SVC_TYPE_INTF_SET_PWRM) => self.0.intf_set_pwrm(hd, msg)?,
+            (false, protocols::GB_SVC_TYPE_PWRMON_RAIL_COUNT_GET) => {
+                self.0.pwrmon_rail_count_get(hd, hdr)
+            }
+            (
+                false,
+                protocols::GB_SVC_TYPE_INTF_VSYS_ENABLE | protocols::GB_SVC_TYPE_INTF_VSYS_DISABLE,
+            ) => self.0.intf_vsys_enable_disable(hd, hdr),
+            (
+                false,
+                protocols::GB_SVC_TYPE_INTF_REFCLK_ENABLE
+                | protocols::GB_SVC_TYPE_INTF_REFCLK_DISABLE,
+            ) => self.0.intf_refclk_enable_disable(hd, hdr),
+            (
+                false,
+                protocols::GB_SVC_TYPE_INTF_UNIPRO_ENABLE
+                | protocols::GB_SVC_TYPE_INTF_UNIPRO_DISABLE,
+            ) => self.0.intf_unipro_enable_disable(hd, hdr),
+            (false, protocols::GB_SVC_TYPE_INTF_ACTIVATE) => self.0.intf_activate(hd, msg),
+            (false, protocols::GB_SVC_TYPE_INTF_RESUME) => self.0.intf_resume(hd, msg),
+            (true, protocols::GB_SVC_TYPE_PROTOCOL_VERSION) => {
+                if let Err(e) = self.0.send_svc_hello(hd) {
+                    dev_err!(hd.as_ref(), "Failed to send SVC Hello request: {e:?}\n");
+                    self.0.handshake.complete_all();
+                }
+            }
+            (true, protocols::GB_SVC_TYPE_SVC_HELLO) => {
+                let global_state = GlobalState::new(self.0.clone(), hd.into());
+                let _ = GLOBAL_STATE.lock().replace(global_state);
+                self.0.handshake.complete_all();
+            }
+            (
+                true,
+                protocols::GB_SVC_TYPE_MODULE_INSERTED | protocols::GB_SVC_TYPE_MODULE_REMOVED,
+            ) => {}
+            (false, ty) => {
+                dev_warn!(hd.as_ref(), "unsupported request 0x{:02x}\n", ty);
+                let rsp = Msg::response(hdr, protocols::GB_OP_PROTOCOL_BAD, ());
+                hd.data_rcvd(protocols::GB_SVC_CPORT_ID, rsp.as_bytes());
+            }
+            (true, ty) => dev_warn!(hd.as_ref(), "unexpected response 0x{:02x}\n", ty),
+        };
+
+        Ok(())
+    }
+}
+
+#[vtable]
+impl hd::HdDriver for GbHdDriver {
+    fn message_send(
+        data: &Self,
+        hd: &hd::Device,
+        dest_cport_id: u16,
+        msg: &greybus::Message,
+        gfp_mask: Flags,
+    ) -> Result {
+        if dest_cport_id == protocols::GB_SVC_CPORT_ID {
+            data.svc_handler(hd, msg)
+        } else {
+            let conn = msg.operation().connection();
+            let intf = data.0.intf_by_id(conn.interface().unwrap().id())?;
+
+            let mut buf = KVec::with_capacity(msg.header().size().into(), gfp_mask)?;
+
+            buf.extend_from_slice(msg.header().as_bytes(), gfp_mask)?;
+            buf.extend_from_slice(msg.payload_bytes(), gfp_mask)?;
+
+            intf.write(&buf, conn.intf_cport_id(), gfp_mask)
+        }
+    }
+
+    fn message_cancel(_msg: &greybus::Message) {}
+}
+
+struct GreybusSoftSvc {
+    _hd: hd::Registration<GbHdDriver>,
+    _faux: faux::Registration,
+}
+
+impl kernel::Module for GreybusSoftSvc {
+    fn init(_module: &'static ThisModule) -> Result<Self> {
+        pr_info!("gb_softsvc (init)\n");
+
+        // SAFETY: This runs once at module init, before anything else can reach `GLOBAL_STATE`.
+        unsafe { GLOBAL_STATE.init() };
+
+        let faux = faux::Registration::new(c_str!("gb-softsvc"), None)?;
+        let svc = Arc::pin_init(Svc::new(), GFP_KERNEL)?;
+        let data = GbHdDriver(svc.clone());
+
+        let dev = faux.as_ref().as_ref();
+        let hd = hd::Registration::new(dev, GB_OPERATION_SIZE_MAX, CPORT_ID_MAX + 1, Ok(data))?;
+
+        svc.send_version(hd.as_ref())?;
+
+        // The handshake runs on the SVC connection's workqueue. Wait for it, so `Module::new()`
+        // works as soon as this module is loaded, and no handshake work is left once it is.
+        svc.handshake.wait_for_completion();
+
+        if GLOBAL_STATE.lock().is_none() {
+            return Err(code::ENODEV);
+        }
+
+        Ok(GreybusSoftSvc {
+            _hd: hd,
+            _faux: faux,
+        })
+    }
+}
+
+impl Drop for GreybusSoftSvc {
+    fn drop(&mut self) {
+        let _ = GLOBAL_STATE.lock().take();
+        pr_info!("gb_softsvc (exit)\n");
+    }
+}
+
+/// The operations a Greybus interface provides.
+///
+/// A node is whatever sits behind an interface — a real transport, an in-kernel emulation, or
+/// anything else that can accept Greybus traffic. This module does not care which.
+pub trait InterfaceOps: Send + Sync {
+    /// Delivers `data` to the node's `cport`.
+    fn write(&self, data: &[u8], cport: u16, gfp_mask: Flags) -> Result<()>;
+}
+
+/// A module attached to the Greybus network.
+pub struct Module {
+    id: u8,
+    intf_count: u8,
+    gb_hd: ARef<hd::Device>,
+    svc: Arc<Svc>,
+}
+
+impl Module {
+    /// Attaches a new module made of `intfs` to the Greybus network.
+    ///
+    /// Dropping the returned [`Module`] removes it from the network.
+    pub fn new(intfs: &[Arc<dyn InterfaceOps>]) -> Result<Self> {
+        let Ok(intf_count) = u8::try_from(intfs.len()) else {
+            return Err(code::E2BIG);
+        };
+
+        if intf_count == 0 {
+            return Err(code::EINVAL);
+        }
+
+        let guard = GLOBAL_STATE.lock();
+        let state = guard.as_ref().ok_or(code::EAGAIN)?;
+        let id = state.svc.module_insert(&state.gb_hd, intfs)?;
+
+        Ok(Self {
+            id,
+            intf_count,
+            gb_hd: state.gb_hd.clone(),
+            svc: state.svc.clone(),
+        })
+    }
+
+    /// Delivers `msg`, received from interface `id` on its `cport`, to the Greybus core.
+    ///
+    /// `intf_id_rel` is the index of the interface within this module, e.g. 0, 1 or 2 for a
+    /// module with three interfaces. `cport` is the interface-side CPort id.
+    ///
+    /// Fails with `EINVAL` if `intf_id_rel` is out of range or no connection is bound to that
+    /// pair.
+    pub fn submit_message(&self, intf_id_rel: u8, cport: u16, msg: &[u8]) -> Result<()> {
+        if intf_id_rel >= self.intf_count {
+            return Err(code::EINVAL);
+        }
+
+        self.gb_hd
+            .data_rcvd_by_intf(self.id + intf_id_rel, cport, msg)
+    }
+}
+
+/// Dropping the module removes it from the Greybus core and waits for that to finish, so no
+/// [`InterfaceOps`] method of its interfaces runs after the drop returns.
+///
+/// This sleeps, and must not happen from within an [`InterfaceOps`] method.
+impl Drop for Module {
+    fn drop(&mut self) {
+        self.svc
+            .module_remove(&self.gb_hd, self.id, self.intf_count);
+    }
+}
diff --git a/drivers/greybus/gb_softsvc_exports.c b/drivers/greybus/gb_softsvc_exports.c
new file mode 100644
index 000000000000..a0e360c4d137
--- /dev/null
+++ b/drivers/greybus/gb_softsvc_exports.c
@@ -0,0 +1,15 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2026 BeagleBoard.org. All rights reserved.
+
+/*
+ * Exports Rust symbols from the `gb_softsvc` crate for use by dependent modules.
+ *
+ * This is a workaround until the build system supports Rust cross-module
+ * dependencies natively.
+ */
+
+#include <linux/export.h>
+
+#define EXPORT_SYMBOL_RUST_GPL(sym) extern int sym; EXPORT_SYMBOL_GPL(sym)
+
+#include "exports_gb_softsvc_generated.h"

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 8/9] dt-bindings: beagle: Add BeagleConnect Freedom
  2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
                   ` (6 preceding siblings ...)
  2026-12-04 10:30 ` [PATCH v6 7/9] drivers: greybus: Add software SVC implementation Ayush Singh
@ 2026-12-04 10:30 ` 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
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh, Conor Dooley

Add devicetree bindings for the BeagleBoard.org BeagleConnect Freedom,
a wireless-enabled board based on the TI CC1352P7. The board exposes an
MCU that can be attached to a host over USB, UART, SPI or I2C, and is
described as a child node of the corresponding bus.

Acked-by: Conor Dooley <conor.dooley@microchip.com>
Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 .../beagle/beagle,beagleconnect-freedom.yaml       | 62 ++++++++++++++++++++++
 MAINTAINERS                                        |  6 +++
 2 files changed, 68 insertions(+)

diff --git a/Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml b/Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
new file mode 100644
index 000000000000..81dfdace33e2
--- /dev/null
+++ b/Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
@@ -0,0 +1,62 @@
+# SPDX-License-Identifier: GPL-2.0-only OR BSD-2-Clause
+%YAML 1.2
+---
+$id: http://devicetree.org/schemas/beagle/beagle,beagleconnect-freedom.yaml#
+$schema: http://devicetree.org/meta-schemas/core.yaml#
+
+title: BeagleBoard.org BeagleConnect Freedom
+
+description:
+  The BeagleBoard.org BeagleConnect Freedom board connected over USB, UART, SPI or I2C.
+
+maintainers:
+  - Ayush Singh <ayush@beagleboard.org>
+
+properties:
+  compatible:
+    const: beagle,beagleconnect-freedom
+
+  reg:
+    maxItems: 1
+
+  vbat-supply: true
+
+required:
+  - compatible
+
+allOf:
+  - if:
+      required:
+        - reg
+    then:
+      $ref: /schemas/spi/spi-peripheral-props.yaml#
+    else:
+      $ref: /schemas/serial/serial-peripheral-props.yaml#
+
+      properties:
+        current-speed:
+          default: 115200
+
+unevaluatedProperties: false
+
+examples:
+  - |
+    serial {
+      mcu {
+        compatible = "beagle,beagleconnect-freedom";
+        vbat-supply = <&vbat>;
+      };
+    };
+
+  - |
+    spi {
+      #address-cells = <1>;
+      #size-cells = <0>;
+
+      mcu@0 {
+        compatible = "beagle,beagleconnect-freedom";
+        reg = <0>;
+        spi-max-frequency = <1000000>;
+        vbat-supply = <&vbat>;
+      };
+    };
diff --git a/MAINTAINERS b/MAINTAINERS
index a5399350a59e..9e6ae43ee311 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -11696,6 +11696,12 @@ L:	greybus-dev@lists.linaro.org (moderated for non-subscribers)
 S:	Maintained
 F:	drivers/greybus/gb_softsvc.rs
 
+GREYBUS UART NODE DRIVERS
+M:	Ayush Singh <ayush@beagleboard.org>
+L:	greybus-dev@lists.linaro.org (moderated for non-subscribers)
+S:	Maintained
+F:	Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
+
 GREYBUS SUBSYSTEM
 M:	Johan Hovold <johan@kernel.org>
 M:	Alex Elder <elder@kernel.org>

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* [PATCH v6 9/9] greybus: Add Rust UART node driver
  2026-12-04 10:30 [PATCH v6 0/9] Add Greybus Sotfsvc and UART Node drivers Ayush Singh
                   ` (7 preceding siblings ...)
  2026-12-04 10:30 ` [PATCH v6 8/9] dt-bindings: beagle: Add BeagleConnect Freedom Ayush Singh
@ 2026-12-04 10:30 ` Ayush Singh
  2026-12-04 11:18   ` sashiko-bot
  8 siblings, 1 reply; 18+ messages in thread
From: Ayush Singh @ 2026-12-04 10:30 UTC (permalink / raw)
  To: Jason Kridner, robertcnelson, Johan Hovold, Alex Elder,
	Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, Daniel Almeida, Tamir Duberstein,
	Alexandre Courbot, Onur Özkan, Eric Biggers, Ard Biesheuvel,
	Ayush Singh, Rob Herring, Krzysztof Kozlowski, Conor Dooley,
	Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
	Uladzislau Rezki, Markus Probst
  Cc: greybus-dev, linux-kernel, rust-for-linux, linux-crypto,
	devicetree, Ayush Singh

Add a driver for Greybus nodes attached over a plain serial port. The
node is registered with the software SVC (gb-softsvc), which handles the
SVC protocol on behalf of the AP, so no dedicated coprocessor running
SVC firmware is needed.

Greybus messages are carried over HDLC framing on the wire. Each frame
carries a one-byte address (0x01 for Greybus) and control byte, followed
by the 16-bit CPort ID and the Greybus message itself.

Port parameters are taken from the firmware node: "current-speed" if
present, otherwise 115200, with flow control and parity disabled.

Since gb-uart-node imports types from gb-softsvc, Rust to Rust calling
setup from nova-core [0] is being used.

[0]: https://lore.kernel.org/all/20260622-nova-exports-v5-0-6191773fc977@nvidia.com/

Signed-off-by: Ayush Singh <ayush@beagleboard.org>
---
 MAINTAINERS                     |   1 +
 drivers/greybus/.gitignore      |   1 +
 drivers/greybus/Kconfig         |  15 +++
 drivers/greybus/Makefile        |  10 ++
 drivers/greybus/gb_uart_node.rs | 270 ++++++++++++++++++++++++++++++++++++++++
 5 files changed, 297 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 9e6ae43ee311..11c0151663ff 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -11701,6 +11701,7 @@ M:	Ayush Singh <ayush@beagleboard.org>
 L:	greybus-dev@lists.linaro.org (moderated for non-subscribers)
 S:	Maintained
 F:	Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
+F:	drivers/greybus/gb_uart_node.rs
 
 GREYBUS SUBSYSTEM
 M:	Johan Hovold <johan@kernel.org>
diff --git a/drivers/greybus/.gitignore b/drivers/greybus/.gitignore
new file mode 100644
index 000000000000..ff9c4a3539b4
--- /dev/null
+++ b/drivers/greybus/.gitignore
@@ -0,0 +1 @@
+exports_gb_softsvc_generated.h
diff --git a/drivers/greybus/Kconfig b/drivers/greybus/Kconfig
index 709563f8c0ad..ce2030161f30 100644
--- a/drivers/greybus/Kconfig
+++ b/drivers/greybus/Kconfig
@@ -61,5 +61,20 @@ config GREYBUS_SOFTSVC
 	  To compile this code as a module, choose M here: the module
 	  will be called gb-softsvc.ko
 
+config GREYBUS_UART_NODE
+	tristate "Greybus UART node transport"
+	depends on GREYBUS_SOFTSVC
+	depends on RUST_SERIAL_DEV_BUS_ABSTRACTIONS
+	depends on RUST_GREYBUS_ABSTRACTIONS
+	select RUST_CRC_CCITT_ABSTRACTIONS
+	help
+	  Select this option if you have a Greybus node connected over a
+	  serial port. The node is registered with the software SVC, which
+	  handles the SVC protocol on behalf of the AP, so no dedicated
+	  coprocessor running SVC firmware is required.
+
+	  To compile this code as a module, choose M here: the module
+	  will be called gb-uart-node.ko
+
 endif	# GREYBUS
 
diff --git a/drivers/greybus/Makefile b/drivers/greybus/Makefile
index 0fa802fdf6ca..023f59c11e65 100644
--- a/drivers/greybus/Makefile
+++ b/drivers/greybus/Makefile
@@ -28,6 +28,12 @@ obj-$(CONFIG_GREYBUS_ES2)	+= gb-es2.o
 obj-$(CONFIG_GREYBUS_SOFTSVC)	+= gb-softsvc.o
 gb-softsvc-y			+= gb_softsvc.o gb_softsvc_exports.o
 
+obj-$(CONFIG_GREYBUS_UART_NODE)	+= gb-uart-node.o
+gb-uart-node-y			+= gb_uart_node.o
+
+# Export Rust symbols from gb-softsvc only if gb-uart-node actually references them.
+gb-softsvc-export-deps := $(if $(CONFIG_GREYBUS_UART_NODE),$(obj)/gb_uart_node.o)
+
 rust_needed_exports = \
 	{ $(if $(strip $(2)),$(NM) -u $(2);,) echo "__DEFINED_RUST_SYMBOLS__"; \
 	  $(NM) -p --defined-only $(1); } | \
@@ -66,3 +72,7 @@ endif
 # Output gb_softsvc's crate metadata for use by gb_uart_node at compile time.
 RUSTFLAGS_gb_softsvc.o += \
 	--emit=metadata=$(objtree)/$(obj)/libgb_softsvc.rmeta
+
+# Allow gb_uart_node to import gb_softsvc's types.
+$(obj)/gb_uart_node.o: $(obj)/gb_softsvc.o
+RUSTFLAGS_gb_uart_node.o := -L $(objtree)/$(obj) --extern gb_softsvc
diff --git a/drivers/greybus/gb_uart_node.rs b/drivers/greybus/gb_uart_node.rs
new file mode 100644
index 000000000000..b38e776c3e85
--- /dev/null
+++ b/drivers/greybus/gb_uart_node.rs
@@ -0,0 +1,270 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Greybus UART Node driver
+
+use kernel::{
+    alloc::Flags,
+    crc_ccitt::crc_ccitt,
+    device::{
+        AsBusDevice,
+        Bound,
+        Core, //
+    },
+    error::code,
+    new_spinlock,
+    of, //
+    prelude::*,
+    serdev,
+    sync::{
+        aref::ARef,
+        Arc,
+        SpinLock, //
+    },
+};
+
+use zerocopy::little_endian;
+use zerocopy_derive::{
+    FromBytes,
+    Immutable,
+    KnownLayout, //
+};
+
+/// Most greybus implementations will have a limit on greybus message length. The theoretical limit
+/// is [`u16::MAX`], but the real limits are much more modest. 256 seems to be the limit I use on
+/// most of my peers, but let's use 512 to be on safe side in kernel. The only real big request that
+/// I frequently encounter is manifest_get. However, if camera protocol ends up being supported at
+/// some point, this might need to be increased.
+const HDLC_MAX_FRAME_LEN: usize = 512;
+const HDLC_FRAME_HEADER_LEN: usize =
+    2 * size_of_val(&HDLC_FRAME) + 2 * size_of::<u16>() + 2 * size_of::<u8>();
+const HDLC_MAX_MSG_LEN: usize = HDLC_MAX_FRAME_LEN - HDLC_FRAME_HEADER_LEN;
+
+const HDLC_FRAME: u8 = 0x7E;
+const HDLC_ESC: u8 = 0x7D;
+const HDLC_XOR: u8 = 0x20;
+const HDLC_EXPECTED_CRC: u16 = 0xf0b8;
+
+const ADDRESS_GREYBUS: u8 = 0x01;
+
+#[repr(C, packed)]
+#[derive(FromBytes, Immutable, KnownLayout)]
+struct GreybusFrame {
+    cport: little_endian::U16,
+    msg: [u8],
+}
+
+struct HdlcRx {
+    rx_buf: KVec<u8>,
+    rx_in_esc: bool,
+    rx_overflow: bool,
+    sdev: ARef<serdev::Device>,
+    node: gb_softsvc::Module,
+}
+
+impl HdlcRx {
+    fn new(sdev: ARef<serdev::Device>, node: gb_softsvc::Module) -> Result<Self> {
+        Ok(Self {
+            node,
+            sdev,
+            rx_buf: KVec::with_capacity(HDLC_MAX_FRAME_LEN, GFP_KERNEL)?,
+            rx_in_esc: false,
+            rx_overflow: false,
+        })
+    }
+
+    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(());
+        }
+
+        let addr = self.rx_buf[0];
+        let _ctrl = self.rx_buf[1];
+        let payload = &self.rx_buf[2..self.rx_buf.len() - size_of::<u16>()];
+
+        match addr {
+            ADDRESS_GREYBUS => {
+                let frame = GreybusFrame::ref_from_bytes(payload).map_err(|_| code::EINVAL)?;
+                self.node.submit_message(0, frame.cport.into(), &frame.msg)
+            }
+            _ => Err(code::EINVAL),
+        }
+    }
+
+    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,
+                // 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();
+                    }
+                }
+            }
+        }
+
+        data.len()
+    }
+}
+
+struct GbNode {
+    sdev: ARef<serdev::Device>,
+}
+
+impl GbNode {
+    const fn new(sdev: ARef<serdev::Device>) -> Self {
+        Self { sdev }
+    }
+
+    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)
+    }
+}
+
+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()) };
+
+        // Drop messages which are bigger than what is supported.
+        if data.len() > HDLC_MAX_MSG_LEN {
+            return Err(code::E2BIG);
+        }
+
+        let mut buf = KVec::with_capacity(HDLC_MAX_FRAME_LEN, gfp_mask)?;
+
+        let mut crc = 0xffff;
+
+        buf.push_within_capacity(HDLC_FRAME)
+            .map_err(|_| code::E2BIG)?;
+
+        crc = Self::fill_buf(crc, &[ADDRESS_GREYBUS, 0x03], &mut buf)?;
+        crc = Self::fill_buf(crc, &cport.to_le_bytes(), &mut buf)?;
+        crc = Self::fill_buf(crc, data, &mut buf)?;
+
+        crc ^= 0xffff;
+        Self::fill_buf(crc, &crc.to_le_bytes(), &mut buf)?;
+
+        buf.push_within_capacity(HDLC_FRAME)
+            .map_err(|_| code::E2BIG)?;
+
+        // 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);
+        }
+
+        Ok(())
+    }
+}
+
+#[pin_data]
+struct GbUartNode {
+    #[pin]
+    rx: SpinLock<HdlcRx>,
+}
+
+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)?;
+
+        let node = gb_softsvc::Module::new(&[Arc::new(GbNode::new(sdev.into()), GFP_KERNEL)?])?;
+
+        HdlcRx::new(sdev.into(), node)
+    }
+}
+
+kernel::of_device_table!(
+    OF_TABLE,
+    <GbUartNode as serdev::Driver>::IdInfo,
+    [(of::DeviceId::new(c"beagle,beagleconnect-freedom"), ())]
+);
+
+#[vtable]
+impl serdev::Driver for GbUartNode {
+    type IdInfo = ();
+    type Data<'bound> = Self;
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
+
+    fn probe<'bound>(
+        sdev: &'bound serdev::Device<Core<'_>>,
+        _info: Option<&'bound Self::IdInfo>,
+    ) -> impl PinInit<Self, Error> + 'bound {
+        dev_dbg!(sdev.as_ref(), "Probe gb_uart_node.\n");
+
+        try_pin_init!(Self {
+            rx <- new_spinlock!(Self::init(sdev)?, "gb_uart_node::rx"),
+        }? Error)
+    }
+
+    fn receive<'bound>(
+        _sdev: &'bound serdev::Device<Bound>,
+        this: Pin<&Self>,
+        data: &[u8],
+    ) -> usize {
+        if let Some(mut guard) = this.rx.try_lock() {
+            return guard.rx(data);
+        }
+
+        0
+    }
+}
+
+kernel::module_serdev_device_driver! {
+    type: GbUartNode,
+    name: "gb_uart_node",
+    authors: ["Ayush Singh <ayush@beagleboard.org>"],
+    description: "Greybus node connected over UART",
+    license: "GPL v2",
+}

-- 
2.56.1


^ permalink raw reply related	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 3/9] greybus: svc: add gb_svc_flush()
  2026-12-04 10:30 ` [PATCH v6 3/9] greybus: svc: add gb_svc_flush() Ayush Singh
@ 2026-12-04 10:43   ` sashiko-bot
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 10:43 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] greybus: svc: missing context and locking docs for
  gb_svc_flush()
--

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

greybus: svc: add gb_svc_flush()

This commit adds and exports gb_svc_flush() so host drivers acting as
their own SVC can wait for all received SVC requests to finish processing
by flushing svc->connection->wq and then svc->wq.

> diff --git a/drivers/greybus/svc.c b/drivers/greybus/svc.c
> index 490577731a190..788d95b4b87b8 100644
> --- a/drivers/greybus/svc.c
> +++ b/drivers/greybus/svc.c
> @@ -1381,6 +1381,20 @@ static void gb_svc_remove_modules(struct gb_svc *svc)
>  	}
>  }
>  
> +/**
> + * gb_svc_flush - wait for received SVC requests to be processed
> + * @svc: the SVC
> + *
> + * Requests pass through the connection workqueue on their way to svc->wq, so
> + * both have to be flushed, in this order.
> + */
> +void gb_svc_flush(struct gb_svc *svc)
> +{
> +	flush_workqueue(svc->connection->wq);
> +	flush_workqueue(svc->wq);
> +}
> +EXPORT_SYMBOL_GPL(gb_svc_flush);

[Severity: Low]
Should this kernel-doc document the calling context and locking constraints
for gb_svc_flush()?

Because it calls flush_workqueue(), it may sleep and requires process
context.  Draining svc->connection->wq and svc->wq also runs handlers that
invoke message_send and wait for SVC responses, so calling gb_svc_flush()
from those paths or while holding a lock taken by message_send deadlocks.

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 4/9] greybus: connection: Add greybus_data_rcvd_by_intf()
  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
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 10:52 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree

Thank you for your contribution! Sashiko AI review found 2 potential
issues to consider:
- [High] greybus: UAF of connection->intf in
  gb_connection_hd_find_by_intf()
- [Low] greybus: inaccurate SVC rationale for new
  greybus_data_rcvd_by_intf() API
--

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

greybus: connection: Add greybus_data_rcvd_by_intf()

This commit adds gb_connection_hd_find_by_intf() and exports
greybus_data_rcvd_by_intf() to deliver incoming Greybus data by interface
id and interface CPort id instead of host CPort id.

> diff --git a/drivers/greybus/connection.c b/drivers/greybus/connection.c
> index bd04485decb3d..ce8646299ce8c 100644
> --- a/drivers/greybus/connection.c
> +++ b/drivers/greybus/connection.c
> @@ -69,6 +69,32 @@ gb_connection_hd_find(struct gb_host_device *hd, u16 cport_id)
>  	return connection;
>  }
>  
> +/*
> + * Returns a reference-counted pointer to the connection if found.
> + */
> +static struct gb_connection *
> +gb_connection_hd_find_by_intf(struct gb_host_device *hd, u8 intf_id,
> +			      u16 intf_cport)
> +{
> +	struct gb_connection *connection;
> +	unsigned long flags;
> +
> +	spin_lock_irqsave(&gb_connections_lock, flags);
> +	list_for_each_entry(connection, &hd->connections, hd_links) {
> +		if (connection->intf &&
> +		    connection->intf->interface_id == intf_id &&
> +		    connection->intf_cport_id == intf_cport) {

[Severity: High]
Can dereferencing connection->intf->interface_id trigger a use-after-free
of struct gb_interface?

Neither _gb_connection_create() nor gb_control_create() takes a reference
on intf->dev, and control->connection is only unlinked from hd->connections
in gb_control_release().

During module removal, gb_control_del() drops control->dev's parent
reference to intf->dev via device_del().  If a bus or PM iterator still
holds control->dev (or CONFIG_DEBUG_KOBJECT_RELEASE delays release),
gb_interface_release() can free intf while control->connection stays listed:

CPU0                                  CPU1
gb_interface_disable()
  gb_control_del()
    device_del(&control->dev)
      put_device(&intf->dev)
  gb_control_put() [held by bus/PM]
gb_interface_release()
  kfree(intf)
                                      greybus_data_rcvd_by_intf()
                                        gb_connection_hd_find_by_intf()
                                          connection->intf->interface_id
                                            <-- use-after-free

Any incoming frame on the shared host device then reads freed memory under
gb_connections_lock with IRQs disabled.  Caching interface_id in struct
gb_connection at creation time (or holding a reference on intf->dev for
the connection's lifetime) would avoid dereferencing a freed gb_interface.

[ ... ]

> @@ -91,6 +117,27 @@ void greybus_data_rcvd(struct gb_host_device *hd, u16 cport_id,
>  }
>  EXPORT_SYMBOL_GPL(greybus_data_rcvd);
>  
> +/*
> + * Callback from a host driver that only knows the remote end of a connection
> + * (interface id and interface CPort id), such as a software SVC.
> + */
> +int greybus_data_rcvd_by_intf(struct gb_host_device *hd, u8 intf_id,
> +			      u16 intf_cport, u8 *data, size_t length)

[Severity: Low]
Is this new exported RX entry point needed for a software SVC, and is the
rationale in the comment and commit message accurate?

For every non-static connection, gb_connection_svc_connection_create()
sends both hd_cport_id and (interface_id, intf_cport_id) to the SVC via
GB_SVC_TYPE_CONN_CREATE, and gb_connection_svc_connection_destroy() pairs
it with GB_SVC_TYPE_CONN_DESTROY.

On TX, gb_message_send() also passes hd_cport_id to message_send().  A
software SVC that tracks its connection table can deliver data through the
existing greybus_data_rcvd() instead of adding a duplicate exported helper.

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 2/9] greybus: operation: arm request timeout before sending
  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
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 10:52 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [High] greybus: operation: UAF and refcount underflow on timeout
  during send error
- [High] greybus: operation: early timeout cancels message before host
  send submits
- [Low] greybus: operation: missing Fixes trailer for timer-arming race
  fix
--

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

> greybus: operation: arm request timeout before sending
>
> The host driver can complete a request before add_timer is called. The
> main case for this is softsvc, although, depending on which transport
> is used, there is a possibility that response arrives much faster than
> expected.
>
> By populating timer earilier, we prevent the starting a timer on
> already completed request (which would then leak an active timer on cleanup).
>
> Signed-off-by: Ayush Singh <ayush@beagleboard.org>

[Severity: Low]
This fixes the timer-arming race introduced with generic operation
timeouts.  Should this include:

  Fixes: dbec27298b0d ("staging: greybus: operation: add generic timeout support")

> diff --git a/drivers/greybus/operation.c b/drivers/greybus/operation.c
> index a9eada39ec793..cac3b0abf62bc 100644
> --- a/drivers/greybus/operation.c
> +++ b/drivers/greybus/operation.c
> @@ -786,18 +786,23 @@ int gb_operation_request_send(struct gb_operation *operation,
>  	if (ret)
>  		goto err_put;
>  
> -	ret = gb_message_send(operation->request, gfp);
> -	if (ret)
> -		goto err_put_active;
> -
> +	/*
> +	 * Arm the timeout before sending: the response can arrive, and the
> +	 * operation complete, before the host driver returns.
> +	 */
>  	if (timeout) {
>  		operation->timer.expires = jiffies + msecs_to_jiffies(timeout);
>  		add_timer(&operation->timer);
>  	}
>  
> +	ret = gb_message_send(operation->request, gfp);
> +	if (ret)
> +		goto err_put_active;

[Severity: High]
Can an early timeout call gb_message_cancel() before the host driver has
finished submitting the request?

If the sender sleeps or is preempted inside gb_message_send() (for
example, in drivers/greybus/es2.c:message_send() between assigning
message->hcpriv and calling usb_submit_urb()), operation->timer can
expire and queue gb_operation_work() before submission completes:

CPU0                                kworker
gb_operation_request_send()
  add_timer(&operation->timer)
  gb_message_send()
    ... es2:message_send()
    message->hcpriv = urb
    usb_fill_bulk_urb(urb, ...)
                                    <timer expires>
                                    gb_operation_timeout()
                                      gb_operation_result_set(-ETIMEDOUT)
                                      queue_work(&operation->work)
                                    gb_operation_work()
                                      gb_message_cancel()
                                        ... es2:message_cancel()
                                        usb_kill_urb(urb)  <-- data race
    usb_submit_urb(urb, ...)  <-- submits timed-out URB

In es2.c, usb_kill_urb() either returns as a no-op when message->hcpriv
is still NULL or races with usb_fill_bulk_urb() on struct urb fields,
allowing the timed-out URB to be submitted afterward.  If that URB
stalls, gb_operation_cancel() during connection teardown sees
operation->errno is already -ETIMEDOUT, skips gb_message_cancel(), and
blocks forever in wait_event().

>  	return 0;
>  
>  err_put_active:
> +	timer_delete_sync(&operation->timer);
>  	gb_operation_put_active(operation);
>  	gb_operation_put_active(operation);
>  err_put:

[Severity: High]
Can err_put_active cause a use-after-free and refcount underflow when
operation->timer expires before gb_message_send() returns an error?

In drivers/greybus/gb-beagleplay.c, hdlc_tx_frames() can sleep up to 1.5
to 2.5 seconds waiting for TX ring space before returning -EAGAIN,
exceeding GB_OPERATION_TIMEOUT_DEFAULT (1000 ms).  When the timer fires
during that window, gb_operation_timeout() queues operation->work, and
timer_delete_sync() returns 0 without cancelling the queued work:

CPU0                              kworker
gb_operation_request_send()
  gb_operation_get() x2
  __gb_operation_get_active(2)
  add_timer(&operation->timer)
  gb_message_send()
    ... hdlc_tx_frames() sleeps
                                  <timer expires>
                                  gb_operation_timeout()
                                    gb_operation_result_set(-ETIMEDOUT)
                                    queue_work(&operation->work)
    returns -EAGAIN
  err_put_active:
    timer_delete_sync() -> 0
    gb_operation_put_active() x2
    gb_operation_put() x2
  caller drops final ref -> free
                                  gb_operation_work()
                                    operation->callback()  <-- use-after-free
                                    gb_operation_put_active()  <-- underflow
                                    gb_operation_put()

Three active-count puts and three kref puts then run against only two
acquisitions, freeing operation while operation->work is still queued or
underflowing operation->active to -1.  Because operation->callback()
also runs despite the error return, callers like
gb_loopback_async_operation() double free op_async and drop an extra
operation reference.

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 1/9] greybus: operation: keep request active across message_send
  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
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 10:55 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree

Thank you for your contribution! Sashiko AI review found 6 potential
issues to consider:
- [High] greybus: double put on gb_message_send() error races with
  cancellation
- [Medium] greybus: gb_operation_cancel() skips gb_message_cancel() on
  set result
- [Medium] greybus: commit message and greybus_message_sent() comment
  are stale
- [Low] greybus: commit message is missing Fixes trailer for teardown
  bug fix
- [Low] greybus: open-coded connection->lock in
  gb_operation_request_send()
- [Low] greybus: missing Fixes trailer for teardown active-count race
  fix
--

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

> greybus: operation: keep request active across message_send
>
> gb_operation_request_send() takes a single active count, and completion
> drops it. This would be fine normally, but in case of cancellation (in
> gb_softsvc context, this would happen in module_removed), completion
> (gb_operation_work), can drop the active count, while message_send is
> running.
> The core does call message_cancel before dropping the active count,
> but in most normal circumstances, cancelling an operation that is
> already writing over a protocol (UART) is not really possible. So we
> are only left with making the core wait for the said write to complete
> instead of making active count 0 while message_send is in progress.
> The patch takes a second reference and active count before the send
> and drop them once it returns. If the connection starts tearing down
> between the two calls, return 0 and let the cancel complete the
> operation.
> Since it took at least me a while to truely understand what the initial
> sashiko-bot report meant, here is an example:
>        Thread A                     Thread B + worker                  active
>        ------------------------     ------------------------------     ------
>   1    get_active()                                                      1
>   2    gb_message_send()
>   3      GbNode::write() ...
>   4      ... blocked                state = DISCONNECTING
>   5      ... blocked                gb_operation_cancel()
>   6      ... blocked                  result_set(-ESHUTDOWN)
>   7      ... blocked                  queue_work(completion)
>   8      ... blocked                  wait_event(!active)  [sleeps]
>   9      ... blocked                [worker] gb_operation_work()
>  10      ... blocked                [worker]   put_active()   [:292]     0
>  11      ... blocked                  wait_event wakes, returns       <- too early
>  12      ... blocked                gb_module_del() returns
>  13      ... blocked                [softsvc] Module::drop finishes
>  14      ... blocked                serdev port closed, unbind done   <- bad
>  15      write() returns
>  16    return to caller
>
> This patch simply takes an extra active count when calling
> gb_message_send. in core. It also treats both requests and response
> the same, i.e. clear an active count when gb_message_sent() is
> called. Earlier, this was only being done for responses.
>
> Signed-off-by: Ayush Singh <ayush@beagleboard.org>

[Severity: Medium]
Does the third paragraph of the commit message match the actual code?

It says the patch drops the second reference and active count once
gb_message_send() returns and returns 0 if the connection starts tearing down
between the two calls.  The implementation instead acquires both active counts
atomically under one connection->lock via __gb_operation_get_active() and
drops the second count in greybus_message_sent(), which runs asynchronously
for drivers such as es2.

The final paragraph also misspells greybus_message_sent() as gb_message_sent()
and has a stray period in "gb_message_send. in core.".  In addition, the
comment in greybus_message_sent() keeps the obsolete response-only paragraph
directly above the new unified description.

[Severity: Low]
This fixes a connection teardown active-count race introduced when
per-connection active-operation tracking was added.  Should this include:

  Fixes: 008974cb528d ("greybus: operation: fix connection tear down")

> diff --git a/drivers/greybus/operation.c b/drivers/greybus/operation.c
> index 7e12ffb2dd60d..a9eada39ec793 100644
> --- a/drivers/greybus/operation.c
> +++ b/drivers/greybus/operation.c

[ ... ]

> @@ -758,11 +772,17 @@ int gb_operation_request_send(struct gb_operation *operation,
>  	gb_operation_result_set(operation, -EINPROGRESS);
>  
>  	/*
> -	 * Get an extra reference on the operation. It'll be dropped when the
> -	 * operation completes.
> +	 * Take two references and active counts. One is dropped when the
> +	 * operation completes, the other when the host driver is done with the
> +	 * request, so that cancelling the operation waits for both. Take both
> +	 * counts under one lock, so the operation can't be cancelled in between.
>  	 */
>  	gb_operation_get(operation);
> -	ret = gb_operation_get_active(operation);
> +	gb_operation_get(operation);
> +
> +	spin_lock_irqsave(&connection->lock, flags);
> +	ret = __gb_operation_get_active(operation, 2);
> +	spin_unlock_irqrestore(&connection->lock, flags);
>  	if (ret)
>  		goto err_put;

[Severity: Low]
This isn't a bug, but __gb_operation_get_active() is only called from
gb_operation_get_active() and here, and no other work is done under
connection->lock.  Having a locked helper take the count argument would avoid
open-coding spin_lock_irqsave()/spin_unlock_irqrestore() in
gb_operation_request_send().

[ ... ]

> @@ -779,8 +799,10 @@ int gb_operation_request_send(struct gb_operation *operation,
>  
>  err_put_active:
>  	gb_operation_put_active(operation);
> +	gb_operation_put_active(operation);
>  err_put:
>  	gb_operation_put(operation);
> +	gb_operation_put(operation);
>  
>  	return ret;
>  }

[Severity: High]
Can err_put_active underflow operation->active and double-put operation if
gb_operation_cancel() runs while a failing gb_message_send() is in progress?

While gb_message_send() is sleeping (for example in hdlc_tx_frames() in
drivers/greybus/gb-beagleplay.c before returning an error), connection
teardown can cancel the operation and queue gb_operation_work():

CPU0                      CPU1                        kworker
gb_operation_request_send()
  __gb_operation_get_active(..., 2)
  gb_message_send()
                            gb_operation_cancel()
                              result_set(-ESHUTDOWN)
                              queue_work(&op->work)
                              wait_event(!is_active)
                                                      gb_operation_work()
                                                        op->callback(op)
                                                        put_active() [2->1]
                                                        put()
  /* returns error */
  err_put_active:
    put_active() [1->0]
    put_active() [0->-1]  <-- active underflow
    put()
    put()                 <-- extra put / use-after-free

Because gb_operation_is_active() converts signed int operation->active to
bool, -1 stays true permanently and gb_operation_cancel() hangs in
wait_event() while holding connection->mutex.  The extra gb_operation_put()
causes a use-after-free on operation, and returning non-zero after
operation->callback() has already run causes async callers such as
gb_loopback_async_operation() to double free op_async and underflow
outstanding_operations.

Even if cancellation does not race during gb_message_send(), calling
gb_operation_put_active() twice in separate lock sections leaves operation on
connection->operations with active == 1 in between.  If gb_operation_work()
runs after err_put_active instead of before, operation can also be freed while
operation->work is still queued.

On gb_message_send() failure, calling gb_operation_result_set(operation, ret)
can arbitrate completion ownership: if it returns true, drop both active
counts under one connection->lock and both krefs and return ret; otherwise
drop only the host driver's active count and kref and return 0.

[ ... ]

> @@ -892,15 +917,15 @@ void greybus_message_sent(struct gb_host_device *hd,
>  				"%s: error sending response 0x%02x: %d\n",
>  				connection->name, operation->type, status);
>  		}
> -
> -		gb_operation_put_active(operation);
> -		gb_operation_put(operation);
>  	} else if (status || gb_operation_is_unidirectional(operation)) {
>  		if (gb_operation_result_set(operation, status)) {
>  			queue_work(gb_operation_completion_wq,
>  				   &operation->work);
>  		}
>  	}
> +
> +	gb_operation_put_active(operation);
> +	gb_operation_put(operation);
>  }

[Severity: Medium]
Now that greybus_message_sent() drops the second active count for outgoing
requests, can gb_operation_cancel() hang if operation->errno was already set
before teardown?

With an async host driver such as es2, if gb_connection_recv_response() sets a
non-ETIMEDOUT result before the bulk-OUT URB completes, gb_operation_work()
does not cancel the request message and drops operation->active from 2 to 1.
A subsequent gb_operation_cancel() then skips gb_message_cancel():

drivers/greybus/operation.c:gb_operation_cancel() {
	...
	if (gb_operation_result_set(operation, errno)) {
		gb_message_cancel(operation->request);
		queue_work(gb_operation_completion_wq, &operation->work);
	}
	trace_gb_message_cancel_outgoing(operation->request);

	atomic_inc(&operation->waiters);
	wait_event(gb_operation_cancellation_queue,
		   !gb_operation_is_active(operation));
	...
}

If the bulk-OUT URB is stalled, greybus_message_sent() never runs and
teardown blocks indefinitely in wait_event() while holding connection->mutex,
unlike gb_operation_cancel_incoming() which cancels the message even when
gb_operation_result_set() returns false.

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 8/9] dt-bindings: beagle: Add BeagleConnect Freedom
  2026-12-04 10:30 ` [PATCH v6 8/9] dt-bindings: beagle: Add BeagleConnect Freedom Ayush Singh
@ 2026-12-04 11:03   ` sashiko-bot
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 11:03 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree, Conor Dooley

Thank you for your contribution! Sashiko AI review found 3 potential
issues to consider:
- [Medium] dt-bindings: beagle: compatible const conflicts with
  usb-device.yaml
- [Low] dt-bindings: beagle: DTS examples use 2-space indent failing
  dt-check-style
- [Low] MAINTAINERS: GREYBUS UART NODE DRIVERS inserted out of
  alphabetical order
--

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

dt-bindings: beagle: Add BeagleConnect Freedom

This commit adds a devicetree binding schema for the BeagleBoard.org
BeagleConnect Freedom board and creates a MAINTAINERS entry for it.

> diff --git a/Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml b/Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
> new file mode 100644
> index 0000000000000..81dfdace33e25
> --- /dev/null
> +++ b/Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
> @@ -0,0 +1,62 @@

[ ... ]

> +description:
> +  The BeagleBoard.org BeagleConnect Freedom board connected over USB, UART, SPI or I2C.

[ ... ]

> +properties:
> +  compatible:
> +    const: beagle,beagleconnect-freedom

[ ... ]

> +allOf:
> +  - if:
> +      required:
> +        - reg
> +    then:
> +      $ref: /schemas/spi/spi-peripheral-props.yaml#
> +    else:
> +      $ref: /schemas/serial/serial-peripheral-props.yaml#
> +
> +      properties:
> +        current-speed:
> +          default: 115200
> +
> +unevaluatedProperties: false

[Severity: Medium]
Can a USB-attached BeagleConnect Freedom node pass dtbs_check with this
schema?

Hardwired USB child nodes carry a port reg property, so usb-hcd.yaml and
usb-hub.yaml validate them against usb-device.yaml, which requires a
usbVID,PID compatible.  That conflicts with the single const compatible
here, so no USB child node can satisfy both schemas.

The allOf block also omits /schemas/usb/usb-device.yaml#, so
unevaluatedProperties: false rejects USB properties such as #address-cells,
#size-cells, and interface subnodes.  Either allow a usbVID,PID compatible
and reference usb-device.yaml, or remove USB from the docs and commit text.

> +
> +examples:
> +  - |
> +    serial {
> +      mcu {
> +        compatible = "beagle,beagleconnect-freedom";
> +        vbat-supply = <&vbat>;
> +      };
> +    };
> +
> +  - |
> +    spi {
> +      #address-cells = <1>;
> +      #size-cells = <0>;
> +
> +      mcu@0 {
> +        compatible = "beagle,beagleconnect-freedom";
> +        reg = <0>;
> +        spi-max-frequency = <1000000>;
> +        vbat-supply = <&vbat>;
> +      };
> +    };

[Severity: Low]
Both DTS examples use 2-space indentation per nesting level instead of
4 spaces, which fails scripts/dtc/dt-check-style in strict mode
(indent-unit-strict).

> diff --git a/MAINTAINERS b/MAINTAINERS
> index a5399350a59e4..9e6ae43ee311e 100644
> --- a/MAINTAINERS
> +++ b/MAINTAINERS
> @@ -11696,6 +11696,12 @@ L:	greybus-dev@lists.linaro.org (moderated for non-subscribers)
>  S:	Maintained
>  F:	drivers/greybus/gb_softsvc.rs
>  
> +GREYBUS UART NODE DRIVERS
> +M:	Ayush Singh <ayush@beagleboard.org>
> +L:	greybus-dev@lists.linaro.org (moderated for non-subscribers)
> +S:	Maintained
> +F:	Documentation/devicetree/bindings/beagle/beagle,beagleconnect-freedom.yaml
> +
>  GREYBUS SUBSYSTEM
>  M:	Johan Hovold <johan@kernel.org>
>  M:	Alex Elder <elder@kernel.org>

[Severity: Low]
This new entry is out of alphabetical order: it is placed before
GREYBUS SUBSYSTEM instead of between GREYBUS SUBSYSTEM and
GREYBUS UART PROTOCOLS DRIVERS.

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 6/9] rust: kernel: Add greybus abstractions
  2026-12-04 10:30 ` [PATCH v6 6/9] rust: kernel: Add greybus abstractions Ayush Singh
@ 2026-12-04 11:06   ` sashiko-bot
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 11:06 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 7/9] drivers: greybus: Add software SVC implementation
  2026-12-04 10:30 ` [PATCH v6 7/9] drivers: greybus: Add software SVC implementation Ayush Singh
@ 2026-12-04 11:07   ` sashiko-bot
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 11:07 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree

Thank you for your contribution! Sashiko AI review found 8 potential
issues to consider:
- [High] greybus: double active/kref put in gb_operation_request_send()
  on send error
- [Medium] greybus: gb_softsvc: missing greybus_disabled() check in
  GreybusSoftSvc::init()
- [Medium] greybus: gb_softsvc: unbounded wait_for_completion() hangs
  GreybusSoftSvc::init()
- [Medium] greybus: gb_softsvc: Svc::module_remove() frees IDs when
  MODULE_REMOVED fails
- [Medium] greybus: permanent operation ID leak in Svc::send_request()
- [Medium] greybus: redundant order-4 KVec allocation and copy in
  message_send()
- [Medium] greybus: Module::new() can lock uninitialized GLOBAL_STATE
  mutex
- [Low] greybus: MAINTAINERS entry omits
  drivers/greybus/gb_softsvc_exports.c
--

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

drivers: greybus: Add software SVC implementation

This commit adds the gb-softsvc Rust module, which implements an in-kernel
software Greybus SVC and registers a Greybus host device for transports
without a hardware SVC.

> diff --git a/MAINTAINERS b/MAINTAINERS
> index 6791104ed3ee4..a5399350a59e4 100644
> --- a/MAINTAINERS
> +++ b/MAINTAINERS
> @@ -11690,6 +11690,12 @@ S:	Maintained
>  F:	Documentation/devicetree/bindings/net/ti,cc1352p7.yaml
>  F:	drivers/greybus/gb-beagleplay.c
>  
> +GREYBUS SOFTSVC DRIVERS
> +M:	Ayush Singh <ayush@beagleboard.org>
> +L:	greybus-dev@lists.linaro.org (moderated for non-subscribers)
> +S:	Maintained
> +F:	drivers/greybus/gb_softsvc.rs
> +

[Severity: Low]
Should this entry also list drivers/greybus/gb_softsvc_exports.c, which is
added in this patch to build gb-softsvc?

[ ... ]

> diff --git a/drivers/greybus/gb_softsvc.rs b/drivers/greybus/gb_softsvc.rs
> new file mode 100644
> index 0000000000000..8fbcfe98e0848
> --- /dev/null
> +++ b/drivers/greybus/gb_softsvc.rs
> @@ -0,0 +1,570 @@

[ ... ]

> +    fn send_request<P: AsBytes>(&self, hd: &hd::Device, ty: u8, payload: P) -> Result<()> {
> +        let msg = Msg::request(self.new_operation_id()?, ty, payload);
> +        hd.data_rcvd(protocols::GB_SVC_CPORT_ID, msg.as_bytes());
> +        Ok(())
> +    }

[Severity: Medium]
Does send_request() permanently leak an operation ID from svc_operation_id
whenever the Greybus core drops an incoming request?

Operation IDs are only released in GbHdDriver::svc_handler() when a response
arrives.  However, gb_connection_recv_request() drops the request without
sending a response on GFP_ATOMIC allocation failure, and
gb_operation_response_send() does the same if response allocation fails.

Once the pool is exhausted, new_operation_id() returns EOVERFLOW and blocks
further SVC requests including Module::new() and Module::drop().  Since
gb_softsvc never tracks pending requests by operation_id, a wrapping atomic
counter like connection->op_cycle would avoid this leak.

[ ... ]

> +    fn module_remove(&self, hd: &hd::Device, intf_id: u8, intf_count: u8) {
> +        let payload = protocols::GbSvcModuleRemovedRequest::new(intf_id);
> +        let res = self.send_request(hd, protocols::GB_SVC_TYPE_MODULE_REMOVED, payload);
> +
> +        if res.is_err() {
> +            dev_warn!(
> +                hd.as_ref(),
> +                "Failed to send module_removed svc request for {}",
> +                intf_id
> +            );
> +        }
> +
> +        // The ids stay taken until the core has removed the module, or a new module could be
> +        // given them while the old connections still exist.
> +        hd.svc_flush();
> +
> +        self.map_remove(intf_id, intf_count, hd.as_ref());
> +    }

[Severity: Medium]
Can module_remove() free interface IDs in intf_map while the old module and
its connections are still live in the Greybus core?

If send_request() fails, or if the core drops GB_SVC_TYPE_MODULE_REMOVED on
allocation failure in gb_svc_queue_deferred_request(), gb_module_del() never
runs.  hd.svc_flush() then returns with the old module and its connections
still registered.

Calling map_remove() anyway breaks Module::drop()'s quiescing guarantee, as
in-flight message_send() calls can still run InterfaceOps::write() after drop
returns.  A later Module::new() reusing those IDs is also rejected by
gb_svc_process_module_inserted() while stale connections route traffic to it.

[ ... ]

> +            let mut buf = KVec::with_capacity(msg.header().size().into(), gfp_mask)?;
> +
> +            buf.extend_from_slice(msg.header().as_bytes(), gfp_mask)?;
> +            buf.extend_from_slice(msg.payload_bytes(), gfp_mask)?;

[Severity: Medium]
Is this per-message KVec allocation and double copy necessary when
gb_operation_message_init() already lays out header and payload contiguously
in message->buffer?

Because GreybusSoftSvc::init() advertises GB_OPERATION_SIZE_MAX (65535
bytes), bulk transfers over 32 KiB trigger order-4 kmalloc allocations on
every outbound message, risking reclaim stalls and avoidable ENOMEM failures.

Exposing a borrowed slice over message->buffer on kernel::greybus::Message,
as es2.c uses directly, would eliminate both the allocation and the copies.

> +
> +            intf.write(&buf, conn.intf_cport_id(), gfp_mask)

[Severity: High]
Can an error from intf.write() cause a use-after-free and active-count
underflow on struct gb_operation when a timeout or cancellation races with
message_send()?

gb_operation_request_send() takes two active counts and two kref references
and arms operation->timer before calling gb_message_send().  When
intf.write() returns an error, HdDriverVTable::message_send() propagates the
errno to gb_operation_request_send() without calling greybus_message_sent().

If operation->timer expires (or gb_operation_cancel() runs) while
intf.write() is blocked, gb_operation_work() is queued and drops one active
count and one kref.  err_put_active in gb_operation_request_send() only calls
timer_delete_sync() and unconditionally puts both active counts and both
krefs without checking whether completion was already claimed:

CPU0                                CPU1
gb_operation_request_send()
  get_active x2, kref_get x2
  add_timer(&operation->timer)
  gb_message_send()
    GbHdDriver::message_send()
      intf.write() [blocks]
                                    gb_operation_timeout()
                                      gb_operation_result_set(-ETIMEDOUT)
                                      queue_work(&operation->work)
                                    gb_operation_work()
                                      gb_operation_put_active() [2 -> 1]
                                      gb_operation_put()        [3 -> 2]
      intf.write() returns Err
  err_put_active:
    timer_delete_sync()
    gb_operation_put_active() x2    <-- active underflows to -1
    gb_operation_put() x2           <-- frees operation early
caller:
  gb_operation_put()                <-- use-after-free / double free

If err_put_active runs before gb_operation_work(), the worker instead hits a
use-after-free on the freed operation.  Underflowing operation->active to -1
also leaves gb_operation_cancel() stuck forever waiting for
!gb_operation_is_active(operation).

[ ... ]

> +        let dev = faux.as_ref().as_ref();
> +        let hd = hd::Registration::new(dev, GB_OPERATION_SIZE_MAX, CPORT_ID_MAX + 1, Ok(data))?;

[Severity: Medium]
Should GreybusSoftSvc::init() check greybus_disabled() before registering
the host device?

When booting with nogreybus=1 (and CONFIG_GREYBUS=y, as selected by
RUST_GREYBUS_ABSTRACTIONS), gb_init() returns -ENODEV before registering
greybus_bus_type or calling gb_hd_init() to initialize gb_hd_bus_id_map.

Because gb_hd_bus_id_map is a zero-initialized static struct ida rather than
DEFINE_IDA, hd::Registration::new() -> gb_hd_create() calls ida_alloc_min()
on an uninitialized IDA (triggering lockdep or spinlock failures) and then
adds the device to an unregistered bus.

> +
> +        svc.send_version(hd.as_ref())?;
> +
> +        // The handshake runs on the SVC connection's workqueue. Wait for it, so `Module::new()`
> +        // works as soon as this module is loaded, and no handshake work is left once it is.
> +        svc.handshake.wait_for_completion();

[Severity: Medium]
Can this unbounded wait_for_completion() hang GreybusSoftSvc::init()
forever?

svc.send_version() and svc.send_svc_hello() submit requests via void
hd.data_rcvd(), and svc.handshake.complete_all() only runs when a response
reaches svc_handler().  If the core drops either handshake request or fails
response allocation under memory pressure, no response ever arrives.

Because wait_for_completion() is uninterruptible and has no timeout, modprobe
or built-in kernel boot would wedge permanently in TASK_UNINTERRUPTIBLE.
Using wait_for_completion_timeout() (or an interruptible timeout) would let
init fail cleanly and unwind.

[ ... ]

> +        let guard = GLOBAL_STATE.lock();
> +        let state = guard.as_ref().ok_or(code::EAGAIN)?;

[Severity: Medium]
Can Module::new() lock GLOBAL_STATE before GreybusSoftSvc::init() has called
GLOBAL_STATE.init()?

GLOBAL_STATE is declared with unsafe(uninit) via global_lock!, which requires
init() before any lock() call.  Because CONFIG_GREYBUS_SOFTSVC is tristate
and drivers/greybus/ is linked after transport subsystems in
drivers/Makefile, a built-in caller can reach Module::new() first.

The same happens if initcall_blacklist=__gb_softsvc_init skips init when
built-in.  Locking the uninitialized struct mutex violates GlobalLock::new()'s
safety contract and triggers immediate debug-mutex or lockdep failures.

Returning EAGAIN instead of EPROBE_DEFER also causes call_driver_probe() to
fail probe permanently instead of deferring.  Guarding GLOBAL_STATE with a
const-initialized Atomic flag (Release after init(), Acquire in Module::new())
and returning EPROBE_DEFER when unset would address both.

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

* Re: [PATCH v6 9/9] greybus: Add Rust UART node driver
  2026-12-04 10:30 ` [PATCH v6 9/9] greybus: Add Rust UART node driver Ayush Singh
@ 2026-12-04 11:18   ` sashiko-bot
  0 siblings, 0 replies; 18+ messages in thread
From: sashiko-bot @ 2026-12-04 11:18 UTC (permalink / raw)
  To: Ayush Singh, Jason Kridner, robertcnelson, Johan Hovold,
	Alex Elder, Greg Kroah-Hartman, Miguel Ojeda, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Danilo Krummrich, Daniel Almeida,
	Tamir Duberstein, Alexandre Courbot, Onur Özkan,
	Eric Biggers, Ard Biesheuvel, Ayush Singh, Rob Herring,
	Krzysztof Kozlowski, Conor Dooley, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Markus Probst
  Cc: linux-crypto, devicetree

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

^ permalink raw reply	[flat|nested] 18+ messages in thread

end of thread, other threads:[~2026-12-04 11:18 UTC | newest]

Thread overview: 18+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
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 is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox