Skip to contentSkip to conversation

rust: adds Bitmap API, ID pool and bindings

PATCH Superseded Burak Emir 4 participants 11 messages Jun 2, 2025 – Jun 11, 2025

Subsystems (7)

v10 of 16 Superseded Latest is v16 →

lore
Share & tools
lore

Burak Emir

author
#0 lore raw

v10 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 v10 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 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.

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]/

*** BLURB HERE ***

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
author
#1 lore raw

PATCH v10 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
index d48dd6726fe6..86cae0ca5287 100644
@@ -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
index ab37e1d35c70..b6bf3b039c1b 100644
@@ -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
new file mode 100644
index 000000000000..a50e2f082e47
@@ -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
index 1e7c84df7252..92721d165e35 100644
@@ -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
author
#2 lore raw

PATCH v10 2/5 rust: add bindings for bitops.h

In reply to Burak Emir

Makes 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
index 86cae0ca5287..04d6727e944c 100644
@@ -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
new file mode 100644
index 000000000000..5d0861d29d3f
@@ -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
index 92721d165e35..4de8ac390241 100644
@@ -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
author
#3 lore raw

PATCH v10 3/5 rust: add bitmap API.

In reply to 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 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
index 04d6727e944c..565eaa015d9e 100644
@@ -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
index de07aadd1ff5..8c4161cd82ac 100644
@@ -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
index 3fe9d7b945c4..3ca3c7dc4381 100644
@@ -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
author
#4 lore raw

PATCH v10 4/5 rust: add find_bit_benchmark_rust module.

In reply to Burak Emir

Microbenchmark 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
index 565eaa015d9e..943d85ed1876 100644
@@ -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
index f9051ab610d5..d8ed53f35495 100644
@@ -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 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
index f07b24ce1b3f..99e49a8f5bf8 100644
@@ -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
index b6bf3b039c1b..f6ca7f1dd08b 100644
@@ -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
index 28c11e400d1e..9fefb2473099 100644
@@ -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
author
#9 lore raw

PATCH v10 5/5 rust: add dynamic ID pool abstraction for bitmap

In reply to 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.

---
 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
index 943d85ed1876..bc95d98f266b 100644
@@ -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
index 8c4161cd82ac..d7def807900a 100644
@@ -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
author
#10 lore raw
In reply to Burak Emir

Sorry for the spam, please ignore this version. Had to fix one more typo in Kconfig.

Quoted 4 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 in dbitmap.h makes use of bitmap and bitops.

maintainer Reviewed-by on v10 4/5
#5 lore raw

Re: [PATCH v10 4/5] rust: add find_bit_benchmark_rust module.

In reply to Burak Emir
Quoted 145 lines · Burak Emir

Microbenchmark 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
index 565eaa015d9e..943d85ed1876 100644
@@ -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
index f9051ab610d5..d8ed53f35495 100644
@@ -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 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
index f07b24ce1b3f..99e49a8f5bf8 100644
@@ -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 +5 -0
new file mode 100644
index 000000000000..468a2087f68c
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: GPL-2.0
+//! Benchmark for find_bit-like methods in Bitmap Rust API.
+
+use kernel::alloc::flags::GFP_KERNEL;
+use kernel::bindings;

lib/find_bit_benchmark_rust.rs line 15

Quoted 10 lines
lib/find_bit_benchmark_rust.rs new file +10 -0
+use kernel::bitmap::Bitmap;
+use kernel::error::{code, Result};
+use kernel::prelude::module;
+use kernel::time::Ktime;
+use kernel::ThisModule;
+use kernel::{pr_cont, pr_err};
+
+const BITMAP_LEN: usize = 4096 * 8 * 10;
+// Reciprocal of the fraction of bits that are set in sparse bitmap.
+const SPARSENESS: usize = 500;

Is there any simple mechanism to keep C and rust sizes synced? (If no, not a big deal to redefine them.)

Quoted 65 lines
lib/find_bit_benchmark_rust.rs new file +65 -0
+
+/// Test module that benchmarks performance of traversing bitmaps.
+struct FindBitBenchmarkModule();
+
+fn test_next_bit(bitmap: &Bitmap) {
+    let mut time = Ktime::ktime_get();
+    let mut cnt = 0;
+    let mut i = 0;
+
+    while let Some(index) = bitmap.next_bit(i) {
+        cnt += 1;
+        i = index + 1;
+    }
+
+    time = Ktime::ktime_get() - time;
+    pr_cont!(
+        "next_bit:           {:18} ns, {:6} iterations\n",
+        time.to_ns(),
+        cnt
+    );
+}
+
+fn test_next_zero_bit(bitmap: &Bitmap) {
+    let mut time = Ktime::ktime_get();
+    let mut cnt = 0;
+    let mut i = 0;
+
+    while let Some(index) = bitmap.next_zero_bit(i) {
+        cnt += 1;
+        i = index + 1;
+    }
+
+    time = Ktime::ktime_get() - time;
+    pr_cont!(
+        "next_zero_bit:      {:18} ns, {:6} iterations\n",
+        time.to_ns(),
+        cnt
+    );
+}
+
+fn find_bit_test() {
+    pr_err!("\n");
+    pr_cont!("Start testing find_bit() Rust with random-filled bitmap\n");
+
+    let mut bitmap = Bitmap::new(BITMAP_LEN, GFP_KERNEL).expect("alloc bitmap failed");
+    bitmap.fill_random();
+
+    test_next_bit(&bitmap);
+    test_next_zero_bit(&bitmap);
+
+    pr_cont!("Start testing find_bit() Rust with sparse bitmap\n");
+
+    let mut bitmap = Bitmap::new(BITMAP_LEN, GFP_KERNEL).expect("alloc sparse bitmap failed");
+    let nbits = BITMAP_LEN / SPARSENESS;
+    for _i in 0..nbits {
+        // SAFETY: BITMAP_LEN fits in 32 bits.
+        let bit: usize =
+            unsafe { bindings::__get_random_u32_below(BITMAP_LEN.try_into().unwrap()) as _ };
+        bitmap.set_bit(bit);
+    }
+
+    test_next_bit(&bitmap);
+    test_next_zero_bit(&bitmap);
+}
+

lib/find_bit_benchmark_rust.rs line 90

Quoted 10 lines
lib/find_bit_benchmark_rust.rs new file +10 -0
+impl kernel::Module for FindBitBenchmarkModule {
+    fn init(_module: &'static ThisModule) -> Result<Self> {
+        find_bit_test();
+        // Return error so test module can be inserted again without rmmod.
+        Err(code::EINVAL)
+    }
+}
+
+module! {
+    type: FindBitBenchmarkModule,

I think we agreed to have the type something less unique, like:

Benchmark.

lib/find_bit_benchmark_rust.rs line 91

Quoted 1 line
lib/find_bit_benchmark_rust.rs new file +1 -0
+    name: "find_bit_benchmark_rust_module",

What is the name policy for rust? Maybe a more human-readable name would work better here?

All the above are nits. Please have my

Thanks,
Yury

Quoted 43 lines
lib/find_bit_benchmark_rust.rs new file +4 -0
+    authors: ["Burak Emir <[email protected]>"],
+    description: "Module with benchmark for bitmap Rust API",
+    license: "GPL v2",
+}
rust/bindings/bindings_helper.h +1 -0
index b6bf3b039c1b..f6ca7f1dd08b 100644
@@ -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
index 28c11e400d1e..9fefb2473099 100644
@@ -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
maintainer
#6 lore raw

Re: [PATCH v10 4/5] rust: add find_bit_benchmark_rust module.

Quoted 79 lines · Yury Norov
Quoted 76 lines · Burak Emir

Microbenchmark 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.

Quoted 6 lines

lib/find_bit_benchmark_rust.rs line 15

Quoted 3 lines
lib/find_bit_benchmark_rust.rs new file +3 -0
+const BITMAP_LEN: usize = 4096 * 8 * 10;
+// Reciprocal of the fraction of bits that are set in sparse bitmap.
+const SPARSENESS: usize = 500;

Is there any simple mechanism to keep C and rust sizes synced? (If no, not a big deal to redefine them.)

Rust can access constants from header files, so you can move it to a header file.

Quoted 11 lines

lib/find_bit_benchmark_rust.rs line 90

Quoted 2 lines
lib/find_bit_benchmark_rust.rs new file +2 -0
+module! {
+    type: FindBitBenchmarkModule,

I think we agreed to have the type something less unique, like:

Benchmark.

Quoted 1 line

+ name: "find_bit_benchmark_rust_module",

What is the name policy for rust? Maybe a more human-readable name would work better here?

I don't think there's any particular policy for Rust. Name modules in the same manner you would C modules.

Quoted 6 lines

All the above are nits. Please have my

Thanks,
Yury

Alice

#7 lore raw

Re: [PATCH v10 4/5] rust: add find_bit_benchmark_rust module.

In reply to Yury Norov
Quoted 7 lines · Yury Norov

lib/find_bit_benchmark_rust.rs line 15

Quoted 4 lines
lib/find_bit_benchmark_rust.rs new file +3 -0
+const BITMAP_LEN: usize = 4096 * 8 * 10;
+// Reciprocal of the fraction of bits that are set in sparse bitmap.
+const SPARSENESS: usize = 500;

Is there any simple mechanism to keep C and rust sizes synced? (If no, not a big deal to redefine them.)

One may pick them from C (possibly with a RUST_HELPER_* if needed). If they are non-trivial macros, then using an enum instead of a #define on the C side is also an alternative.

Quoted 2 lines

What is the name policy for rust? Maybe a more human-readable name would work better here?

Up to the maintainers, and generally the same as for C. In the global Rust samples and things like that we have rust in the name since they are Rust samples after all, but there is no need to say rust or module in actual modules etc. unless there is a reason for it.

I hope that helps!

Cheers,
Miguel

author
#8 lore raw

Re: [PATCH v10 4/5] rust: add find_bit_benchmark_rust module.

Thanks all for the review & comments.

Quoted 10 lines · Miguel Ojeda
Quoted 7 lines · Yury Norov

lib/find_bit_benchmark_rust.rs line 15

Quoted 4 lines
lib/find_bit_benchmark_rust.rs new file +3 -0
+const BITMAP_LEN: usize = 4096 * 8 * 10;
+// Reciprocal of the fraction of bits that are set in sparse bitmap.
+const SPARSENESS: usize = 500;

Is there any simple mechanism to keep C and rust sizes synced? (If no, not a big deal to redefine them.)

Quoted 3 lines

One may pick them from C (possibly with a RUST_HELPER_* if needed). If they are non-trivial macros, then using an enum instead of a #define on the C side is also an alternative.

I'd prefer not to move these to a header file and define RUST_HELPER and such. I'd prefer if test & benchmark code was somewhat contained (although I agree it would be nice to keep the two definitions in sync).

Quoted 9 lines
Quoted 2 lines

What is the name policy for rust? Maybe a more human-readable name would work better here?

Up to the maintainers, and generally the same as for C. In the global Rust samples and things like that we have rust in the name since they are Rust samples after all, but there is no need to say rust or module in actual modules etc. unless there is a reason for it.

I hope that helps!

I renamed the module struct to Benchmark now and made the "name" the same as the file name.
So the _rust suffix is there because the rust file really corresponds to the C file.
In this particular case, I think it does help to see how it relates to the C file.

Cheers,
- Burak