Skip to contentSkip to conversation

Rate limited printing for Rust

PATCH Superseded Alice Ryhl 3 participants 12 messages Aug 3 – Oct 2

Subsystems (4)

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

v5 cover Rate limited printing for Rust

To avoid DoS on the kernel log, the Rust Binder driver is being switched to rate limited printing. But before we can do that, we must first implement rate limited printing for Rust. Thus, do that.

However, it turns out that before we can implement rate limited printing, we must first implement the ability declare a raw_spinlock_t in a global variable. Thus, do that too.

---
Changes in v5:
- Rebase on char-misc-next.
- Pick up Acked-by tags.
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- Rebase series.
- Mark Ratelimit::new_static() with #[inline]
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Rebase on char-misc-testing.
- Add rust/kernel/sync/lockdep.rs to MAINTAINERS file.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Rebase on top of binder_debug! patch series.
- As a consequence, the logic for printing the size of transaction
failures is changed to print the size of each piece of the
transaction, rather than the total buffer size.
- Add doc aliases for raw_spin_lock_unlocked.
- Make raw_spin_lock_unlocked and raw_lockdep_map private.
- Add Ratelimit::new_static.
- Add some missing links to docs.
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Alice Ryhl (5):
rust: sync: move lockdep types to rust/kernel/sync/lockdep.rs
rust: sync: add const constructor for raw_spinlock_t
rust: add pr_*_ratelimit! macros for printing
rust_binder: consolidate transaction failure prints
rust_binder: use pr_*_ratelimited! for printing

 MAINTAINERS                           |   1 +
 drivers/android/binder/allocation.rs  |   4 +-
 drivers/android/binder/context.rs     |   6 +-
 drivers/android/binder/debug.rs       |   4 +-
 drivers/android/binder/error.rs       |   4 -
 drivers/android/binder/freeze.rs      |   2 +-
 drivers/android/binder/node.rs        |   4 +-
 drivers/android/binder/page_range.rs  |  12 +-
 drivers/android/binder/process.rs     |  22 ++--
 drivers/android/binder/thread.rs      | 119 +++++++++----------
 drivers/android/binder/transaction.rs |  24 +---
 include/linux/spinlock_types_raw.h    |   4 +
 rust/bindings/lib.rs                  |  24 ++++
 rust/helpers/helpers.c                |   1 +
 rust/helpers/ratelimit.c              |  14 +++
 rust/kernel/error.rs                  |   2 +-
 rust/kernel/lib.rs                    |   1 +
 rust/kernel/prelude.rs                |   8 ++
 rust/kernel/ratelimit.rs              | 216 ++++++++++++++++++++++++++++++++++
 rust/kernel/sync.rs                   | 135 +--------------------
 rust/kernel/sync/lock/spinlock.rs     |  30 +++++
 rust/kernel/sync/lockdep.rs           | 161 +++++++++++++++++++++++++
 22 files changed, 553 insertions(+), 245 deletions(-)

---
base-commit: 220190f97da558e67cd01c62f1b84fe77b267a5a
change-id: 20260619-pr-ratelimited-6e20fa89bd5b

Best regards,

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

PATCH v5 1/5 rust: sync: move lockdep types to rust/kernel/sync/lockdep.rs

The lockdep types are currently stored directly in rust/kernel/sync.rs, but there are starting to be too many of them to keep them in that file. Thus, move them to a submodule. The new module is listed under LOCKING PRIMITIVES in the MAINTAINERS file.

For commonly used lockdep logic it's useful to keep re-exports in kernel::sync, and this also avoids the need to update any users.

---
 MAINTAINERS                 |   1 +
 rust/kernel/sync.rs         | 135 +-----------------------------------------
 rust/kernel/sync/lockdep.rs | 139 ++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 142 insertions(+), 133 deletions(-)
MAINTAINERS +1 -0
index 1e27c49ffe48..5c945f981fee 100644
@@ -15161,6 +15161,7 @@ F:	rust/helpers/mutex.c
 F:	rust/helpers/spinlock.c
 F:	rust/kernel/sync/lock.rs
 F:	rust/kernel/sync/lock/
+F:	rust/kernel/sync/lockdep.rs
 F:	rust/kernel/sync/locked_by.rs
 X:	kernel/locking/locktorture.c
 
rust/kernel/sync.rs +2 -133

153 lines not on this page · raw message

rust/kernel/sync/lockdep.rs new file +139 -0

139 lines not on this page · raw message

Signature · 1 line
2.55.0.508.g3f0d502094-goog
author maintainer
#2 lore raw

PATCH v5 2/5 rust: sync: add const constructor for raw_spinlock_t

In reply to Alice Ryhl

The abstractions for pr_*_ratelimited! need to construct a global struct ratelimit_state, which contains a raw_spinlock_t field. Thus, add a const constructor for the raw_spinlock_t type.

The SPINLOCK_OWNER_INIT constant isn't mirrored via a const helper because bindgen generates a 'static mut' instead of a constant from the pointer constant.,

The __ARCH_SPIN_LOCK_UNLOCKED constant cannot be translated by bindgen because it's a define for a struct without type annotations, so it's explicitly declared in Rust.

---
 include/linux/spinlock_types_raw.h |  4 ++++
 rust/bindings/lib.rs               | 24 ++++++++++++++++++++++++
 rust/kernel/sync/lock/spinlock.rs  | 31 +++++++++++++++++++++++++++++++
 rust/kernel/sync/lockdep.rs        | 22 ++++++++++++++++++++++
 4 files changed, 81 insertions(+)
include/linux/spinlock_types_raw.h +4 -0
index e5644ab2161f..942c229c90bb 100644
@@ -11,6 +11,10 @@
 
 #include <linux/lockdep_types.h>
 
+/*
+ * Keep in sync with rust/kernel/sync/lock/spinlock.rs
+ */
+
 context_lock_struct(raw_spinlock) {
 	arch_spinlock_t raw_lock;
 #ifdef CONFIG_DEBUG_SPINLOCK
rust/bindings/lib.rs +24 -0
index 812f8e5a08d5..bb35e64957cd 100644
@@ -81,3 +81,27 @@ mod bindings_helper {
         None
     }
 };
+
+// Explicitly list architectures where this logic is checked correct.
+#[cfg(any(
+    CONFIG_ARM,
+    CONFIG_ARM64,
+    CONFIG_LOONGARCH,
+    CONFIG_PPC,
+    CONFIG_RISCV,
+    CONFIG_S390,
+    CONFIG_X86,
+))]
+pub const __ARCH_SPIN_LOCK_UNLOCKED: arch_spinlock_t = {
+    // SAFETY: The `arch_spinlock_t` type can be zeroed.
+    #[allow(unused_mut)]
+    let mut lock: arch_spinlock_t = unsafe { core::mem::zeroed() };
+
+    #[cfg(not(CONFIG_SMP))]
+    #[cfg(CONFIG_DEBUG_SPINLOCK)]
+    {
+        lock.slock = 1;
+    }
+
+    lock
+};
rust/kernel/sync/lock/spinlock.rs +31 -0
index ef76fa07ca3a..697efa7e04c6 100644
@@ -4,6 +4,8 @@
 //!
 //! This module allows Rust code to use the kernel's `spinlock_t`.
 
+use kernel::prelude::*;
+
 /// Creates a [`SpinLock`] initialiser with the given name and a newly-created lock class.
 ///
 /// It uses the name if one is given, otherwise it generates one based on the file name and line
@@ -144,3 +146,32 @@ unsafe fn assert_is_held(ptr: *mut Self::State) {
         unsafe { bindings::spin_assert_is_held(ptr) }
     }
 }
+
+/// Helper for creating a raw unlocked `bindings::raw_spinlock_t`.
+///
+/// For use in statics containing raw spinlocks.
+#[doc(alias("__SPIN_LOCK_UNLOCKED", "DEFINE_SPINLOCK"))]
+#[expect(dead_code)]
+pub(crate) const fn raw_spin_lock_unlocked(name: &'static CStr) -> bindings::raw_spinlock_t {
+    // Silence unused variable warnings.
+    #[cfg(not(CONFIG_DEBUG_LOCK_ALLOC))]
+    let _ = name;
+
+    bindings::raw_spinlock_t {
+        raw_lock: bindings::__ARCH_SPIN_LOCK_UNLOCKED,
+
+        #[cfg(CONFIG_DEBUG_SPINLOCK)]
+        magic: bindings::SPINLOCK_MAGIC,
+        #[cfg(CONFIG_DEBUG_SPINLOCK)]
+        owner_cpu: u32::MAX,
+        #[cfg(CONFIG_DEBUG_SPINLOCK)]
+        owner: usize::MAX as *mut c_void,
+
+        #[cfg(CONFIG_DEBUG_LOCK_ALLOC)]
+        dep_map: kernel::sync::lockdep::raw_lockdep_map(
+            name,
+            kernel::sync::lockdep::LD_WAIT_SPIN,
+            kernel::sync::lockdep::LD_WAIT_INV,
+        ),
+    }
+}
rust/kernel/sync/lockdep.rs +22 -0
index 784821cc2a39..d9222be0fb29 100644
@@ -137,3 +137,25 @@ macro_rules! optional_name {
         $crate::c_str!($name)
     };
 }
+
+/// Not checked, catch all.
+pub const LD_WAIT_INV: u8 = bindings::lockdep_wait_type_LD_WAIT_INV as u8;
+/// Spin loops, `raw_spinlock_t` etc
+pub const LD_WAIT_SPIN: u8 = bindings::lockdep_wait_type_LD_WAIT_SPIN as u8;
+
+/// Helper for declaring a raw `struct lockdep_map` for locks in statics.
+///
+/// It's up to the caller to use the returned `struct lockdep_map` correctly.
+#[cfg(CONFIG_DEBUG_LOCK_ALLOC)]
+pub(crate) const fn raw_lockdep_map(
+    name: &'static CStr,
+    wait_type_inner: u8,
+    wait_type_outer: u8,
+) -> bindings::lockdep_map {
+    // SAFETY: All zeros is valid for this type.
+    let mut map: bindings::lockdep_map = unsafe { core::mem::zeroed() };
+    map.name = kernel::str::as_char_ptr_in_const_context(name);
+    map.wait_type_inner = wait_type_inner;
+    map.wait_type_outer = wait_type_outer;
+    map
+}
Signature · 1 line
2.55.0.508.g3f0d502094-goog
#3 lore raw

Re: [PATCH v5 2/5] rust: sync: add const constructor for raw_spinlock_t

rust/bindings/lib.rs mod bindings_helper { · line 94

Quoted 11 lines · Alice Ryhl
rust/bindings/lib.rs +10 -0
+// Explicitly list architectures where this logic is checked correct.
+#[cfg(any(
+    CONFIG_ARM,
+    CONFIG_ARM64,
+    CONFIG_LOONGARCH,
+    CONFIG_PPC,
+    CONFIG_RISCV,
+    CONFIG_S390,
+    CONFIG_X86,
+))]

Sashiko is right, we need UML here to avoid a build error.

However, I think we should be specific, just in case, and thus use CONFIG_UML_X86 instead of CONFIG_UML, since this list is about having checked that the logic is correct manually.

Cheers,
Miguel

author maintainer
#4 lore raw

PATCH v5 3/5 rust: add pr_*_ratelimit! macros for printing

In reply to Alice Ryhl

Printing can be very expensive if it occurs often, so printing that can be triggered by userspace should be rate limited. For this purpose, add a Rust wrapper around struct ratelimit_state and use it in the new macros.

The new files will fall under the catch-all RUST maintainers entry.

---
 rust/helpers/helpers.c            |   1 +
 rust/helpers/ratelimit.c          |  14 +++
 rust/kernel/lib.rs                |   1 +
 rust/kernel/prelude.rs            |   8 ++
 rust/kernel/ratelimit.rs          | 216 ++++++++++++++++++++++++++++++++++++++
 rust/kernel/sync/lock/spinlock.rs |   1 -
 6 files changed, 240 insertions(+), 1 deletion(-)
rust/helpers/helpers.c +1 -0
index 1d4ee51f576b..cbecf152f647 100644
@@ -82,6 +82,7 @@
 #include "processor.c"
 #include "property.c"
 #include "pwm.c"
+#include "ratelimit.c"
 #include "rbtree.c"
 #include "rcu.c"
 #include "refcount.c"
rust/helpers/ratelimit.c new file +14 -0
new file mode 100644
index 000000000000..e5052f568b81
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/ratelimit.h>
+
+__rust_helper void rust_helper_ratelimit_state_init(struct ratelimit_state *rs,
+						    int interval, int burst)
+{
+	ratelimit_state_init(rs, interval, burst);
+}
+
+__rust_helper void rust_helper_ratelimit_state_exit(struct ratelimit_state *rs)
+{
+	ratelimit_state_exit(rs);
+}
rust/kernel/lib.rs +1 -0
index 9512af7156df..f53dd564aef5 100644
@@ -112,6 +112,7 @@
 pub mod ptr;
 #[cfg(CONFIG_RUST_PWM_ABSTRACTIONS)]
 pub mod pwm;
+pub mod ratelimit;
 pub mod rbtree;
 pub mod regulator;
 pub mod revocable;
rust/kernel/prelude.rs +8 -0
index ca396f1f78a6..bcaa232205be 100644
@@ -107,13 +107,21 @@
     },
     init::InPlaceInit,
     pr_alert,
+    pr_alert_ratelimited,
     pr_crit,
+    pr_crit_ratelimited,
     pr_debug,
+    pr_debug_ratelimited,
     pr_emerg,
+    pr_emerg_ratelimited,
     pr_err,
+    pr_err_ratelimited,
     pr_info,
+    pr_info_ratelimited,
     pr_notice,
+    pr_notice_ratelimited,
     pr_warn,
+    pr_warn_ratelimited,
     str::CStrExt as _,
     try_init,
     try_pin_init,
rust/kernel/ratelimit.rs new file +216 -0

216 lines not on this page · raw message

rust/kernel/sync/lock/spinlock.rs +0 -1
index 697efa7e04c6..b9869f958ce0 100644
@@ -151,7 +151,6 @@ unsafe fn assert_is_held(ptr: *mut Self::State) {
 ///
 /// For use in statics containing raw spinlocks.
 #[doc(alias("__SPIN_LOCK_UNLOCKED", "DEFINE_SPINLOCK"))]
-#[expect(dead_code)]
 pub(crate) const fn raw_spin_lock_unlocked(name: &'static CStr) -> bindings::raw_spinlock_t {
     // Silence unused variable warnings.
     #[cfg(not(CONFIG_DEBUG_LOCK_ALLOC))]
Signature · 1 line
2.55.0.508.g3f0d502094-goog
#5 lore raw

Re: [PATCH v5 3/5] rust: add pr_*_ratelimit! macros for printing

rust/kernel/ratelimit.rs line 87

Quoted 11 lines · Alice Ryhl
rust/kernel/ratelimit.rs new file +10 -0
+    pub const unsafe fn new_static(name: &'static CStr, interval: i32, burst: i32) -> Self {
+        Self {
+            inner: Opaque::new(bindings::ratelimit_state {
+                lock: kernel::sync::lock::spinlock::raw_spin_lock_unlocked(name),
+                interval,
+                burst,
+                ..pin_init::zeroed()
+            }),
+        }
+    }

Sashiko is right here -- missing // INVARIANT.

Quoted 1 line

+ // We don't set RATELIMIT_MSG_ON_RELEASE, so the function name parameter is not used.

This seems inverted as well.

I hope that helps!

Cheers,
Miguel

author maintainer
#6 lore raw

PATCH v5 4/5 rust_binder: consolidate transaction failure prints

In reply to Alice Ryhl

When a transaction fails, it currently hits multiple print statements meaning that a single failure can result in several lines in the kernel log. This is unnecessary, so consolidate them into one print used for all transaction failures.

---
 drivers/android/binder/error.rs       |  4 --
 drivers/android/binder/thread.rs      | 71 +++++++++++++++--------------------
 drivers/android/binder/transaction.rs | 20 ++--------
 rust/kernel/error.rs                  |  2 +-
 4 files changed, 34 insertions(+), 63 deletions(-)
drivers/android/binder/error.rs +0 -4
index 1296072c35d9..aed1c747640b 100644
@@ -37,10 +37,6 @@ pub(crate) fn new_frozen_oneway() -> Self {
             source: None,
         }
     }
-
-    pub(crate) fn is_dead(&self) -> bool {
-        self.reply == BR_DEAD_REPLY
-    }
 }
 
 /// Convert an errno into a `BinderError` and store the errno used to construct it. The errno
drivers/android/binder/thread.rs +30 -41

109 lines not on this page · raw message

drivers/android/binder/transaction.rs +3 -17
index 245f1556b5db..81df588d96ad 100644
@@ -166,21 +166,13 @@ pub(crate) fn new(
         let txn_security_ctx = node_ref.node.flags & FLAT_BINDER_FLAG_TXN_SECURITY_CTX != 0;
         let mut txn_security_ctx_off = if txn_security_ctx { Some(0) } else { None };
         let to = node_ref.node.owner.clone();
-        let mut alloc = match from.copy_transaction_data(
+        let mut alloc = from.copy_transaction_data(
             to.clone(),
             info,
             info.debug_id,
             allow_fds,
             txn_security_ctx_off.as_mut(),
-        ) {
-            Ok(alloc) => alloc,
-            Err(err) => {
-                if !err.is_dead() {
-                    pr_warn!("Failure in copy_transaction_data: {:?}", err);
-                }
-                return Err(err);
-            }
-        };
+        )?;
         if info.is_oneway() {
             if from_parent.is_some() {
                 pr_warn!("Oneway transaction should not be in a transaction stack.");
@@ -221,13 +213,7 @@ pub(crate) fn new_reply(
         allow_fds: bool,
     ) -> BinderResult<DLArc<Self>> {
         let mut alloc =
-            match from.copy_transaction_data(to.clone(), info, info.debug_id, allow_fds, None) {
-                Ok(alloc) => alloc,
-                Err(err) => {
-                    pr_warn!("Failure in copy_transaction_data: {:?}", err);
-                    return Err(err);
-                }
-            };
+            from.copy_transaction_data(to.clone(), info, info.debug_id, allow_fds, None)?;
         if info.flags.contains(TransactionFlag::ClearBuf) {
             alloc.set_info_clear_on_drop();
         }
rust/kernel/error.rs +1 -1
index a56ba6309594..380cd3f7276b 100644
@@ -135,7 +135,7 @@ pub fn from_errno(errno: crate::ffi::c_int) -> Error {
     /// Creates an [`Error`] from a kernel error code.
     ///
     /// Returns [`None`] if `errno` is out-of-range.
-    const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
+    pub const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
             return None;
         }
Signature · 1 line
2.55.0.508.g3f0d502094-goog
#7 lore raw

Re: [PATCH v5 4/5] rust_binder: consolidate transaction failure prints

Quoted 6 lines · Alice Ryhl
rust/kernel/error.rs +0 -0
index a56ba6309594..380cd3f7276b 100644

rust/kernel/error.rs pub fn from_errno(errno: crate::ffi::c_int) -> Error { · line 141

Quoted 8 lines
rust/kernel/error.rs +1 -1
@@ -135,7 +135,7 @@ pub fn from_errno(errno: crate::ffi::c_int) -> Error {
     /// Creates an [`Error`] from a kernel error code.
     ///
     /// Returns [`None`] if `errno` is out-of-range.
-    const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
+    pub const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
             return None;
         }

Generally speaking, one should know from the context whether an integer is supposed to be an error or not, and thus it is rare to need this function instead of the public one (this one is private, and the two callers are here, not elsewhere in kernel).

So I wondered if Binder needs this -- I noticed the change when doing my usual go-through-the-ML exercise and asked Alice about it, since it seemed to me like Binder could perhaps avoid using the fallible operation (and maybe even define an enum for BinderError instead of a struct to be more precise about when a source is needed).

Alice told me that the Option in BinderError is just meant for the zero case, i.e. the raw integer there should not be a random value. Thus, since the if already covers the zero case, it does look like this could use the infallible operation since we do know statically it should be an error (modulo a bug).

So it sounds like the change can indeed be avoided, which should also improve the code.

In any case, if we keep it, then the error.rs change should be mentioned in the commit message.

By the way, I am still happy to take the first three patches unless Binder is picking this up.

Thanks!

Cheers,
Miguel

#8 lore raw

Re: [PATCH v5 4/5] rust_binder: consolidate transaction failure prints

Quoted 33 lines · Miguel Ojeda
Quoted 6 lines · Alice Ryhl
rust/kernel/error.rs +0 -0
index a56ba6309594..380cd3f7276b 100644

rust/kernel/error.rs pub fn from_errno(errno: crate::ffi::c_int) -> Error { · line 141

Quoted 8 lines
rust/kernel/error.rs +1 -1
@@ -135,7 +135,7 @@ pub fn from_errno(errno: crate::ffi::c_int) -> Error {
     /// Creates an [`Error`] from a kernel error code.
     ///
     /// Returns [`None`] if `errno` is out-of-range.
-    const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
+    pub const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
             return None;
         }

Generally speaking, one should know from the context whether an integer is supposed to be an error or not, and thus it is rare to need this function instead of the public one (this one is private, and the two callers are here, not elsewhere in kernel).

So I wondered if Binder needs this -- I noticed the change when doing my usual go-through-the-ML exercise and asked Alice about it, since it seemed to me like Binder could perhaps avoid using the fallible operation (and maybe even define an enum for BinderError instead of a struct to be more precise about when a source is needed).

Alice told me that the Option in BinderError is just meant for the zero case, i.e. the raw integer there should not be a random value. Thus, since the if already covers the zero case, it does look like this could use the infallible operation since we do know statically it should be an error (modulo a bug).

Quoted 8 lines

So it sounds like the change can indeed be avoided, which should also improve the code.

In any case, if we keep it, then the error.rs change should be mentioned in the commit message.

By the way, I am still happy to take the first three patches unless Binder is picking this up.

I'll just take them all now, thanks.

greg k-h

#9 lore raw

Re: [PATCH v5 4/5] rust_binder: consolidate transaction failure prints

Quoted 37 lines · Greg Kroah-Hartman
Quoted 36 lines · Miguel Ojeda
Quoted 6 lines · Alice Ryhl
rust/kernel/error.rs +0 -0
index a56ba6309594..380cd3f7276b 100644

rust/kernel/error.rs pub fn from_errno(errno: crate::ffi::c_int) -> Error { · line 141

Quoted 8 lines
rust/kernel/error.rs +1 -1
@@ -135,7 +135,7 @@ pub fn from_errno(errno: crate::ffi::c_int) -> Error {
     /// Creates an [`Error`] from a kernel error code.
     ///
     /// Returns [`None`] if `errno` is out-of-range.
-    const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
+    pub const fn try_from_errno(errno: crate::ffi::c_int) -> Option<Error> {
         if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
             return None;
         }

Generally speaking, one should know from the context whether an integer is supposed to be an error or not, and thus it is rare to need this function instead of the public one (this one is private, and the two callers are here, not elsewhere in kernel).

So I wondered if Binder needs this -- I noticed the change when doing my usual go-through-the-ML exercise and asked Alice about it, since it seemed to me like Binder could perhaps avoid using the fallible operation (and maybe even define an enum for BinderError instead of a struct to be more precise about when a source is needed).

Alice told me that the Option in BinderError is just meant for the zero case, i.e. the raw integer there should not be a random value. Thus, since the if already covers the zero case, it does look like this could use the infallible operation since we do know statically it should be an error (modulo a bug).

So it sounds like the change can indeed be avoided, which should also improve the code.

Quoted 7 lines
Quoted 5 lines

In any case, if we keep it, then the error.rs change should be mentioned in the commit message.

By the way, I am still happy to take the first three patches unless Binder is picking this up.

I'll just take them all now, thanks.

Nope, the first patch doesn't apply against my tree, so I can't take this :(

#10 lore raw

Re: [PATCH v5 4/5] rust_binder: consolidate transaction failure prints

In reply to Alice Ryhl
Quoted 5 lines · Alice Ryhl

When a transaction fails, it currently hits multiple print statements meaning that a single failure can result in several lines in the kernel log. This is unnecessary, so consolidate them into one print used for all transaction failures.

Just in case: did you see what Sashiko found about info.errno?

Cheers,
Miguel

author maintainer
#11 lore raw

PATCH v5 5/5 rust_binder: use pr_*_ratelimited! for printing

In reply to Alice Ryhl

To avoid DoS from printing too much, make printing in Binder rate limited.

A big portion of these print statements have been updated to use binder_debug!, but some still remain to be converted. For now, just update them to use pr_*_ratelimted! until we get around to converting them to use binder_debug! too. While we're at it, fix the missing newlines at the end of some of those println statements.

---
 drivers/android/binder/allocation.rs  |  4 +--
 drivers/android/binder/context.rs     |  6 ++---
 drivers/android/binder/debug.rs       |  4 +--
 drivers/android/binder/freeze.rs      |  2 +-
 drivers/android/binder/node.rs        |  4 +--
 drivers/android/binder/page_range.rs  | 12 ++++-----
 drivers/android/binder/process.rs     | 22 ++++++++--------
 drivers/android/binder/thread.rs      | 48 ++++++++++++++++++++---------------
 drivers/android/binder/transaction.rs |  4 +--
 9 files changed, 57 insertions(+), 49 deletions(-)
drivers/android/binder/allocation.rs +2 -2
index 165cb797eb1e..8151ba3ea7f4 100644
@@ -261,7 +261,7 @@ fn drop(&mut self) {
                 let view = AllocationView::new(self, offsets.start);
                 for i in offsets.step_by(size_of::<u64>()) {
                     if view.cleanup_object(i).is_err() {
-                        pr_warn!("Error cleaning up object at offset {}\n", i)
+                        pr_warn_ratelimited!("Error cleaning up object at offset {}\n", i)
                     }
                 }
             }
@@ -286,7 +286,7 @@ fn drop(&mut self) {
 
             if info.clear_on_free {
                 if let Err(e) = self.fill_zero() {
-                    pr_warn!("Failed to clear data on free: {:?}", e);
+                    pr_warn_ratelimited!("Failed to clear data on free: {:?}\n", e);
                 }
             }
         }
drivers/android/binder/context.rs +3 -3
index ddddb66b3557..431d6007a9b1 100644
@@ -80,7 +80,7 @@ pub(crate) fn deregister(self: &Arc<Self>) {
 
     pub(crate) fn register_process(self: &Arc<Self>, proc: Arc<Process>) -> Result {
         if !Arc::ptr_eq(self, &proc.ctx) {
-            pr_err!("Context::register_process called on the wrong context.");
+            pr_err_ratelimited!("Context::register_process called on the wrong context.\n");
             return Err(EINVAL);
         }
         self.manager.lock().all_procs.push(proc, GFP_KERNEL)?;
@@ -89,7 +89,7 @@ pub(crate) fn register_process(self: &Arc<Self>, proc: Arc<Process>) -> Result {
 
     pub(crate) fn deregister_process(self: &Arc<Self>, proc: &Arc<Process>) {
         if !Arc::ptr_eq(self, &proc.ctx) {
-            pr_err!("Context::deregister_process called on the wrong context.");
+            pr_err_ratelimited!("Context::deregister_process called on the wrong context.\n");
             return;
         }
         let mut manager = self.manager.lock();
@@ -110,7 +110,7 @@ pub(crate) fn deregister_process(self: &Arc<Self>, proc: &Arc<Process>) {
     pub(crate) fn set_manager_node(&self, node_ref: NodeRef) -> Result {
         let mut manager = self.manager.lock();
         if manager.node.is_some() {
-            pr_warn!("BINDER_SET_CONTEXT_MGR already set");
+            pr_warn_ratelimited!("BINDER_SET_CONTEXT_MGR already set\n");
             return Err(EBUSY);
         }
         security::binder_set_context_mgr(&node_ref.node.owner.cred)?;
drivers/android/binder/debug.rs +2 -2
index 824b10c004c3..6d8dcddf4619 100644
@@ -53,7 +53,7 @@ macro_rules! binder_debug {
     // Rule to explicitly specify a PID (used in kworkers).
     (pid=$pid:expr, $mask:ident, $($arg:tt)*) => {
         if $crate::debug::debug_mask_enabled($crate::debug::DebugMask::$mask) {
-            kernel::pr_info!(
+            kernel::pr_info_ratelimited!(
                 "{}: {}\n",
                 $pid,
                 kernel::prelude::fmt!($($arg)*)
@@ -65,7 +65,7 @@ macro_rules! binder_debug {
     ($mask:ident, $($arg:tt)*) => {
         if $crate::debug::debug_mask_enabled($crate::debug::DebugMask::$mask) {
             let thread = kernel::current!();
-            kernel::pr_info!(
+            kernel::pr_info_ratelimited!(
                 "{}:{} {}\n",
                 thread.tgid(),
                 thread.pid(),
drivers/android/binder/freeze.rs +1 -1
index 66912b4cb527..7fbde3345ced 100644
@@ -412,7 +412,7 @@ fn find_freeze_recipients(&self) -> Result<KVVec<(DArc<Node>, Arc<Process>)>, Al
                 recipients
                     .push_within_capacity(node_proc_pair)
                     .map_err(|_| {
-                        pr_err!(
+                        pr_err_ratelimited!(
                             "push_within_capacity failed even though we checked the capacity\n"
                         );
                         AllocError
drivers/android/binder/node.rs +2 -2
index 0a82af14cda3..69b36951dbbe 100644
@@ -405,7 +405,7 @@ pub(crate) fn update_refcount_locked(
             !is_dead && !state.has_count
         } else {
             if state.count < count {
-                pr_err!("Failure: refcount underflow!");
+                pr_err_ratelimited!("Failure: refcount underflow!\n");
                 return None;
             }
             state.count -= count;
@@ -693,7 +693,7 @@ pub(crate) fn remove_freeze_listener(&self, p: &Process) -> KVVec<Arc<Process>>
             .freeze_list
             .retain(|proc| !core::ptr::eq::<Process>(&**proc, p));
         if len == inner.freeze_list.len() {
-            pr_warn!(
+            pr_warn_ratelimited!(
                 "Could not remove freeze listener for {}\n",
                 p.pid_in_current_ns()
             );
drivers/android/binder/page_range.rs +6 -6
index 52ffbf3504e7..c1f4f635c2c0 100644
@@ -212,7 +212,7 @@ unsafe fn set_page(me: *mut PageInfo, page: Page) {
 
         // SAFETY: The pointer is valid for writing, so also valid for reading.
         if unsafe { (*ptr).is_some() } {
-            pr_err!("set_page called when there is already a page");
+            pr_err_ratelimited!("set_page called when there is already a page\n");
             // SAFETY: We will initialize the page again below.
             unsafe { ptr::drop_in_place(ptr) };
         }
@@ -300,11 +300,11 @@ pub(crate) fn register_with_vma(&self, vma: &virt::VmaNew) -> Result<usize> {
         let num_pages = num_bytes >> PAGE_SHIFT;
 
         if !ptr::eq::<Mm>(&*self.mm, &**vma.mm()) {
-            pr_debug!("Failed to register with vma: invalid vma->vm_mm");
+            pr_debug_ratelimited!("Failed to register with vma: invalid vma->vm_mm\n");
             return Err(EINVAL);
         }
         if num_pages == 0 {
-            pr_debug!("Failed to register with vma: size zero");
+            pr_debug_ratelimited!("Failed to register with vma: size zero\n");
             return Err(EINVAL);
         }
 
@@ -325,7 +325,7 @@ pub(crate) fn register_with_vma(&self, vma: &virt::VmaNew) -> Result<usize> {
 
         let mut inner = self.lock.lock();
         if inner.size > 0 {
-            pr_debug!("Failed to register with vma: already registered");
+            pr_debug_ratelimited!("Failed to register with vma: already registered\n");
             drop(inner);
             return Err(EBUSY);
         }
@@ -380,7 +380,7 @@ pub(crate) fn use_range(&self, start: usize, end: usize) -> Result<()> {
                 match unsafe { self.use_page_slow(i) } {
                     Ok(()) => {}
                     Err(err) => {
-                        pr_warn!("Error in use_page_slow: {:?}", err);
+                        pr_warn_ratelimited!("Error in use_page_slow: {:?}\n", err);
                         return Err(err);
                     }
                 }
@@ -529,7 +529,7 @@ unsafe fn iterate<T>(&self, mut offset: usize, mut size: usize, mut cb: T) -> Re
             // duration of this call to `iterate`, so nobody will change the page.
             let page = unsafe { PageInfo::get_page(page_info) };
             if page.is_none() {
-                pr_warn!("Page is null!");
+                pr_warn_ratelimited!("Page is null!\n");
             }
             let page = page.ok_or(EFAULT)?;
             cb(page, offset, available)?;
drivers/android/binder/process.rs +12 -10
index 1778628d8acd..87628e7a3306 100644
@@ -324,7 +324,7 @@ pub(crate) fn death_delivered(&mut self, death: DArc<NodeDeath>) {
         if let Some(death) = ListArc::try_from_arc_or_drop(death) {
             self.delivered_deaths.push_back(death);
         } else {
-            pr_warn!("Notification added to `delivered_deaths` twice.");
+            pr_warn_ratelimited!("Notification added to `delivered_deaths` twice.\n");
         }
     }
 
@@ -701,7 +701,7 @@ fn get_current_thread(self: ArcBorrow<'_, Self>) -> Result<Arc<Thread>> {
         let id = {
             let current = kernel::current!();
             if self.task != current.group_leader() {
-                pr_err!("get_current_thread was called from the wrong process.");
+                pr_err_ratelimited!("get_current_thread was called from the wrong process.\n");
                 return Err(EINVAL);
             }
             current.pid()
@@ -725,7 +725,7 @@ fn get_current_thread(self: ArcBorrow<'_, Self>) -> Result<Arc<Thread>> {
                 Ok(ta)
             }
             rbtree::Entry::Occupied(_entry) => {
-                pr_err!("Cannot create two threads with the same id.");
+                pr_err_ratelimited!("Cannot create two threads with the same id.\n");
                 Err(EINVAL)
             }
         }
@@ -861,7 +861,9 @@ pub(crate) fn insert_or_update_handle(
                 match refs.by_handle.entry(res.as_u32()) {
                     rbtree::Entry::Vacant(entry) => break (res, entry),
                     rbtree::Entry::Occupied(_) => {
-                        pr_err!("Detected mismatch between handle_is_present and by_handle");
+                        pr_err_ratelimited!(
+                            "Detected mismatch between handle_is_present and by_handle\n"
+                        );
                         res.acquire();
                         kernel::warn_on!(true);
                         return Err(EINVAL);
@@ -1101,7 +1103,7 @@ pub(crate) fn buffer_alloc(
         ) {
             Ok(()) => {}
             Err(err) => {
-                pr_warn!("use_range failure {:?}", err);
+                pr_warn_ratelimited!("use_range failure {:?}\n", err);
                 return Err(err.into());
             }
         }
@@ -1132,7 +1134,7 @@ pub(crate) fn buffer_raw_free(&self, ptr: usize) {
             let freed_range = match mapping.alloc.reservation_abort(offset) {
                 Ok(freed_range) => freed_range,
                 Err(_) => {
-                    pr_warn!(
+                    pr_warn_ratelimited!(
                         "Pointer {:x} failed to free, base = {:x}\n",
                         ptr,
                         mapping.address
@@ -1154,7 +1156,7 @@ pub(crate) fn buffer_make_freeable(&self, offset: usize, mut data: Option<Alloca
         let mut inner = self.inner.lock();
         if let Some(ref mut mapping) = &mut inner.mapping {
             if mapping.alloc.reservation_commit(offset, &mut data).is_err() {
-                pr_warn!("Offset {} failed to be marked freeable\n", offset);
+                pr_warn_ratelimited!("Offset {} failed to be marked freeable\n", offset);
             }
         }
     }
@@ -1516,7 +1518,7 @@ pub(crate) fn drop_outstanding_txn(&self) {
         let wake = {
             let mut inner = self.inner.lock();
             if inner.outstanding_txns == 0 {
-                pr_err!("outstanding_txns underflow");
+                pr_err_ratelimited!("outstanding_txns underflow\n");
                 return;
             }
             inner.outstanding_txns -= 1;
@@ -1832,7 +1834,7 @@ fn new(thread: &'a Arc<Thread>, guard: &mut Guard<'_, ProcessInner, SpinLockBack
             // It is an error to hit this branch, and it should not be reachable. We try to do
             // something reasonable when the failure path happens. Most likely, the thread in
             // question will sleep forever.
-            pr_err!("Same thread registered with `ready_threads` twice.");
+            pr_err_ratelimited!("Same thread registered with `ready_threads` twice.\n");
         }
         Self { thread }
     }
@@ -1857,7 +1859,7 @@ impl Drop for WithNodes<'_> {
     fn drop(&mut self) {
         core::mem::swap(&mut self.nodes, &mut self.inner.nodes);
         if self.nodes.iter().next().is_some() {
-            pr_err!("nodes array was modified while using lock_with_nodes\n");
+            pr_err_ratelimited!("nodes array was modified while using lock_with_nodes\n");
         }
     }
 }
drivers/android/binder/thread.rs +27 -21

132 lines not on this page · raw message

drivers/android/binder/transaction.rs +2 -2
index 81df588d96ad..227e98ed1393 100644
@@ -175,7 +175,7 @@ pub(crate) fn new(
         )?;
         if info.is_oneway() {
             if from_parent.is_some() {
-                pr_warn!("Oneway transaction should not be in a transaction stack.");
+                pr_warn_ratelimited!("Oneway transaction should not be in a transaction stack.\n");
                 return Err(EINVAL.into());
             }
             alloc.set_info_oneway_node(node_ref.node.clone());
@@ -370,7 +370,7 @@ pub(crate) fn submit(self: DLArc<Self>, info: &mut TransactionInfo) -> BinderRes
                     return Ok(());
                 }
             } else {
-                pr_err!("Failed to submit oneway transaction to node.");
+                pr_err_ratelimited!("Failed to submit oneway transaction to node.\n");
             }
         }
 
Signature · 1 line
2.55.0.508.g3f0d502094-goog