Skip to contentSkip to conversation

Rust netlink support + use in Rust Binder

PATCH New Alice Ryhl 1 participant 4 messages Jul 7

Subsystems (4)
lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

v7 cover Rust netlink support + use in Rust Binder

The C Binder driver exposes messages over netlink when transactions fail, so that a userpace daemon can respond to processes with many failing transactions.

This patch series adds netlink support from Rust, then implements an equivalent API in Rust Binder.

As Binder only uses broadcast messages, I did not add support for other kinds of messages.

This series is based on top of the result of merging together the two branches 'char-misc/char-misc-linus' and 'char-misc/char-misc-next'.

---
Changes in v7:
- Rebase on char-misc-linus and char-misc-next.
- Fix conflict with commit 77bfebf11077 ("rust_binder: fix BINDER_GET_EXTENDED_ERROR")
- Pick up tags
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- Introduce MAINTAINERS entry update for net files.
- Move netlink.rs to rust/kernel/net/.
- Tweak info.reply logic in Binder patch.
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- Remove patch 2.
- Squash patches 3 and 4.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Fix typo in 'report netlink transactions' commit message.
- Document that some methods are for const context only.
- Rebase and pick up tags.
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Fix spurious 'return' statements in Rust helpers (Patch 1).
- Sashiko review:
- Fix ynl_gen to handle empty multicast groups and correct multicast indexing (Patch 2).
- Fix transaction failed reply logic to report via Netlink inside reply_inner() (Patch 4).
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Make inclusion of to_pid conditional too.
- Add note about file name in second patch.
- Make it clear that the sk_buff wrapper is netlink-specific.
- Better handle bitfield in patch 1.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Alice Ryhl (2):
rust: net: add rust/kernel/net to NETWORKING [GENERAL]
rust: netlink: add raw netlink abstraction

Carlos Llamas (1):
rust_binder: report netlink transactions

 MAINTAINERS                                |   2 +
 drivers/android/Kconfig                    |   2 +-
 drivers/android/binder/netlink.rs          | 117 ++++++++++
 drivers/android/binder/rust_binder_main.rs |   8 +-
 drivers/android/binder/thread.rs           |  11 +-
 drivers/android/binder/transaction.rs      |  40 ++++
 rust/bindings/bindings_helper.h            |   3 +
 rust/helpers/helpers.c                     |   1 +
 rust/helpers/net/genetlink.c               |  46 ++++
 rust/kernel/{net.rs => net/mod.rs}         |   2 +
 rust/kernel/net/netlink.rs                 | 337 +++++++++++++++++++++++++++++
 rust/uapi/uapi_helper.h                    |   1 +
 12 files changed, 566 insertions(+), 4 deletions(-)

---
base-commit: 2c7a7db3aa6370f46761b6d8eb821f5bde8901eb
change-id: 20260306-binder-netlink-c82110b2fb74

Best regards,

Signature · 1 line
Alice Ryhl <[email protected]>
author maintainer
#1 lore raw

PATCH v7 1/3 rust: net: add rust/kernel/net to NETWORKING [GENERAL]

To ensure that networking code can be found in a single shared place, add it to the relevant NETWORKING entry. The net.rs file is moved into the net/ directory so that it's included under the MAINTAINERS entry without needing a separate rust/kernel/net.rs entry.

---
 MAINTAINERS                        | 2 ++
 rust/kernel/{net.rs => net/mod.rs} | 0
 2 files changed, 2 insertions(+)
MAINTAINERS +2 -0
index 15011f5752a9..303a06da4279 100644
@@ -18849,6 +18849,8 @@ F:	include/uapi/linux/sctp.h
 F:	lib/net_utils.c
 F:	lib/random32.c
 F:	net/
+F:	rust/helpers/net/
+F:	rust/kernel/net/
 F:	samples/pktgen/
 F:	tools/net/
 F:	tools/testing/selftests/net/
rust/kernel/net/mod.rs renamed from rust/kernel/net.rs +0 -0
similarity index 100%
rename from rust/kernel/net.rs
rename to rust/kernel/net/mod.rs
Signature · 1 line
2.55.0.rc2.803.g1fd1e6609c-goog
author maintainer
#2 lore raw

PATCH v7 2/3 rust: netlink: add raw netlink abstraction

In reply to Alice Ryhl

This implements a safe and relatively simple API over the netlink API, that allows you to add different attributes to a netlink message and broadcast it. As the first user of this API only makes use of broadcast, only broadcast messages are supported here.

This API is intended to be safe and to be easy to use in *generated* code. This is because netlink is generally used with yaml files that describe the underlying API, and the python generator outputs C code (or, soon, Rust code) that lets you use the API more easily. So for example, if there is a string field, the code generator will output a method that internall calls put_string() with the right attr type.

---
 rust/bindings/bindings_helper.h |   3 +
 rust/helpers/helpers.c          |   1 +
 rust/helpers/net/genetlink.c    |  46 ++++++
 rust/kernel/net/mod.rs          |   2 +
 rust/kernel/net/netlink.rs      | 337 ++++++++++++++++++++++++++++++++++++++++
 5 files changed, 389 insertions(+)
rust/bindings/bindings_helper.h +3 -0
index 1124785e210b..ec96e811610d 100644
@@ -93,6 +93,8 @@
 #include <linux/wait.h>
 #include <linux/workqueue.h>
 #include <linux/xarray.h>
+#include <net/genetlink.h>
+#include <net/netlink.h>
 #include <trace/events/rust_sample.h>
 
 /*
@@ -110,6 +112,7 @@
 const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN = ARCH_SLAB_MINALIGN;
 const size_t RUST_CONST_HELPER_ARCH_KMALLOC_MINALIGN = ARCH_KMALLOC_MINALIGN;
 const size_t RUST_CONST_HELPER_PAGE_SIZE = PAGE_SIZE;
+const size_t RUST_CONST_HELPER_GENLMSG_DEFAULT_SIZE = GENLMSG_DEFAULT_SIZE;
 const gfp_t RUST_CONST_HELPER_GFP_ATOMIC = GFP_ATOMIC;
 const gfp_t RUST_CONST_HELPER_GFP_KERNEL = GFP_KERNEL;
 const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT = GFP_KERNEL_ACCOUNT;
rust/helpers/helpers.c +1 -0
index 998e31052e66..1d4ee51f576b 100644
@@ -72,6 +72,7 @@
 #include "maple_tree.c"
 #include "mm.c"
 #include "mutex.c"
+#include "net/genetlink.c"
 #include "of.c"
 #include "page.c"
 #include "pci.c"
rust/helpers/net/genetlink.c new file +46 -0

46 lines not on this page · raw message

rust/kernel/net/mod.rs +2 -0
index fe415cb369d3..8ecae7577ed2 100644
@@ -4,3 +4,5 @@
 
 #[cfg(CONFIG_RUST_PHYLIB_ABSTRACTIONS)]
 pub mod phy;
+
+pub mod netlink;
rust/kernel/net/netlink.rs new file +337 -0

337 lines not on this page · raw message

Signature · 1 line
2.55.0.rc2.803.g1fd1e6609c-goog
author maintainer
#3 lore raw

PATCH v7 3/3 rust_binder: report netlink transactions

In reply to Alice Ryhl

From: Carlos Llamas <[email protected]>

The Android Binder driver supports a netlink API that reports transaction *failures* to a userspace daemon. This allows devices to monitor processes with many failed transactions so that it can e.g. kill misbehaving apps.

One very important thing that this monitors is when many oneway messages are sent to a frozen process, so there is special handling to ensure this scenario is surfaced over netlink.

---
 drivers/android/Kconfig                    |   2 +-
 drivers/android/binder/netlink.rs          | 117 +++++++++++++++++++++++++++++
 drivers/android/binder/rust_binder_main.rs |   8 +-
 drivers/android/binder/thread.rs           |  11 ++-
 drivers/android/binder/transaction.rs      |  40 ++++++++++
 rust/uapi/uapi_helper.h                    |   1 +
 6 files changed, 175 insertions(+), 4 deletions(-)
drivers/android/Kconfig +1 -1
index e2e402c9d175..606a9d07f774 100644
@@ -16,7 +16,7 @@ config ANDROID_BINDER_IPC
 
 config ANDROID_BINDER_IPC_RUST
 	bool "Rust version of Android Binder IPC Driver"
-	depends on RUST && MMU && !ANDROID_BINDER_IPC
+	depends on RUST && MMU && NET && !ANDROID_BINDER_IPC
 	help
 	  This enables the Rust implementation of the Binder driver.
 
drivers/android/binder/netlink.rs new file +117 -0

117 lines not on this page · raw message

drivers/android/binder/rust_binder_main.rs +6 -2
index 432390aab25b..df47aba05133 100644
@@ -32,6 +32,7 @@
 mod deferred_close;
 mod defs;
 mod error;
+mod netlink;
 mod node;
 mod page_range;
 mod process;
@@ -282,19 +283,22 @@ fn ptr_align(value: usize) -> Option<usize> {
 // SAFETY: We call register in `init`.
 static BINDER_SHRINKER: Shrinker = unsafe { Shrinker::new() };
 
-struct BinderModule {}
+struct BinderModule {
+    _netlink: kernel::net::netlink::Registration,
+}
 
 impl kernel::Module for BinderModule {
     fn init(_module: &'static kernel::ThisModule) -> Result<Self> {
         // SAFETY: The module initializer never runs twice, so we only call this once.
         unsafe { crate::context::CONTEXTS.init() };
 
+        let netlink = crate::netlink::BINDER_NL_FAMILY.register()?;
         BINDER_SHRINKER.register(c"android-binder")?;
 
         // SAFETY: The module is being loaded, so we can initialize binderfs.
         unsafe { kernel::error::to_result(binderfs::init_rust_binderfs())? };
 
-        Ok(Self {})
+        Ok(Self { _netlink: netlink })
     }
 }
 
drivers/android/binder/thread.rs +10 -1
index 19f881948a84..33368f7fd551 100644
@@ -1284,6 +1284,15 @@ fn transaction(self: &Arc<Self>, cmd: u32, reader: &mut UserSliceReader) -> Resu
             }
         }
 
+        if info.oneway_spam_suspect {
+            // If this is both a oneway spam suspect and a failure, we report it twice. This is
+            // useful in case the transaction failed with BR_TRANSACTION_PENDING_FROZEN.
+            info.report_netlink(BR_ONEWAY_SPAM_SUSPECT, &self.process.ctx);
+        }
+        if info.reply != 0 {
+            info.report_netlink(info.reply, &self.process.ctx);
+        }
+
         Ok(())
     }
 
@@ -1354,11 +1363,11 @@ fn reply_inner(self: &Arc<Self>, info: &mut TransactionInfo) -> BinderResult {
                 info.from_tid,
                 info.to_pid
             );
-
             let param = err.source.as_ref().map_or(0, |e| e.to_errno());
             let ee = ExtendedError::new(info.debug_id as u32, err.reply, param);
             orig.from
                 .deliver_reply(Err(BR_FAILED_REPLY), &orig, Some(ee));
+            info.reply = BR_FAILED_REPLY;
             err.reply = BR_TRANSACTION_COMPLETE;
             err
         });
drivers/android/binder/transaction.rs +40 -0
index afef5b46eac2..6cb7b745c52e 100644
@@ -3,6 +3,7 @@
 // Copyright (C) 2025 Google LLC.
 
 use kernel::{
+    net::netlink::GENLMSG_DEFAULT_SIZE,
     prelude::*,
     seq_file::SeqFile,
     seq_print,
@@ -18,6 +19,7 @@
     allocation::{Allocation, TranslatedFds},
     defs::*,
     error::{BinderError, BinderResult},
+    netlink::Report,
     node::{Node, NodeRef},
     process::{Process, ProcessInner},
     ptr_align,
@@ -51,6 +53,44 @@ impl TransactionInfo {
     pub(crate) fn is_oneway(&self) -> bool {
         self.flags & TF_ONE_WAY != 0
     }
+
+    pub(crate) fn report_netlink(&self, reply: u32, ctx: &crate::Context) {
+        if let Err(err) = self.report_netlink_inner(reply, ctx) {
+            pr_warn!(
+                "{}:{} netlink report failed: {err:?}\n",
+                self.from_pid,
+                self.from_tid
+            );
+        }
+    }
+
+    fn report_netlink_inner(&self, reply: u32, ctx: &crate::Context) -> kernel::error::Result {
+        if !Report::has_listeners() {
+            return Ok(());
+        }
+        let mut report = Report::new(GENLMSG_DEFAULT_SIZE, 0, 0, GFP_KERNEL)?;
+
+        report.error(reply)?;
+        report.context(&ctx.name)?;
+        report.from_pid(self.from_pid as u32)?;
+        report.from_tid(self.from_tid as u32)?;
+        if self.to_pid != 0 {
+            report.to_pid(self.to_pid as u32)?;
+        }
+        if self.to_tid != 0 {
+            report.to_tid(self.to_tid as u32)?;
+        }
+
+        if self.is_reply {
+            report.is_reply()?;
+        }
+        report.flags(self.flags)?;
+        report.code(self.code)?;
+        report.data_size(self.data_size as u32)?;
+
+        report.multicast(0, GFP_KERNEL)?;
+        Ok(())
+    }
 }
 
 use core::mem::offset_of;
rust/uapi/uapi_helper.h +1 -0
index 06d7d1a2e8da..86c7b6b284b0 100644
@@ -11,6 +11,7 @@
 #include <uapi/drm/nova_drm.h>
 #include <uapi/drm/panthor_drm.h>
 #include <uapi/linux/android/binder.h>
+#include <uapi/linux/android/binder_netlink.h>
 #include <uapi/linux/mdio.h>
 #include <uapi/linux/mii.h>
 #include <uapi/linux/ethtool.h>
Signature · 1 line
2.55.0.rc2.803.g1fd1e6609c-goog