From: Igor Belousov A reference counted `Page` can be shared through `ARef`s, but its data can then only be accessed with byte-wise atomic operations, and there is no way to look up a page lock-free the way brd_lookup_page() does. Add a `Guarded` page kind for a reference counted page used as plain memory, such as a page holding the contents of a RAM disk: - `Page::alloc_guarded()` allocates a zeroed `Page`; - `Page::lock_data()` takes a bit spinlock in the page's `private` field and returns a guard that releases it. While held, the guard gives access to the data of the page as a slice, so a page that is shared through `ARef`s can be read and written with plain memory accesses, such as the bio segment copies. This gives a page a lock of its own at no memory cost; - `Page::try_get_raw()` takes a reference from a possibly stale pointer with `get_page_unless_zero()`, for lock-free lookups like brd_lookup_page(). This is sound because a `struct page` is never freed, even once its memory is. The caller must confirm that the page is still the one it looked up before it uses the reference. A `Page` only dereferences to `Page`, not to `Page`: the safe operations that access the data of a page otherwise, such as `with_page_as_sysmem_local()`, or that hand the page to someone who could, such as `vm_insert_page()`, cannot be applied to it. So the lock cannot be bypassed, and `lock_data()` is safe. Add Rust helpers for `get_page_unless_zero()`, `bit_spin_lock()` and `bit_spin_unlock()`. Signed-off-by: Igor Belousov Signed-off-by: Vitaly Wool Co-Authored-By: Claude Opus 5.5 --- rust/helpers/bit_spinlock.c | 13 ++ rust/helpers/helpers.c | 1 + rust/helpers/page.c | 5 + rust/kernel/page.rs | 235 ++++++++++++++++++++++++++++++++++++ 4 files changed, 254 insertions(+) create mode 100644 rust/helpers/bit_spinlock.c diff --git a/rust/helpers/bit_spinlock.c b/rust/helpers/bit_spinlock.c new file mode 100644 index 000000000000..5c59632bd171 --- /dev/null +++ b/rust/helpers/bit_spinlock.c @@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +__rust_helper void rust_helper_bit_spin_lock(int bitnum, unsigned long *addr) +{ + bit_spin_lock(bitnum, addr); +} + +__rust_helper void rust_helper_bit_spin_unlock(int bitnum, unsigned long *addr) +{ + bit_spin_unlock(bitnum, addr); +} diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index ab8d38b43117..0dc7a587f43c 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -44,6 +44,7 @@ #include "barrier.c" #include "binder.c" #include "bitmap.c" +#include "bit_spinlock.c" #include "bitops.c" #include "blk.c" #include "bug.c" diff --git a/rust/helpers/page.c b/rust/helpers/page.c index 313a3a3b30b7..071de61112af 100644 --- a/rust/helpers/page.c +++ b/rust/helpers/page.c @@ -47,3 +47,8 @@ __rust_helper int rust_helper_page_to_nid(const struct page *page) return page_to_nid(page); } #endif + +__rust_helper bool rust_helper_get_page_unless_zero(struct page *page) +{ + return get_page_unless_zero(page); +} diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs index 969dd6752841..50a965917190 100644 --- a/rust/kernel/page.rs +++ b/rust/kernel/page.rs @@ -16,6 +16,10 @@ code::*, Result, // }, + ffi::{ + c_int, + c_ulong, // + }, io::{ Io, IoCopyable, @@ -29,6 +33,7 @@ AlwaysRefCounted, // }, types::{ + NotThreadSafe, Opaque, Ownable, Owned, // @@ -178,6 +183,7 @@ impl PageKind for RefCounted {} /// - `Page` is a page for which nothing is known beyond its validity. /// - `Page` is a page whose data is initialized and not referenced by Rust references. /// - `Page`, or just `Page`, is a page that is managed by the page reference count. +/// - `Page` is a reference counted page whose data is only accessed under a lock. /// - `Page` is a uniquely owned page that references cannot be taken to. /// - `Page` is a uniquely owned page whose data follows standard Rust aliasing rules. /// @@ -709,6 +715,235 @@ pub fn with_page_as_sysmem_local( } } +/// A [`PageKind`] for a reference counted page whose data is only accessed under a lock. +/// +/// Like a [`Page`], a [`Page`] is managed by the page reference count and +/// shared through [`ARef`]s. Its data, however, can only be reached through [`Page::lock_data`], +/// which takes a bit spinlock in the `private` field of the page. Since that lock serializes all +/// accesses to the data, the data can be accessed through plain Rust references while the lock is +/// held, see [`PageDataGuard::with_slice`] and [`PageDataGuard::with_mut_slice`]. +/// +/// A [`Page`] only dereferences to a [`Page`]. Thus, the operations that access the +/// data of a page in other ways, or that hand the page to someone who could, such as mapping it to +/// user space, are not available for it. This is what makes [`Page::lock_data`] safe: the lock +/// cannot be bypassed. +/// +/// A [`Page`] suits a page used as plain memory that is shared between threads, such as +/// a page holding the contents of a RAM disk. +/// +/// # Invariants +/// +/// For a [`Page`]: +/// +/// - The page was allocated by [`Page::alloc_guarded`]. Its allocation is managed by the page +/// reference count, and the reference count is non-zero. +/// - The data of the page is initialized. +/// - The `private` field of the page is only accessed as the bit spinlock of +/// [`Page::lock_data`], and the data of the page is only accessed while holding that lock. +pub struct Guarded; + +impl private::Sealed for Guarded {} +impl PageKind for Guarded {} + +impl Deref for Page { + type Target = Page; + + #[inline] + fn deref(&self) -> &Self::Target { + // SAFETY: `Page` is transparent over `struct page` for all page kinds, so the pointer cast + // is valid. `Base` has no invariants in addition to the ones of `Page`, which hold for + // `self`. + unsafe { &*ptr::from_ref(self).cast() } + } +} + +/// The bit of `page->private` that [`Page::lock_data`] uses as a bit spinlock. +const GUARDED_LOCK_BIT: c_int = 0; + +impl Page { + /// Allocates a new guarded page. + /// + /// The page is always zeroed. That is, `__GFP_ZERO` is added to `flags`. + /// + /// # Examples + /// + /// ``` + /// use kernel::page::Page; + /// + /// let page = Page::alloc_guarded(GFP_KERNEL)?; + /// + /// let data = [0xdeu8, 0xad, 0xbe, 0xef]; + /// let mut buf = [0u8; 4]; + /// { + /// let mut guard = page.lock_data(); + /// guard.with_mut_slice(|s| s[..4].copy_from_slice(&data)); + /// guard.with_slice(|s| buf.copy_from_slice(&s[..4])); + /// } + /// assert_eq!(buf, data); + /// # Ok::<(), kernel::alloc::AllocError>(()) + /// ``` + #[inline] + pub fn alloc_guarded(flags: Flags) -> Result, AllocError> { + let flags = flags | __GFP_ZERO; + + // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it + // is always safe to call this method. + let page = unsafe { bindings::alloc_pages(flags.as_raw(), 0) }; + let page = NonNull::new(page).ok_or(AllocError)?; + // INVARIANT: The page was just allocated with `alloc_pages()`, so it is managed by the + // page reference count, and we hold a reference. We allocated with `__GFP_ZERO`, so the + // data of the page is initialized. The page allocator clears `private` when it hands out + // a page, so the lock starts out released, and the page is newly allocated, so nothing + // else accesses its `private` field or its data. + // SAFETY: We just successfully allocated a page, so we own the reference count returned + // by `alloc_pages`, and we transfer that reference to the new `ARef`. Since `Page` is + // transparent, we can cast the pointer directly. + Ok(unsafe { ARef::from_raw(page.cast()) }) + } + + /// Attempts to take a reference to a page from a raw, possibly stale pointer. + /// + /// Returns a new reference on success, or `None` if the reference count of the page had + /// already dropped to zero, i.e. if its last owner released it. + /// + /// This allows a lock-free lookup, such as `brd_lookup_page()`, to turn a page pointer it + /// loaded into a reference without knowing whether the page is still alive. A caller that + /// gets a reference checks that the pointer is still published where it was loaded from, since + /// the page may have been freed and reallocated in the meantime. + /// + /// # Safety + /// + /// - `ptr` must have been obtained from a [`Page`], for instance with + /// [`ARef::into_raw`]. Unlike most kernel objects, a `struct page` is never freed: only the + /// memory it describes is, once its reference count drops to zero. So it is safe to operate + /// on the reference count through a pointer that was once validly obtained, even if the page + /// has been released since. + /// - The page may have been freed and reallocated to another user since, who may manage it by + /// other means than the page reference count, and who may use its `private` field and its + /// data in any way. Thus, the caller must not use the returned reference other than to drop + /// it until it has confirmed that the page is still the [`Page`] it looked up. + #[inline] + pub unsafe fn try_get_raw(ptr: NonNull) -> Option> { + // SAFETY: By the safety requirements of this function, `ptr` points to a `struct page`. + if unsafe { bindings::get_page_unless_zero(ptr.as_ptr().cast()) } { + // INVARIANT: The reference count was non-zero, so the page is managed by it, and we + // just took a reference. The caller confirms that the page is still a + // `Page` before it uses it otherwise than by dropping it. + // SAFETY: We just took a reference to the page, which we transfer to the `ARef`. + Some(unsafe { ARef::from_raw(ptr) }) + } else { + None + } + } + + /// Returns a pointer to the `private` field of this page. + #[inline] + fn private_ptr(&self) -> *mut c_ulong { + // SAFETY: `self.as_ptr()` points to a valid `struct page` by the type invariant. Taking + // the address of a field neither reads nor writes it. + unsafe { &raw mut (*self.as_ptr()).__bindgen_anon_1.__bindgen_anon_1.private } + } + + /// Locks the data of this page. + /// + /// Spins until the bit spinlock in the `private` field of the page is released, then takes + /// it. The lock is released when the returned guard is dropped. As with any spinlock, + /// preemption is disabled while it is held. Bit spinlocks are not tracked by lockdep. + /// + /// While the lock is held, the guard gives access to the data of the page as a slice, see + /// [`PageDataGuard::with_slice`] and [`PageDataGuard::with_mut_slice`]. + #[inline] + pub fn lock_data(&self) -> PageDataGuard<'_> { + // SAFETY: `private_ptr()` returns a valid pointer, and by the type invariant, the field is + // only accessed by this lock. + unsafe { bindings::bit_spin_lock(GUARDED_LOCK_BIT, self.private_ptr()) }; + // INVARIANT: The lock was just acquired. + PageDataGuard { + page: self, + _not_send: NotThreadSafe, + } + } +} + +/// The lock on the data of a [`Page`]. +/// +/// Created by [`Page::lock_data`]. The lock is released when the guard is dropped. While it is +/// held, the guard gives access to the data of the page as a slice. +/// +/// # Invariants +/// +/// The guard holds the lock of [`Page::lock_data`] on `page`. +#[must_use = "the lock is released immediately when the guard is unused"] +pub struct PageDataGuard<'a> { + page: &'a Page, + _not_send: NotThreadSafe, +} + +impl PageDataGuard<'_> { + /// Runs `f` with the data of the locked page as a slice of [`PAGE_SIZE`] bytes. + #[inline] + pub fn with_slice(&self, f: impl FnOnce(&[u8]) -> T) -> T { + self.page.with_page_mapped(|ptr| { + // SAFETY: + // - `with_page_mapped` maps the page at `ptr` for `PAGE_SIZE` bytes for the duration + // of this closure, and the slice does not escape it. + // - By the invariant of `Guarded`, the data of the page is initialized. + // - By the invariant of `Guarded` and the type invariant, nobody else accesses the + // data of the page while we hold the lock, and it is only written through + // `with_mut_slice`, which takes `&mut self` and thus cannot run while this shared + // borrow of `self` exists. + f(unsafe { core::slice::from_raw_parts(ptr, PAGE_SIZE) }) + }) + } + + /// Runs `f` with the data of the locked page as a mutable slice of [`PAGE_SIZE`] bytes. + #[inline] + pub fn with_mut_slice(&mut self, f: impl FnOnce(&mut [u8]) -> T) -> T { + self.page.with_page_mapped(|ptr| { + // SAFETY: + // - `with_page_mapped` maps the page at `ptr` for `PAGE_SIZE` bytes for the duration + // of this closure, and the slice does not escape it. + // - By the invariant of `Guarded`, the data of the page is initialized, and safe code + // can only write initialized bytes through the slice. + // - By the invariant of `Guarded` and the type invariant, nobody else accesses the + // data of the page while we hold the lock, and `&mut self` makes this the only + // access through the guard. + f(unsafe { core::slice::from_raw_parts_mut(ptr, PAGE_SIZE) }) + }) + } +} + +impl Drop for PageDataGuard<'_> { + #[inline] + fn drop(&mut self) { + // SAFETY: By the type invariant, we hold the lock. + unsafe { bindings::bit_spin_unlock(GUARDED_LOCK_BIT, self.page.private_ptr()) }; + } +} + +// SAFETY: By the type invariant, a `Page` is managed by the page reference count. +// Incrementing it via `get_page()` keeps the page alive at least until a matching `put_page()`, +// which frees the page when the count reaches zero. +unsafe impl aref::RefCounted for Page { + #[inline] + fn inc_ref(&self) { + // SAFETY: By the type invariant, `self.as_ptr()` points to a valid `struct page` with a + // non-zero reference count. + unsafe { bindings::get_page(self.as_ptr()) }; + } + + #[inline] + unsafe fn dec_ref(obj: NonNull) { + // SAFETY: By the function safety requirements, the caller relinquishes a reference count + // on the page. Since `Page` is transparent, we can cast the pointer directly. + unsafe { bindings::put_page(obj.cast().as_ptr()) }; + } +} + +// SAFETY: A `&Page` proves that the reference count is non-zero, so it is okay to obtain +// an `ARef>` from it. +unsafe impl AlwaysRefCounted for Page {} + // SAFETY: By the type invariant, a `Page` is managed by the page reference count. // Incrementing it via `get_page()` keeps the page alive at least until a matching `put_page()`, // which frees the page when the count reaches zero. -- 2.39.5 Add a RAM backed block driver written in Rust, based on rnull and working like brd: pages are allocated on first write, unwritten areas read as zeroes and discards free the pages they fully cover. Devices are created through configfs, with `power`, `blocksize` and `size` (MiB) attributes: mkdir /sys/kernel/config/rbrd/rram0 echo 1 > /sys/kernel/config/rbrd/rram0/power # adds /dev/rram0 Pages are kept in a flat array of atomic pointers allocated at power on. Lookups take a speculative reference with `Page::try_get_raw()` and re-check the slot, like brd_lookup_page(); inserts use a compare-and-exchange and discards an exchange with null, so the I/O path takes no lock. Pages are `Page`s: copies to and from each page are serialized by the bit spinlock in its `page->private`, as opposed to the existing RAM block device driver which allows simultaneous reads and writes to pages. Thus, this driver always keeps data integrity. Data is copied with the bio `Segment` methods, to and from the slice of page data the lock guard provides; holes are read from a zeroed page. Requests are served from queue_rq(). The pages a write needs are allocated with GFP_NOWAIT before the request is started, so that an allocation failure can be returned as BLK_STS_RESOURCE and the block layer retries the request later. There is one hardware queue per CPU, which also avoids mq-deadline, and a queue depth of 32. Signed-off-by: Vitaly Wool --- MAINTAINERS | 1 + drivers/block/Kconfig | 1 + drivers/block/Makefile | 1 + drivers/block/rbrd/Kconfig | 17 ++ drivers/block/rbrd/Makefile | 2 + drivers/block/rbrd/configfs.rs | 192 +++++++++++++ drivers/block/rbrd/rbrd.rs | 473 +++++++++++++++++++++++++++++++++ 7 files changed, 687 insertions(+) create mode 100644 drivers/block/rbrd/Kconfig create mode 100644 drivers/block/rbrd/Makefile create mode 100644 drivers/block/rbrd/configfs.rs create mode 100644 drivers/block/rbrd/rbrd.rs diff --git a/MAINTAINERS b/MAINTAINERS index 845503be1f28..0893247db93b 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -4886,6 +4886,7 @@ W: https://rust-for-linux.com B: https://github.com/Rust-for-Linux/linux/issues C: https://rust-for-linux.zulipchat.com/#narrow/stream/Block T: git https://github.com/Rust-for-Linux/linux.git rust-block-next +F: drivers/block/rbrd/ F: drivers/block/rnull/ F: rust/kernel/block.rs F: rust/kernel/block/ diff --git a/drivers/block/Kconfig b/drivers/block/Kconfig index 858320b6ebb7..34face102851 100644 --- a/drivers/block/Kconfig +++ b/drivers/block/Kconfig @@ -18,6 +18,7 @@ if BLK_DEV source "drivers/block/null_blk/Kconfig" source "drivers/block/rnull/Kconfig" +source "drivers/block/rbrd/Kconfig" config BLK_DEV_FD tristate "Normal floppy disk support" diff --git a/drivers/block/Makefile b/drivers/block/Makefile index 2d8096eb8cdf..54e3e06fbce1 100644 --- a/drivers/block/Makefile +++ b/drivers/block/Makefile @@ -36,6 +36,7 @@ obj-$(CONFIG_BLK_DEV_RNBD) += rnbd/ obj-$(CONFIG_BLK_DEV_NULL_BLK) += null_blk/ obj-$(CONFIG_BLK_DEV_RUST_NULL) += rnull/ +obj-$(CONFIG_BLK_DEV_RUST_RAM) += rbrd/ obj-$(CONFIG_BLK_DEV_UBLK) += ublk_drv.o obj-$(CONFIG_BLK_DEV_ZONED_LOOP) += zloop.o diff --git a/drivers/block/rbrd/Kconfig b/drivers/block/rbrd/Kconfig new file mode 100644 index 000000000000..94b836d3ff35 --- /dev/null +++ b/drivers/block/rbrd/Kconfig @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# Rust RAM backed block device driver configuration + +config BLK_DEV_RUST_RAM + tristate "Rust RAM block device driver (Experimental)" + depends on RUST && CONFIGFS_FS + help + This is a RAM backed block device driver written in Rust, based + on the Rust null block driver. Like the C brd driver, it stores + device contents in pages allocated on demand. Devices are created + and configured through configfs under /sys/kernel/config/rbrd/. + + Device contents are lost when a device is powered off or the + module is unloaded. + + If unsure, say N. diff --git a/drivers/block/rbrd/Makefile b/drivers/block/rbrd/Makefile new file mode 100644 index 000000000000..b5e0c10b4bea --- /dev/null +++ b/drivers/block/rbrd/Makefile @@ -0,0 +1,2 @@ +obj-$(CONFIG_BLK_DEV_RUST_RAM) += rbrd_mod.o +rbrd_mod-y := rbrd.o diff --git a/drivers/block/rbrd/configfs.rs b/drivers/block/rbrd/configfs.rs new file mode 100644 index 000000000000..48e17b7378e2 --- /dev/null +++ b/drivers/block/rbrd/configfs.rs @@ -0,0 +1,192 @@ +// SPDX-License-Identifier: GPL-2.0 + +use super::RamDisk; +use kernel::{ + block::mq::gen_disk::{ + GenDisk, + GenDiskBuilder, // + }, + configfs::{ + self, + AttributeOperations, // + }, + configfs_attrs, + fmt::Write as _, + new_mutex, + page::PAGE_SIZE, + prelude::*, + str::{ + kstrtobool_bytes, + CString, // + }, + sync::{ + Arc, + Mutex, // + }, // +}; + +pub(crate) fn subsystem() -> impl PinInit, Error> { + let item_type = configfs_attrs! { + container: configfs::Subsystem, + data: Config, + child: DeviceConfig, + attributes: [ + features: 0, + ], + }; + + kernel::configfs::Subsystem::new(c"rbrd", item_type, try_pin_init!(Config {})) +} + +#[pin_data] +pub(crate) struct Config {} + +#[vtable] +impl AttributeOperations<0> for Config { + type Data = Config; + + fn show(_this: &Config, page: &mut [u8; PAGE_SIZE]) -> Result { + let mut writer = kernel::str::Formatter::new(page); + writer.write_str("blocksize,size,power\n")?; + Ok(writer.bytes_written()) + } +} + +#[vtable] +impl configfs::GroupOperations for Config { + type Child = DeviceConfig; + + fn make_group( + &self, + name: &CStr, + ) -> Result, Error>> { + let item_type = configfs_attrs! { + container: configfs::Group, + data: DeviceConfig, + attributes: [ + power: 0, + blocksize: 1, + size: 2, + ], + }; + + Ok(configfs::Group::new( + name.try_into()?, + item_type, + try_pin_init!(DeviceConfig { + data <- new_mutex!(DeviceConfigInner { + powered: false, + block_size: 512, + disk: None, + capacity_mib: 64, + name: name.try_into()?, + }), + }), + core::iter::empty(), + )) + } +} + +#[pin_data] +pub(crate) struct DeviceConfig { + #[pin] + data: Mutex, +} + +#[pin_data] +struct DeviceConfigInner { + powered: bool, + name: CString, + block_size: u32, + capacity_mib: u64, + disk: Option>>, +} + +#[vtable] +impl configfs::AttributeOperations<0> for DeviceConfig { + type Data = DeviceConfig; + + fn show(this: &DeviceConfig, page: &mut [u8; PAGE_SIZE]) -> Result { + let mut writer = kernel::str::Formatter::new(page); + + if this.data.lock().powered { + writer.write_str("1\n")?; + } else { + writer.write_str("0\n")?; + } + + Ok(writer.bytes_written()) + } + + fn store(this: &DeviceConfig, page: &[u8]) -> Result { + let power_op = kstrtobool_bytes(page)?; + let mut guard = this.data.lock(); + + if !guard.powered && power_op { + guard.disk = Some(RamDisk::new( + &guard.name, + guard.block_size, + guard.capacity_mib, + )?); + guard.powered = true; + } else if guard.powered && !power_op { + // Removes the disk and frees all of its contents. + drop(guard.disk.take()); + guard.powered = false; + } + + Ok(()) + } +} + +#[vtable] +impl configfs::AttributeOperations<1> for DeviceConfig { + type Data = DeviceConfig; + + fn show(this: &DeviceConfig, page: &mut [u8; PAGE_SIZE]) -> Result { + let mut writer = kernel::str::Formatter::new(page); + writer.write_fmt(fmt!("{}\n", this.data.lock().block_size))?; + Ok(writer.bytes_written()) + } + + fn store(this: &DeviceConfig, page: &[u8]) -> Result { + let mut guard = this.data.lock(); + if guard.powered { + return Err(EBUSY); + } + + let text = core::str::from_utf8(page)?.trim(); + let value = text.parse::().map_err(|_| EINVAL)?; + + GenDiskBuilder::::validate_block_size(value)?; + guard.block_size = value; + Ok(()) + } +} + +#[vtable] +impl configfs::AttributeOperations<2> for DeviceConfig { + type Data = DeviceConfig; + + fn show(this: &DeviceConfig, page: &mut [u8; PAGE_SIZE]) -> Result { + let mut writer = kernel::str::Formatter::new(page); + writer.write_fmt(fmt!("{}\n", this.data.lock().capacity_mib))?; + Ok(writer.bytes_written()) + } + + fn store(this: &DeviceConfig, page: &[u8]) -> Result { + let mut guard = this.data.lock(); + if guard.powered { + return Err(EBUSY); + } + + let text = core::str::from_utf8(page)?.trim(); + let value = text.parse::().map_err(|_| EINVAL)?; + if value == 0 { + return Err(EINVAL); + } + + guard.capacity_mib = value; + Ok(()) + } +} diff --git a/drivers/block/rbrd/rbrd.rs b/drivers/block/rbrd/rbrd.rs new file mode 100644 index 000000000000..c2095105c6e2 --- /dev/null +++ b/drivers/block/rbrd/rbrd.rs @@ -0,0 +1,473 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! A RAM backed block device driver written in Rust. +//! +//! The driver is based on the Rust null block driver and works like the C +//! `brd` driver: every device stores its contents in pages that are allocated +//! on the first write to them. Unlike `brd`, the pages are tracked in a flat +//! array with one slot per page of the device, allocated when the device is +//! created, instead of in an XArray. Reads of never written areas return +//! zeroes. Discards free whole pages. +//! +//! Devices are created through configfs: +//! +//! ```text +//! mkdir /sys/kernel/config/rbrd/rram0 +//! echo 512 > /sys/kernel/config/rbrd/rram0/size # MiB +//! echo 1 > /sys/kernel/config/rbrd/rram0/power # creates /dev/rram0 +//! ``` +//! +//! The contents of a device are lost when it is powered off. + +mod configfs; + +use kernel::{ + bindings, + block::{ + self, + bio::Segment, + error::{ + code::BLK_STS_NOTSUPP, + BlkError, + BlkResult, // + }, + mq::{ + self, + gen_disk::{ + self, + GenDisk, // + }, + Command, + IdleRequest, + Operations, + TagSet, // + }, // + }, + numa::NumaNode, + page::{ + Exclusive, + Guarded, + Page, + PAGE_SHIFT, + PAGE_SIZE, // + }, + prelude::*, + sync::{ + aref::ARef, + atomic::{ + Acquire, + Atomic, + Relaxed, + Release, // + }, + Arc, // + }, + types::Owned, // +}; + +use core::ptr::{ + self, + NonNull, // +}; + +module! { + type: RamDiskModule, + name: "rbrd", + authors: ["Vitaly Wool"], + description: "Rust RAM backed block device driver", + license: "GPL v2", +} + +#[pin_data] +struct RamDiskModule { + #[pin] + configfs_subsystem: kernel::configfs::Subsystem, +} + +impl kernel::InPlaceModule for RamDiskModule { + fn init(_module: &'static ThisModule) -> impl PinInit { + pr_info!("Rust RAM block driver loaded\n"); + + try_pin_init!(Self { + configfs_subsystem <- configfs::subsystem(), + }) + } +} + +/// Maximum size of a single discard request. +/// +/// Discards are processed in atomic context, page by page. Bound the amount of +/// work done per request; larger discards are split by the block layer. +const MAX_DISCARD_SECTORS: u32 = (128 << 20) >> block::SECTOR_SHIFT; + +/// GFP flags for allocations in the I/O path, which must not sleep. +fn io_gfp() -> kernel::alloc::Flags { + GFP_NOWAIT | __GFP_NOWARN +} + +struct RamDisk; + +impl RamDisk { + fn new(name: &CStr, block_size: u32, capacity_mib: u64) -> Result>> { + if capacity_mib == 0 { + return Err(EINVAL); + } + + let capacity_sectors = capacity_mib + .checked_mul(1 << (20 - block::SECTOR_SHIFT)) + .ok_or(EINVAL)?; + let nr_pages = usize::try_from(capacity_mib)? + .checked_mul((1 << 20) / PAGE_SIZE) + .ok_or(EINVAL)?; + + // One hardware queue per CPU. Besides avoiding contention on a single + // hardware context, this keeps blk-mq from attaching the mq-deadline + // scheduler, which it does by default for single queue devices. + // + // Requests are completed within `queue_rq()`, which releases their tag + // right away, so only a few tags per queue are ever in use at once. A + // small depth keeps the requests preallocated for every queue cheap. + let tagset = Arc::pin_init( + TagSet::new( + kernel::cpu::nr_cpu_ids(), + (), + 32, + 1, + NumaNode::NO_NODE, + mq::tag_set::Flags::default(), + // Requests complete in `queue_rq()` and never time out; keep + // the block layer default. + 0, + ), + GFP_KERNEL, + )?; + let storage = KBox::try_pin_init(Storage::new(nr_pages), GFP_KERNEL)?; + + gen_disk::GenDiskBuilder::new() + .capacity_sectors(capacity_sectors) + .logical_block_size(block_size)? + .physical_block_size(block_size)? + .max_hw_discard_sectors(MAX_DISCARD_SECTORS) + .build(fmt!("{}", name.to_str()?), tagset, storage) + } +} + +/// A flat array of page slots, one per page of the device. +/// +/// Each slot is either null or holds a pointer obtained from +/// [`ARef::into_raw`], i.e. owns one reference to that page. +struct PageArray(KVVec>>); + +impl PageArray { + fn new(nr_pages: usize) -> Result { + let mut slots = KVVec::with_capacity(nr_pages, GFP_KERNEL)?; + for _ in 0..nr_pages { + // Cannot fail: the capacity was reserved above. + slots.push(Atomic::new(ptr::null_mut()), GFP_KERNEL)?; + } + Ok(Self(slots)) + } + + fn slot(&self, index: usize) -> Result<&Atomic<*mut Page>> { + self.0.get(index).ok_or(EIO) + } +} + +impl Drop for PageArray { + fn drop(&mut self) { + for slot in self.0.iter() { + if let Some(ptr) = NonNull::new(slot.xchg(ptr::null_mut(), Relaxed)) { + // SAFETY: Non-null slots hold pointers from `ARef::into_raw` + // and own the reference they stand for, which we take back. + drop(unsafe { ARef::from_raw(ptr) }); + } + } + } +} + +/// The backing store of a RAM disk. +/// +/// Slot `n` of `pages` holds the page for bytes `n * PAGE_SIZE .. (n + 1) * +/// PAGE_SIZE` of the device, or null if it was never written or since +/// discarded. +/// +/// The slot array is allocated up front and lives as long as the device, so, +/// unlike the nodes of an XArray, it never needs RCU protection, and no lock is +/// taken to look up, insert or remove a page: [`Self::lookup_page`] is an +/// atomic load followed by a speculative reference (see [`Page::try_get_raw`]), +/// [`Self::try_insert_page`] a compare-and-exchange on an empty slot, and +/// [`Self::discard`] an exchange with null. The price is 8 bytes of slot per +/// page of capacity, whether or not it is ever written. +/// +/// Copies to and from a backing page are serialized by a bit spinlock in its +/// `page->private` (see [`Page::lock_data`]), which also gives access to the +/// data of the page as a slice. Unlike the C `brd` driver, overlapping I/O thus +/// never observes a partially written block. The lock is held only for the +/// duration of a single copy, never while looking up, allocating or removing a +/// page. +#[pin_data] +struct Storage { + pages: PageArray, + /// A zeroed page, the source for reads of pages that are not allocated. + zero_page: Owned>, +} + +impl Storage { + fn new(nr_pages: usize) -> impl PinInit { + try_pin_init!(Self { + pages: PageArray::new(nr_pages)?, + zero_page: Page::alloc_exclusive(GFP_KERNEL)?, + }) + } + + /// Looks up the page in `slot`, without taking any lock. + /// + /// Takes a reference on the page in the slot with an operation that fails + /// if the page's reference count has already reached zero, i.e. if a + /// concurrent [`Self::discard`] already released it, and then re-reads the + /// slot to confirm it still holds the same page, retrying otherwise: + /// without that check, a page that was concurrently discarded and whose + /// memory was reused for something else in the meantime could be mistaken + /// for one that is still ours. See [`Page::try_get_raw`] for more on why + /// this is safe. + fn lookup_page(slot: &Atomic<*mut Page>) -> Option>> { + loop { + let ptr = NonNull::new(slot.load(Acquire))?; + + // SAFETY: Every non-null pointer stored in a slot came from + // `ARef::into_raw` on a `Page`, whether or not the page is + // (still) owned by this slot. The reference is only dropped, not + // used, unless the re-check below confirms that the slot still + // holds it, and thus that it is still our page. + let page = unsafe { Page::try_get_raw(ptr) }?; + + // `try_get_raw()` is fully ordered when it succeeds, so this load + // cannot be reordered before it. It is `Acquire` because the slot + // may have been emptied and refilled with the same page in the + // meantime: the page contents must then be those published by the + // `Release` compare-and-exchange in `try_insert_page()` that + // refilled it. + if slot.load(Acquire) == ptr.as_ptr() { + return Some(page); + } + + // The slot was concurrently emptied, or now holds a different + // page; `page` is not (or no longer) ours to use. Drop our + // reference and retry. + drop(page); + } + } + + /// Allocates a page and installs it in `slot` if the slot is still empty. + /// + /// Returns `None` if another writer installed a page there first, in which + /// case the caller looks it up again. + fn try_insert_page(slot: &Atomic<*mut Page>) -> Result>>> { + // The page is always zeroed. + let page = Page::alloc_guarded(io_gfp() | __GFP_HIGHMEM)?; + // Take our own reference before handing the other one to the slot. + let ours = page.clone(); + let ptr = ARef::into_raw(page); + + // `Release` publishes the zeroed page contents, including the cleared + // lock bit in `page->private`, along with the pointer, pairing with + // the `Acquire` loads in `lookup_page()`. A failed exchange needs no + // ordering: its result is not used, and the caller looks the slot up + // again with an `Acquire` load. + if slot.cmpxchg(ptr::null_mut(), ptr.as_ptr(), Release).is_ok() { + return Ok(Some(ours)); + } + + drop(ours); + // SAFETY: `ptr` came from `into_raw` above and was not stored, so we + // still own the reference it stands for. + drop(unsafe { ARef::from_raw(ptr) }); + Ok(None) + } + + /// Returns the page in `slot`, allocating it if needed. + fn get_or_insert_page(slot: &Atomic<*mut Page>) -> Result>> { + loop { + if let Some(page) = Self::lookup_page(slot) { + return Ok(page); + } + if let Some(page) = Self::try_insert_page(slot)? { + return Ok(page); + } + } + } + + /// Returns the range of page indices covered by `bytes` bytes at `sector`. + fn page_range(&self, sector: u64, bytes: u32) -> Result> { + let start = sector << block::SECTOR_SHIFT; + let end = start + u64::from(bytes); + let range = + usize::try_from(start >> PAGE_SHIFT)?..usize::try_from(end.div_ceil(PAGE_SIZE as u64))?; + + // The block layer never issues I/O beyond the capacity of the device, + // which the array covers in full. + if range.end > self.pages.0.len() { + return Err(EIO); + } + Ok(range) + } + + /// Allocates the backing pages a write of `bytes` bytes at `sector` needs. + /// + /// This is done before the request is started, so that an allocation + /// failure can be reported to the block layer as `BLK_STS_RESOURCE`, which + /// makes it retry the request later. + fn populate(&self, sector: u64, bytes: u32) -> Result { + for index in self.page_range(sector, bytes)? { + let slot = self.pages.slot(index)?; + if slot.load(Relaxed).is_null() { + Self::get_or_insert_page(slot)?; + } + } + Ok(()) + } + + /// Transfer all data of `rq` between the request buffers and the backing + /// store. + fn transfer(&self, rq: &mut Owned>, write: bool) -> Result { + let mut pos = rq.sector() << block::SECTOR_SHIFT; + self.page_range(rq.sector(), rq.bytes())?; + + for bio in rq.bio_iter_mut() { + for mut segment in bio.segment_iter() { + // Each copy stops at the next page boundary of both the + // segment and the backing store. + while !segment.at_end() { + let slot = self.pages.slot(usize::try_from(pos >> PAGE_SHIFT)?)?; + let page_off = (pos as usize) & (PAGE_SIZE - 1); + + let len = if write { + Self::write_chunk(&mut segment, slot, page_off)? + } else { + self.read_chunk(&mut segment, slot, page_off) + }; + + pos += len as u64; + } + } + } + + Ok(()) + } + + fn read_chunk( + &self, + segment: &mut Segment<'_>, + slot: &Atomic<*mut Page>, + off: usize, + ) -> usize { + match Self::lookup_page(slot) { + Some(page) => page + .lock_data() + .with_slice(|data| segment.write(&data[off..])), + // Never written; reads as zeroes. + None => segment.write(&self.zero_page.as_slice()[off..]), + } + } + + fn write_chunk( + segment: &mut Segment<'_>, + slot: &Atomic<*mut Page>, + off: usize, + ) -> Result { + // The page was allocated by `populate()`, unless a concurrent discard + // freed it again since. + let page = Self::get_or_insert_page(slot)?; + let mut guard = page.lock_data(); + Ok(guard.with_mut_slice(|data| segment.read(&mut data[off..]))) + } + + /// Free all backing pages that are entirely covered by the range. + fn discard(&self, sector: u64, bytes: u32) { + let start = sector << block::SECTOR_SHIFT; + let end = start + u64::from(bytes); + let first = start.div_ceil(PAGE_SIZE as u64); + let last = end >> PAGE_SHIFT; + + for index in first..last { + let Some(slot) = usize::try_from(index) + .ok() + .and_then(|index| self.pages.0.get(index)) + else { + break; + }; + + // No ordering is needed: discard does not access the page data, + // and freeing the page is ordered by its reference count. + if let Some(ptr) = NonNull::new(slot.xchg(ptr::null_mut(), Relaxed)) { + // SAFETY: Non-null slots hold pointers from `ARef::into_raw` + // and own the reference they stand for, which we just took + // back by emptying the slot. A concurrent `lookup_page()` that + // already took its own reference keeps the page alive until + // that reference is dropped too. + drop(unsafe { ARef::from_raw(ptr) }); + } + } + } +} + +#[vtable] +impl Operations for RamDisk { + type RequestData = (); + type QueueData = Pin>; + type HwData = (); + type TagSetData = (); + + fn new_request_data() -> impl PinInit { + Ok(()) + } + + fn queue_rq( + _hw_data: (), + storage: Pin<&Storage>, + rq: Owned>, + _is_last: bool, + ) -> BlkResult { + // Errors returned before the request is started end it with that + // status, or, for `BLK_STS_RESOURCE`, make the block layer retry it. + match rq.command() { + Command::Read | Command::Discard | Command::Flush => {} + Command::Write => { + if storage.populate(rq.sector(), rq.bytes()).is_err() { + return Err(BlkError::from_blk_status(bindings::BLK_STS_RESOURCE)); + } + } + _ => return Err(BLK_STS_NOTSUPP), + } + + let mut rq = rq.start(); + + let status = match rq.command() { + Command::Read => storage.transfer(&mut rq, false), + Command::Write => storage.transfer(&mut rq, true), + Command::Discard => { + storage.discard(rq.sector(), rq.bytes()); + Ok(()) + } + // There is no volatile cache; data is in RAM once written. + _ => Ok(()), + }; + + match status { + Ok(()) => rq.end_ok(), + Err(_) => rq.end(bindings::BLK_STS_IOERR), + } + + Ok(()) + } + + fn commit_rqs(_hw_data: (), _storage: Pin<&Storage>) {} + + fn init_hctx(_tagset_data: (), _hctx_idx: u32) -> Result { + Ok(()) + } + + fn complete(_rq: ARef>) { + // All requests are completed synchronously in `queue_rq`. + } +} -- 2.39.5