mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
From: Vitaly Wool <vitaly.wool@konsulko.se>
To: Andreas Hindborg <a.hindborg@kernel.org>,
	Jens Axboe <axboe@kernel.dk>, Yury Norov <yury.norov@gmail.com>
Cc: "Burak Emir" <burak.emir@gmail.com>,
	"Boqun Feng" <boqun@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Miguel Ojeda" <ojeda@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"Alexandre Courbot" <acourbot@nvidia.com>,
	"Onur Özkan" <work@onurozkan.dev>,
	linux-block@vger.kernel.org, rust-for-linux@vger.kernel.org,
	linux-kernel@vger.kernel.org,
	"Vitaly Wool" <vitaly.wool@konsulko.se>,
	"Igor Belousov" <igor.b@beldev.am>,
	"Claude Opus 5 . 5" <noreply@anthropic.com>
Subject: [PATCH 1/2] rust: bitmap: add BitmapArray
Date: Wed,  2 Dec 2026 10:23:31 +0100	[thread overview]
Message-ID: <20261202092332.136789-2-vitaly.wool@konsulko.se> (raw)
In-Reply-To: <20261202092332.136789-1-vitaly.wool@konsulko.se>

A `BitmapVec` keeps up to `usize::BITS` bits inline and allocates its
storage with `bitmap_zalloc()` beyond that. A bitmap embedded in a
structure that is allocated anyway, with a maximum length known at
compile time, then needs a second allocation and a pointer to follow,
or `unsafe` code that wraps an array with `Bitmap::from_raw()`.

Add `BitmapArray<WORDS>`, an owned bitmap of up to `WORDS` words of
bits stored inline, which never allocates and dereferences to `Bitmap`
like `BitmapVec`.

Signed-off-by: Vitaly Wool <vitaly.wool@konsulko.se>
Tested-by: Igor Belousov <igor.b@beldev.am>
Assisted-by: Claude Opus 5.5 <noreply@anthropic.com>
---
 rust/kernel/bitmap.rs | 91 +++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 91 insertions(+)

diff --git a/rust/kernel/bitmap.rs b/rust/kernel/bitmap.rs
index 610d565535cc..7d7bd40e2e2b 100644
--- a/rust/kernel/bitmap.rs
+++ b/rust/kernel/bitmap.rs
@@ -8,6 +8,7 @@
 
 use crate::alloc::{AllocError, Flags};
 use crate::bindings;
+use crate::error::{code::EINVAL, Result};
 #[cfg(not(CONFIG_RUST_BITMAP_HARDENED))]
 use crate::pr_err;
 use crate::ptr::Alignment;
@@ -320,6 +321,96 @@ pub fn fill_random(&mut self) {
     }
 }
 
+/// An owned bitmap of up to `WORDS * usize::BITS` bits, stored inline.
+///
+/// Unlike [`BitmapVec`], it never allocates, so it suits bitmaps whose maximum length is known at
+/// compile time and that are embedded in other structures. See [`Bitmap`] for available methods.
+///
+/// # Examples
+///
+/// ```
+/// use kernel::bitmap::BitmapArray;
+///
+/// let mut b = BitmapArray::<2>::new(100)?;
+///
+/// assert_eq!(100, b.len());
+/// b.set_bit(3);
+/// b.set_bit(99);
+/// assert_eq!(Some(3), b.next_bit(0));
+/// assert_eq!(Some(99), b.next_bit(4));
+/// assert_eq!(Some(99), b.last_bit());
+///
+/// b.clear_all();
+/// assert_eq!(None, b.next_bit(0));
+///
+/// assert!(BitmapArray::<2>::new(129).is_err());
+/// # Ok::<(), Error>(())
+/// ```
+///
+/// # Invariants
+///
+/// `nbits` is at most [`BitmapArray::CAPACITY`] and at most [`BitmapVec::MAX_LEN`].
+pub struct BitmapArray<const WORDS: usize> {
+    /// Storage of the bitmap.
+    words: [usize; WORDS],
+    /// Length of this bitmap.
+    nbits: usize,
+}
+
+impl<const WORDS: usize> BitmapArray<WORDS> {
+    /// The maximum length of a `BitmapArray` with `WORDS` words.
+    pub const CAPACITY: usize = WORDS.saturating_mul(usize::BITS as usize);
+
+    /// Constructs a new [`BitmapArray`] of `nbits` bits, all clear.
+    ///
+    /// Fails with [`EINVAL`] if `nbits` is greater than [`BitmapArray::CAPACITY`] or than
+    /// [`BitmapVec::MAX_LEN`].
+    #[inline]
+    pub fn new(nbits: usize) -> Result<Self> {
+        if nbits > Self::CAPACITY || nbits > BitmapVec::MAX_LEN {
+            return Err(EINVAL);
+        }
+        // INVARIANT: `nbits` was checked above.
+        Ok(Self {
+            words: [0; WORDS],
+            nbits,
+        })
+    }
+
+    /// Returns length of this [`BitmapArray`].
+    #[allow(clippy::len_without_is_empty)]
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.nbits
+    }
+
+    /// Clears all bits of this [`BitmapArray`].
+    #[inline]
+    pub fn clear_all(&mut self) {
+        self.words = [0; WORDS];
+    }
+}
+
+impl<const WORDS: usize> core::ops::Deref for BitmapArray<WORDS> {
+    type Target = Bitmap;
+
+    #[inline]
+    fn deref(&self) -> &Bitmap {
+        // SAFETY: `self.words` is an initialized array that holds `CAPACITY >= nbits` bits,
+        // `nbits <= MAX_LEN` by the type invariants, and the array lives as long as the returned
+        // shared borrow of `self`.
+        unsafe { Bitmap::from_raw(self.words.as_ptr(), self.nbits) }
+    }
+}
+
+impl<const WORDS: usize> core::ops::DerefMut for BitmapArray<WORDS> {
+    #[inline]
+    fn deref_mut(&mut self) -> &mut Bitmap {
+        // SAFETY: As in `deref`, and the returned borrow of `self` is exclusive.
+        unsafe { Bitmap::from_raw_mut(self.words.as_mut_ptr(), self.nbits) }
+    }
+}
+
 impl Bitmap {
     /// Set bit with index `index`.
     ///
-- 
2.39.5


  reply	other threads:[~2026-12-02  9:23 UTC|newest]

Thread overview: 3+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-12-02  9:23 [PATCH 0/2] rnull: support 64K pages Vitaly Wool
2026-12-02  9:23 ` Vitaly Wool [this message]
2026-12-02 14:13 ` Yury Norov

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261202092332.136789-2-vitaly.wool@konsulko.se \
    --to=vitaly.wool@konsulko.se \
    --cc=a.hindborg@kernel.org \
    --cc=acourbot@nvidia.com \
    --cc=aliceryhl@google.com \
    --cc=axboe@kernel.dk \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=burak.emir@gmail.com \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=gary@garyguo.net \
    --cc=igor.b@beldev.am \
    --cc=linux-block@vger.kernel.org \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=noreply@anthropic.com \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=work@onurozkan.dev \
    --cc=yury.norov@gmail.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®