gen_disk.rs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. // SPDX-License-Identifier: GPL-2.0
  2. //! 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)
  6. use crate::block::mq::{raw_writer::RawWriter, Operations, TagSet};
  7. use crate::{bindings, error::from_err_ptr, error::Result, sync::Arc};
  8. use crate::{error, static_lock_class};
  9. use core::fmt::{self, Write};
  10. /// A builder for [`GenDisk`].
  11. ///
  12. /// Use this struct to configure and add new [`GenDisk`] to the VFS.
  13. pub struct GenDiskBuilder {
  14. rotational: bool,
  15. logical_block_size: u32,
  16. physical_block_size: u32,
  17. capacity_sectors: u64,
  18. }
  19. impl Default for GenDiskBuilder {
  20. fn default() -> Self {
  21. Self {
  22. rotational: false,
  23. logical_block_size: bindings::PAGE_SIZE as u32,
  24. physical_block_size: bindings::PAGE_SIZE as u32,
  25. capacity_sectors: 0,
  26. }
  27. }
  28. }
  29. impl GenDiskBuilder {
  30. /// Create a new instance.
  31. pub fn new() -> Self {
  32. Self::default()
  33. }
  34. /// Set the rotational media attribute for the device to be built.
  35. pub fn rotational(mut self, rotational: bool) -> Self {
  36. self.rotational = rotational;
  37. self
  38. }
  39. /// Validate block size by verifying that it is between 512 and `PAGE_SIZE`,
  40. /// and that it is a power of two.
  41. fn validate_block_size(size: u32) -> Result<()> {
  42. if !(512..=bindings::PAGE_SIZE as u32).contains(&size) || !size.is_power_of_two() {
  43. Err(error::code::EINVAL)
  44. } else {
  45. Ok(())
  46. }
  47. }
  48. /// Set the logical block size of the device to be built.
  49. ///
  50. /// This method will check that block size is a power of two and between 512
  51. /// and 4096. If not, an error is returned and the block size is not set.
  52. ///
  53. /// This is the smallest unit the storage device can address. It is
  54. /// typically 4096 bytes.
  55. pub fn logical_block_size(mut self, block_size: u32) -> Result<Self> {
  56. Self::validate_block_size(block_size)?;
  57. self.logical_block_size = block_size;
  58. Ok(self)
  59. }
  60. /// Set the physical block size of the device to be built.
  61. ///
  62. /// This method will check that block size is a power of two and between 512
  63. /// and 4096. If not, an error is returned and the block size is not set.
  64. ///
  65. /// This is the smallest unit a physical storage device can write
  66. /// atomically. It is usually the same as the logical block size but may be
  67. /// bigger. One example is SATA drives with 4096 byte physical block size
  68. /// that expose a 512 byte logical block size to the operating system.
  69. pub fn physical_block_size(mut self, block_size: u32) -> Result<Self> {
  70. Self::validate_block_size(block_size)?;
  71. self.physical_block_size = block_size;
  72. Ok(self)
  73. }
  74. /// Set the capacity of the device to be built, in sectors (512 bytes).
  75. pub fn capacity_sectors(mut self, capacity: u64) -> Self {
  76. self.capacity_sectors = capacity;
  77. self
  78. }
  79. /// Build a new `GenDisk` and add it to the VFS.
  80. pub fn build<T: Operations>(
  81. self,
  82. name: fmt::Arguments<'_>,
  83. tagset: Arc<TagSet<T>>,
  84. ) -> Result<GenDisk<T>> {
  85. // SAFETY: `bindings::queue_limits` contain only fields that are valid when zeroed.
  86. let mut lim: bindings::queue_limits = unsafe { core::mem::zeroed() };
  87. lim.logical_block_size = self.logical_block_size;
  88. lim.physical_block_size = self.physical_block_size;
  89. if self.rotational {
  90. lim.features = bindings::BLK_FEAT_ROTATIONAL;
  91. }
  92. // SAFETY: `tagset.raw_tag_set()` points to a valid and initialized tag set
  93. let gendisk = from_err_ptr(unsafe {
  94. bindings::__blk_mq_alloc_disk(
  95. tagset.raw_tag_set(),
  96. &mut lim,
  97. core::ptr::null_mut(),
  98. static_lock_class!().as_ptr(),
  99. )
  100. })?;
  101. const TABLE: bindings::block_device_operations = bindings::block_device_operations {
  102. submit_bio: None,
  103. open: None,
  104. release: None,
  105. ioctl: None,
  106. compat_ioctl: None,
  107. check_events: None,
  108. unlock_native_capacity: None,
  109. getgeo: None,
  110. set_read_only: None,
  111. swap_slot_free_notify: None,
  112. report_zones: None,
  113. devnode: None,
  114. alternative_gpt_sector: None,
  115. get_unique_id: None,
  116. // TODO: Set to THIS_MODULE. Waiting for const_refs_to_static feature to
  117. // be merged (unstable in rustc 1.78 which is staged for linux 6.10)
  118. // https://github.com/rust-lang/rust/issues/119618
  119. owner: core::ptr::null_mut(),
  120. pr_ops: core::ptr::null_mut(),
  121. free_disk: None,
  122. poll_bio: None,
  123. };
  124. // SAFETY: `gendisk` is a valid pointer as we initialized it above
  125. unsafe { (*gendisk).fops = &TABLE };
  126. let mut raw_writer = RawWriter::from_array(
  127. // SAFETY: `gendisk` points to a valid and initialized instance. We
  128. // have exclusive access, since the disk is not added to the VFS
  129. // yet.
  130. unsafe { &mut (*gendisk).disk_name },
  131. )?;
  132. raw_writer.write_fmt(name)?;
  133. raw_writer.write_char('\0')?;
  134. // SAFETY: `gendisk` points to a valid and initialized instance of
  135. // `struct gendisk`. `set_capacity` takes a lock to synchronize this
  136. // operation, so we will not race.
  137. unsafe { bindings::set_capacity(gendisk, self.capacity_sectors) };
  138. crate::error::to_result(
  139. // SAFETY: `gendisk` points to a valid and initialized instance of
  140. // `struct gendisk`.
  141. unsafe {
  142. bindings::device_add_disk(core::ptr::null_mut(), gendisk, core::ptr::null_mut())
  143. },
  144. )?;
  145. // INVARIANT: `gendisk` was initialized above.
  146. // INVARIANT: `gendisk` was added to the VFS via `device_add_disk` above.
  147. Ok(GenDisk {
  148. _tagset: tagset,
  149. gendisk,
  150. })
  151. }
  152. }
  153. /// A generic block device.
  154. ///
  155. /// # Invariants
  156. ///
  157. /// - `gendisk` must always point to an initialized and valid `struct gendisk`.
  158. /// - `gendisk` was added to the VFS through a call to
  159. /// `bindings::device_add_disk`.
  160. pub struct GenDisk<T: Operations> {
  161. _tagset: Arc<TagSet<T>>,
  162. gendisk: *mut bindings::gendisk,
  163. }
  164. // SAFETY: `GenDisk` is an owned pointer to a `struct gendisk` and an `Arc` to a
  165. // `TagSet` It is safe to send this to other threads as long as T is Send.
  166. unsafe impl<T: Operations + Send> Send for GenDisk<T> {}
  167. impl<T: Operations> Drop for GenDisk<T> {
  168. fn drop(&mut self) {
  169. // SAFETY: By type invariant, `self.gendisk` points to a valid and
  170. // initialized instance of `struct gendisk`, and it was previously added
  171. // to the VFS.
  172. unsafe { bindings::del_gendisk(self.gendisk) };
  173. }
  174. }