// SPDX-License-Identifier: GPL-2.012//! Generic disk abstraction.3//!4//! C header: [`include/linux/blkdev.h`](srctree/include/linux/blkdev.h)5//! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h)67use crate::{8bindings,9block::mq::{Operations, TagSet},10error::{self, from_err_ptr, Result},11fmt::{self, Write},12prelude::*,13static_lock_class,14str::NullTerminatedFormatter,15sync::Arc,16types::{ForeignOwnable, ScopeGuard},17};1819/// A builder for [`GenDisk`].20///21/// Use this struct to configure and add new [`GenDisk`] to the VFS.22pub struct GenDiskBuilder {23rotational: bool,24logical_block_size: u32,25physical_block_size: u32,26capacity_sectors: u64,27}2829impl Default for GenDiskBuilder {30fn default() -> Self {31Self {32rotational: false,33logical_block_size: bindings::PAGE_SIZE as u32,34physical_block_size: bindings::PAGE_SIZE as u32,35capacity_sectors: 0,36}37}38}3940impl GenDiskBuilder {41/// Create a new instance.42pub fn new() -> Self {43Self::default()44}4546/// Set the rotational media attribute for the device to be built.47pub fn rotational(mut self, rotational: bool) -> Self {48self.rotational = rotational;49self50}5152/// Validate block size by verifying that it is between 512 and `PAGE_SIZE`,53/// and that it is a power of two.54pub fn validate_block_size(size: u32) -> Result {55if !(512..=bindings::PAGE_SIZE as u32).contains(&size) || !size.is_power_of_two() {56Err(error::code::EINVAL)57} else {58Ok(())59}60}6162/// Set the logical block size of the device to be built.63///64/// This method will check that block size is a power of two and between 51265/// and 4096. If not, an error is returned and the block size is not set.66///67/// This is the smallest unit the storage device can address. It is68/// typically 4096 bytes.69pub fn logical_block_size(mut self, block_size: u32) -> Result<Self> {70Self::validate_block_size(block_size)?;71self.logical_block_size = block_size;72Ok(self)73}7475/// Set the physical block size of the device to be built.76///77/// This method will check that block size is a power of two and between 51278/// and 4096. If not, an error is returned and the block size is not set.79///80/// This is the smallest unit a physical storage device can write81/// atomically. It is usually the same as the logical block size but may be82/// bigger. One example is SATA drives with 4096 byte physical block size83/// that expose a 512 byte logical block size to the operating system.84pub fn physical_block_size(mut self, block_size: u32) -> Result<Self> {85Self::validate_block_size(block_size)?;86self.physical_block_size = block_size;87Ok(self)88}8990/// Set the capacity of the device to be built, in sectors (512 bytes).91pub fn capacity_sectors(mut self, capacity: u64) -> Self {92self.capacity_sectors = capacity;93self94}9596/// Build a new `GenDisk` and add it to the VFS.97pub fn build<T: Operations>(98self,99name: fmt::Arguments<'_>,100tagset: Arc<TagSet<T>>,101queue_data: T::QueueData,102) -> Result<GenDisk<T>> {103let data = queue_data.into_foreign();104let recover_data = ScopeGuard::new(|| {105// SAFETY: T::QueueData was created by the call to `into_foreign()` above106drop(unsafe { T::QueueData::from_foreign(data) });107});108109// SAFETY: `bindings::queue_limits` contain only fields that are valid when zeroed.110let mut lim: bindings::queue_limits = unsafe { core::mem::zeroed() };111112lim.logical_block_size = self.logical_block_size;113lim.physical_block_size = self.physical_block_size;114if self.rotational {115lim.features = bindings::BLK_FEAT_ROTATIONAL;116}117118// SAFETY: `tagset.raw_tag_set()` points to a valid and initialized tag set119let gendisk = from_err_ptr(unsafe {120bindings::__blk_mq_alloc_disk(121tagset.raw_tag_set(),122&mut lim,123data,124static_lock_class!().as_ptr(),125)126})?;127128const TABLE: bindings::block_device_operations = bindings::block_device_operations {129submit_bio: None,130open: None,131release: None,132ioctl: None,133compat_ioctl: None,134check_events: None,135unlock_native_capacity: None,136getgeo: None,137set_read_only: None,138swap_slot_free_notify: None,139report_zones: None,140devnode: None,141alternative_gpt_sector: None,142get_unique_id: None,143// TODO: Set to THIS_MODULE. Waiting for const_refs_to_static feature to144// be merged (unstable in rustc 1.78 which is staged for linux 6.10)145// <https://github.com/rust-lang/rust/issues/119618>146owner: core::ptr::null_mut(),147pr_ops: core::ptr::null_mut(),148free_disk: None,149poll_bio: None,150};151152// SAFETY: `gendisk` is a valid pointer as we initialized it above153unsafe { (*gendisk).fops = &TABLE };154155let mut writer = NullTerminatedFormatter::new(156// SAFETY: `gendisk` points to a valid and initialized instance. We157// have exclusive access, since the disk is not added to the VFS158// yet.159unsafe { &mut (*gendisk).disk_name },160)161.ok_or(EINVAL)?;162writer.write_fmt(name)?;163164// SAFETY: `gendisk` points to a valid and initialized instance of165// `struct gendisk`. `set_capacity` takes a lock to synchronize this166// operation, so we will not race.167unsafe { bindings::set_capacity(gendisk, self.capacity_sectors) };168169crate::error::to_result(170// SAFETY: `gendisk` points to a valid and initialized instance of171// `struct gendisk`.172unsafe {173bindings::device_add_disk(core::ptr::null_mut(), gendisk, core::ptr::null_mut())174},175)?;176177recover_data.dismiss();178179// INVARIANT: `gendisk` was initialized above.180// INVARIANT: `gendisk` was added to the VFS via `device_add_disk` above.181// INVARIANT: `gendisk.queue.queue_data` is set to `data` in the call to182// `__blk_mq_alloc_disk` above.183Ok(GenDisk {184_tagset: tagset,185gendisk,186})187}188}189190/// A generic block device.191///192/// # Invariants193///194/// - `gendisk` must always point to an initialized and valid `struct gendisk`.195/// - `gendisk` was added to the VFS through a call to196/// `bindings::device_add_disk`.197/// - `self.gendisk.queue.queuedata` is initialized by a call to `ForeignOwnable::into_foreign`.198pub struct GenDisk<T: Operations> {199_tagset: Arc<TagSet<T>>,200gendisk: *mut bindings::gendisk,201}202203// SAFETY: `GenDisk` is an owned pointer to a `struct gendisk` and an `Arc` to a204// `TagSet` It is safe to send this to other threads as long as T is Send.205unsafe impl<T: Operations + Send> Send for GenDisk<T> {}206207impl<T: Operations> Drop for GenDisk<T> {208fn drop(&mut self) {209// SAFETY: By type invariant of `Self`, `self.gendisk` points to a valid210// and initialized instance of `struct gendisk`, and, `queuedata` was211// initialized with the result of a call to212// `ForeignOwnable::into_foreign`.213let queue_data = unsafe { (*(*self.gendisk).queue).queuedata };214215// SAFETY: By type invariant, `self.gendisk` points to a valid and216// initialized instance of `struct gendisk`, and it was previously added217// to the VFS.218unsafe { bindings::del_gendisk(self.gendisk) };219220// SAFETY: `queue.queuedata` was created by `GenDiskBuilder::build` with221// a call to `ForeignOwnable::into_foreign` to create `queuedata`.222// `ForeignOwnable::from_foreign` is only called here.223drop(unsafe { T::QueueData::from_foreign(queue_data) });224}225}226227228