From nobody Mon Jun 8 23:56:24 2026 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id E5DEE384CFD for ; Mon, 25 May 2026 13:17:44 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779715076; cv=none; b=CCdRg0vVUVmcJxZWJ/35U2XuL+sO07/5RukH/jOxOxCP433T0cB172IwZTbWLSFozVFCKzLGlBo+ZkJd7S1dfWf5isEzRFLx022uu0rdG/uVlSz8sYjAzTVw1FG1noPQ+qcB7a7q/0hJPhgz8WmUoI7b7ZRV6GyV/kyhmwIlofU= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779715076; c=relaxed/simple; bh=JV9g8f82E8nimbxYfUusfB9wzLVp58NDwYwaEKMH+gE=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=mHS16xIaoX3fUflGwMIQNYc9tEOWmaWP72qoqEei4LgR+ghF0HyfzNOmVvVcqZgXUknPOezMJnGXR2v0SMChkNVFiZDJd8ldJXjXxNmaYE9h98PetDDj9g+BXUtVrmZB9j57O3WHpveHXvVmLGy+s19c48JNVaHPPS2ewo+PO9M= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=OTvzNzUx; arc=none smtp.client-ip=209.85.128.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="OTvzNzUx" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-49049100a40so18165885e9.2 for ; Mon, 25 May 2026 06:17:44 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1779715063; x=1780319863; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=ZeXVch/Uab55fFQ75i/nws6Wka9h9A29LXPDA42s1qw=; b=OTvzNzUxleZ+IUS3Uw9Q5hwZaYgDEc4FIzQMlIBB5XBKYETNfY1np/aGAQLeJNm2BC MdhI3rfPVEc4M15NGPmOz8m1/lphN/NxIo3BjqiqPRji13LI3692fzp9yb5T3VzXd1+t 1+3vcU2RQXktS55cVhc1C/Ar5Pmr3Al0cVnCFoViWy5X2T9NWf4UrlW5Wz/ZC0wg1nt5 QXIPj9xJSTcuyOEBv1etTqD/MMLp7eqfdi4Kb/8iFTDW7VmMuEqP/nFmtgwa14D3A8k/ hXVu72vB3cDpMSgMpr2aZoKCiJpAS2XFPvXc23ZRniLWfBNQTUKb0+zmeGHrvmP5QG1Y o43A== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1779715063; x=1780319863; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=ZeXVch/Uab55fFQ75i/nws6Wka9h9A29LXPDA42s1qw=; b=V8yEUSpI+rpsAbii8NGoBLjfp47QYXtxz2D1xMyQl6TaJDWNVIUi+bbxoDiWrOQomh Vij/wuELzLzebDgeaojM6qvxxzoCHK+s4nvRuDASlHIJej55vT+th26eI5JLsphJeI8S PoW8XIB8oYyRyoWRawmTSKjYU9LHt+ifk7ToSiKeWrDTb0LCGSmCkBJR0rgsAql/JsvG KvCmAAH8oQZ64EV2v+i8kT0890PGtWaA4cjlFravowBLpqAvbW7sOQabbkEB16o9VfoG PJdni9M4oDeGa+ASUC7ouwjOljsYoCq6a+qGikppAZLo1ooawNZwRgbtxyY6dvMDjEQF oAyQ== X-Forwarded-Encrypted: i=1; AFNElJ/JGORDOTdxC3bI3EcjTOKbwSwn0mIISFdCzZiH40DaHjwuM35L9zdUGOWn7M98l+pArM5KU4GyX+Ikun8=@vger.kernel.org X-Gm-Message-State: AOJu0YwepdunNFZnzY83BSZNXisRfljuIwJqxiMRz719bSuFLLI4a6Kd /ynzJqeNqSIAcnbPJJUh9DijSdx1fCPVlXCdXuwNWrgWnw/+UTmvA2inoJ96JOzaru+UJ6sDO7i 8QhGz58y7SgDDGsaAMw== X-Received: from wmbel15.prod.google.com ([2002:a05:600c:3e0f:b0:488:7c5a:b238]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:138c:b0:490:60cb:55f0 with SMTP id 5b1f17b1804b1-49060cb56femr101500605e9.21.1779715063057; Mon, 25 May 2026 06:17:43 -0700 (PDT) Date: Mon, 25 May 2026 13:17:27 +0000 In-Reply-To: <20260525-binder-netlink-v5-0-a90e2923ebeb@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20260525-binder-netlink-v5-0-a90e2923ebeb@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=15720; i=aliceryhl@google.com; h=from:subject:message-id; bh=JV9g8f82E8nimbxYfUusfB9wzLVp58NDwYwaEKMH+gE=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBqFEvzjgXmgda1xmA/TpyH9xqJftswPOogH3Gn2 gkW2XFYO0OJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCahRL8wAKCRAEWL7uWMY5 RibLD/4hD1Je4hamFB5uBagbuTJFSERoC4qTxxQWzkcocXEoyn0JE28VMSjwgZHuKYodU6j5y8l LTU/+U1svGM5edP9sRCu6b7ejzxUB8E9MgWgo1SNyqfSRC4TLYGHwJAOk8i3wykXplpT9LFdtcn pBYcH877CWl3fz3BFgMNIKaFgbwqJurgH9d+s/fLnFEHlwK6M05rLsuh4aSSKuBBH6wvnbxuV0N mNvH4KBVVenQeyyQrS7vh8rYHxXWrRVOhqos//nmnAouuNjiL12hYb88EEUA82tnVFYsviaLju8 FAv2sl/jTGm7swcEMYGnHww/JOEw4TkOGNb1lDc8zlxAtf8/tLCUqGMrmZ9TMcRAhpFyqK86OfI johaQ18GhXcBgDpd+xE/3txOMvBDYKXK1cahdIxVYkQvlrqsFmUlK/nFK9l2V9wX9p3NrjtVx4F qUyPmvFxKXo/kdiz+X7bSYsznBLKE4bP0sPmCSXTVwqsOxdfhQvrLciuHhX1R2DairVJoEQ5eQr FcIK0gQxBboTjTymN4kEQ3DOvD3Qd6tySNOZhwSO2doTWo93LGy8xVdNEwsEySugIMXiLHkRjjR OfjHg1TH5cpjiDGihLa9Ee1GfxlkShJ6LbbE8T9IfOFT6mQU6RYjwvpWUbA51fdfo8lo7KfD1VV Gyc7SpTbfFDYqYg== X-Mailer: b4 0.14.3 Message-ID: <20260525-binder-netlink-v5-1-a90e2923ebeb@google.com> Subject: [PATCH v5 1/2] rust: netlink: add raw netlink abstraction From: Alice Ryhl To: Carlos Llamas , Greg Kroah-Hartman , Andrew Lunn , Donald Hunter , Jakub Kicinski , "David S. Miller" , Eric Dumazet , Paolo Abeni , Simon Horman , Matthew Maurer Cc: Miguel Ojeda , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Christian Brauner , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, netdev@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable 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. Reviewed-by: Matthew Maurer Reviewed-by: Andrew Lunn Signed-off-by: Alice Ryhl --- rust/bindings/bindings_helper.h | 3 + rust/helpers/genetlink.c | 46 ++++++ rust/helpers/helpers.c | 1 + rust/kernel/lib.rs | 1 + rust/kernel/netlink.rs | 336 ++++++++++++++++++++++++++++++++++++= ++++ 5 files changed, 387 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 446dbeaf0866..612fa5388b7d 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -92,6 +92,8 @@ #include #include #include +#include +#include #include =20 /* @@ -109,6 +111,7 @@ const size_t RUST_CONST_HELPER_ARCH_SLAB_MINALIGN =3D ARCH_SLAB_MINALIGN; const size_t RUST_CONST_HELPER_ARCH_KMALLOC_MINALIGN =3D ARCH_KMALLOC_MINA= LIGN; const size_t RUST_CONST_HELPER_PAGE_SIZE =3D PAGE_SIZE; +const size_t RUST_CONST_HELPER_GENLMSG_DEFAULT_SIZE =3D GENLMSG_DEFAULT_SI= ZE; const gfp_t RUST_CONST_HELPER_GFP_ATOMIC =3D GFP_ATOMIC; const gfp_t RUST_CONST_HELPER_GFP_KERNEL =3D GFP_KERNEL; const gfp_t RUST_CONST_HELPER_GFP_KERNEL_ACCOUNT =3D GFP_KERNEL_ACCOUNT; diff --git a/rust/helpers/genetlink.c b/rust/helpers/genetlink.c new file mode 100644 index 000000000000..3530b69f6cf7 --- /dev/null +++ b/rust/helpers/genetlink.c @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: GPL-2.0 + +/* + * Copyright (C) 2026 Google LLC. + */ + +#include + +#ifdef CONFIG_NET + +__rust_helper struct sk_buff *rust_helper_genlmsg_new(size_t payload, gfp_= t flags) +{ + return genlmsg_new(payload, flags); +} + +__rust_helper +int rust_helper_genlmsg_multicast(const struct genl_family *family, + struct sk_buff *skb, u32 portid, + unsigned int group, gfp_t flags) +{ + return genlmsg_multicast(family, skb, portid, group, flags); +} + +__rust_helper void rust_helper_genlmsg_cancel(struct sk_buff *skb, void *h= dr) +{ + genlmsg_cancel(skb, hdr); +} + +__rust_helper void rust_helper_genlmsg_end(struct sk_buff *skb, void *hdr) +{ + genlmsg_end(skb, hdr); +} + +__rust_helper void rust_helper_nlmsg_free(struct sk_buff *skb) +{ + nlmsg_free(skb); +} + +__rust_helper +int rust_helper_genl_has_listeners(const struct genl_family *family, + struct net *net, unsigned int group) +{ + return genl_has_listeners(family, net, group); +} + +#endif diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 625921e27dfb..8de05ae7d928 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -62,6 +62,7 @@ #include "err.c" #include "irq.c" #include "fs.c" +#include "genetlink.c" #include "gpu.c" #include "io.c" #include "jump_label.c" diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index b72b2fbe046d..d69f13b77845 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -96,6 +96,7 @@ pub mod module_param; #[cfg(CONFIG_NET)] pub mod net; +pub mod netlink; pub mod num; pub mod of; #[cfg(CONFIG_PM_OPP)] diff --git a/rust/kernel/netlink.rs b/rust/kernel/netlink.rs new file mode 100644 index 000000000000..24177fb685b4 --- /dev/null +++ b/rust/kernel/netlink.rs @@ -0,0 +1,336 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2026 Google LLC. + +//! Rust support for generic netlink. +//! +//! Currently only supports exposing multicast groups. +//! +//! C header: [`include/net/genetlink.h`](srctree/include/net/genetlink.h) +#![cfg(CONFIG_NET)] + +use kernel::{ + alloc::{self, AllocError}, + error::to_result, + prelude::*, + transmute::AsBytes, + types::Opaque, + ThisModule, +}; + +use core::{ + mem::ManuallyDrop, + ptr::NonNull, // +}; + +/// The default netlink message size. +pub const GENLMSG_DEFAULT_SIZE: usize =3D bindings::GENLMSG_DEFAULT_SIZE; + +/// A wrapper around `struct sk_buff` for generic netlink messages. +/// +/// This type is intended to be specific for buffers used with netlink onl= y, and other usecases for +/// `struct sk_buff` are out-of-scope for this abstraction. +/// +/// # Invariants +/// +/// The pointer has ownership over a valid `sk_buff`. +pub struct NetlinkSkBuff { + skb: NonNull, +} + +impl NetlinkSkBuff { + /// Creates a new `NetlinkSkBuff` with the given size. + pub fn new(size: usize, flags: alloc::Flags) -> Result { + // SAFETY: `genlmsg_new` only requires its arguments to be valid i= ntegers. + let skb =3D unsafe { bindings::genlmsg_new(size, flags.as_raw()) }; + let skb =3D NonNull::new(skb).ok_or(AllocError)?; + Ok(NetlinkSkBuff { skb }) + } + + /// Puts a generic netlink header into the `NetlinkSkBuff`. + pub fn genlmsg_put( + self, + portid: u32, + seq: u32, + family: &'static Family, + cmd: u8, + ) -> Result { + let skb =3D self.skb.as_ptr(); + // SAFETY: The skb and family pointers are valid. + let hdr =3D unsafe { bindings::genlmsg_put(skb, portid, seq, famil= y.as_raw(), 0, cmd) }; + let hdr =3D NonNull::new(hdr).ok_or(AllocError)?; + Ok(GenlMsg { skb: self, hdr }) + } +} + +impl Drop for NetlinkSkBuff { + fn drop(&mut self) { + // SAFETY: We have ownership over the `sk_buff`, so we may free it. + unsafe { bindings::nlmsg_free(self.skb.as_ptr()) } + } +} + +/// A generic netlink message being constructed. +/// +/// # Invariants +/// +/// `hdr` references the header in this netlink message. +pub struct GenlMsg { + skb: NetlinkSkBuff, + hdr: NonNull, +} + +impl GenlMsg { + /// Puts an attribute into the message. + #[inline] + fn put(&mut self, attrtype: c_int, value: &T) -> Result + where + T: ?Sized + AsBytes, + { + let skb =3D self.skb.skb.as_ptr(); + let len =3D size_of_val(value); + let ptr =3D core::ptr::from_ref(value).cast::(); + // SAFETY: `skb` is valid by `NetlinkSkBuff` type invariants, and = the provided value is + // readable and initialized for its `size_of` bytes. + to_result(unsafe { bindings::nla_put(skb, attrtype, len as c_int, = ptr) }) + } + + /// Puts a `u32` attribute into the message. + #[inline] + pub fn put_u32(&mut self, attrtype: c_int, value: u32) -> Result { + self.put(attrtype, &value) + } + + /// Puts a string attribute into the message. + #[inline] + pub fn put_string(&mut self, attrtype: c_int, value: &CStr) -> Result { + self.put(attrtype, value.to_bytes_with_nul()) + } + + /// Puts a flag attribute into the message. + #[inline] + pub fn put_flag(&mut self, attrtype: c_int) -> Result { + let skb =3D self.skb.skb.as_ptr(); + // SAFETY: `skb` is valid by `NetlinkSkBuff` type invariants, and = a null pointer is valid + // when the length is zero. + to_result(unsafe { bindings::nla_put(skb, attrtype, 0, core::ptr::= null()) }) + } + + /// Sends the generic netlink message as a multicast message. + #[inline] + pub fn multicast( + self, + family: &'static Family, + portid: u32, + group: u32, + flags: alloc::Flags, + ) -> Result { + let me =3D ManuallyDrop::new(self); + // SAFETY: The `skb` and `family` pointers are valid. We pass owne= rship of the `skb` to + // `genlmsg_multicast` by not dropping `self`. + unsafe { + bindings::genlmsg_end(me.skb.skb.as_ptr(), me.hdr.as_ptr()); + to_result(bindings::genlmsg_multicast( + family.as_raw(), + me.skb.skb.as_ptr(), + portid, + group, + flags.as_raw(), + )) + } + } +} +impl Drop for GenlMsg { + fn drop(&mut self) { + // SAFETY: The `hdr` pointer references the header of this generic= netlink message. + unsafe { bindings::genlmsg_cancel(self.skb.skb.as_ptr(), self.hdr.= as_ptr()) }; + } +} + +/// Flags for a generic netlink family. +struct FamilyFlags { + /// Whether the family supports network namespaces. + netnsok: bool, + /// Whether the family supports parallel operations. + parallel_ops: bool, +} + +impl FamilyFlags { + /// Converts the flags to the bitfield representation used by `genl_fa= mily`. + const fn into_bitfield(self) -> bindings::__BindgenBitfieldUnit<[u8; 1= ]> { + // The below shifts are verified correct by test_family_flags_bitf= ield() below. + // + // Although bindgen generates helpers to change bitfields based on= the C headers, these + // helpers unfortunately can't be used in const context. Since `Fa= mily` needs to be filled + // out at build-time, we use this helper instead. + let mut bits =3D 0; + if self.netnsok { + bits |=3D 1 << 0; + } + if self.parallel_ops { + bits |=3D 1 << 1; + } + // SAFETY: This bitfield is represented as an u8. + unsafe { core::mem::transmute::>(bits) } + } +} + +/// A generic netlink family. +#[repr(transparent)] +pub struct Family { + inner: Opaque, +} + +// SAFETY: The `Family` type is thread safe. +unsafe impl Sync for Family {} + +impl Family { + /// Creates a new `Family` instance. + /// + /// Intended to be used from const context only. Will panic if provide= d with invalid arguments. + /// + /// The name must be a nul-terminated string, but it is taken as `&[u8= ]` so that it can be used + /// more conveniently with the strings generated by bindgen. + pub const fn const_new( + module: &ThisModule, + name: &[u8], + version: u32, + mcgrps: &'static [MulticastGroup], + ) -> Family { + let n_mcgrps =3D mcgrps.len() as u8; + if n_mcgrps as usize !=3D mcgrps.len() { + panic!("too many mcgrps"); + } + let mut genl_family =3D bindings::genl_family { + version, + _bitfield_1: FamilyFlags { + netnsok: true, + parallel_ops: true, + } + .into_bitfield(), + module: module.as_ptr(), + mcgrps: mcgrps.as_ptr().cast(), + n_mcgrps, + ..pin_init::zeroed() + }; + if CStr::from_bytes_with_nul(name).is_err() { + panic!("genl_family name not nul-terminated"); + } + if genl_family.name.len() < name.len() { + panic!("genl_family name too long"); + } + let mut i =3D 0; + while i < name.len() { + genl_family.name[i] =3D name[i]; + i +=3D 1; + } + Family { + inner: Opaque::new(genl_family), + } + } + + /// Checks if there are any listeners for the given multicast group. + pub fn has_listeners(&self, group: u32) -> bool { + // SAFETY: The family and init_net pointers are valid. + unsafe { + bindings::genl_has_listeners(self.as_raw(), &raw mut bindings:= :init_net, group) !=3D 0 + } + } + + /// Returns a raw pointer to the underlying `genl_family` structure. + pub fn as_raw(&self) -> *mut bindings::genl_family { + self.inner.get() + } +} + +/// A generic netlink multicast group. +#[repr(transparent)] +pub struct MulticastGroup { + // No Opaque because fully immutable + group: bindings::genl_multicast_group, +} + +// SAFETY: Pure data so thread safe. +unsafe impl Sync for MulticastGroup {} + +impl MulticastGroup { + /// Creates a new `MulticastGroup` instance. + /// + /// Intended to be used from const context only. Will panic if provide= d with invalid arguments. + pub const fn const_new(name: &CStr) -> MulticastGroup { + let mut group: bindings::genl_multicast_group =3D pin_init::zeroed= (); + + let name =3D name.to_bytes_with_nul(); + if group.name.len() < name.len() { + panic!("genl_multicast_group name too long"); + } + let mut i =3D 0; + while i < name.len() { + group.name[i] =3D name[i]; + i +=3D 1; + } + + MulticastGroup { group } + } +} + +/// A registration of a generic netlink family. +/// +/// This type represents the registration of a [`Family`]. When an instanc= e of this type is +/// dropped, its respective generic netlink family will be unregistered fr= om the system. +/// +/// # Invariants +/// +/// `self.family` always holds a valid reference to an initialized and reg= istered [`Family`]. +pub struct Registration { + family: &'static Family, +} + +impl Family { + /// Registers the generic netlink family with the kernel. + pub fn register(&'static self) -> Result { + // SAFETY: `self.as_raw()` is a valid pointer to a `genl_family` s= truct. + // The `genl_family` struct is static, so it will outlive the regi= stration. + to_result(unsafe { bindings::genl_register_family(self.as_raw()) }= )?; + Ok(Registration { family: self }) + } +} + +impl Drop for Registration { + fn drop(&mut self) { + // SAFETY: `self.family.as_raw()` is a valid pointer to a register= ed `genl_family` struct. + // The `Registration` struct ensures that `genl_unregister_family`= is called exactly once + // for this family when it goes out of scope. + unsafe { bindings::genl_unregister_family(self.family.as_raw()) }; + } +} + +#[macros::kunit_tests(rust_netlink)] +mod tests { + use super::*; + + #[test] + fn test_family_flags_bitfield() { + for netnsok in [false, true] { + for parallel_ops in [false, true] { + let mut b_fam =3D bindings::genl_family { + ..Default::default() + }; + b_fam.set_netnsok(if netnsok { 1 } else { 0 }); + b_fam.set_parallel_ops(if parallel_ops { 1 } else { 0 }); + + let c_bitfield =3D FamilyFlags { + netnsok, + parallel_ops, + } + .into_bitfield(); + + // SAFETY: The bit field is stored as u8. + let b_val: u8 =3D unsafe { core::mem::transmute(b_fam._bit= field_1) }; + // SAFETY: The bit field is stored as u8. + let c_val: u8 =3D unsafe { core::mem::transmute(c_bitfield= ) }; + assert_eq!(b_val, c_val); + } + } + } +} --=20 2.54.0.746.g67dd491aae-goog From nobody Mon Jun 8 23:56:24 2026 Received: from mail-wm1-f74.google.com (mail-wm1-f74.google.com [209.85.128.74]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 7B36D384CC8 for ; Mon, 25 May 2026 13:17:46 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=209.85.128.74 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779715070; cv=none; b=U0sKA/g9qwnPRZ0ufvtIa94+F7kfMxW7++XQ0Y/11bxxY3EFy5v9o4jfqpl4bNEU540uZBNn0OseEdL+RutUshEvsoUIN5m/yeAUYG+S2c/38vS2GScj5PTA9Z47rJfvO3GMtl3wNh9wYDMzfiSHPSntTg158V3pprCJkhJjPPI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1779715070; c=relaxed/simple; bh=cXkggUMWdYmJT2UG2mDh/fQnlEuCCAgIFTLuPJak0FE=; h=Date:In-Reply-To:Mime-Version:References:Message-ID:Subject:From: To:Cc:Content-Type; b=RULpxVcYxTOrtcxliYmAoBZW1ViPO3UJQ5UCWyRJvKQmrEMtKDn5zNCkgDb4KuFe3nf5zlCNEgEn92T+ZNYWDi2sZYuPjv5vImR2xUK7LuKFtajuFHScaUA+/9H10MGS9U3Z/3aU5yFBtuvmqZd1lIj0Ejf8LRuSsHxCYDBTbwA= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b=jAEyjkse; arc=none smtp.client-ip=209.85.128.74 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--aliceryhl.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.b="jAEyjkse" Received: by mail-wm1-f74.google.com with SMTP id 5b1f17b1804b1-48fe40b61a3so61802835e9.3 for ; Mon, 25 May 2026 06:17:46 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20251104; t=1779715065; x=1780319865; darn=vger.kernel.org; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:from:to:cc:subject:date:message-id:reply-to; bh=KNbG2HJ2MZ13W/tRCu38pNn9hGvLRzMifdYB/tdu2zc=; b=jAEyjkseISXtOamMDEmaKkn4G+KlZliUg+FrJMzqvwGG/o7q/nrHcwuN5JUPcQmVBg hGT60bzLx2s957d0uXuZjpm/CQ9J0Fj3vW0fmu7k4RbrW2mjhAwExq5U4UHDUJCNzPD3 Zyd/j7NP4P12hmJPjQvXX9FS24aCSrpScUAe8e9VKPMyeBs50XGYd+G0WQA6ayhV9XQU pq1WpA08NwHzVE5irB4Lr9weolfRUFmg/MFiZICvlJlz4dkldwj+2jeU5W4AH9flltYX rOT0QOkZJGafujA+aksk4EJvvgB/Y7QdGo6HlkIrfPPlO71nGi0ODyG9GkS+TAs5vapb 0U4w== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20251104; t=1779715065; x=1780319865; h=cc:to:from:subject:message-id:references:mime-version:in-reply-to :date:x-gm-message-state:from:to:cc:subject:date:message-id:reply-to; bh=KNbG2HJ2MZ13W/tRCu38pNn9hGvLRzMifdYB/tdu2zc=; b=QGX8vceBgMGRvKPJ0av4AODtqwyzFNqoCorY4DBOVD/uNv42eUTxe6aoRGRPCLtKL6 3bNPU75sQG9eSnLJmFEC5TMhYB26rlpHpT4blu5l5bGkvkV4eZxSNW8vbKj/VRiC5LjQ 6cJ9TeOGBpFnwvjF3ehiJvi804B0p1CNXjOLIKtV5HgC7v0rO5882UkzxrdAZe/gCo4n nlEphCSeE+GcRTafK3rjeaM6GIZSK4IVVZ3KSUZJcNbdUx1JpjowsHRi0FVq4Dx7nV3G uSRqMmOXDKv1ANBGGtbm2Unfuugv59Iu5OPrXBSY3ZiBX5OGJe6GtCfQHd7LD4UwuXF6 mizg== X-Forwarded-Encrypted: i=1; AFNElJ/Mgalt8NwTtvwCad/q4M+3//X/RxrVYqN1kb+peQUwTBQieEYPtAF6cXlaWOE2qtB8j+GCFl4Jq3/rCBQ=@vger.kernel.org X-Gm-Message-State: AOJu0YzSEdhRflWUP2kGjs520bgBjgSzj0hSXwjCoo5n6ij79q49qt6L 8Wwqa7ym1V/pm40CBddTKIUcCPp+PdFYsQr1IqZdi3LdpniawAAiPnpCZd+3xvjbWCWJi8UhQmO fzlwrNTD6/nG4VbGh0g== X-Received: from wmep20.prod.google.com ([2002:a05:600c:4314:b0:489:1f97:aec7]) (user=aliceryhl job=prod-delivery.src-stubby-dispatcher) by 2002:a05:600c:4f52:b0:490:4f91:5519 with SMTP id 5b1f17b1804b1-4904f91568dmr207512105e9.18.1779715064610; Mon, 25 May 2026 06:17:44 -0700 (PDT) Date: Mon, 25 May 2026 13:17:28 +0000 In-Reply-To: <20260525-binder-netlink-v5-0-a90e2923ebeb@google.com> Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: Mime-Version: 1.0 References: <20260525-binder-netlink-v5-0-a90e2923ebeb@google.com> X-Developer-Key: i=aliceryhl@google.com; a=openpgp; fpr=49F6C1FAA74960F43A5B86A1EE7A392FDE96209F X-Developer-Signature: v=1; a=openpgp-sha256; l=11302; i=aliceryhl@google.com; h=from:subject:message-id; bh=oqg7PkgyuFpdSHZMroM+y5quqYpOBs1htUkwsJ8R/8c=; b=owEBbQKS/ZANAwAKAQRYvu5YxjlGAcsmYgBqFEvznwLPvxPxyuavoTjmHREwRQvXPngCSNim/ CTdbY12tbmJAjMEAAEKAB0WIQSDkqKUTWQHCvFIvbIEWL7uWMY5RgUCahRL8wAKCRAEWL7uWMY5 RprCD/9w73QGw1Svtvfz2T7YBtimsZyxq7IWWS3bpjB2bI8ZZFIC9pUGZDvY3ATeRO1lpC4Td01 JK42P3vJbgkVTVq3YD3pm/JKPWSwX+qCXf5QOZluwwPik4gMk8aHXp19q8kDk1zAXszGuhx7VKo HDkK9D03UtTX+BrXMfnG2aoIZwmhlnC+EVr8f3Rhno1ag0wYL8BuuuFNGdGSmbqse7rSqx81+37 XXnZQ/Aoly9MCRgETIqg+QUC+2uJG6/0EN5SnGsa6537FnNGB1xjm5zXCwAx2qrxke8yzeQy+jw B68SIF8AMrNmnf9PncumjNvKI0SjM40nZJPGkRN4sAz1GQzSbXwiP3R0dmvZzBl9/aUlIgXW89m Lj/tEXXOv90kvn30Km0LCtYR7XPU9sSo4WC/WrlUMLrrax150g21tnVp+4mdDia+vHcwDMsycht M5aKCHleLzj2BJ0kuVYpBdweAdJQWQWxpRbMGc0x0llEHXLlgg/BGPDrdvEIO8WkVzecXaQVZYY K+nP3iNEHuOmBZuTQaUldlmCz16GUeg0nIJ/xUV0aCm0Vi2nstrrTJuW4ONLE+udU9fOudBmVnV iZgLhiR6J8ZmhRPSV3nf4q6OMnloBQS7xUBZcCnxBDdLsh+U/yPXloVKoxv9VHjURBpeiwmVKhZ YUs7/3Kv/bed5Dw== X-Mailer: b4 0.14.3 Message-ID: <20260525-binder-netlink-v5-2-a90e2923ebeb@google.com> Subject: [PATCH v5 2/2] rust_binder: report netlink transactions From: Alice Ryhl To: Carlos Llamas , Greg Kroah-Hartman , Andrew Lunn , Donald Hunter , Jakub Kicinski , "David S. Miller" , Eric Dumazet , Paolo Abeni , Simon Horman , Matthew Maurer Cc: Miguel Ojeda , Boqun Feng , Gary Guo , "=?utf-8?q?Bj=C3=B6rn_Roy_Baron?=" , Benno Lossin , Andreas Hindborg , Trevor Gross , Danilo Krummrich , Christian Brauner , linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, netdev@vger.kernel.org, Alice Ryhl Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable From: Carlos Llamas 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. Signed-off-by: Carlos Llamas Co-developed-by: Alice Ryhl Signed-off-by: Alice Ryhl --- drivers/android/Kconfig | 2 +- drivers/android/binder/netlink.rs | 110 +++++++++++++++++++++++++= ++++ drivers/android/binder/rust_binder_main.rs | 8 ++- drivers/android/binder/thread.rs | 10 +++ drivers/android/binder/transaction.rs | 40 +++++++++++ rust/uapi/uapi_helper.h | 1 + 6 files changed, 168 insertions(+), 3 deletions(-) diff --git a/drivers/android/Kconfig b/drivers/android/Kconfig index e2e402c9d175..606a9d07f774 100644 --- a/drivers/android/Kconfig +++ b/drivers/android/Kconfig @@ -16,7 +16,7 @@ config ANDROID_BINDER_IPC =20 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. =20 diff --git a/drivers/android/binder/netlink.rs b/drivers/android/binder/net= link.rs new file mode 100644 index 000000000000..818ac6f2536d --- /dev/null +++ b/drivers/android/binder/netlink.rs @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: ((GPL-2.0 WITH Linux-syscall-note) OR BSD-3-Cl= ause) +/* Based on: Documentation/netlink/specs/binder.yaml */ + +#![allow(unreachable_pub, clippy::wrong_self_convention)] +use kernel::netlink::{Family, MulticastGroup}; +use kernel::prelude::*; + +pub static BINDER_NL_FAMILY: Family =3D Family::const_new( + &crate::THIS_MODULE, + kernel::uapi::BINDER_FAMILY_NAME, + kernel::uapi::BINDER_FAMILY_VERSION, + &BINDER_NL_FAMILY_MCGRPS, +); + +static BINDER_NL_FAMILY_MCGRPS: [MulticastGroup; 1] =3D [MulticastGroup::c= onst_new(c"report")]; + +/// A multicast event sent to userspace subscribers to notify them about +/// binder transaction failures. The generated report provides the full +/// details of the specific transaction that failed. The intention is for +/// programs to monitor these events and react to the failures as needed. +pub struct Report { + skb: kernel::netlink::GenlMsg, +} + +impl Report { + /// Create a new multicast message. + pub fn new( + size: usize, + portid: u32, + seq: u32, + flags: kernel::alloc::Flags, + ) -> Result { + const BINDER_CMD_REPORT: u8 =3D kernel::uapi::BINDER_CMD_REPORT as= u8; + let skb =3D kernel::netlink::NetlinkSkBuff::new(size, flags)?; + let skb =3D skb.genlmsg_put(portid, seq, &BINDER_NL_FAMILY, BINDER= _CMD_REPORT)?; + Ok(Self { skb }) + } + + /// Broadcast this message. + pub fn multicast(self, portid: u32, flags: kernel::alloc::Flags) -> Re= sult { + self.skb.multicast(&BINDER_NL_FAMILY, portid, 0, flags) + } + + /// Check if this message type has listeners. + pub fn has_listeners() -> bool { + BINDER_NL_FAMILY.has_listeners(0) + } + + /// The enum binder_driver_return_protocol returned to the sender. + pub fn error(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_ERROR: c_int =3D kernel::uapi::BINDER_A_REPO= RT_ERROR as c_int; + self.skb.put_u32(BINDER_A_REPORT_ERROR, val) + } + + /// The binder context where the transaction occurred. + pub fn context(&mut self, val: &CStr) -> Result { + const BINDER_A_REPORT_CONTEXT: c_int =3D kernel::uapi::BINDER_A_RE= PORT_CONTEXT as c_int; + self.skb.put_string(BINDER_A_REPORT_CONTEXT, val) + } + + /// The PID of the sender process. + pub fn from_pid(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_FROM_PID: c_int =3D kernel::uapi::BINDER_A_R= EPORT_FROM_PID as c_int; + self.skb.put_u32(BINDER_A_REPORT_FROM_PID, val) + } + + /// The TID of the sender thread. + pub fn from_tid(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_FROM_TID: c_int =3D kernel::uapi::BINDER_A_R= EPORT_FROM_TID as c_int; + self.skb.put_u32(BINDER_A_REPORT_FROM_TID, val) + } + + /// The PID of the recipient process. This attribute may not be present + /// if the target could not be determined. + pub fn to_pid(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_TO_PID: c_int =3D kernel::uapi::BINDER_A_REP= ORT_TO_PID as c_int; + self.skb.put_u32(BINDER_A_REPORT_TO_PID, val) + } + + /// The TID of the recipient thread. This attribute may not be present + /// if the target could not be determined. + pub fn to_tid(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_TO_TID: c_int =3D kernel::uapi::BINDER_A_REP= ORT_TO_TID as c_int; + self.skb.put_u32(BINDER_A_REPORT_TO_TID, val) + } + + /// When present, indicates the failed transaction is a reply. + pub fn is_reply(&mut self) -> Result { + const BINDER_A_REPORT_IS_REPLY: c_int =3D kernel::uapi::BINDER_A_R= EPORT_IS_REPLY as c_int; + self.skb.put_flag(BINDER_A_REPORT_IS_REPLY) + } + + /// The bitmask of enum transaction_flags from the transaction. + pub fn flags(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_FLAGS: c_int =3D kernel::uapi::BINDER_A_REPO= RT_FLAGS as c_int; + self.skb.put_u32(BINDER_A_REPORT_FLAGS, val) + } + + /// The application-defined code from the transaction. + pub fn code(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_CODE: c_int =3D kernel::uapi::BINDER_A_REPOR= T_CODE as c_int; + self.skb.put_u32(BINDER_A_REPORT_CODE, val) + } + + /// The transaction payload size in bytes. + pub fn data_size(&mut self, val: u32) -> Result { + const BINDER_A_REPORT_DATA_SIZE: c_int =3D kernel::uapi::BINDER_A_= REPORT_DATA_SIZE as c_int; + self.skb.put_u32(BINDER_A_REPORT_DATA_SIZE, val) + } +} diff --git a/drivers/android/binder/rust_binder_main.rs b/drivers/android/b= inder/rust_binder_main.rs index dc1941cd2407..bbef68993b8d 100644 --- a/drivers/android/binder/rust_binder_main.rs +++ b/drivers/android/binder/rust_binder_main.rs @@ -38,6 +38,7 @@ mod deferred_close; mod defs; mod error; +mod netlink; mod node; mod page_range; mod process; @@ -288,19 +289,22 @@ fn ptr_align(value: usize) -> Option { // SAFETY: We call register in `init`. static BINDER_SHRINKER: Shrinker =3D unsafe { Shrinker::new() }; =20 -struct BinderModule {} +struct BinderModule { + _netlink: kernel::netlink::Registration, +} =20 impl kernel::Module for BinderModule { fn init(_module: &'static kernel::ThisModule) -> Result { // SAFETY: The module initializer never runs twice, so we only cal= l this once. unsafe { crate::context::CONTEXTS.init() }; =20 + let netlink =3D crate::netlink::BINDER_NL_FAMILY.register()?; BINDER_SHRINKER.register(c"android-binder")?; =20 // SAFETY: The module is being loaded, so we can initialize binder= fs. unsafe { kernel::error::to_result(binderfs::init_rust_binderfs())?= }; =20 - Ok(Self {}) + Ok(Self { _netlink: netlink }) } } =20 diff --git a/drivers/android/binder/thread.rs b/drivers/android/binder/thre= ad.rs index 97d5f31e8fe3..aa4e93a877ac 100644 --- a/drivers/android/binder/thread.rs +++ b/drivers/android/binder/thread.rs @@ -1263,6 +1263,15 @@ fn transaction(self: &Arc, cmd: u32, reader: &= mut UserSliceReader) -> Resu } } =20 + if info.oneway_spam_suspect { + // If this is both a oneway spam suspect and a failure, we rep= ort it twice. This is + // useful in case the transaction failed with BR_TRANSACTION_P= ENDING_FROZEN. + info.report_netlink(BR_ONEWAY_SPAM_SUSPECT, &self.process.ctx); + } + if info.reply !=3D 0 { + info.report_netlink(info.reply, &self.process.ctx); + } + Ok(()) } =20 @@ -1332,6 +1341,7 @@ fn reply_inner(self: &Arc, info: &mut Transacti= onInfo) -> BinderResult { ); let reply =3D Err(BR_FAILED_REPLY); orig.from.deliver_reply(reply, &orig); + info.reply =3D BR_FAILED_REPLY; err.reply =3D BR_TRANSACTION_COMPLETE; err }); diff --git a/drivers/android/binder/transaction.rs b/drivers/android/binder= /transaction.rs index 47d5e4d88b07..3fa7091ed8a6 100644 --- a/drivers/android/binder/transaction.rs +++ b/drivers/android/binder/transaction.rs @@ -3,6 +3,7 @@ // Copyright (C) 2025 Google LLC. =20 use kernel::{ + netlink::GENLMSG_DEFAULT_SIZE, prelude::*, seq_file::SeqFile, seq_print, @@ -17,6 +18,7 @@ allocation::{Allocation, TranslatedFds}, defs::*, error::{BinderError, BinderResult}, + netlink::Report, node::{Node, NodeRef}, process::{Process, ProcessInner}, ptr_align, @@ -49,6 +51,44 @@ impl TransactionInfo { pub(crate) fn is_oneway(&self) -> bool { self.flags & TF_ONE_WAY !=3D 0 } + + pub(crate) fn report_netlink(&self, reply: u32, ctx: &crate::Context) { + if let Err(err) =3D 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) -> ke= rnel::error::Result { + if !Report::has_listeners() { + return Ok(()); + } + let mut report =3D Report::new(GENLMSG_DEFAULT_SIZE, 0, 0, GFP_KER= NEL)?; + + 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 !=3D 0 { + report.to_pid(self.to_pid as u32)?; + } + if self.to_tid !=3D 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(()) + } } =20 use core::mem::offset_of; diff --git a/rust/uapi/uapi_helper.h b/rust/uapi/uapi_helper.h index 06d7d1a2e8da..86c7b6b284b0 100644 --- a/rust/uapi/uapi_helper.h +++ b/rust/uapi/uapi_helper.h @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include --=20 2.54.0.746.g67dd491aae-goog