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