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