Skip to main content

file_system/devices/
partition_device.rs

1//! Partition device implementation for accessing individual partitions.
2
3//!
4//! This module provides [`PartitionDevice`], which allows treating individual
5//! partitions on a storage device as separate devices. This is essential for file
6//! systems that need to operate on specific partitions rather than entire disks.
7
8use core::fmt;
9
10use shared::AnyByLayout;
11
12use crate::{
13    BaseOperations, ControlCommand, ControlCommandIdentifier, DirectBaseOperations,
14    DirectBlockDevice, IoErrorKind, MountOperations, Position, Result, Size,
15    block_device::{self, ERASE, EraseRange, GET_BLOCK_COUNT, GET_BLOCK_SIZE},
16};
17
18/// A device implementation that represents a partition within a larger storage device.
19///
20/// This type wraps a base device and provides access to only a specific region (partition)
21/// of that device. It maintains its own position cursor and ensures all operations stay
22/// within the partition boundaries. This allows file systems to operate on individual
23/// partitions without needing to know about the partition layout.
24///
25///
26/// Note: The partition device does not manage position state internally and does not use atomic operations.
27/// Thread safety depends on the underlying base device implementation.
28///
29///
30/// # Examples
31///
32/// ```rust
33/// # extern crate alloc;
34/// # use file_system::{MemoryDevice, PartitionDevice, DirectBaseOperations};
35///
36/// // Create a memory device for testing
37/// let base_device = MemoryDevice::<512>::new(1024 * 1024);
38///
39/// // Create a partition device for blocks 100-199 (100 blocks of 512 bytes = 51.2KB)
40/// let partition_device = PartitionDevice::new(&base_device, 100, 100, 512);
41///
42/// // Now you can use partition_device like any other device
43/// let data = b"Hello, Partition!";
44/// partition_device.write_sync(data, 0).unwrap();
45/// ```
46pub struct PartitionDevice<'a, D> {
47    /// Base device containing this partition
48    base_device: &'a D,
49    /// Block size
50    block_size: u32,
51    /// Byte offset from the beginning of the base device
52    offset: Size,
53    /// Size of this partition in bytes
54    size: Size,
55}
56
57impl<'a, D: BaseOperations> PartitionDevice<'a, D> {
58    /// Create a new partition device with explicit byte offset and size.
59    ///
60    /// # Arguments
61    ///
62    /// * `base_device` - The underlying storage device
63    /// * `start_block` - Block index where the partition starts
64    /// * `block_count` - Number of blocks in the partition
65    /// * `block_size` - Size of each block in bytes
66    ///
67    /// # Examples
68    ///
69    /// ```rust
70    /// # extern crate alloc;
71    /// # use file_system::{MemoryDevice, PartitionDevice};
72    ///
73    /// let base_device = MemoryDevice::<512>::new(1024 * 1024);
74    /// // Create a partition starting at block 128 (64KB) with 256 blocks (128KB)
75    /// let partition = PartitionDevice::new(&base_device, 128, 256, 512);
76    /// ```
77    pub fn new(base_device: &'a D, start_block: Size, block_count: Size, block_size: u32) -> Self {
78        Self {
79            base_device,
80            block_size,
81            offset: start_block * (block_size as Size),
82            size: block_count * (block_size as Size),
83        }
84    }
85    /// Get the number of blocks in this partition.
86    ///
87    /// # Returns
88    ///
89    /// The number of blocks in this partition, where each block is of the partition's configured block size.
90    /// The number of 512-byte sectors this partition contains.
91    ///
92    /// # Examples
93    ///
94    /// ```rust
95    /// # extern crate alloc;
96    /// # use file_system::{MemoryDevice, PartitionDevice};
97    ///
98    /// let base_device = MemoryDevice::<512>::new(1024 * 1024);
99    /// let partition = PartitionDevice::new(&base_device, 100, 50, 512);
100    /// assert_eq!(partition.get_block_count(), 50);
101    /// ```
102    pub const fn get_block_count(&self) -> Size {
103        self.size / (self.block_size as Size)
104    }
105
106    pub const fn get_start_lba(&self) -> Size {
107        self.offset / (self.block_size as Size)
108    }
109
110    /// Get the base device
111    pub const fn get_base_device(&self) -> &D {
112        self.base_device
113    }
114
115    /// Check if the partition device is valid (non-zero size)
116    pub const fn is_valid(&self) -> bool {
117        self.size > 0
118    }
119
120    const fn get_device_position(&self, absolute_position: Size) -> Option<Size> {
121        if absolute_position >= self.size {
122            return None;
123        }
124
125        let device_position = match self.offset.checked_add(absolute_position) {
126            Some(pos) => pos,
127            None => return None,
128        };
129
130        Some(device_position)
131    }
132
133    const fn get_total_buffer_length(
134        &self,
135        absolute_position: Size,
136        buffer_length: usize,
137    ) -> usize {
138        let remaining_size = self.size.saturating_sub(absolute_position) as usize;
139
140        if buffer_length > remaining_size {
141            remaining_size
142        } else {
143            buffer_length
144        }
145    }
146}
147
148impl<'a, D: DirectBaseOperations> DirectBaseOperations for PartitionDevice<'a, D> {
149    fn read(
150        &self,
151        cx: &mut core::task::Context<'_>,
152        buffer: &mut [u8],
153        absolute_position: Size,
154    ) -> core::task::Poll<Result<usize>> {
155        let Some(position) = self.get_device_position(absolute_position) else {
156            return core::task::Poll::Ready(Ok(0));
157        };
158        let length = self.get_total_buffer_length(absolute_position, buffer.len());
159        DirectBaseOperations::read(self.base_device, cx, &mut buffer[..length], position)
160    }
161
162    fn write(
163        &self,
164        cx: &mut core::task::Context<'_>,
165        buffer: &[u8],
166        absolute_position: Size,
167    ) -> core::task::Poll<Result<usize>> {
168        let Some(position) = self.get_device_position(absolute_position) else {
169            return core::task::Poll::Ready(Ok(0));
170        };
171        let length = self.get_total_buffer_length(absolute_position, buffer.len());
172        DirectBaseOperations::write(self.base_device, cx, &buffer[..length], position)
173    }
174
175    fn write_pattern(
176        &self,
177        cx: &mut core::task::Context<'_>,
178        pattern: &[u8],
179        count: usize,
180        absolute_position: Size,
181    ) -> core::task::Poll<Result<usize>> {
182        let Some(position) = self.get_device_position(absolute_position) else {
183            return core::task::Poll::Ready(Ok(0));
184        };
185        if pattern.is_empty() {
186            return core::task::Poll::Ready(Ok(0));
187        }
188        let count = count.min(
189            self.get_total_buffer_length(absolute_position, pattern.len().saturating_mul(count))
190                / pattern.len(),
191        );
192        DirectBaseOperations::write_pattern(self.base_device, cx, pattern, count, position)
193    }
194
195    fn set_position(&self, current_position: Size, position: &Position) -> Result<Size> {
196        let position = block_device::set_position(current_position, position, self.size)?;
197
198        let device_position = self
199            .get_device_position(position)
200            .ok_or(IoErrorKind::InvalidArgument)?;
201
202        self.base_device
203            .set_position(device_position, &Position::Start(0))?;
204
205        Ok(position)
206    }
207
208    fn flush(&self, cx: &mut core::task::Context<'_>) -> core::task::Poll<Result<()>> {
209        DirectBaseOperations::flush(self.base_device, cx)
210    }
211
212    fn control(
213        &self,
214        cx: &mut core::task::Context<'_>,
215        command: ControlCommandIdentifier,
216        input: &AnyByLayout,
217        output: &mut AnyByLayout,
218    ) -> core::task::Poll<Result<()>> {
219        match command {
220            GET_BLOCK_SIZE::IDENTIFIER => {
221                *GET_BLOCK_SIZE::cast_output(output)? = self.block_size;
222                core::task::Poll::Ready(Ok(()))
223            }
224            GET_BLOCK_COUNT::IDENTIFIER => {
225                *GET_BLOCK_COUNT::cast_output(output)? = self.get_block_count();
226                core::task::Poll::Ready(Ok(()))
227            }
228            ERASE::IDENTIFIER => {
229                // Ranges are relative to the partition, never to the base device.
230                let range = match ERASE::cast_input(input) {
231                    Ok(range) => *range,
232                    Err(error) => return core::task::Poll::Ready(Err(error)),
233                };
234                let Some(position) = range
235                    .position
236                    .checked_add(range.size)
237                    .filter(|end| *end <= self.size)
238                    .and_then(|_| self.offset.checked_add(range.position))
239                else {
240                    return core::task::Poll::Ready(Err(IoErrorKind::InvalidArgument));
241                };
242                let range = EraseRange {
243                    position,
244                    size: range.size,
245                };
246                DirectBaseOperations::control(
247                    self.base_device,
248                    cx,
249                    command,
250                    AnyByLayout::from(&range),
251                    output,
252                )
253            }
254            _ => DirectBaseOperations::control(self.base_device, cx, command, input, output),
255        }
256    }
257    fn cancel_operation(&self, operation: crate::Operation) {
258        DirectBaseOperations::cancel_operation(self.base_device, operation);
259    }
260}
261
262impl<'a, D: MountOperations> MountOperations for PartitionDevice<'a, D> {}
263
264impl<'a, D: DirectBlockDevice> DirectBlockDevice for PartitionDevice<'a, D> {}
265
266impl<'a, D> fmt::Debug for PartitionDevice<'a, D> {
267    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
268        formatter
269            .debug_struct("PartitionDevice")
270            .field("block_size", &self.block_size)
271            .field("offset", &self.offset)
272            .field("size", &self.size)
273            .finish()
274    }
275}
276
277#[cfg(test)]
278#[allow(
279    clippy::disallowed_types,
280    reason = "host-only unit tests count cancellations"
281)]
282mod tests {
283    use alloc::boxed::Box;
284
285    use crate::{MemoryDevice, implement_block_device_tests};
286
287    use super::*;
288
289    struct Deferred(core::sync::atomic::AtomicUsize);
290    impl DirectBaseOperations for Deferred {
291        fn read(
292            &self,
293            _: &mut core::task::Context<'_>,
294            _: &mut [u8],
295            _: Size,
296        ) -> core::task::Poll<Result<usize>> {
297            core::task::Poll::Pending
298        }
299        fn write(
300            &self,
301            _: &mut core::task::Context<'_>,
302            _: &[u8],
303            _: Size,
304        ) -> core::task::Poll<Result<usize>> {
305            core::task::Poll::Pending
306        }
307        fn cancel_operation(&self, _: crate::Operation) {
308            self.0.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
309        }
310    }
311    /// Records the last erased range of the base device.
312    struct Erasable(core::cell::Cell<Option<EraseRange>>);
313    // SAFETY: tests are single-threaded.
314    unsafe impl Sync for Erasable {}
315    impl DirectBaseOperations for Erasable {
316        fn read(
317            &self,
318            _: &mut core::task::Context<'_>,
319            _: &mut [u8],
320            _: Size,
321        ) -> core::task::Poll<Result<usize>> {
322            core::task::Poll::Ready(Ok(0))
323        }
324        fn write(
325            &self,
326            _: &mut core::task::Context<'_>,
327            _: &[u8],
328            _: Size,
329        ) -> core::task::Poll<Result<usize>> {
330            core::task::Poll::Ready(Ok(0))
331        }
332        fn control(
333            &self,
334            _: &mut core::task::Context<'_>,
335            command: ControlCommandIdentifier,
336            input: &AnyByLayout,
337            _: &mut AnyByLayout,
338        ) -> core::task::Poll<Result<()>> {
339            crate::ready(|| match command {
340                ERASE::IDENTIFIER => {
341                    self.0.set(Some(*ERASE::cast_input(input)?));
342                    Ok(())
343                }
344                _ => Err(IoErrorKind::Unsupported),
345            })
346        }
347    }
348    impl MountOperations for Erasable {}
349    impl DirectBlockDevice for Erasable {}
350
351    #[test]
352    fn partition_erases_only_inside_its_own_range() {
353        let base = Erasable(core::cell::Cell::new(None));
354        let partition = PartitionDevice::new(&base, 4, 2, 512);
355
356        partition.erase(512, 512).unwrap();
357        assert_eq!(
358            base.0.take(),
359            Some(EraseRange {
360                position: 5 * 512,
361                size: 512
362            })
363        );
364
365        assert_eq!(
366            partition.erase(512, 1024),
367            Err(IoErrorKind::InvalidArgument)
368        );
369        assert_eq!(
370            partition.erase(u64::MAX, 2),
371            Err(IoErrorKind::InvalidArgument)
372        );
373        assert_eq!(base.0.take(), None);
374    }
375
376    #[test]
377    fn rewritable_device_reports_erase_as_unsupported() {
378        let base = MemoryDevice::<512>::new(4096);
379        assert_eq!(base.erase(0, 512), Err(IoErrorKind::Unsupported));
380    }
381
382    #[test]
383    fn partition_forwards_pending_and_cancellation_to_its_device() {
384        let device = Deferred(core::sync::atomic::AtomicUsize::new(0));
385        let partition = PartitionDevice::new(&device, 0, 1, 512);
386        let mut cx = core::task::Context::from_waker(core::task::Waker::noop());
387        assert!(DirectBaseOperations::read(&partition, &mut cx, &mut [0], 0).is_pending());
388        DirectBaseOperations::cancel_operation(&partition, crate::Operation::Read);
389        assert_eq!(device.0.load(core::sync::atomic::Ordering::Relaxed), 1);
390    }
391
392    implement_block_device_tests!(PartitionDevice::new(
393        Box::leak(Box::new(MemoryDevice::<512>::new(1024 * 1024))),
394        0,
395        1024 * 512,
396        512
397    ));
398}