Skip to main content

file_system/operations/
block_device.rs

1use crate::{
2    BaseOperations, ControlCommand, DirectBaseOperations, IoErrorKind, MountOperations, Position,
3    Result, Size, define_command,
4};
5use shared::AnyByLayout;
6
7// Kind byte `b'B'` is registered as `device::kind::BLOCK_DEVICE` (kept as a literal here because `device` depends on `file_system`).
8define_command!(GET_BLOCK_SIZE, Read, b'B', 0, (), u32);
9define_command!(GET_BLOCK_COUNT, Read, b'B', 1, (), Size);
10define_command!(ERASE, Write, b'B', 2, EraseRange, ());
11
12crate::plain_data! {
13    #[repr(C)]
14    /// Byte range of a block device, relative to its start.
15    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
16    pub struct EraseRange {
17        pub position: Size,
18        pub size: Size,
19    }
20}
21
22pub trait BlockDevice: BaseOperations + MountOperations {}
23
24pub trait DirectBlockDevice: DirectBaseOperations + MountOperations {
25    fn get_block_size(&self) -> Result<u32> {
26        let mut block_size: u32 = 0;
27
28        self.control_sync(
29            GET_BLOCK_SIZE::IDENTIFIER,
30            AnyByLayout::NONE,
31            AnyByLayout::from_mutable(&mut block_size),
32        )?;
33        Ok(block_size)
34    }
35
36    fn get_block_count(&self) -> Result<Size> {
37        let mut total_size: Size = 0;
38
39        self.control_sync(
40            GET_BLOCK_COUNT::IDENTIFIER,
41            AnyByLayout::NONE,
42            AnyByLayout::from_mutable(&mut total_size),
43        )?;
44        Ok(total_size)
45    }
46
47    /// Prepare a byte range for writing, as raw flash requires before programming.
48    ///
49    /// The range reads back unspecified data afterwards, and any write to it then
50    /// succeeds. Devices that can rewrite in place need not implement `ERASE`:
51    /// callers treat [`IoErrorKind::Unsupported`] as "nothing to do".
52    fn erase(&self, position: Size, size: Size) -> Result<()> {
53        self.control_sync(
54            ERASE::IDENTIFIER,
55            AnyByLayout::from(&EraseRange { position, size }),
56            AnyByLayout::NONE,
57        )
58    }
59}
60
61pub fn set_position(current_position: Size, position: &Position, size: Size) -> Result<Size> {
62    let new_position = match position {
63        Position::Start(position) => (*position)
64            .try_into()
65            .map_err(|_| IoErrorKind::InvalidArgument)?,
66        Position::Current(offset) => (current_position as i64).wrapping_add(*offset),
67        Position::End(offset) => (size as i64).saturating_add(*offset),
68    };
69
70    if new_position < 0 || (new_position as u64) > size {
71        return Err(IoErrorKind::InvalidArgument);
72    }
73
74    Ok(new_position as Size)
75}
76
77impl<T> BlockDevice for T where T: DirectBlockDevice + MountOperations {}
78
79pub mod tests {
80    use alloc::vec;
81
82    use crate::{Context, Position};
83
84    use super::*;
85
86    /// Generic test for open and close operations.
87    pub fn test_open_and_close<T: BlockDevice>(device: &T) {
88        let mut context = Context::new_empty();
89        device.open(&mut context).unwrap();
90        device.close(&mut context).unwrap();
91    }
92
93    /// Generic test for basic read and write operations.
94    pub fn test_basic_read_write<T: BlockDevice>(device: &T) {
95        let mut context = Context::new_empty();
96
97        let write_data = b"Hello, Context!";
98        let bytes_written = device.write_sync(&mut context, write_data, 0).unwrap();
99        assert_eq!(bytes_written, write_data.len());
100
101        let mut read_buffer = vec![0u8; write_data.len()];
102        let bytes_read = device.read_sync(&mut context, &mut read_buffer, 0).unwrap();
103        assert_eq!(bytes_read, write_data.len());
104        assert_eq!(&read_buffer[..], write_data);
105    }
106
107    /// Generic test for writing at a specific offset.
108    pub fn test_write_at_offset<T: BlockDevice>(device: &T) {
109        let mut context = Context::new_empty();
110
111        let data = b"Xila";
112        let offset = 100;
113        let bytes_written = device.write_sync(&mut context, data, offset).unwrap();
114        assert_eq!(bytes_written, data.len());
115
116        let mut read_buffer = vec![0u8; data.len()];
117        let bytes_read = device
118            .read_sync(&mut context, &mut read_buffer, offset)
119            .unwrap();
120        assert_eq!(bytes_read, data.len());
121        assert_eq!(&read_buffer[..], data);
122    }
123
124    /// Generic test for position management.
125    pub fn test_position_management<T: BlockDevice>(device: &T) {
126        let mut context = Context::new_empty();
127
128        let position = 80;
129
130        let position = device
131            .set_position(&mut context, position, &Position::Start(50))
132            .unwrap();
133        assert_eq!(position, 50);
134
135        let position = device
136            .set_position(&mut context, position, &Position::Current(25))
137            .unwrap();
138        assert_eq!(position, 75);
139    }
140
141    /// Generic test for write pattern functionality.
142    pub fn test_write_pattern<T: BlockDevice>(device: &T) {
143        let mut context = Context::new_empty();
144
145        let pattern = b"XY";
146        let pattern_count = 4;
147        let position = 200;
148        let bytes_written = device
149            .write_pattern_sync(&mut context, pattern, pattern_count, position)
150            .unwrap();
151        assert_eq!(bytes_written, pattern.len() * pattern_count);
152
153        let mut read_buffer = vec![0u8; pattern.len() * pattern_count];
154        let bytes_read = device
155            .read_sync(&mut context, &mut read_buffer, position)
156            .unwrap();
157        assert_eq!(bytes_read, pattern.len() * pattern_count);
158        assert_eq!(&read_buffer[..], b"XYXYXYXY");
159    }
160
161    /// Generic test for vectored write operations.
162    pub fn test_write_vectored<T: BlockDevice>(device: &T) {
163        let mut context = Context::new_empty();
164
165        let buffers = [b"Alpha".as_slice(), b"Beta".as_slice()];
166        let position = 300;
167        let total_written = device
168            .write_vectored_sync(&mut context, &buffers, position)
169            .unwrap();
170        assert_eq!(total_written, 9); // 5 + 4
171
172        let mut read_buffer = vec![0u8; 9];
173        let bytes_read = device
174            .read_sync(&mut context, &mut read_buffer, position)
175            .unwrap();
176        assert_eq!(bytes_read, 9);
177        assert_eq!(&read_buffer[..], b"AlphaBeta");
178    }
179
180    /// Generic test for read until delimiter.
181    pub fn test_read_until_delimiter<T: BlockDevice>(device: &T) {
182        let mut context = Context::new_empty();
183
184        let test_data = b"Start|Middle|End";
185        device.write_sync(&mut context, test_data, 400).unwrap();
186
187        let mut read_buffer = vec![0u8; 20];
188        let bytes_read = device
189            .read_until_sync(&mut context, &mut read_buffer, 400, b"|")
190            .unwrap();
191        assert_eq!(&read_buffer[..bytes_read], b"Start|");
192    }
193
194    /// Generic test for flush operation.
195    pub fn test_flush<T: BlockDevice>(device: &T) {
196        let mut context = Context::new_empty();
197        device.flush_sync(&mut context).unwrap();
198    }
199
200    /// Generic test for context cloning.
201    pub fn test_clone_context<T: BlockDevice>(device: &T) {
202        let context = Context::new_empty();
203        let cloned_context = device.clone_context(&context).unwrap();
204        drop(cloned_context);
205    }
206
207    /// Generic test for control command.
208    pub fn test_control_commands<T: BlockDevice>(device: &T) {
209        let mut context = Context::new_empty();
210        let mut block_count: Size = 0;
211        device
212            .control_sync(
213                &mut context,
214                GET_BLOCK_COUNT::IDENTIFIER,
215                AnyByLayout::NONE,
216                AnyByLayout::from_mutable(&mut block_count),
217            )
218            .unwrap();
219
220        assert!(block_count > 0);
221
222        let mut block_size: u32 = 0;
223        device
224            .control_sync(
225                &mut context,
226                GET_BLOCK_SIZE::IDENTIFIER,
227                AnyByLayout::NONE,
228                AnyByLayout::from_mutable(&mut block_size),
229            )
230            .unwrap();
231
232        assert!(block_size > 0);
233    }
234
235    /// Generic test for read until boundary conditions.
236    pub fn test_read_until_boundary_conditions<T: BlockDevice>(device: &T) {
237        let mut context = Context::new_empty();
238
239        // Test: delimiter not found
240        let test_data = b"NoDelimiterHere";
241        device.write_sync(&mut context, test_data, 0).unwrap();
242
243        let mut read_buffer = vec![0u8; test_data.len()];
244        let bytes_read = device
245            .read_until_sync(&mut context, &mut read_buffer, 0, b"|")
246            .unwrap();
247        assert_eq!(bytes_read, test_data.len());
248        assert_eq!(&read_buffer[..], test_data);
249
250        // Test: delimiter at start
251        let test_data = b"|Start";
252        device.write_sync(&mut context, test_data, 100).unwrap();
253
254        let mut read_buffer = vec![0u8; 10];
255        let bytes_read = device
256            .read_until_sync(&mut context, &mut read_buffer, 100, b"|")
257            .unwrap();
258        assert_eq!(&read_buffer[..bytes_read], b"|");
259
260        // Test: partial delimiter match followed by different character
261        let test_data = b"ABACD";
262        device.write_sync(&mut context, test_data, 200).unwrap();
263
264        let mut read_buffer = vec![0u8; test_data.len()];
265        let bytes_read = device
266            .read_until_sync(&mut context, &mut read_buffer, 200, b"ABC")
267            .unwrap();
268        assert_eq!(bytes_read, test_data.len());
269        assert_eq!(&read_buffer[..], test_data);
270    }
271
272    /// Generic test for write pattern edge cases.
273    pub fn test_write_pattern_edge_cases<T: BlockDevice>(device: &T) {
274        let mut context = Context::new_empty();
275
276        // Test: zero count
277        let pattern = b"XYZ";
278        let bytes_written = device
279            .write_pattern_sync(&mut context, pattern, 0, 0)
280            .unwrap();
281        assert_eq!(bytes_written, 0);
282
283        // Test: single byte pattern
284        let pattern = b"A";
285        let bytes_written = device
286            .write_pattern_sync(&mut context, pattern, 10, 0)
287            .unwrap();
288        assert_eq!(bytes_written, 10);
289
290        let mut read_buffer = vec![0u8; 10];
291        device.read_sync(&mut context, &mut read_buffer, 0).unwrap();
292        assert_eq!(&read_buffer[..], b"AAAAAAAAAA");
293    }
294
295    /// Generic test for write vectored edge cases.
296    pub fn test_write_vectored_edge_cases<T: BlockDevice>(device: &T) {
297        let mut context = Context::new_empty();
298
299        // Test: empty buffers array
300        let buffers: [&[u8]; 0] = [];
301        let bytes_written = device
302            .write_vectored_sync(&mut context, &buffers, 0)
303            .unwrap();
304        assert_eq!(bytes_written, 0);
305
306        // Test: buffers with empty slices
307        let buffers = [b"First".as_slice(), b"".as_slice(), b"Third".as_slice()];
308        let bytes_written = device
309            .write_vectored_sync(&mut context, &buffers, 0)
310            .unwrap();
311        assert_eq!(bytes_written, buffers.into_iter().map(|b| b.len()).sum());
312
313        let mut read_buffer = vec![0u8; 10];
314        device.read_sync(&mut context, &mut read_buffer, 0).unwrap();
315        assert_eq!(&read_buffer[..], b"FirstThird");
316    }
317
318    /// Generic test for position wraparound scenarios.
319    pub fn test_position_wraparound<T: BlockDevice>(device: &T, device_size: Size) {
320        let mut context = Context::new_empty();
321
322        let position = 0;
323        // Set to near end
324        let near_end = device_size.saturating_sub(100);
325        let position = device
326            .set_position(&mut context, position, &Position::Start(near_end))
327            .unwrap();
328        assert_eq!(position, near_end);
329
330        // Move forward from current
331        let position = device
332            .set_position(&mut context, position, &Position::Current(50))
333            .unwrap();
334        assert_eq!(position, near_end + 50);
335
336        // Move backward from current
337        let position = device
338            .set_position(&mut context, position, &Position::Current(-100))
339            .unwrap();
340        assert_eq!(position, near_end.saturating_sub(50));
341
342        // Position from end
343        let position = device
344            .set_position(&mut context, position, &Position::End(-50))
345            .unwrap();
346        assert_eq!(position, device_size - 50);
347
348        // Position exactly at end
349        let position = device
350            .set_position(&mut context, position, &Position::End(0))
351            .unwrap();
352        assert_eq!(position, device_size);
353    }
354
355    /// Generic test for concurrent operations.
356    pub fn test_concurrent_operations<T: BlockDevice + Sync>(device: &T) {
357        let mut context = Context::new_empty();
358        let mut context_clone = Context::new_empty();
359
360        // Write from one context
361        let write_data = b"Concurrent Write Test";
362        device.write_sync(&mut context, write_data, 0).unwrap();
363
364        // Read from another context
365        let mut read_buffer = vec![0u8; write_data.len()];
366        device
367            .read_sync(&mut context_clone, &mut read_buffer, 0)
368            .unwrap();
369        assert_eq!(&read_buffer[..], write_data);
370    }
371
372    /// Generic test for large read/write operations.
373    pub fn test_large_read_write<T: BlockDevice>(device: &T) {
374        let mut context = Context::new_empty();
375
376        // Test with a large buffer
377        let large_data = vec![0x42u8; 4096];
378        let bytes_written = device.write_sync(&mut context, &large_data, 0).unwrap();
379        assert_eq!(bytes_written, large_data.len());
380
381        let mut read_buffer = vec![0u8; 4096];
382        let bytes_read = device.read_sync(&mut context, &mut read_buffer, 0).unwrap();
383        assert_eq!(bytes_read, large_data.len());
384        assert_eq!(read_buffer, large_data);
385    }
386
387    #[macro_export]
388    macro_rules! implement_block_device_tests {
389        ($device:expr) => {
390            #[test]
391            fn test_open_close() {
392                let device = $device;
393                $crate::block_device::tests::test_open_and_close(&device);
394            }
395
396            #[test]
397            fn test_basic_read_write() {
398                let device = $device;
399                 $crate::block_device::tests::test_basic_read_write(&device);
400            }
401
402            #[test]
403            fn test_write_at_offset() {
404                let device = $device;
405                 $crate::block_device::tests::test_write_at_offset(&device);
406            }
407
408            #[test]
409            fn test_position_management() {
410                let device = $device;
411                 $crate::block_device::tests::test_position_management(&device);
412            }
413
414            #[test]
415            fn test_write_pattern() {
416                let device = $device;
417                 $crate::block_device::tests::test_write_pattern(&device);
418            }
419
420            #[test]
421            fn test_write_vectored() {
422                let device = $device;
423                 $crate::block_device::tests::test_write_vectored(&device);
424            }
425
426            #[test]
427            fn test_read_until_delimiter() {
428                let device = $device;
429                 $crate::block_device::tests::test_read_until_delimiter(&device);
430            }
431
432            #[test]
433            fn test_flush() {
434                let device = $device;
435                 $crate::block_device::tests::test_flush(&device);
436            }
437
438            #[test]
439            fn test_clone_context() {
440                let device = $device;
441                 $crate::block_device::tests::test_clone_context(&device);
442            }
443
444            #[test]
445            fn test_control_commands() {
446                let device = $device;
447                 $crate::block_device::tests::test_control_commands(&device);
448            }
449
450            #[test]
451            fn test_read_until_boundary_conditions() {
452                let device = $device;
453                 $crate::block_device::tests::test_read_until_boundary_conditions(&device);
454            }
455
456            #[test]
457            fn test_write_pattern_edge_cases() {
458                let device = $device;
459                 $crate::block_device::tests::test_write_pattern_edge_cases(&device);
460            }
461
462            #[test]
463            fn test_write_vectored_edge_cases() {
464                let device = $device;
465                 $crate::block_device::tests::test_write_vectored_edge_cases(&device);
466            }
467
468            #[test]
469            fn test_concurrent_operations() {
470                let device = $device;
471                 $crate::block_device::tests::test_concurrent_operations(&device);
472            }
473
474            #[test]
475            fn test_large_read_write() {
476                let device = $device;
477                 $crate::block_device::tests::test_large_read_write(&device);
478            }
479        };
480        (
481            instance: $device:expr,
482            size: $size:expr
483        ) => {
484            implement!(instance: $device);
485
486            #[test]
487            fn test_position_wraparound() {
488                let device = $device;
489                test_position_wraparound(&device, $size);
490            }
491        };
492    }
493
494    /// Tests for the set_position function.
495    #[cfg(test)]
496    mod set_position_tests {
497        use super::*;
498
499        #[test]
500        fn test_position_start_valid() {
501            let result = set_position(100, &Position::Start(50), 1000);
502            assert_eq!(result.unwrap(), 50);
503        }
504
505        #[test]
506        fn test_position_start_at_zero() {
507            let result = set_position(100, &Position::Start(0), 1000);
508            assert_eq!(result.unwrap(), 0);
509        }
510
511        #[test]
512        fn test_position_start_at_size() {
513            let result = set_position(100, &Position::Start(1000), 1000);
514            assert_eq!(result.unwrap(), 1000);
515        }
516
517        #[test]
518        fn test_position_start_exceeds_size() {
519            let result = set_position(100, &Position::Start(1001), 1000);
520            assert!(result.is_err());
521            assert_eq!(result.unwrap_err(), IoErrorKind::InvalidArgument);
522        }
523
524        #[test]
525        fn test_position_current_positive_offset() {
526            let result = set_position(100, &Position::Current(50), 1000);
527            assert_eq!(result.unwrap(), 150);
528        }
529
530        #[test]
531        fn test_position_current_negative_offset() {
532            let result = set_position(100, &Position::Current(-50), 1000);
533            assert_eq!(result.unwrap(), 50);
534        }
535
536        #[test]
537        fn test_position_current_zero_offset() {
538            let result = set_position(100, &Position::Current(0), 1000);
539            assert_eq!(result.unwrap(), 100);
540        }
541
542        #[test]
543        fn test_position_current_exceeds_size() {
544            let result = set_position(100, &Position::Current(901), 1000);
545            assert!(result.is_err());
546            assert_eq!(result.unwrap_err(), IoErrorKind::InvalidArgument);
547        }
548
549        #[test]
550        fn test_position_current_wraps_to_valid() {
551            // Test wraparound behavior
552            let result = set_position(Size::MAX - 50, &Position::Current(100), Size::MAX);
553            assert_eq!(result.unwrap(), Size::MAX.wrapping_add(50));
554        }
555
556        #[test]
557        fn test_position_end_zero_offset() {
558            let result = set_position(100, &Position::End(0), 1000);
559            assert_eq!(result.unwrap(), 1000);
560        }
561
562        #[test]
563        fn test_position_end_negative_offset() {
564            let result = set_position(100, &Position::End(-50), 1000);
565            assert_eq!(result.unwrap(), 950);
566        }
567
568        #[test]
569        fn test_position_end_positive_offset() {
570            let result = set_position(100, &Position::End(10), 1000);
571            assert!(result.is_err());
572            assert_eq!(result.unwrap_err(), IoErrorKind::InvalidArgument);
573        }
574
575        #[test]
576        fn test_position_end_negative_exceeds_zero() {
577            let result = set_position(100, &Position::End(-1001), 1000);
578            assert!(result.is_err());
579            assert_eq!(result.unwrap_err(), IoErrorKind::InvalidArgument);
580        }
581
582        #[test]
583        fn test_position_end_exactly_at_start() {
584            let result = set_position(100, &Position::End(-1000), 1000);
585            assert_eq!(result.unwrap(), 0);
586        }
587
588        #[test]
589        fn test_position_boundaries() {
590            // Test at exact boundaries
591            let size = 1000;
592
593            // Start boundary
594            assert_eq!(set_position(0, &Position::Start(0), size).unwrap(), 0);
595            assert_eq!(set_position(0, &Position::Start(size), size).unwrap(), size);
596
597            // End boundary
598            assert_eq!(set_position(0, &Position::End(0), size).unwrap(), size);
599            assert_eq!(
600                set_position(0, &Position::End(-(size as i64)), size).unwrap(),
601                0
602            );
603
604            // Current boundary
605            assert_eq!(set_position(0, &Position::Current(0), size).unwrap(), 0);
606            assert_eq!(
607                set_position(0, &Position::Current(size as i64), size).unwrap(),
608                size
609            );
610        }
611    }
612}