rust: adds Bitmap API, ID pool and bindings
Subsystems (7)
v9 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 benchmark (sample size 32), with RUST_BITMAP_HARDENED=n on a x86_64 production machine that was not running other processes.
Results for random-filled bitmap:
+------------+------+-----------+--------------+-----------+-----------+ | Benchmark | Code | Mean (ns) | Std Dev (ns) | 95% CI Lo | 95% CI Hi | +------------+------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 5.18 | 0.32 | 5.17 | 5.18 | | next_bit | Rust | 5.30 | 0.37 | 5.30 | 5.31 | +------------+------+-----------+--------------+-----------+-----------+ | find_zero/ | C | 5.66 | 0.33 | 5.66 | 5.67 | | next_zero | Rust | 5.88 | 0.32 | 5.88 | 5.89 | +------------+------+-----------+--------------+-----------+-----------+
Results for sparse bitmap:
+------------+------+-----------+--------------+-----------+-----------+ | Benchmark | Code | Mean (ns) | Std Dev (ns) | 95% CI Lo | 95% CI Hi | +------------+------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 22.51 | 12.34 | 22.38 | 22.65 | | next_bit | Rust | 30.53 | 20.44 | 30.30 | 30.75 | +------------+------+-----------+--------------+-----------+-----------+ | find_zero/ | C | 5.69 | 0.22 | 5.68 | 5.69 | | next_zero | Rust | 5.68 | 0.29 | 5.68 | 5.68 | +------------+------+-----------+--------------+-----------+-----------+
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 v9 of a patch introducing Rust bitmap API [v7]. Thanks for all the helpful comments, this series has improved significantly as a result of your work.
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 the 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 [v8] https://lore.kernel.org/rust-for-linux/[email protected]/
Burak Emir (6):
rust: add bindings for bitmap.h
rust: add bindings for bitops.h
rust: add bitmap API.
bitmap: fix find_bit_benchmark module name and config description
rust: add find_bit_benchmark_rust module.
rust: add dynamic ID pool abstraction for bitmap
MAINTAINERS | 15 ++ lib/Kconfig.debug | 18 +- lib/Makefile | 1 + lib/find_bit_benchmark_rust.rs | 94 +++++++ 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 | 429 ++++++++++++++++++++++++++++++++ rust/kernel/id_pool.rs | 201 +++++++++++++++ rust/kernel/lib.rs | 2 + security/Kconfig.hardening | 11 + 12 files changed, 805 insertions(+), 2 deletions(-) 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 · 30 lines
2.49.0.1101.gccaa498523-goog 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 | 94 ++++++ 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 | 568 ++++++++++++++++++++++++++++++++ rust/kernel/id_pool.rs | 222 +++++++++++++ rust/kernel/lib.rs | 2 + security/Kconfig.hardening | 10 + 12 files changed, 961 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 -- 2.49.0.1151.ga128411c76-goog
PATCH v9 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.1151.ga128411c76-goog
PATCH v9 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 int nr,unsigned long *addr) +{ +__set_bit (nr, addr); +} + +void rust_helper___clear_bit (unsigned int nr,unsigned long *addr) +{ +__clear_bit (nr, addr); +} + +void rust_helper_set_bit (unsigned int nr,volatile unsigned long *addr) +{ +set_bit (nr, addr); +} + +void rust_helper_clear_bit (unsigned int 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.1151.ga128411c76-goog
Re: [PATCH v9 2/5] rust: add bindings for bitops.h
Quoted 37 lines · Burak Emir
Makes atomic
set_bitandclear_bitinline functions as well as the non-atomic variants__set_bitand__clear_bitavailable to Rust. Adds a newMAINTAINERSsection BITOPS API BINDINGS [RUST].Suggested-by Alice Ryhl <[email protected]>Suggested-by Yury Norov <[email protected]>Signed-off-by Burak Emir <[email protected]>--- MAINTAINERS | 5 +++++ rust/helpers/bitops.c | 23 +++++++++++++++++++++++ rust/helpers/helpers.c | 1 + 3 files changed, 29 insertions(+) create mode 100644 rust/helpers/bitops.cMAINTAINERS +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: Maintainedrust/helpers/bitops.c new file +0
-0
rust/helpers/bitops.c line 5
Quoted 5 lines
rust/helpers/bitops.c new file +5
-0@@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/bitops.h> + +void rust_helper___set_bit (unsigned int nr,unsigned long *addr)
Why "unsigned int" instead of "unsigned long"? The C API uses "unsigned long" and in the Rust API, you uses "usize" for nbits and indexs, therefore using "unsigned int" only introduces unnecessary "as u32" casting IMO, am I missing something here?
Regards,
Boqun
Quoted 33 lines
rust/helpers/bitops.c new file +18
-0+{ +__set_bit (nr, addr); +} + +void rust_helper___clear_bit (unsigned int nr,unsigned long *addr) +{ +__clear_bit (nr, addr); +} + +void rust_helper_set_bit (unsigned int nr,volatile unsigned long *addr) +{ +set_bit (nr, addr); +} + +void rust_helper_clear_bit (unsigned int 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.1151.ga128411c76-goog
Re: [PATCH v9 2/5] rust: add bindings for bitops.h
Quoted 15 lines · Boqun Feng
rust/helpers/bitops.c line 5
Quoted 8 lines · Burak Emir
rust/helpers/bitops.c new file +5
-0@@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include <linux/bitops.h> + +void rust_helper___set_bit (unsigned int nr,unsigned long *addr)Why "unsigned int" instead of "unsigned long"? The C API uses "unsigned long" and in the Rust API, you uses "usize" for
nbitsandindexs, therefore using "unsigned int" only introduces unnecessary "as u32" casting IMO, am I missing something here?
This is certainly a bit confusing to me.
As Jann points out here [1] the expand to asm macros arch___set_bit, where nr is indeed unsigned long.
There is also the constraint that a bitmap's length must be shorter than INT32_MAX bits, but that does not matter.
Being consistent with the C API, including parameter names, is what we should do, so fixing this.
I found the underlying C API is just hard to find for these macros. Thanks for catching.
cheers
- Burak
PATCH v9 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 | 554 +++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + security/Kconfig.hardening | 10 + 4 files changed, 572 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 +554 -0
554 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.1151.ga128411c76-goog
Re: [PATCH v9 3/5] rust: add bitmap API.
Quoted 118 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 | 554 +++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + security/Kconfig.hardening | 10 + 4 files changed, 572 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 +10
-0@@ -0,0 +1,554 @@ +// SPDX-License-Identifier: GPL-2.0 + +// Copyright (C) 2025 Google LLC. + +//! Rust API for bitmap. +//! +//! C headers: [`include/linux/bitmap.h`](srctree/include/linux/bitmap.h). + +use crate ::alloc::{AllocError ,Flags }; +use crate ::bindings;
rust/kernel/bitmap.rs line 20
Quoted 10 lines
rust/kernel/bitmap.rs new file +10
-0+use crate ::pr_err; +use core::ptr::NonNull ; + +/// Represents a C bitmap. Wraps underlying C bitmap API. +/// +/// # Invariants +/// +/// Must reference a `[c_ulong]` long enough to fit `data.len()` bits. +pub struct CBitmap { + _align: [usize ;0 ],
This is the same as #[repr(align(8)] on 64bit architecture? If so, maybe we should do:
#[cfg_attr(CONFIG_64BIT, repr(align(8)))]
#[cfg_attr(not(CONFIG_64BIT), repr(align(4)))]
pub struct CBitmap {
data: [()],
}? I find it slightly better because it's explicit on the targeted alignment.
Quoted 4 lines
rust/kernel/bitmap.rs new file +4
-0+ data: [()], +} + +impl CBitmap {
rust/kernel/bitmap.rs line 34
Quoted 10 lines
rust/kernel/bitmap.rs new file +10
-0+/// Borrows a C bitmap. +/// +/// # Safety +/// +/// * `ptr` holds a non-null address of an initialized array of `unsigned long` +/// that is large enough to hold `nbits` bits. +/// * the array must not be freed for the lifetime of this [`CBitmap`] +/// * concurrent access only happens through atomic operations +pub unsafe fn from_raw <'a>(ptr: *const usize , nbits:usize ) -> &'aCBitmap { +let data: *const [()] = core::ptr::slice_from_raw_parts (ptr.cast (), nbits);
Need "// INVARIANT:" here and in from_raw_mut() to explain why the references are valid.
Quoted 32 lines
rust/kernel/bitmap.rs new file +32
-0+unsafe { &*(dataas *const CBitmap ) } + } + +/// Borrows a C bitmap exclusively. +/// +/// # Safety +/// +/// * `ptr` holds a non-null address of an initialized array of `unsigned long` +/// that is large enough to hold `nbits` bits. +/// * the array must not be freed for the lifetime of this [`CBitmap`] +/// * no concurrent access may happen. +pub unsafe fn from_raw_mut <'a>(ptr: *mut usize , nbits:usize ) -> &'amut CBitmap { +let data: *mut [()] = core::ptr::slice_from_raw_parts_mut (ptr.cast (), nbits); +unsafe { &mut *(dataas *mut CBitmap ) } + } + +/// 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`]. +pub fn len (&self) ->usize { + self.data.len () + } +} +
[...]
rust/kernel/bitmap.rs line 175
Quoted 5 lines
rust/kernel/bitmap.rs new file +5
-0+/// Enable ownership transfer to other threads. +/// +/// # Safety +/// +/// We own the underlying bitmap representation.
Usually the comment here should be a:
// SAFETY: <explain why Bitmap is Send>
"# Safety" is for describing the safety requirement.
rust/kernel/bitmap.rs line 186
Quoted 11 lines
rust/kernel/bitmap.rs new file +11
-0+unsafe impl Send for Bitmap {} + +/// Enable unsynchronized concurrent access to [`Bitmap`] through shared references. +/// +/// # Safety +/// +/// * When no thread performs any mutations, concurrent access is safe. +/// * Mutations are permitted through atomic operations and interior mutability. +/// All such methods are marked unsafe, to account for the lack of ordering +/// guarantees. Callers must acknowledge that updates may be observed in any +/// order.
I think this comment is out-of-date. What makes Bitmap is that all methods will immutable references are either atomic or read-only (more accurately, Bitmap's deref() will return a reference to a CBitmap which is Sync).
Quoted 34 lines
rust/kernel/bitmap.rs new file +34
-0+unsafe impl Sync for Bitmap {} + +impl Drop for Bitmap { +fn drop (&mut self) { +if self.nbits <= bindings::BITS_PER_LONG as _ { +return ; + } +// SAFETY: `self.ptr` was returned by the C `bitmap_zalloc`. +// +// INVARIANT: there is no other use of the `self.ptr` after this +// call and the value is being dropped so the broken invariant is +// not observable on function exit. +unsafe { bindings::bitmap_free (self.repr.ptr.as_ptr ()) }; + } +} + +impl Bitmap { +/// Constructs a new [`Bitmap`]. +/// +/// Fails with [`AllocError`] when the [`Bitmap`] could not be allocated. This +/// includes the case when `nbits` is greater than `i32::MAX`. +#[inline] +pub fn new (nbits:usize , flags:Flags ) ->Result <Self ,AllocError > { +if nbits <= bindings::BITS_PER_LONG as _ { +return Ok (Bitmap { + repr:BitmapRepr { bitmap:0 }, + nbits, + }); + } +if nbits > i32::MAX .try_into ().unwrap () { +return Err (AllocError ); + } +let nbits_u32 = u32::try_from (nbits).unwrap (); +// SAFETY: `bindings::BITS_PER_LONG < nbits` and `nbits <= i32::MAX`.
rust/kernel/bitmap.rs line 230
Quoted 10 lines
rust/kernel/bitmap.rs new file +10
-0+let ptr =unsafe { bindings::bitmap_zalloc (nbits_u32, flags.as_raw ()) }; +let ptr =NonNull ::new (ptr).ok_or (AllocError )?; +// INVARIANT: `ptr` returned by C `bitmap_zalloc` and `nbits` checked. +return Ok (Bitmap { + repr:BitmapRepr { ptr }, + nbits, + }); + } + +/// Returns length of this [`CBitmap`].
Copy-pasta? It should be "[Bitmap]".
rust/kernel/bitmap.rs line 236
Quoted 6 lines
rust/kernel/bitmap.rs new file +6
-0+#[inline] +pub fn len (&self) ->usize { + self.nbits + } +} +
Probably need:
unsafe impl Sync for CBitmap { }
Quoted 15 lines
rust/kernel/bitmap.rs new file +15
-0+impl CBitmap { +/// Set bit with index `index`. +/// +/// ATTENTION: `set_bit` is non-atomic, which differs from the naming +/// convention in C code. The corresponding C function is `__set_bit`. +/// +/// If RUST_BITMAP_HARDENED is not enabled and `index` is greater than +/// or equal to `self.nbits`, does nothing. +/// +/// # Panics +/// +/// Panics if RUST_BITMAP_HARDENED is enabled and `index` is greater than +/// or equal to `self.nbits`. +#[inline] +pub fn set_bit (&mut self, index:usize ) {
rust/kernel/bitmap.rs line 261
Quoted 10 lines
rust/kernel/bitmap.rs new file +10
-0+bitmap_assert_return! ( + index < self.len (), +"Bit `index` must be < {}, was {}" , + self.len (), + index + ); +// SAFETY: Bit `index` is within bounds. +unsafe { bindings::__set_bit (indexas u32 , self.as_mut_ptr ()) }; + } +
[...]
Regards,
Boqun
PATCH v9 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.
--- MAINTAINERS | 1 + lib/Kconfig.debug | 13 +++++ lib/Makefile | 1 + lib/find_bit_benchmark_rust.rs | 94 +++++++++++++++++++++++++++++++++ rust/bindings/bindings_helper.h | 1 + rust/kernel/bitmap.rs | 14 +++++ 6 files changed, 124 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" + 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 +94 -0
94 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
@@ -232,6 +232,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.1151.ga128411c76-goog
kernel test robot
build botRe: [PATCH v9 4/5] rust: add find_bit_benchmark_rust module.
kernel test robot noticed the following build errors:
Hi Burak,
kernel test robot noticed the following build errors:
[auto build test ERROR on akpm-mm/mm-nonmm-unstable]
[also build test ERROR on kees/for-next/hardening kees/for-next/pstore kees/for-next/kspp linus/master v6.15] [cannot apply to rust/rust-next next-20250527]
[If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Burak-Emir/rust-add-bindings-for-bitmap-h/20250526-230435 base: https://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm.git mm-nonmm-unstable patch link: https://lore.kernel.org/r/20250526150141.3407433-5-bqe%40google.com patch subject: [PATCH v9 4/5] rust: add find_bit_benchmark_rust module. config: powerpc-allyesconfig (https://download.01.org/0day-ci/archive/20250528/[email protected]/config) compiler: clang version 21.0.0git (https://github.com/llvm/llvm-project f819f46284f2a79790038e1f6649172789734ae8) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20250528/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> error[E0463]: can't find crate for `core`
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
PATCH v9 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.1151.ga128411c76-goog
Yury Norov
maintainerQuoted 23 lines · Burak Emir
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 indbitmap.hmakes 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_atomicandclear_bit_atomicoperations. 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 benchmark (sample size 32), with RUST_BITMAP_HARDENED=n on a
x86_64production machine that was not running other processes.Results for random-filled bitmap:
Quoted 9 lines
+------------+------+-----------+--------------+-----------+-----------+ | Benchmark | Code | Mean (ns) | Std Dev (ns) | 95% CI Lo | 95% CI Hi | +------------+------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 5.18 | 0.32 | 5.17 | 5.18 | | next_bit | Rust | 5.30 | 0.37 | 5.30 | 5.31 | +------------+------+-----------+--------------+-----------+-----------+ | find_zero/ | C | 5.66 | 0.33 | 5.66 | 5.67 | | next_zero | Rust | 5.88 | 0.32 | 5.88 | 5.89 | +------------+------+-----------+--------------+-----------+-----------+
So, 95% CI means z=1.96, isn't? And to me it should be, for example for the first line: 5.18 +- 1.96*0.32/sqrt(32) = 5.18 +- 0.11 = [5.07, 5.29]. Can you check your math please?
Quoted 10 lines
Results for sparse bitmap:
+------------+------+-----------+--------------+-----------+-----------+ | Benchmark | Code | Mean (ns) | Std Dev (ns) | 95% CI Lo | 95% CI Hi | +------------+------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 22.51 | 12.34 | 22.38 | 22.65 | | next_bit | Rust | 30.53 | 20.44 | 30.30 | 30.75 | +------------+------+-----------+--------------+-----------+-----------+ | find_zero/ | C | 5.69 | 0.22 | 5.68 | 5.69 | | next_zero | Rust | 5.68 | 0.29 | 5.68 | 5.68 | +------------+------+-----------+--------------+-----------+-----------+
Your numbers look pretty weird. I wrote the test such that on a typical x86 system it takes milliseconds for each subtest to pass. Here you report nanoseconds-scaled times. Did you divide by the number of iterations? If so, please mention it.
Please print raw output of your test in patch #4 which adds the test. Because the test is tightly coupled to it's C version, we need to make sure it hast the same format - fields alignment, etc.
I would prefer to have detailed performance discussion in the corresponding patch (#4), and here in cover letter you'd just mention the overall performance difference - 2%, as I can see.
Quoted 156 lines
We introduce a Rust API that would replace (
dbitmap.h) in fileid_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 v9 of a patch introducing Rust bitmap API [v7]. Thanks for all the helpful comments, this series has improved significantly as a result of your work.
Changes v8 --> v9:
- added a new typeCBitmapthat 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 onCONFIG_RUSTthat was missing fromCONIG_FIND_BIT_BENCHMARK_RUST.
- implemented Send for Bitmap, it is actually needed by Binder.
- reworded commit msg for clarity.
- removed unsafe for atomic ops.
- renamedbitmap_hardening_asserttobitmap_assertand make operations do nothing and log error whenRUST_BITMAP_HARDENEDis off.
- update author information infind_bit_benchmark_rust.rs
- Various improvements toid_pool, better names and comments.Changes v7 --> v8:
- added Acked-by for bindings patches
- addRUST_BITMAP_HARDENEDconfig, making the extra bound-checks configurable. This is added tosecurity/Kconfig.hardening
- changed checks ofindexreturn value to >=
- removed change toFIND_BIT_BENCHMARKChanges v6 --> v7:
- Added separate unit tests inbitmap.rsand benchmark module, following the example infind_bit_benchmark.c
- Added discussion about using vendored bitset to commit message.
- Refined warning about naming conventionChanges v5 --> v6:
- Added SAFETY comment for atomic operations.
- Added missing volatile to bitopsset_bitandclear_bitbindings.
- Fixed condition onnbitsto 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
- splitMAINTAINERSchanges
- no dependencies on [1] and [2] anymore - Viresh,
please do add a separate section if you want to maintaincpumask.rsseparately.
- imports atomic and non-atomic variants, introduces a naming conventionset_bitandset_bit_atomicon the Rust side.
- changed naming and comments. Keepingnew.
- changedynamic_id_pooltoid_pool
- represent bitmap inline when possible
- add some more tests
- add myself to M: line for the Rust abstractionsChanges v3 --> v4:
- Rebased on Viresh's v3 [2].
- split into multiple patches, separate Rust and bindings. (Yury)
- addsdynamic_id_pool.rsto show the Binder use case. (Yury)
- include example usage that requires release of spinlock (Alice)
- changed bounds checks toassert!, 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 returnAllocErrorinBitmap::newin 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::MAXsituations differently.Changes v2 --> v3:
- changebitmap_copytocopy_from_bitmap_and_extendwhich 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 ofbindings::*, 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 forbitmap.rswhich goes to Alice (Viresh, Alice)
- Changed calls from find_* to _find_*, removed helpers (Yury)
- Use non-atomic__set_bitand__clear_bitfrom 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 [v8] https://lore.kernel.org/rust-for-linux/[email protected]/Burak Emir (6):
rust: add bindings forbitmap.h
rust: add bindings forbitops.h
rust: add bitmap API.
bitmap: fixfind_bit_benchmarkmodule name and config description
rust: addfind_bit_benchmark_rustmodule.
rust: add dynamic ID pool abstraction for bitmapMAINTAINERS | 15 ++ lib/Kconfig.debug | 18 +- lib/Makefile | 1 + lib/find_bit_benchmark_rust.rs | 94 +++++++ 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 | 429 ++++++++++++++++++++++++++++++++ rust/kernel/id_pool.rs | 201 +++++++++++++++ rust/kernel/lib.rs | 2 + security/Kconfig.hardening | 11 + 12 files changed, 805 insertions(+), 2 deletions(-) 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.rsSignature · 30 lines
2.49.0.1101.gccaa498523-goog 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 | 94 ++++++ 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 | 568 ++++++++++++++++++++++++++++++++ rust/kernel/id_pool.rs | 222 +++++++++++++ rust/kernel/lib.rs | 2 + security/Kconfig.hardening | 10 + 12 files changed, 961 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 -- 2.49.0.1151.ga128411c76-goog
Quoted 3 lines · Yury Norov
So, 95% CI means z=1.96, isn't? And to me it should be, for example for the first line: 5.18 +- 1.96*0.32/sqrt(32) = 5.18 +- 0.11 = [5.07, 5.29]. Can you check your math please?
Facepalm... I used scipy to get the CI, and passed alpha (5%) instead of 1-alpha (95%) for confidence level.
I am very sorry...
Quoted 11 lines
Quoted 10 lines
Results for sparse bitmap:
+------------+------+-----------+--------------+-----------+-----------+ | Benchmark | Code | Mean (ns) | Std Dev (ns) | 95% CI Lo | 95% CI Hi | +------------+------+-----------+--------------+-----------+-----------+ | find_bit/ | C | 22.51 | 12.34 | 22.38 | 22.65 | | next_bit | Rust | 30.53 | 20.44 | 30.30 | 30.75 | +------------+------+-----------+--------------+-----------+-----------+ | find_zero/ | C | 5.69 | 0.22 | 5.68 | 5.69 | | next_zero | Rust | 5.68 | 0.29 | 5.68 | 5.68 | +------------+------+-----------+--------------+-----------+-----------+
Quoted 4 lines
Your numbers look pretty weird. I wrote the test such that on a typical x86 system it takes milliseconds for each subtest to pass. Here you report nanoseconds-scaled times. Did you divide by the number of iterations? If so, please mention it.
Yes, I had divided by number of iterations.
Now that you are questioning this, I have second thoughts. I will repeat the benchmark, without dividing by iterations.
Quoted 3 lines
Please print raw output of your test in patch #4 which adds the test. Because the test is tightly coupled to it's C version, we need to make sure it hast the same format - fields alignment, etc.
Will do. In v10, I have removed the module name from the output and the lines match exactly now.
Quoted 4 lines
I would prefer to have detailed performance discussion in the corresponding patch (#4), and here in cover letter you'd just mention the overall performance difference - 2%, as I can see.
ok.
cheers,
Burak
Yury Norov
maintainerQuoted 9 lines · Burak Emir
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 indbitmap.hmakes 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.
Quoted 6 lines
We include
set_bit_atomicandclear_bit_atomicoperations. 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.
Here I'm lost. In the other email you say:
Quoted 5 lines
You also commented on the API. The weirdness of the API is all due to the separating "request to shrink/grow" from allocation. Since allocation can happen while other threads may mess with the id pool, one has to double check that the request to shrink/grow still makes sense.
And here you say:
Quoted 3 lines
there is a
exclusive reference &mut bitmap, in which case there is no concurrent access
So to me it sounds like if I want to resize, I just allocate a new bitmap, take this exclusive reference, copy IDs, swap the pointers in corresponding class, and that's it. What did I miss?
+Carlos
Quoted 19 lines · Yury Norov
Quoted 6 lines · Burak Emir
We include
set_bit_atomicandclear_bit_atomicoperations. 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.Here I'm lost. In the other email you say:
Quoted 5 lines
You also commented on the API. The weirdness of the API is all due to the separating "request to shrink/grow" from allocation. Since allocation can happen while other threads may mess with the id pool, one has to double check that the request to shrink/grow still makes sense.
And here you say:
Quoted 7 lines
Quoted 3 lines
there is a
exclusive reference &mut bitmap, in which case there is no concurrent accessSo to me it sounds like if I want to resize, I just allocate a new bitmap, take this exclusive reference, copy IDs, swap the pointers in corresponding class, and that's it. What did I miss?
The two emails are about two related but different things:
1. the bitmap API which uses kmalloc with GFP_KERNEL, and what you suggest could be done with &mut references
2. the id_pool and its fine-grained API that permits controlling the time of allocation, which is used in binder which relies on a spinlock.
My limited understanding is that calling kmalloc w/ GFP_KERNEL while holding a spinlock is not good, since the kmalloc may sleep. You can see this "first unlock, then alloc, then lock again" pattern in binder code here:
https://github.com/torvalds/linux/blob/15d9da3f818cae676f822a04407d3c17b53357d2/drivers/android/binder.c#L1099
cheers,
- Burak