1 // SPDX-License-Identifier: GPL-2.0 2 3 // Copyright (C) 2025 Google LLC. 4 5 //! Rust API for bitmap. 6 //! 7 //! C headers: [`include/linux/bitmap.h`](srctree/include/linux/bitmap.h). 8 9 use crate::alloc::{AllocError, Flags}; 10 use crate::bindings; 11 #[cfg(not(CONFIG_RUST_BITMAP_HARDENED))] 12 use crate::pr_err; 13 use core::ptr::NonNull; 14 15 const BITS_PER_LONG: usize = bindings::BITS_PER_LONG as usize; 16 17 /// Represents a C bitmap. Wraps underlying C bitmap API. 18 /// 19 /// # Invariants 20 /// 21 /// Must reference a `[c_ulong]` long enough to fit `data.len()` bits. 22 #[cfg_attr(CONFIG_64BIT, repr(align(8)))] 23 #[cfg_attr(not(CONFIG_64BIT), repr(align(4)))] 24 pub struct Bitmap { 25 data: [()], 26 } 27 28 impl Bitmap { 29 /// Borrows a C bitmap. 30 /// 31 /// # Safety 32 /// 33 /// * `ptr` holds a non-null address of an initialized array of `unsigned long` 34 /// that is large enough to hold `nbits` bits. 35 /// * the array must not be freed for the lifetime of this [`Bitmap`] 36 /// * concurrent access only happens through atomic operations 37 pub unsafe fn from_raw<'a>(ptr: *const usize, nbits: usize) -> &'a Bitmap { 38 let data: *const [()] = core::ptr::slice_from_raw_parts(ptr.cast(), nbits); 39 // INVARIANT: `data` references an initialized array that can hold `nbits` bits. 40 // SAFETY: 41 // The caller guarantees that `data` (derived from `ptr` and `nbits`) 42 // points to a valid, initialized, and appropriately sized memory region 43 // that will not be freed for the lifetime 'a. 44 // We are casting `*const [()]` to `*const Bitmap`. The `Bitmap` 45 // struct is a ZST with a `data: [()]` field. This means its layout 46 // is compatible with a slice of `()`, and effectively it's a "thin pointer" 47 // (its size is 0 and alignment is 1). The `slice_from_raw_parts` 48 // function correctly encodes the length (number of bits, not elements) 49 // into the metadata of the fat pointer. Therefore, dereferencing this 50 // pointer as `&Bitmap` is safe given the caller's guarantees. 51 unsafe { &*(data as *const Bitmap) } 52 } 53 54 /// Borrows a C bitmap exclusively. 55 /// 56 /// # Safety 57 /// 58 /// * `ptr` holds a non-null address of an initialized array of `unsigned long` 59 /// that is large enough to hold `nbits` bits. 60 /// * the array must not be freed for the lifetime of this [`Bitmap`] 61 /// * no concurrent access may happen. 62 pub unsafe fn from_raw_mut<'a>(ptr: *mut usize, nbits: usize) -> &'a mut Bitmap { 63 let data: *mut [()] = core::ptr::slice_from_raw_parts_mut(ptr.cast(), nbits); 64 // INVARIANT: `data` references an initialized array that can hold `nbits` bits. 65 // SAFETY: 66 // The caller guarantees that `data` (derived from `ptr` and `nbits`) 67 // points to a valid, initialized, and appropriately sized memory region 68 // that will not be freed for the lifetime 'a. 69 // Furthermore, the caller guarantees no concurrent access will happen, 70 // which upholds the exclusivity requirement for a mutable reference. 71 // Similar to `from_raw`, casting `*mut [()]` to `*mut Bitmap` is 72 // safe because `Bitmap` is a ZST with a `data: [()]` field, 73 // making its layout compatible with a slice of `()`. 74 unsafe { &mut *(data as *mut Bitmap) } 75 } 76 77 /// Returns a raw pointer to the backing [`Bitmap`]. 78 pub fn as_ptr(&self) -> *const usize { 79 core::ptr::from_ref::<Bitmap>(self).cast::<usize>() 80 } 81 82 /// Returns a mutable raw pointer to the backing [`Bitmap`]. 83 pub fn as_mut_ptr(&mut self) -> *mut usize { 84 core::ptr::from_mut::<Bitmap>(self).cast::<usize>() 85 } 86 87 /// Returns length of this [`Bitmap`]. 88 #[expect(clippy::len_without_is_empty)] 89 pub fn len(&self) -> usize { 90 self.data.len() 91 } 92 } 93 94 /// Holds either a pointer to array of `unsigned long` or a small bitmap. 95 #[repr(C)] 96 union BitmapRepr { 97 bitmap: usize, 98 ptr: NonNull<usize>, 99 } 100 101 macro_rules! bitmap_assert { 102 ($cond:expr, $($arg:tt)+) => { 103 #[cfg(CONFIG_RUST_BITMAP_HARDENED)] 104 assert!($cond, $($arg)*); 105 } 106 } 107 108 macro_rules! bitmap_assert_return { 109 ($cond:expr, $($arg:tt)+) => { 110 #[cfg(CONFIG_RUST_BITMAP_HARDENED)] 111 assert!($cond, $($arg)*); 112 113 #[cfg(not(CONFIG_RUST_BITMAP_HARDENED))] 114 if !($cond) { 115 pr_err!($($arg)*); 116 return 117 } 118 } 119 } 120 121 /// Represents an owned bitmap. 122 /// 123 /// Wraps underlying C bitmap API. See [`Bitmap`] for available 124 /// methods. 125 /// 126 /// # Examples 127 /// 128 /// Basic usage 129 /// 130 /// ``` 131 /// use kernel::alloc::flags::GFP_KERNEL; 132 /// use kernel::bitmap::BitmapVec; 133 /// 134 /// let mut b = BitmapVec::new(16, GFP_KERNEL)?; 135 /// 136 /// assert_eq!(16, b.len()); 137 /// for i in 0..16 { 138 /// if i % 4 == 0 { 139 /// b.set_bit(i); 140 /// } 141 /// } 142 /// assert_eq!(Some(0), b.next_bit(0)); 143 /// assert_eq!(Some(1), b.next_zero_bit(0)); 144 /// assert_eq!(Some(4), b.next_bit(1)); 145 /// assert_eq!(Some(5), b.next_zero_bit(4)); 146 /// assert_eq!(Some(12), b.last_bit()); 147 /// # Ok::<(), Error>(()) 148 /// ``` 149 /// 150 /// # Invariants 151 /// 152 /// * `nbits` is `<= i32::MAX` and never changes. 153 /// * if `nbits <= bindings::BITS_PER_LONG`, then `repr` is a `usize`. 154 /// * otherwise, `repr` holds a non-null pointer to an initialized 155 /// array of `unsigned long` that is large enough to hold `nbits` bits. 156 pub struct BitmapVec { 157 /// Representation of bitmap. 158 repr: BitmapRepr, 159 /// Length of this bitmap. Must be `<= i32::MAX`. 160 nbits: usize, 161 } 162 163 impl core::ops::Deref for BitmapVec { 164 type Target = Bitmap; 165 166 fn deref(&self) -> &Bitmap { 167 let ptr = if self.nbits <= BITS_PER_LONG { 168 // SAFETY: Bitmap is represented inline. 169 unsafe { core::ptr::addr_of!(self.repr.bitmap) } 170 } else { 171 // SAFETY: Bitmap is represented as array of `unsigned long`. 172 unsafe { self.repr.ptr.as_ptr() } 173 }; 174 175 // SAFETY: We got the right pointer and invariants of [`Bitmap`] hold. 176 // An inline bitmap is treated like an array with single element. 177 unsafe { Bitmap::from_raw(ptr, self.nbits) } 178 } 179 } 180 181 impl core::ops::DerefMut for BitmapVec { 182 fn deref_mut(&mut self) -> &mut Bitmap { 183 let ptr = if self.nbits <= BITS_PER_LONG { 184 // SAFETY: Bitmap is represented inline. 185 unsafe { core::ptr::addr_of_mut!(self.repr.bitmap) } 186 } else { 187 // SAFETY: Bitmap is represented as array of `unsigned long`. 188 unsafe { self.repr.ptr.as_ptr() } 189 }; 190 191 // SAFETY: We got the right pointer and invariants of [`BitmapVec`] hold. 192 // An inline bitmap is treated like an array with single element. 193 unsafe { Bitmap::from_raw_mut(ptr, self.nbits) } 194 } 195 } 196 197 /// Enable ownership transfer to other threads. 198 /// 199 /// SAFETY: We own the underlying bitmap representation. 200 unsafe impl Send for BitmapVec {} 201 202 /// Enable unsynchronized concurrent access to [`BitmapVec`] through shared references. 203 /// 204 /// SAFETY: `deref()` will return a reference to a [`Bitmap`]. Its methods 205 /// take immutable references are either atomic or read-only. 206 unsafe impl Sync for BitmapVec {} 207 208 impl Drop for BitmapVec { 209 fn drop(&mut self) { 210 if self.nbits <= BITS_PER_LONG { 211 return; 212 } 213 // SAFETY: `self.ptr` was returned by the C `bitmap_zalloc`. 214 // 215 // INVARIANT: there is no other use of the `self.ptr` after this 216 // call and the value is being dropped so the broken invariant is 217 // not observable on function exit. 218 unsafe { bindings::bitmap_free(self.repr.ptr.as_ptr()) }; 219 } 220 } 221 222 impl BitmapVec { 223 /// Constructs a new [`BitmapVec`]. 224 /// 225 /// Fails with [`AllocError`] when the [`BitmapVec`] could not be allocated. This 226 /// includes the case when `nbits` is greater than `i32::MAX`. 227 #[inline] 228 pub fn new(nbits: usize, flags: Flags) -> Result<Self, AllocError> { 229 if nbits <= BITS_PER_LONG { 230 return Ok(BitmapVec { 231 repr: BitmapRepr { bitmap: 0 }, 232 nbits, 233 }); 234 } 235 if nbits > i32::MAX.try_into().unwrap() { 236 return Err(AllocError); 237 } 238 let nbits_u32 = u32::try_from(nbits).unwrap(); 239 // SAFETY: `BITS_PER_LONG < nbits` and `nbits <= i32::MAX`. 240 let ptr = unsafe { bindings::bitmap_zalloc(nbits_u32, flags.as_raw()) }; 241 let ptr = NonNull::new(ptr).ok_or(AllocError)?; 242 // INVARIANT: `ptr` returned by C `bitmap_zalloc` and `nbits` checked. 243 Ok(BitmapVec { 244 repr: BitmapRepr { ptr }, 245 nbits, 246 }) 247 } 248 249 /// Returns length of this [`Bitmap`]. 250 #[allow(clippy::len_without_is_empty)] 251 #[inline] 252 pub fn len(&self) -> usize { 253 self.nbits 254 } 255 } 256 257 impl Bitmap { 258 /// Set bit with index `index`. 259 /// 260 /// ATTENTION: `set_bit` is non-atomic, which differs from the naming 261 /// convention in C code. The corresponding C function is `__set_bit`. 262 /// 263 /// If CONFIG_RUST_BITMAP_HARDENED is not enabled and `index` is greater than 264 /// or equal to `self.nbits`, does nothing. 265 /// 266 /// # Panics 267 /// 268 /// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `index` is greater than 269 /// or equal to `self.nbits`. 270 #[inline] 271 pub fn set_bit(&mut self, index: usize) { 272 bitmap_assert_return!( 273 index < self.len(), 274 "Bit `index` must be < {}, was {}", 275 self.len(), 276 index 277 ); 278 // SAFETY: Bit `index` is within bounds. 279 unsafe { bindings::__set_bit(index, self.as_mut_ptr()) }; 280 } 281 282 /// Set bit with index `index`, atomically. 283 /// 284 /// This is a relaxed atomic operation (no implied memory barriers). 285 /// 286 /// ATTENTION: The naming convention differs from C, where the corresponding 287 /// function is called `set_bit`. 288 /// 289 /// If CONFIG_RUST_BITMAP_HARDENED is not enabled and `index` is greater than 290 /// or equal to `self.len()`, does nothing. 291 /// 292 /// # Panics 293 /// 294 /// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `index` is greater than 295 /// or equal to `self.len()`. 296 #[inline] 297 pub fn set_bit_atomic(&self, index: usize) { 298 bitmap_assert_return!( 299 index < self.len(), 300 "Bit `index` must be < {}, was {}", 301 self.len(), 302 index 303 ); 304 // SAFETY: `index` is within bounds and the caller has ensured that 305 // there is no mix of non-atomic and atomic operations. 306 unsafe { bindings::set_bit(index, self.as_ptr().cast_mut()) }; 307 } 308 309 /// Clear `index` bit. 310 /// 311 /// ATTENTION: `clear_bit` is non-atomic, which differs from the naming 312 /// convention in C code. The corresponding C function is `__clear_bit`. 313 /// 314 /// If CONFIG_RUST_BITMAP_HARDENED is not enabled and `index` is greater than 315 /// or equal to `self.len()`, does nothing. 316 /// 317 /// # Panics 318 /// 319 /// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `index` is greater than 320 /// or equal to `self.len()`. 321 #[inline] 322 pub fn clear_bit(&mut self, index: usize) { 323 bitmap_assert_return!( 324 index < self.len(), 325 "Bit `index` must be < {}, was {}", 326 self.len(), 327 index 328 ); 329 // SAFETY: `index` is within bounds. 330 unsafe { bindings::__clear_bit(index, self.as_mut_ptr()) }; 331 } 332 333 /// Clear `index` bit, atomically. 334 /// 335 /// This is a relaxed atomic operation (no implied memory barriers). 336 /// 337 /// ATTENTION: The naming convention differs from C, where the corresponding 338 /// function is called `clear_bit`. 339 /// 340 /// If CONFIG_RUST_BITMAP_HARDENED is not enabled and `index` is greater than 341 /// or equal to `self.len()`, does nothing. 342 /// 343 /// # Panics 344 /// 345 /// Panics if CONFIG_RUST_BITMAP_HARDENED is enabled and `index` is greater than 346 /// or equal to `self.len()`. 347 #[inline] 348 pub fn clear_bit_atomic(&self, index: usize) { 349 bitmap_assert_return!( 350 index < self.len(), 351 "Bit `index` must be < {}, was {}", 352 self.len(), 353 index 354 ); 355 // SAFETY: `index` is within bounds and the caller has ensured that 356 // there is no mix of non-atomic and atomic operations. 357 unsafe { bindings::clear_bit(index, self.as_ptr().cast_mut()) }; 358 } 359 360 /// Copy `src` into this [`Bitmap`] and set any remaining bits to zero. 361 /// 362 /// # Examples 363 /// 364 /// ``` 365 /// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; 366 /// use kernel::bitmap::BitmapVec; 367 /// 368 /// let mut long_bitmap = BitmapVec::new(256, GFP_KERNEL)?; 369 /// 370 /// assert_eq!(None, long_bitmap.last_bit()); 371 /// 372 /// let mut short_bitmap = BitmapVec::new(16, GFP_KERNEL)?; 373 /// 374 /// short_bitmap.set_bit(7); 375 /// long_bitmap.copy_and_extend(&short_bitmap); 376 /// assert_eq!(Some(7), long_bitmap.last_bit()); 377 /// 378 /// # Ok::<(), AllocError>(()) 379 /// ``` 380 #[inline] 381 pub fn copy_and_extend(&mut self, src: &Bitmap) { 382 let len = core::cmp::min(src.len(), self.len()); 383 // SAFETY: access to `self` and `src` is within bounds. 384 unsafe { 385 bindings::bitmap_copy_and_extend( 386 self.as_mut_ptr(), 387 src.as_ptr(), 388 len as u32, 389 self.len() as u32, 390 ) 391 }; 392 } 393 394 /// Finds last set bit. 395 /// 396 /// # Examples 397 /// 398 /// ``` 399 /// use kernel::alloc::{AllocError, flags::GFP_KERNEL}; 400 /// use kernel::bitmap::BitmapVec; 401 /// 402 /// let bitmap = BitmapVec::new(64, GFP_KERNEL)?; 403 /// 404 /// match bitmap.last_bit() { 405 /// Some(idx) => { 406 /// pr_info!("The last bit has index {idx}.\n"); 407 /// } 408 /// None => { 409 /// pr_info!("All bits in this bitmap are 0.\n"); 410 /// } 411 /// } 412 /// # Ok::<(), AllocError>(()) 413 /// ``` 414 #[inline] 415 pub fn last_bit(&self) -> Option<usize> { 416 // SAFETY: `_find_next_bit` access is within bounds due to invariant. 417 let index = unsafe { bindings::_find_last_bit(self.as_ptr(), self.len()) }; 418 if index >= self.len() { 419 None 420 } else { 421 Some(index) 422 } 423 } 424 425 /// Finds next set bit, starting from `start`. 426 /// 427 /// Returns `None` if `start` is greater or equal to `self.nbits`. 428 #[inline] 429 pub fn next_bit(&self, start: usize) -> Option<usize> { 430 bitmap_assert!( 431 start < self.len(), 432 "`start` must be < {} was {}", 433 self.len(), 434 start 435 ); 436 // SAFETY: `_find_next_bit` tolerates out-of-bounds arguments and returns a 437 // value larger than or equal to `self.len()` in that case. 438 let index = unsafe { bindings::_find_next_bit(self.as_ptr(), self.len(), start) }; 439 if index >= self.len() { 440 None 441 } else { 442 Some(index) 443 } 444 } 445 446 /// Finds next zero bit, starting from `start`. 447 /// Returns `None` if `start` is greater than or equal to `self.len()`. 448 #[inline] 449 pub fn next_zero_bit(&self, start: usize) -> Option<usize> { 450 bitmap_assert!( 451 start < self.len(), 452 "`start` must be < {} was {}", 453 self.len(), 454 start 455 ); 456 // SAFETY: `_find_next_zero_bit` tolerates out-of-bounds arguments and returns a 457 // value larger than or equal to `self.len()` in that case. 458 let index = unsafe { bindings::_find_next_zero_bit(self.as_ptr(), self.len(), start) }; 459 if index >= self.len() { 460 None 461 } else { 462 Some(index) 463 } 464 } 465 } 466 467 use macros::kunit_tests; 468 469 #[kunit_tests(rust_kernel_bitmap)] 470 mod tests { 471 use super::*; 472 use kernel::alloc::flags::GFP_KERNEL; 473 474 #[test] 475 fn bitmap_borrow() { 476 let fake_bitmap: [usize; 2] = [0, 0]; 477 // SAFETY: `fake_c_bitmap` is an array of expected length. 478 let b = unsafe { Bitmap::from_raw(fake_bitmap.as_ptr(), 2 * BITS_PER_LONG) }; 479 assert_eq!(2 * BITS_PER_LONG, b.len()); 480 assert_eq!(None, b.next_bit(0)); 481 } 482 483 #[test] 484 fn bitmap_copy() { 485 let fake_bitmap: usize = 0xFF; 486 // SAFETY: `fake_c_bitmap` can be used as one-element array of expected length. 487 let b = unsafe { Bitmap::from_raw(core::ptr::addr_of!(fake_bitmap), 8) }; 488 assert_eq!(8, b.len()); 489 assert_eq!(None, b.next_zero_bit(0)); 490 } 491 492 #[test] 493 fn bitmap_vec_new() -> Result<(), AllocError> { 494 let b = BitmapVec::new(0, GFP_KERNEL)?; 495 assert_eq!(0, b.len()); 496 497 let b = BitmapVec::new(3, GFP_KERNEL)?; 498 assert_eq!(3, b.len()); 499 500 let b = BitmapVec::new(1024, GFP_KERNEL)?; 501 assert_eq!(1024, b.len()); 502 503 // Requesting too large values results in [`AllocError`]. 504 let res = BitmapVec::new(1 << 31, GFP_KERNEL); 505 assert!(res.is_err()); 506 Ok(()) 507 } 508 509 #[test] 510 fn bitmap_set_clear_find() -> Result<(), AllocError> { 511 let mut b = BitmapVec::new(128, GFP_KERNEL)?; 512 513 // Zero-initialized 514 assert_eq!(None, b.next_bit(0)); 515 assert_eq!(Some(0), b.next_zero_bit(0)); 516 assert_eq!(None, b.last_bit()); 517 518 b.set_bit(17); 519 520 assert_eq!(Some(17), b.next_bit(0)); 521 assert_eq!(Some(17), b.next_bit(17)); 522 assert_eq!(None, b.next_bit(18)); 523 assert_eq!(Some(17), b.last_bit()); 524 525 b.set_bit(107); 526 527 assert_eq!(Some(17), b.next_bit(0)); 528 assert_eq!(Some(17), b.next_bit(17)); 529 assert_eq!(Some(107), b.next_bit(18)); 530 assert_eq!(Some(107), b.last_bit()); 531 532 b.clear_bit(17); 533 534 assert_eq!(Some(107), b.next_bit(0)); 535 assert_eq!(Some(107), b.last_bit()); 536 Ok(()) 537 } 538 539 #[test] 540 fn owned_bitmap_out_of_bounds() -> Result<(), AllocError> { 541 // TODO: Kunit #[test]s do not support `cfg` yet, 542 // so we add it here in the body. 543 #[cfg(not(CONFIG_RUST_BITMAP_HARDENED))] 544 { 545 let mut b = BitmapVec::new(128, GFP_KERNEL)?; 546 b.set_bit(2048); 547 b.set_bit_atomic(2048); 548 b.clear_bit(2048); 549 b.clear_bit_atomic(2048); 550 assert_eq!(None, b.next_bit(2048)); 551 assert_eq!(None, b.next_zero_bit(2048)); 552 assert_eq!(None, b.last_bit()); 553 } 554 Ok(()) 555 } 556 557 // TODO: uncomment once kunit supports [should_panic] and `cfg`. 558 // #[cfg(CONFIG_RUST_BITMAP_HARDENED)] 559 // #[test] 560 // #[should_panic] 561 // fn owned_bitmap_out_of_bounds() -> Result<(), AllocError> { 562 // let mut b = BitmapVec::new(128, GFP_KERNEL)?; 563 // 564 // b.set_bit(2048); 565 // } 566 567 #[test] 568 fn bitmap_copy_and_extend() -> Result<(), AllocError> { 569 let mut long_bitmap = BitmapVec::new(256, GFP_KERNEL)?; 570 571 long_bitmap.set_bit(3); 572 long_bitmap.set_bit(200); 573 574 let mut short_bitmap = BitmapVec::new(32, GFP_KERNEL)?; 575 576 short_bitmap.set_bit(17); 577 578 long_bitmap.copy_and_extend(&short_bitmap); 579 580 // Previous bits have been cleared. 581 assert_eq!(Some(17), long_bitmap.next_bit(0)); 582 assert_eq!(Some(17), long_bitmap.last_bit()); 583 Ok(()) 584 } 585 } 586