rust: adds Bitmap API, ID pool and bindings
Subsystems (7)
v11 cover rust: adds Bitmap API, ID pool and bindings
This series adds a Rust bitmap API for porting the approach from commit 15d9da3f818c ("binder: use bitmap for faster descriptor lookup") to Rust. The functionality in dbitmap.h makes use of bitmap and bitops.
The Rust bitmap API provides a safe abstraction to underlying bitmap and bitops operations. For now, only includes method necessary for dbitmap.h, more can be added later. We perform bounds checks for hardening, violations are programmer errors that result in panics.
We include set_bit_atomic and clear_bit_atomic operations. One has to avoid races with non-atomic operations, which is ensure by the Rust type system: either callers have shared references &bitmap in which case the mutations are atomic operations. Or there is a exclusive reference &mut bitmap, in which case there is no concurrent access.
This version includes an optimization to represent the bitmap inline, as suggested by Yury.
We ran a simple microbenchmark which shows that overall the Rust API can be expected to be about 4.5% slower than C API.
We introduce a Rust API that would replace (dbitmap.h) in file id_pool.rs. This data structure is tightly coupled to the bitmap API. Includes an example of usage that requires releasing a spinlock, as expected in Binder driver.
This is v11 of a patch introducing Rust bitmap API [v9]. Thanks for all the helpful comments, this series has improved significantly as a result of your work.
Changes v10 --> v11:
- Fix Kconfig dependency, Rust benchmark depends on CONFIG_RUST
- Disable clippy warning for len() without is_empty() in id_pool.rs
Changes v9 --> v10:
- change helper to use unsigned long for nr parameter (Boqun)
- add missing and fix safety comments (Boqun, Pekka)
- move benchmark module output and results to #4 commit msg.
- use pr_cont to avoid repeating find_bit_benchmark_rust log prefix.
- Disable clippy warning for len() without is_empty() in bitmap.rs
Changes v8 --> v9:
- added a new type CBitmap that makes any C bitmap accessible with the same API, and add Deref so both Bitmap and
CBitmap can share the same implementation. Full credit for this goes to Alice who suggested idea and code.
- added config dependency on CONFIG_RUST that was missing from CONIG_FIND_BIT_BENCHMARK_RUST.
- implemented Send for Bitmap, it is actually needed by Binder.
- reworded commit msg for clarity.
- removed unsafe for atomic ops.
- renamed bitmap_hardening_assert to bitmap_assert and make operations do nothing and log error when RUST_BITMAP_HARDENED is off.
- update author information in find_bit_benchmark_rust.rs
- Various improvements to id_pool, better names and comments.
Changes v7 --> v8:
- added Acked-by for bindings patches
- add RUST_BITMAP_HARDENED config, making extra bound-checks configurable. This is added to security/Kconfig.hardening
- changed checks of index return value to >=
- removed change to FIND_BIT_BENCHMARK
Changes v6 --> v7:
- Added separate unit tests in bitmap.rs and benchmark module, following the example in find_bit_benchmark.c
- Added discussion about using vendored bitset to commit message.
- Refined warning about naming convention
Changes v5 --> v6:
- Added SAFETY comment for atomic operations.
- Added missing volatile to bitops set_bit and clear_bit bindings.
- Fixed condition on nbits to be <= i32::MAX, update SAFETY comments.
- Readability improvements.
- Updated doc comments wording and indentation.
Changes v4 --> v5: (suggested by Yury and Alice)
- rebased on next-20250318
- split MAINTAINERS changes
- no dependencies on [1] and [2] anymore - Viresh,
please do add a separate section if you want to maintain cpumask.rs separately.
- imports atomic and non-atomic variants, introduces a naming convention set_bit and set_bit_atomic on the Rust side.
- changed naming and comments. Keeping new.
- change dynamic_id_pool to id_pool
- represent bitmap inline when possible
- add some more tests
- add myself to M: line for the Rust abstractions
Changes v3 --> v4:
- Rebased on Viresh's v3 [2].
- split into multiple patches, separate Rust and bindings. (Yury)
- adds dynamic_id_pool.rs to show the Binder use case. (Yury)
- include example usage that requires release of spinlock (Alice)
- changed bounds checks to assert!, shorter (Yury)
- fix param names in binding helpers. (Miguel)
- proper rustdoc formatting, and use examples as kunit tests. (Miguel)
- reduce number of Bitmap methods, and simplify API through use Option<usize> to handle the "not found" case.
- make Bitmap pointer accessors private, so Rust Bitmap API provides an actual abstraction boundary (Tamir)
- we still return AllocError in Bitmap::new in case client code asks for a size that is too large. Intentionally different from other bounds checks because it is not about access but allocation, and we expect that client code need never handle AllocError and nbits > u32::MAX situations differently.
Changes v2 --> v3:
- change bitmap_copy to copy_from_bitmap_and_extend which zeroes out extra bits. This enables dbitmap shrink and grow use cases while offering a consistent and understandable Rust API for other uses (Alice)
Changes v1 --> v2:
- Rebased on Yury's v2 [1] and Viresh's v3 [2] changes related to bitmap.
- Removed import of bindings::*, keeping only prefix (Miguel)
- Renamed panic methods to make more explicit (Miguel)
- use markdown in doc comments and added example/kunit test (Miguel)
- Added maintainer section for BITOPS API BINDINGS [RUST] (Yury)
- Added M: entry for bitmap.rs which goes to Alice (Viresh, Alice)
- Changed calls from find_* to _find_*, removed helpers (Yury)
- Use non-atomic __set_bit and __clear_bit from Bitmap Rust API (Yury)
Link [1] https://lore.kernel.org/all/[email protected]/
Link [2] https://lore.kernel.org/rust-for-linux/[email protected]/
Link [v9] https://lore.kernel.org/rust-for-linux/[email protected]/
Burak Emir (5):
rust: add bindings for bitmap.h
rust: add bindings for bitops.h
rust: add bitmap API.
rust: add find_bit_benchmark_rust module.
rust: add dynamic ID pool abstraction for bitmap
MAINTAINERS | 15 + lib/Kconfig.debug | 13 + lib/Makefile | 1 + lib/find_bit_benchmark_rust.rs | 95 ++++++ rust/bindings/bindings_helper.h | 2 + rust/helpers/bitmap.c | 9 + rust/helpers/bitops.c | 23 ++ rust/helpers/helpers.c | 2 + rust/kernel/bitmap.rs | 588 ++++++++++++++++++++++++++++++++ rust/kernel/id_pool.rs | 222 ++++++++++++ rust/kernel/lib.rs | 2 + security/Kconfig.hardening | 10 + 12 files changed, 982 insertions(+) create mode 100644 lib/find_bit_benchmark_rust.rs create mode 100644 rust/helpers/bitmap.c create mode 100644 rust/helpers/bitops.c create mode 100644 rust/kernel/bitmap.rs create mode 100644 rust/kernel/id_pool.rs
Signature · 1 line
2.49.0.1204.g71687c7c1d-goog
PATCH v11 1/5 rust: add bindings for bitmap.h
Makes the bitmap_copy_and_extend inline function available to Rust. Adds F: to existing MAINTAINERS section BITMAP API BINDINGS [RUST].
--- MAINTAINERS | 1 + rust/bindings/bindings_helper.h | 1 + rust/helpers/bitmap.c | 9 +++++++++ rust/helpers/helpers.c | 1 + 4 files changed, 12 insertions(+) create mode 100644 rust/helpers/bitmap.c
MAINTAINERS +1 -0
@@ -4124,6 +4124,7 @@ F: tools/lib/find_bit.c BITMAP API BINDINGS [RUST] M: Yury Norov <[email protected]> S: Maintained +F: rust/helpers/bitmap.c F: rust/helpers/cpumask.c BITOPS API
rust/bindings/bindings_helper.h +1 -0
@@ -7,6 +7,7 @@*/ #include <kunit/test.h> +#include <linux/bitmap.h> #include <linux/blk-mq.h> #include <linux/blk_types.h> #include <linux/blkdev.h>
rust/helpers/bitmap.c new file +9 -0
@@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/bitmap.h> + +void rust_helper_bitmap_copy_and_extend (unsigned long *to,const unsigned long *from, +unsigned int count,unsigned int size) +{ +bitmap_copy_and_extend (to, from, count, size); +}
rust/helpers/helpers.c +1 -0
@@ -7,6 +7,7 @@* Sorted alphabetically. */ +#include "bitmap.c" #include "blk.c" #include "bug.c" #include "build_assert.c"
Signature · 1 line
2.49.0.1204.g71687c7c1d-goog
PATCH v11 2/5 rust: add bindings for bitops.h
In reply to Burak EmirMakes atomic set_bit and clear_bit inline functions as well as the non-atomic variants __set_bit and __clear_bit available to Rust. Adds a new MAINTAINERS section BITOPS API BINDINGS [RUST].
--- MAINTAINERS | 5 +++++ rust/helpers/bitops.c | 23 +++++++++++++++++++++++ rust/helpers/helpers.c | 1 + 3 files changed, 29 insertions(+) create mode 100644 rust/helpers/bitops.c
MAINTAINERS +5 -0
@@ -4141,6 +4141,11 @@ F: include/linux/bitops.h F: lib/test_bitops.c F: tools/*/bitops* +BITOPS API BINDINGS [RUST] +M: Yury Norov <[email protected]> +S: Maintained +F: rust/helpers/bitops.c + BLINKM RGB LED DRIVER M: Jan-Simon Moeller <[email protected]> S: Maintained
rust/helpers/bitops.c new file +23 -0
@@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/bitops.h> + +void rust_helper___set_bit (unsigned long nr,unsigned long *addr) +{ +__set_bit (nr, addr); +} + +void rust_helper___clear_bit (unsigned long nr,unsigned long *addr) +{ +__clear_bit (nr, addr); +} + +void rust_helper_set_bit (unsigned long nr,volatile unsigned long *addr) +{ +set_bit (nr, addr); +} + +void rust_helper_clear_bit (unsigned long nr,volatile unsigned long *addr) +{ +clear_bit (nr, addr); +}
rust/helpers/helpers.c +1 -0
@@ -8,6 +8,7 @@*/ #include "bitmap.c" +#include "bitops.c" #include "blk.c" #include "bug.c" #include "build_assert.c"
Signature · 1 line
2.49.0.1204.g71687c7c1d-goog
PATCH v11 3/5 rust: add bitmap API.
In reply to Burak EmirProvides an abstraction for C bitmap API and bitops operations.
This commit enables a Rust implementation of an Android Binder data structure from commit 15d9da3f818c ("binder: use bitmap for faster descriptor lookup"), which can be found in drivers/android/dbitmap.h. It is a step towards upstreaming the Rust port of Android Binder driver.
We follow the C Bitmap API closely in naming and semantics, with a few differences that take advantage of Rust language facilities and idioms:
* We leverage Rust type system guarantees as follows:
* all (non-atomic) mutating operations require a &mut reference which amounts to exclusive access.
* the Bitmap type implements Send. This enables transferring ownership between threads and is needed for Binder.
* the Bitmap type implements Sync, which enables passing shared references &Bitmap between threads. Atomic operations can be used to safely modify from multiple threads (interior mutability), though without ordering guarantees.
* The Rust API uses {set,clear}_bit vs {set,clear}_bit_atomic as names, which differs from the C naming convention which uses set_bit for atomic vs __set_bit for non-atomic.
* we include enough operations for the API to be useful, but not all operations are exposed yet in order to avoid dead code. The missing ones can be added later.
* We follow the C API closely with a fine-grained approach to safety:
* Low-level bit-ops get a safe API with bounds checks. Calling with an out-of-bounds arguments to {set,clear}_bit becomes a no-op and get logged as errors.
* We introduce a RUST_BITMAP_HARDENED config, which causes invocations with out-of-bounds arguments to panic.
* methods correspond to find_* C methods tolerate out-of-bounds since the C implementation does. Also here, we log out-of-bounds arguments as errors and panic in RUST_BITMAP_HARDENED mode.
* We add a way to "borrow" bitmaps from C in Rust, to make C bitmaps that were allocated in C directly usable in Rust code (CBitmap).
* the Rust API is optimized to represent the bitmap inline if it would fit into a pointer. This saves allocations which is relevant in the Binder use case.
The underlying C bitmap is *not* exposed, and must never be exposed (except in tests). Exposing the representation of the owned bitmap would lose static guarantees.
An alternative route of vendoring an existing Rust bitmap package was considered but suboptimal overall. Reusing the C implementation is preferable for a basic data structure like bitmaps. It enables Rust code to be a lot more similar and predictable with respect to C code that uses the same data structures and enables the use of code that has been tried-and-tested in the kernel, with the same performance characteristics whenever possible.
We use the usize type for sizes and indices into the bitmap, because Rust generally always uses that type for indices and lengths and it will be more convenient if the API accepts that type. This means that we need to perform some casts to/from u32 and usize, since the C headers use unsigned int instead of size_t/unsigned long for these numbers in some places.
Adds new MAINTAINERS section BITMAP API [RUST].
--- MAINTAINERS | 7 + rust/kernel/bitmap.rs | 574 +++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + security/Kconfig.hardening | 10 + 4 files changed, 592 insertions(+) create mode 100644 rust/kernel/bitmap.rs
MAINTAINERS +7 -0
@@ -4127,6 +4127,13 @@ S: Maintained F: rust/helpers/bitmap.c F: rust/helpers/cpumask.c +BITMAP API [RUST] +M: Alice Ryhl <[email protected]> +M: Burak Emir <[email protected]> +R: Yury Norov <[email protected]> +S: Maintained +F: rust/kernel/bitmap.rs + BITOPS API M: Yury Norov <[email protected]> R: Rasmus Villemoes <[email protected]>
rust/kernel/bitmap.rs new file +574 -0
574 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -38,6 +38,7 @@pub use ffi;pub mod alloc; +pub mod bitmap;#[cfg( CONFIG_BLOCK )] pub mod block;#[doc(hidden)]
security/Kconfig.hardening +10 -0
@@ -324,6 +324,16 @@ config LIST_HARDENED If unsure, say N. +config RUST_BITMAP_HARDENED + bool "Check integrity of linked list manipulation" + depends on CONFIG_RUST + help + Enables additional assertions in the Rust Bitmap API to catch + arguments that are not guaranteed to result in an immediate access + fault. + + If unsure, say N. + config BUG_ON_DATA_CORRUPTION bool "Trigger a BUG when data corruption is detected" select LIST_HARDENED
Signature · 1 line
2.49.0.1204.g71687c7c1d-goog
Re: [PATCH v11 3/5] rust: add bitmap API.
Quoted 108 lines · Burak Emir
Provides an abstraction for C bitmap API and bitops operations.
This commit enables a Rust implementation of an Android Binder data structure from commit
15d9da3f818c("binder: use bitmap for faster descriptor lookup"), which can be found indrivers/android/dbitmap.h. It is a step towards upstreaming the Rust port of Android Binder driver.We follow the C Bitmap API closely in naming and semantics, with a few differences that take advantage of Rust language facilities and idioms:
* We leverage Rust type system guarantees as follows:
* all (non-atomic) mutating operations require a &mut reference which amounts to exclusive access.
* the Bitmap type implements Send. This enables transferring ownership between threads and is needed for Binder.
* the Bitmap type implements Sync, which enables passing shared references &Bitmap between threads. Atomic operations can be used to safely modify from multiple threads (interior mutability), though without ordering guarantees.
* The Rust API uses
{set,clear}_bitvs{set,clear}_bit_atomicas names, which differs from the C naming convention which usesset_bitfor atomic vs__set_bitfor non-atomic.* we include enough operations for the API to be useful, but not all operations are exposed yet in order to avoid dead code. The missing ones can be added later.
* We follow the C API closely with a fine-grained approach to safety:
* Low-level bit-ops get a safe API with bounds checks. Calling with an out-of-bounds arguments to {set,clear}_bit becomes a no-op and get logged as errors.
* We introduce a
RUST_BITMAP_HARDENEDconfig, which causes invocations with out-of-bounds arguments to panic.* methods correspond to find_* C methods tolerate out-of-bounds since the C implementation does. Also here, we log out-of-bounds arguments as errors and panic in
RUST_BITMAP_HARDENEDmode.* We add a way to "borrow" bitmaps from C in Rust, to make C bitmaps that were allocated in C directly usable in Rust code (
CBitmap).* the Rust API is optimized to represent the bitmap inline if it would fit into a pointer. This saves allocations which is relevant in the Binder use case.
The underlying C bitmap is *not* exposed, and must never be exposed (except in tests). Exposing the representation of the owned bitmap would lose static guarantees.
An alternative route of vendoring an existing Rust bitmap package was considered but suboptimal overall. Reusing the C implementation is preferable for a basic data structure like bitmaps. It enables Rust code to be a lot more similar and predictable with respect to C code that uses the same data structures and enables the use of code that has been tried-and-tested in the kernel, with the same performance characteristics whenever possible.
We use the
usizetype for sizes and indices into the bitmap, because Rust generally always uses that type for indices and lengths and it will be more convenient if the API accepts that type. This means that we need to perform some casts to/from u32 and usize, since the C headers use unsigned int instead of size_t/unsigned long for these numbers in some places.Adds new
MAINTAINERSsection BITMAP API [RUST].Suggested-by Alice Ryhl <[email protected]>Suggested-by Yury Norov <[email protected]>Signed-off-by Burak Emir <[email protected]>--- MAINTAINERS | 7 + rust/kernel/bitmap.rs | 574 +++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + security/Kconfig.hardening | 10 + 4 files changed, 592 insertions(+) create mode 100644 rust/kernel/bitmap.rsMAINTAINERS +7
-0@@ -4127,6 +4127,13 @@ S: Maintained F: rust/helpers/bitmap.c F: rust/helpers/cpumask.c +BITMAP API [RUST] +M: Alice Ryhl <[email protected]> +M: Burak Emir <[email protected]> +R: Yury Norov <[email protected]> +S: Maintained +F: rust/kernel/bitmap.rs + BITOPS API M: Yury Norov <[email protected]> R: Rasmus Villemoes <[email protected]>rust/kernel/bitmap.rs new file +0
-0@@ -0,0 +1,574 @@
[...]
rust/kernel/bitmap.rs line 88
Quoted 12 lines
rust/kernel/bitmap.rs new file +12
-0+/// Returns a raw pointer to the backing [`Bitmap`]. +pub fn as_ptr (&self) -> *const usize { + selfas *const CBitmap as *const usize + } + +/// Returns a mutable raw pointer to the backing [`Bitmap`]. +pub fn as_mut_ptr (&mut self) -> *mut usize { + selfas *mut CBitmap as *mut usize + } + +/// Returns length of this [`CBitmap`]. +#[allow(clippy::len_without_is_empty)]
Using expect would be more idiomatic than allow.
Quoted 5 lines
rust/kernel/bitmap.rs new file +5
-0+pub fn len (&self) ->usize { + self.data.len () + } +} +
rust/kernel/bitmap.rs line 103
Quoted 10 lines
rust/kernel/bitmap.rs new file +10
-0+/// Holds either a pointer to array of `unsigned long` or a small bitmap. +#[repr( C )] +union BitmapRepr { + bitmap:usize , + ptr:NonNull <usize >, +} + +macro_rules! bitmap_assert { + ($cond:expr, $($arg:tt)+) => { +#[cfg( RUST_BITMAP_HARDENED )]
The config name should be prefixed with CONFIG_.
Quoted 1 line
+ assert!($e, $($arg)*);
$e is not defined, it should be $cond.
Quoted 5 lines
rust/kernel/bitmap.rs new file +5
-0+ } +} + +macro_rules! bitmap_assert_return { + ($cond:expr, $($arg:tt)+) => {
rust/kernel/bitmap.rs line 119
Quoted 10 lines
rust/kernel/bitmap.rs new file +10
-0+#[cfg( RUST_BITMAP_HARDENED )] +assert! ($e, $($arg)*); + +#[cfg(not( RUST_BITMAP_HARDENED ))] +if !($cond) { +pr_err! ($($arg)*); +return + } + } +}
Same for this macro.
[...]
Quoted 20 lines
rust/kernel/bitmap.rs new file +20
-0+#[test] +fn bitmap_set_clear_find () { +let mut b =Bitmap ::new (128 ,GFP_KERNEL ).unwrap (); + +// Zero-initialized +assert_eq! (None , b.next_bit (0 )); +assert_eq! (Some (0 ), b.next_zero_bit (0 )); +assert_eq! (None , b.last_bit ()); + + b.set_bit (17 ); + +assert_eq! (Some (17 ), b.next_bit (0 )); +assert_eq! (Some (17 ), b.next_bit (17 )); +assert_eq! (None , b.next_bit (18 )); +assert_eq! (Some (17 ), b.last_bit ()); + + b.set_bit (107 ); + +assert_eq! (Some (17 ), b.next_bit (0 )); +assert_eq! (Some (17 ), b.next_bit (17 ));
rust/kernel/bitmap.rs line 541
Quoted 10 lines
rust/kernel/bitmap.rs new file +10
-0+assert_eq! (Some (107 ), b.next_bit (18 )); +assert_eq! (Some (107 ), b.last_bit ()); + + b.clear_bit (17 ); + +assert_eq! (Some (107 ), b.next_bit (0 )); +assert_eq! (Some (107 ), b.last_bit ()); + } + +#[cfg(not( RUST_BITMAP_HARDENED ))]
Here as well, the config name should be CONFIG_RUST_BITMAP_HARDENED.
Quoted 12 lines
rust/kernel/bitmap.rs new file +12
-0+#[test] +fn bitmap_out_of_bounds () { +let mut b =Bitmap ::new (128 ,GFP_KERNEL ).unwrap (); + + b.set_bit (2048 ); + b.set_bit_atomic (2048 ); + b.clear_bit (2048 ); + b.clear_bit_atomic (2048 ); +assert_eq! (None , b.next_bit (2048 )); +assert_eq! (None , b.next_zero_bit (2048 )); +assert_eq! (None , b.last_bit ()); + }
[...]
security/Kconfig.hardening config LIST_HARDENED · line 328
Quoted 10 lines
security/Kconfig.hardening +2
-0@@ -324,6 +324,16 @@ config LIST_HARDENED If unsure, say N. +config RUST_BITMAP_HARDENED + bool "Check integrity of linked list manipulation"
The description seems to have been copied from the previous menu entry.
security/Kconfig.hardening config LIST_HARDENED · line 329
Quoted 1 line
security/Kconfig.hardening +1
-0+ depends on CONFIG_RUST
This needs to be depends on RUST, as Kconfig doesn't use the CONFIG_ prefix here.
Quoted 11 lines
security/Kconfig.hardening +7
-1+ help + Enables additional assertions in the Rust Bitmap API to catch + arguments that are not guaranteed to result in an immediate access + fault. + + If unsure, say N. + config BUG_ON_DATA_CORRUPTION bool "Trigger a BUG when data corruption is detected" select LIST_HARDENED --
Quoted 1 line
2.49.0.1204.g71687c7c1d-goog
Cheers,
Pekka
Re: [PATCH v11 3/5] rust: add bitmap API.
Quoted 2 lines · Pekka Ristola
On Monday, June 2nd, 2025 at 16.53, Burak Emir <[email protected]> wrote:
[...]
Quoted 10 lines
Review
Quoted 3 lines
(quoted diff) +2
-0+ ($cond:expr, $($arg:tt)+) => { + #[cfg(RUST_BITMAP_HARDENED)]The config name should be prefixed with
CONFIG_.Quoted 1 line
+ assert!($e, $($arg)*);
$eis not defined, it should be$cond.
Thanks for pointing out the macro and config mistakes around CONFIG_RUST_BITMAP_HARDENED.
Fixing all these.
I could not get kunit to enable RUST_BITMAP_HARDENED - now I understand why! Also added the missing test now, exercised the code and observed the fault (though [should_panic] does not seem to work).
Cheers,
- Burak
Re: [PATCH v11 3/5] rust: add bitmap API.
Quoted 4 lines · Burak Emir
I could not get kunit to enable
RUST_BITMAP_HARDENED- now I understand why! Also added the missing test now, exercised the code and observed the fault (though [should_panic] does not seem to work).
Yeah, should_panic is not supported. Note that assert!s maps back to KUnit in doctests and #[test]s, so you should not need it for assertions anyway, i.e. you should see a KUnit assertion failure like in C if the assert is not correct.
I hope that helps.
Cheers,
Miguel
PATCH v11 4/5 rust: add find_bit_benchmark_rust module.
In reply to Burak EmirMicrobenchmark protected by a config FIND_BIT_BENCHMARK_RUST, following find_bit_benchmark.c but testing the Rust Bitmap API.
We add a fill_random() method protected by the config in order to maintain the abstraction.
The sample output from the benchmark, both C and Rust version:
find_bit_benchmark.c output:
```
Start testing find_bit() with random-filled bitmap
[ 438.101937] find_next_bit: 860188 ns, 163419 iterations
[ 438.109471] find_next_zero_bit: 912342 ns, 164262 iterations
[ 438.116820] find_last_bit: 726003 ns, 163419 iterations
[ 438.130509] find_nth_bit: 7056993 ns, 16269 iterations
[ 438.139099] find_first_bit: 1963272 ns, 16270 iterations
[ 438.173043] find_first_and_bit: 27314224 ns, 32654 iterations
[ 438.180065] find_next_and_bit: 398752 ns, 73705 iterations
[ 438.186689]
Start testing find_bit() with sparse bitmap
[ 438.193375] find_next_bit: 9675 ns, 656 iterations
[ 438.201765] find_next_zero_bit: 1766136 ns, 327025 iterations
[ 438.208429] find_last_bit: 9017 ns, 656 iterations
[ 438.217816] find_nth_bit: 2749742 ns, 655 iterations
[ 438.225168] find_first_bit: 721799 ns, 656 iterations
[ 438.231797] find_first_and_bit: 2819 ns, 1 iterations
[ 438.238441] find_next_and_bit: 3159 ns, 1 iterations
```find_bit_benchmark_rust.rs output:
``` [ 451.182459] find_bit_benchmark_rust_module: [ 451.186688] Start testing find_bit() Rust with random-filled bitmap [ 451.194450] next_bit: 777950 ns, 163644 iterations [ 451.201997] next_zero_bit: 918889 ns, 164036 iterations [ 451.208642] Start testing find_bit() Rust with sparse bitmap [ 451.214300] next_bit: 9181 ns, 654 iterations [ 451.222806] next_zero_bit: 1855504 ns, 327026 iterations ```
Here are the results from 32 samples, with 95% confidence interval. The microbenchmark was built with RUST_BITMAP_HARDENED=n and run on a machine that did not execute other processes.
Random-filled bitmap:
+-----------+-------+-----------+--------------+-----------+-----------+ | Benchmark | Lang | Mean (ms) | Std Dev (ms) | 95% CI Lo | 95% CI Hi | +-----------+-------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 825.07 | 53.89 | 806.40 | 843.74 | | next_bit | Rust | 870.91 | 46.29 | 854.88 | 886.95 | +-----------+-------+-----------+--------------+-----------+-----------+ | find_zero/| C | 933.56 | 56.34 | 914.04 | 953.08 | | next_zero | Rust | 945.85 | 60.44 | 924.91 | 966.79 | +-----------+-------+-----------+--------------+-----------+-----------+
Rust appears 5.5% slower for next_bit, 1.3% slower for next_zero.
Sparse bitmap:
+-----------+-------+-----------+--------------+-----------+-----------+ | Benchmark | Lang | Mean (ms) | Std Dev (ms) | 95% CI Lo | 95% CI Hi | +-----------+-------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 13.17 | 6.21 | 11.01 | 15.32 | | next_bit | Rust | 14.30 | 8.27 | 11.43 | 17.17 | +-----------+-------+-----------+--------------+-----------+-----------+ | find_zero/| C | 1859.31 | 82.30 | 1830.80 | 1887.83 | | next_zero | Rust | 1908.09 | 139.82 | 1859.65 | 1956.54 | +-----------+-------+-----------+--------------+-----------+-----------+
Rust appears 8.5% slower for next_bit, 2.6% slower for next_zero.
In summary, taking the arithmetic mean of all slow-downs, we can say the Rust API has a 4.5% slowdown.
--- MAINTAINERS | 1 + lib/Kconfig.debug | 13 +++++ lib/Makefile | 1 + lib/find_bit_benchmark_rust.rs | 95 +++++++++++++++++++++++++++++++++ rust/bindings/bindings_helper.h | 1 + rust/kernel/bitmap.rs | 14 +++++ 6 files changed, 125 insertions(+) create mode 100644 lib/find_bit_benchmark_rust.rs
MAINTAINERS +1 -0
@@ -4132,6 +4132,7 @@ M: Alice Ryhl <[email protected]> M: Burak Emir <[email protected]> R: Yury Norov <[email protected]> S: Maintained +F: lib/find_bit_benchmark_rust.rs F: rust/kernel/bitmap.rs BITOPS API
lib/Kconfig.debug +13 -0
@@ -2605,6 +2605,19 @@ config FIND_BIT_BENCHMARK If unsure, say N. +config FIND_BIT_BENCHMARK_RUST + tristate "Test find_bit functions in Rust" + depends on CONFIG_RUST + help + This builds the "find_bit_benchmark_rust" module. It is a micro + benchmark that measures the performance of Rust functions that + correspond to the find_*_bit() operations in C. It follows the + FIND_BIT_BENCHMARK closely but will in general not yield same + numbers due to extra bounds checks and overhead of foreign + function calls. + + If unsure, say N. + config TEST_FIRMWARE tristate "Test firmware loading via userspace interface" depends on FW_LOADER
lib/Makefile +1 -0
@@ -62,6 +62,7 @@ obj-y += hexdump.o obj-$(CONFIG_TEST_HEXDUMP) += test_hexdump.o obj-y += kstrtox.o obj-$(CONFIG_FIND_BIT_BENCHMARK) += find_bit_benchmark.o +obj-$(CONFIG_FIND_BIT_BENCHMARK_RUST) += find_bit_benchmark_rust.o obj-$(CONFIG_TEST_BPF) += test_bpf.o test_dhry-objs := dhry_1.o dhry_2.o dhry_run.o obj-$(CONFIG_TEST_DHRY) += test_dhry.o
lib/find_bit_benchmark_rust.rs new file +95 -0
95 lines not on this page · raw message
rust/bindings/bindings_helper.h +1 -0
@@ -31,6 +31,7 @@#include <linux/platform_device.h> #include <linux/poll.h> #include <linux/property.h> +#include <linux/random.h> #include <linux/refcount.h> #include <linux/sched.h> #include <linux/security.h>
rust/kernel/bitmap.rs +14 -0
@@ -252,6 +252,20 @@ pub fn new(nbits: usize, flags: Flags) -> Result<Self, AllocError> {pub fn len (&self) ->usize { self.nbits } + +/// Fills this `Bitmap` with random bits. +#[cfg( CONFIG_FIND_BIT_BENCHMARK_RUST )] +pub fn fill_random (&mut self) { +// SAFETY: `self.as_mut_ptr` points to either an array of the +// appropriate length or one usize. +unsafe { + bindings::get_random_bytes ( + self.as_mut_ptr ()as *mut ffi::c_void , + usize::div_ceil (self.nbits, bindings::BITS_PER_LONG as usize ) + * bindings::BITS_PER_LONG as usize , + ); + } + } }impl CBitmap {
Signature · 1 line
2.49.0.1204.g71687c7c1d-goog
Re: [PATCH v11 4/5] rust: add find_bit_benchmark_rust module.
Quoted 103 lines · Burak Emir
Microbenchmark protected by a config
FIND_BIT_BENCHMARK_RUST, followingfind_bit_benchmark.cbut testing the Rust Bitmap API.We add a
fill_random()method protected by the config in order to maintain the abstraction.The sample output from the benchmark, both C and Rust version:
find_bit_benchmark.coutput:``` Start testing find_bit() with random-filled bitmap [ 438.101937] find_next_bit: 860188 ns, 163419 iterations [ 438.109471] find_next_zero_bit: 912342 ns, 164262 iterations [ 438.116820] find_last_bit: 726003 ns, 163419 iterations [ 438.130509] find_nth_bit: 7056993 ns, 16269 iterations [ 438.139099] find_first_bit: 1963272 ns, 16270 iterations [ 438.173043] find_first_and_bit: 27314224 ns, 32654 iterations [ 438.180065] find_next_and_bit: 398752 ns, 73705 iterations [ 438.186689] Start testing find_bit() with sparse bitmap [ 438.193375] find_next_bit: 9675 ns, 656 iterations [ 438.201765] find_next_zero_bit: 1766136 ns, 327025 iterations [ 438.208429] find_last_bit: 9017 ns, 656 iterations [ 438.217816] find_nth_bit: 2749742 ns, 655 iterations [ 438.225168] find_first_bit: 721799 ns, 656 iterations [ 438.231797] find_first_and_bit: 2819 ns, 1 iterations [ 438.238441] find_next_and_bit: 3159 ns, 1 iterations ```
find_bit_benchmark_rust.rsoutput:``` [ 451.182459] find_bit_benchmark_rust_module: [ 451.186688] Start testing find_bit() Rust with random-filled bitmap [ 451.194450] next_bit: 777950 ns, 163644 iterations [ 451.201997] next_zero_bit: 918889 ns, 164036 iterations [ 451.208642] Start testing find_bit() Rust with sparse bitmap [ 451.214300] next_bit: 9181 ns, 654 iterations [ 451.222806] next_zero_bit: 1855504 ns, 327026 iterations ```Here are the results from 32 samples, with 95% confidence interval. The microbenchmark was built with RUST_BITMAP_HARDENED=n and run on a machine that did not execute other processes.
Random-filled bitmap:
+-----------+-------+-----------+--------------+-----------+-----------+ | Benchmark | Lang | Mean (ms) | Std Dev (ms) | 95% CI Lo | 95% CI Hi | +-----------+-------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 825.07 | 53.89 | 806.40 | 843.74 | | next_bit | Rust | 870.91 | 46.29 | 854.88 | 886.95 | +-----------+-------+-----------+--------------+-----------+-----------+ | find_zero/| C | 933.56 | 56.34 | 914.04 | 953.08 | | next_zero | Rust | 945.85 | 60.44 | 924.91 | 966.79 | +-----------+-------+-----------+--------------+-----------+-----------+Rust appears 5.5% slower for
next_bit, 1.3% slower fornext_zero.Sparse bitmap:
+-----------+-------+-----------+--------------+-----------+-----------+ | Benchmark | Lang | Mean (ms) | Std Dev (ms) | 95% CI Lo | 95% CI Hi | +-----------+-------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 13.17 | 6.21 | 11.01 | 15.32 | | next_bit | Rust | 14.30 | 8.27 | 11.43 | 17.17 | +-----------+-------+-----------+--------------+-----------+-----------+ | find_zero/| C | 1859.31 | 82.30 | 1830.80 | 1887.83 | | next_zero | Rust | 1908.09 | 139.82 | 1859.65 | 1956.54 | +-----------+-------+-----------+--------------+-----------+-----------+Rust appears 8.5% slower for
next_bit, 2.6% slower fornext_zero.In summary, taking the arithmetic mean of all slow-downs, we can say the Rust API has a 4.5% slowdown.
Suggested-by Alice Ryhl <[email protected]>Suggested-by Yury Norov <[email protected]>Signed-off-by Burak Emir <[email protected]>--- MAINTAINERS | 1 + lib/Kconfig.debug | 13 +++++ lib/Makefile | 1 + lib/find_bit_benchmark_rust.rs | 95 +++++++++++++++++++++++++++++++++ rust/bindings/bindings_helper.h | 1 + rust/kernel/bitmap.rs | 14 +++++ 6 files changed, 125 insertions(+) create mode 100644 lib/find_bit_benchmark_rust.rsMAINTAINERS +1
-0@@ -4132,6 +4132,7 @@ M: Alice Ryhl <[email protected]> M: Burak Emir <[email protected]> R: Yury Norov <[email protected]> S: Maintained +F: lib/find_bit_benchmark_rust.rs F: rust/kernel/bitmap.rs BITOPS APIlib/Kconfig.debug +0
-0
lib/Kconfig.debug config FIND_BIT_BENCHMARK · line 2610
Quoted 6 lines
lib/Kconfig.debug +3
-0@@ -2605,6 +2605,19 @@ config FIND_BIT_BENCHMARK If unsure, say N. +config FIND_BIT_BENCHMARK_RUST + tristate "Test find_bit functions in Rust" + depends on CONFIG_RUST
The CONFIG_ prefix should be removed.
Quoted 13 lines
lib/Kconfig.debug +10
-0+ help + This builds the "find_bit_benchmark_rust" module. It is a micro + benchmark that measures the performance of Rust functions that + correspond to the find_*_bit() operations in C. It follows the + FIND_BIT_BENCHMARK closely but will in general not yield same + numbers due to extra bounds checks and overhead of foreign + function calls. + + If unsure, say N. + config TEST_FIRMWARE tristate "Test firmware loading via userspace interface" depends on FW_LOADER
[...]
Quoted 9 lines
rust/kernel/bitmap.rs +1
-0@@ -252,6 +252,20 @@ pub fn new(nbits: usize, flags: Flags) -> Result<Self, AllocError> {pub fn len (&self) ->usize { self.nbits } +
rust/kernel/bitmap.rs pub fn new(nbits: usize, flags: Flags) -> Result<Self, AllocError> { · line 265
Quoted 10 lines
rust/kernel/bitmap.rs +10
-0+/// Fills this `Bitmap` with random bits. +#[cfg( CONFIG_FIND_BIT_BENCHMARK_RUST )] +pub fn fill_random (&mut self) { +// SAFETY: `self.as_mut_ptr` points to either an array of the +// appropriate length or one usize. +unsafe { + bindings::get_random_bytes ( + self.as_mut_ptr ()as *mut ffi::c_void , + usize::div_ceil (self.nbits, bindings::BITS_PER_LONG as usize ) + * bindings::BITS_PER_LONG as usize,
I think the second argument to get_random_bytes should be in bytes, not bits. So it should be multiplied by "bytes per long", not "bits per long".
Quoted 8 lines
rust/kernel/bitmap.rs +3
-1+ ); + } + } }impl CBitmap { --2.49.0.1204.g71687c7c1d-goog
Cheers,
Pekka
Re: [PATCH v11 4/5] rust: add find_bit_benchmark_rust module.
Quoted 2 lines · Pekka Ristola
On Monday, June 2nd, 2025 at 16.53, Burak Emir <[email protected]> wrote:
[...]
Quoted 6 lines
Quoted 6 lines
lib/Kconfig.debug +0
-0@@ -2605,6 +2605,19 @@ config FIND_BIT_BENCHMARK
Quoted 7 lines
lib/Kconfig.debug config FIND_BIT_BENCHMARK · line 2610
Quoted 5 lines
lib/Kconfig.debug +3
-0If unsure, say N. +config FIND_BIT_BENCHMARK_RUST + tristate "Test find_bit functions in Rust" + depends on CONFIG_RUSTThe
CONFIG_prefix should be removed.
Done.
[...]
Quoted 14 lines
Quoted 14 lines
rust/kernel/bitmap.rs +6
-0@@ -252,6 +252,20 @@ pub fn new(nbits: usize, flags: Flags) -> Result<Self, AllocError> {pub fn len (&self) ->usize { self.nbits } + +/// Fills this `Bitmap` with random bits. +#[cfg( CONFIG_FIND_BIT_BENCHMARK_RUST )] +pub fn fill_random (&mut self) { +// SAFETY: `self.as_mut_ptr` points to either an array of the +// appropriate length or one usize.
Quoted 8 lines
rust/kernel/bitmap.rs pub fn new(nbits: usize, flags: Flags) -> Result<Self, AllocError> { · line 265
Quoted 5 lines
rust/kernel/bitmap.rs +5
-0+unsafe { + bindings::get_random_bytes ( + self.as_mut_ptr ()as *mut ffi::c_void , + usize::div_ceil (self.nbits, bindings::BITS_PER_LONG as usize ) + * bindings::BITS_PER_LONG as usize,I think the second argument to
get_random_bytesshould be in bytes, not bits. So it should be multiplied by "bytes per long", not "bits per long".
Thanks for catching this. At least I had memory safety in mind when I overflowed the buffer (facepalm)!
Fixed.
Cheers,
-- Burak
PATCH v11 5/5 rust: add dynamic ID pool abstraction for bitmap
In reply to Burak EmirThis is a port of the Binder data structure introduced in commit 15d9da3f818c ("binder: use bitmap for faster descriptor lookup") to Rust.
Like drivers/android/dbitmap.h, the ID pool abstraction lets clients acquire and release IDs. The implementation uses a bitmap to know what IDs are in use, and gives clients fine-grained control over the time of allocation. This fine-grained control is needed in the Android Binder. We provide an example that release a spinlock for allocation and unit tests (rustdoc examples).
The implementation does not permit shrinking below capacity below BITS_PER_LONG.
--- MAINTAINERS | 1 + rust/kernel/id_pool.rs | 222 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 224 insertions(+) create mode 100644 rust/kernel/id_pool.rs
MAINTAINERS +1 -0
@@ -4134,6 +4134,7 @@ R: Yury Norov <[email protected]> S: Maintained F: lib/find_bit_benchmark_rust.rs F: rust/kernel/bitmap.rs +F: rust/kernel/id_pool.rs BITOPS API M: Yury Norov <[email protected]>
rust/kernel/id_pool.rs new file +222 -0
222 lines not on this page · raw message
rust/kernel/lib.rs +1 -0
@@ -54,6 +54,7 @@#[cfg( CONFIG_RUST_FW_LOADER_ABSTRACTIONS )] pub mod firmware;pub mod fs; +pub mod id_pool;pub mod init;pub mod io;pub mod ioctl;
Signature · 1 line
2.49.0.1204.g71687c7c1d-goog
Re: [PATCH v11 5/5] rust: add dynamic ID pool abstraction for bitmap
Quoted 128 lines · Burak Emir
This is a port of the Binder data structure introduced in commit
15d9da3f818c("binder: use bitmap for faster descriptor lookup") to Rust.Like
drivers/android/dbitmap.h, the ID pool abstraction lets clients acquire and release IDs. The implementation uses a bitmap to know what IDs are in use, and gives clients fine-grained control over the time of allocation. This fine-grained control is needed in the Android Binder. We provide an example that release a spinlock for allocation and unit tests (rustdoc examples).The implementation does not permit shrinking below capacity below
BITS_PER_LONG.Suggested-by Alice Ryhl <[email protected]>Suggested-by Yury Norov <[email protected]>Signed-off-by Burak Emir <[email protected]>--- MAINTAINERS | 1 + rust/kernel/id_pool.rs | 222 +++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 3 files changed, 224 insertions(+) create mode 100644 rust/kernel/id_pool.rsMAINTAINERS +1
-0@@ -4134,6 +4134,7 @@ R: Yury Norov <[email protected]> S: Maintained F: lib/find_bit_benchmark_rust.rs F: rust/kernel/bitmap.rs +F: rust/kernel/id_pool.rs BITOPS API M: Yury Norov <[email protected]>rust/kernel/id_pool.rs new file +86
-0@@ -0,0 +1,222 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2025 Google LLC. + +//! Rust API for an ID pool backed by a [`Bitmap`]. + +use crate ::alloc::{AllocError ,Flags }; +use crate ::bitmap::Bitmap ; + +/// Represents a dynamic ID pool backed by a [`Bitmap`]. +/// +/// Clients acquire and release IDs from unset bits in a bitmap. +/// +/// The capacity of the ID pool may be adjusted by users as +/// needed. The API supports the scenario where users need precise control +/// over the time of allocation of a new backing bitmap, which may require +/// release of spinlock. +/// Due to concurrent updates, all operations are re-verified to determine +/// if the grow or shrink is sill valid. +/// +/// # Examples +/// +/// Basic usage +/// +/// ``` +/// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; +/// use kernel::id_pool::IdPool; +/// +/// let mut pool = IdPool::new(64, GFP_KERNEL)?; +/// for i in 0..64 { +/// assert_eq!(i, pool.acquire_next_id(i).ok_or(ENOSPC)?); +/// } +/// +/// pool.release_id(23); +/// assert_eq!(23, pool.acquire_next_id(0).ok_or(ENOSPC)?); +/// +/// assert_eq!(None, pool.acquire_next_id(0)); // time to realloc. +/// let resizer = pool.grow_request().ok_or(ENOSPC)?.realloc(GFP_KERNEL)?; +/// pool.grow(resizer); +/// +/// assert_eq!(pool.acquire_next_id(0), Some(64)); +/// # Ok::<(), Error>(()) +/// ``` +/// +/// Releasing spinlock to grow the pool +/// +/// ```no_run +/// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; +/// use kernel::sync::{new_spinlock, SpinLock}; +/// use kernel::id_pool::IdPool; +/// +/// fn get_id_maybe_realloc(guarded_pool: &SpinLock<IdPool>) -> Result<usize, AllocError> { +/// let mut pool = guarded_pool.lock(); +/// loop { +/// match pool.acquire_next_id(0) { +/// Some(index) => return Ok(index), +/// None => { +/// let alloc_request = pool.grow_request(); +/// drop(pool); +/// let resizer = alloc_request.ok_or(AllocError)?.realloc(GFP_KERNEL)?; +/// pool = guarded_pool.lock(); +/// pool.grow(resizer) +/// } +/// } +/// } +/// } +/// ``` +pub struct IdPool { + map:Bitmap , +} + +/// Indicates that an [`IdPool`] should change to a new target size. +pub struct ReallocRequest { + num_ids:usize , +} + +/// Contains a [`Bitmap`] of a size suitable for reallocating [`IdPool`]. +pub struct PoolResizer { + new:Bitmap , +} + +impl ReallocRequest { +/// Allocates a new backing [`Bitmap`] for [`IdPool`]. +/// +/// This method only prepares reallocation and does not complete it. +/// Reallocation will complete after passing the [`PoolResizer`] to the
rust/kernel/id_pool.rs line 96
Quoted 10 lines
rust/kernel/id_pool.rs new file +10
-0+/// [`IdPool::grow`] or [`IdPool::shrink`] operation, which will check +/// that reallocation still makes sense. +pub fn realloc (&self, flags:Flags ) ->Result <PoolResizer ,AllocError > { +let new =Bitmap ::new (self.num_ids, flags)?; +Ok (PoolResizer { new }) + } +} + +impl IdPool { +/// Constructs a new `[IdPool]`.
The link is broken, it should be [IdPool].
rust/kernel/id_pool.rs line 98
Quoted 2 lines
rust/kernel/id_pool.rs new file +2
-0+/// +/// A capacity below [`BITS_PER_LONG`] is adjusted to [`BITS_PER_LONG`].
Since BITS_PER_LONG is defined in the bindings, it needs an explicit path. Rustdoc won't link to it otherwise.
Maybe something like:
``` /// [`BITS_PER_LONG`]: srctree/include/asm-generic/bitsperlong.h ```
rust/kernel/id_pool.rs line 110
Quoted 12 lines
rust/kernel/id_pool.rs new file +12
-0+#[inline] +pub fn new (num_ids:usize , flags:Flags ) ->Result <Self ,AllocError > { +let num_ids = core::cmp::max (num_ids, bindings::BITS_PER_LONG as usize ); +let map =Bitmap ::new (num_ids, flags)?; +Ok (Self { map }) + } + +/// Returns how many IDs this pool can currently have. +#[inline] +pub fn len (&self) ->usize { + self.map.len () + }
This needs #[expect(clippy::len_without_is_empty)] or adding the is_empty method.
rust/kernel/id_pool.rs line 114
Quoted 4 lines
rust/kernel/id_pool.rs new file +4
-0+ +/// Returns a [`ReallocRequest`] if the [`IdPool`] can be shrunk, [`None`] otherwise. +/// +/// The capacity of an [`IdPool`] cannot be shrunk below [`BITS_PER_LONG`].
The BITS_PER_LONG link is broken here as well.
Quoted 22 lines
rust/kernel/id_pool.rs new file +22
-0+/// +/// # Examples +/// +/// ``` +/// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; +/// use kernel::id_pool::{ReallocRequest, IdPool}; +/// +/// let mut pool = IdPool::new(1024, GFP_KERNEL)?; +/// let alloc_request = pool.shrink_request().ok_or(AllocError)?; +/// let resizer = alloc_request.realloc(GFP_KERNEL)?; +/// pool.shrink(resizer); +/// assert_eq!(pool.len(), kernel::bindings::BITS_PER_LONG as usize); +/// # Ok::<(), AllocError>(()) +/// ``` +#[inline] +pub fn shrink_request (&self) ->Option <ReallocRequest > { +let len = self.map.len (); +// Shrinking below [`BITS_PER_LONG`] is never possible. +if len <= bindings::BITS_PER_LONG as usize { +return None ; + } +// Determine if the bitmap can shrink based on the position of
rust/kernel/id_pool.rs line 146
Quoted 10 lines
rust/kernel/id_pool.rs new file +10
-0+// its last set bit. If the bit is within the first quarter of +// the bitmap then shrinking is possible. In this case, the +// bitmap should shrink to half its current size. +let last_bit = self.map.last_bit (); +if last_bit.is_none () { +return Some (ReallocRequest { + num_ids: bindings::BITS_PER_LONG as usize , + }); + } +let bit = last_bit.unwrap ();
Instead of unwrap, consider using let else:
```
let Some(bit) = self.map.last_bit() else {
return Some(ReallocRequest { ... });
};
```Quoted 10 lines
rust/kernel/id_pool.rs new file +10
-0+if bit >= (len /4 ) { +return None ; + } +let num_ids = core::cmp::max (bindings::BITS_PER_LONG as usize , len /2 ); +Some (ReallocRequest { num_ids }) + } + +/// Shrinks pool by using a new [`Bitmap`], if still possible. +#[inline] +pub fn shrink (&mut self,mut resizer:PoolResizer ) {
rust/kernel/id_pool.rs line 166
Quoted 10 lines
rust/kernel/id_pool.rs new file +10
-0+// Between request to shrink that led to allocation of `resizer` and now, +// bits may have changed. +// Verify that shrinking is still possible. In case shrinking to +// the size of `resizer` is no longer possible, do nothing, +// drop `resizer` and move on. +let updated = self.shrink_request (); +if updated.is_none () { +return ; + } +if updated.unwrap ().num_ids > resizer.new.len () {
Same here, the unwrap can be replaced with let else.
Quoted 13 lines
rust/kernel/id_pool.rs new file +13
-0+return ; + } + + resizer.new.copy_and_extend (&self.map); + self.map = resizer.new; + } + +/// Returns a [`ReallocRequest`] for growing this [`IdPool`], if possible. +/// +/// The capacity of an [`IdPool`] cannot be grown above [`i32::MAX`]. +#[inline] +pub fn grow_request (&self) ->Option <ReallocRequest > { +let num_ids = self.map.len () *2 ;
rust/kernel/id_pool.rs line 189
Quoted 10 lines
rust/kernel/id_pool.rs new file +10
-0+if num_ids > i32::MAX .try_into ().unwrap () { +return None ; + } +Some (ReallocRequest { num_ids }) + } + +/// Grows pool by using a new [`Bitmap`], if still necessary. +/// +/// The `resizer` arguments has to be obtained by calling [`grow_request`] +/// on this object and performing a `realloc`.
The grow_request link doesn't work. Also realloc should be a link to the ReallocRequest::realloc method.
Quoted 8 lines
rust/kernel/id_pool.rs new file +8
-0+#[inline] +pub fn grow (&mut self,mut resizer:PoolResizer ) { +// Between request to grow that led to allocation of `resizer` and now, +// another thread may have already grown the capacity. +// In this case, do nothing, drop `resizer` and move on. +if resizer.new.len () <= self.map.len () { +return ; + }
rust/kernel/id_pool.rs line 207
Quoted 10 lines
rust/kernel/id_pool.rs new file +10
-0+ + resizer.new.copy_and_extend (&self.map); + self.map = resizer.new; + } + +/// Acquires a new ID by finding and setting the next zero bit in the +/// bitmap. +/// +/// Upon success, returns its index. Otherwise, returns `None` +/// to indicate that a `grow_request` is needed.
None and grow_request should be changed to links.
Quoted 28 lines
rust/kernel/id_pool.rs new file +15
-0+#[inline] +pub fn acquire_next_id (&mut self, offset:usize ) ->Option <usize > { +let next_zero_bit = self.map.next_zero_bit (offset); +if let Some (nr) = next_zero_bit { + self.map.set_bit (nr); + } + next_zero_bit + } + +/// Releases an ID. +#[inline] +pub fn release_id (&mut self, id:usize ) { + self.map.clear_bit (id); + } +}rust/kernel/lib.rs +1
-1@@ -54,6 +54,7 @@#[cfg( CONFIG_RUST_FW_LOADER_ABSTRACTIONS )] pub mod firmware;pub mod fs; +pub mod id_pool;pub mod init;pub mod io;pub mod ioctl; --
Quoted 1 line
2.49.0.1204.g71687c7c1d-goog
Cheers,
Pekka