-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathlib.rs
More file actions
1663 lines (1505 loc) · 57.4 KB
/
Copy pathlib.rs
File metadata and controls
1663 lines (1505 loc) · 57.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Block Layer for Zero-OS
//!
//! This module provides the core abstractions for block device I/O operations.
//! It follows a layered design similar to Linux's block layer:
//!
//! ```text
//! +----------------+ +----------------+
//! | File System | | Page Cache |
//! +--------+-------+ +-------+--------+
//! | |
//! v v
//! +---+---------------------+---+
//! | Block Layer |
//! | (Bio, RequestQueue, etc.) |
//! +-------------+---------------+
//! |
//! +---------+---------+
//! | |
//! v v
//! +-----------+ +-----------+
//! | virtio-blk| | AHCI |
//! +-----------+ +-----------+
//! ```
//!
//! # Key Components
//!
//! - [`BlockDevice`]: Trait for block device drivers
//! - [`Bio`]: Block I/O request structure
//! - [`BioVec`]: Owned CPU buffers transferred with each BIO
//! - [`RequestQueue`]: Per-device request queue with FIFO scheduling
//! - [`BlockDeviceRegistry`]: Global registry for block devices
//!
//! # Security Integration
//!
//! Each BIO can carry a [`SecurityTag`] containing inode/path information
//! for LSM policy enforcement at the block layer.
#![no_std]
#![allow(unused_variables)]
#![allow(unused_assignments)]
#![allow(dead_code)]
#![allow(clippy::manual_div_ceil)]
#![allow(clippy::manual_is_multiple_of)]
#![allow(clippy::new_without_default)]
#![feature(allocator_api)]
extern crate alloc;
extern crate drivers;
#[macro_use]
extern crate klog;
extern crate mm;
pub mod geometry;
pub use geometry::BlockGeometry;
pub mod pci;
pub mod virtio;
use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;
use core::sync::atomic::{AtomicU64, Ordering};
use mm::{AdmittedDeque, AdmittedVec, HeapClass};
use spin::{Mutex, RwLock};
// ============================================================================
// Constants
// ============================================================================
/// Default logical sector size in bytes.
pub const DEFAULT_SECTOR_SIZE: u32 = 512;
/// Maximum sectors per BIO (512 KB with 512-byte sectors).
pub const MAX_BIO_SECTORS: u32 = 1024;
/// Maximum BIO payload size in bytes.
pub const MAX_BIO_BYTES: usize = (MAX_BIO_SECTORS as usize) * (DEFAULT_SECTOR_SIZE as usize);
/// Maximum number of scatter-gather vectors per BIO.
pub const MAX_BIO_VECS: usize = 256;
/// Maximum number of registered block devices.
pub const MAX_BLOCK_DEVICES: usize = 64;
// ============================================================================
// Error Types
// ============================================================================
/// Block layer error type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockError {
/// Generic I/O failure.
Io,
/// Invalid arguments (alignment, overflow, etc.).
Invalid,
/// Request size exceeds device or global limits.
TooLarge,
/// Device is busy or queue is full.
Busy,
/// Memory allocation failed.
NoMem,
/// Operation not supported by device.
NotSupported,
/// Device not found.
NotFound,
/// Device offline or removed.
Offline,
/// Read-only device.
ReadOnly,
/// Media error (bad sector, etc.).
MediaError,
/// Permission denied (LSM policy).
PermissionDenied,
}
impl fmt::Display for BlockError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BlockError::Io => write!(f, "I/O error"),
BlockError::Invalid => write!(f, "invalid argument"),
BlockError::TooLarge => write!(f, "request too large"),
BlockError::Busy => write!(f, "device busy"),
BlockError::NoMem => write!(f, "out of memory"),
BlockError::NotSupported => write!(f, "operation not supported"),
BlockError::NotFound => write!(f, "device not found"),
BlockError::Offline => write!(f, "device offline"),
BlockError::ReadOnly => write!(f, "read-only device"),
BlockError::MediaError => write!(f, "media error"),
BlockError::PermissionDenied => write!(f, "permission denied"),
}
}
}
// ============================================================================
// BIO Types
// ============================================================================
/// Block I/O operation type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BioOp {
/// Read data from device.
Read,
/// Write data to device.
Write,
/// Flush device write cache.
Flush,
/// Discard (TRIM) sectors.
Discard,
}
impl fmt::Display for BioOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BioOp::Read => write!(f, "READ"),
BioOp::Write => write!(f, "WRITE"),
BioOp::Flush => write!(f, "FLUSH"),
BioOp::Discard => write!(f, "DISCARD"),
}
}
}
/// KSA-018: exclusively owned CPU buffer for a BIO transfer.
///
/// Slice construction copies bytes into admitted storage. The source may be
/// changed or dropped immediately; read completion returns this owner to its
/// callback. DMA drivers own a separate pinned buffer while the device runs.
#[derive(Debug)]
pub struct BioVec {
data: AdmittedVec<u8>,
}
impl BioVec {
pub fn zeroed(len: usize) -> Result<Self, BlockError> {
if len > MAX_BIO_BYTES {
return Err(BlockError::TooLarge);
}
let mut data = AdmittedVec::new(HeapClass::BlockingIo);
data.try_reserve_exact(len).map_err(|_| BlockError::NoMem)?;
for _ in 0..len {
data.push_reserved(0).map_err(|_| BlockError::NoMem)?;
}
Ok(Self { data })
}
/// Copy input into writable owned storage; never retain a source pointer.
pub fn from_slice(slice: &[u8]) -> Result<Self, BlockError> {
if slice.len() > MAX_BIO_BYTES {
return Err(BlockError::TooLarge);
}
let data = AdmittedVec::try_copy_from_slice(HeapClass::BlockingIo, slice)
.map_err(|_| BlockError::NoMem)?;
Ok(Self { data })
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
/// CPU address alignment is irrelevant to the driver's DMA bounce buffer.
pub fn is_aligned(&self, sector_size: u32) -> bool {
sector_size != 0 && self.len() % sector_size as usize == 0
}
pub fn as_slice(&self) -> &[u8] {
self.data.as_slice()
}
pub fn as_mut_slice(&mut self) -> &mut [u8] {
self.data.as_mut_slice()
}
}
/// Security context tag for LSM integration.
///
/// This tag carries file/inode context through the block layer,
/// allowing LSM policies to be enforced at the device level.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SecurityTag {
/// Inode number (0 if not applicable).
pub ino: u64,
/// File mode bits (type + permissions).
pub mode: u32,
/// Path hash for policy lookup (FNV-1a hash).
pub path_hash: u64,
/// Process ID that initiated the I/O.
pub pid: u32,
/// User ID that initiated the I/O.
pub uid: u32,
}
impl SecurityTag {
/// Create a new security tag with the given parameters.
pub const fn new(ino: u64, mode: u32, path_hash: u64, pid: u32, uid: u32) -> Self {
Self {
ino,
mode,
path_hash,
pid,
uid,
}
}
}
/// BIO completion result.
pub type BioResult = Result<usize, BlockError>;
/// Completion transfers `(result, owned_request)` after driver locks are released.
pub type BioComplete = Box<dyn FnOnce(BioResult, Bio) + Send + 'static>;
/// Block I/O request.
///
/// A Bio represents a single block I/O operation. It contains:
/// - The operation type (read/write/flush/discard)
/// - The starting sector (LBA)
/// - Scatter-gather list of buffers
/// - Optional completion callback for async operations
/// - Optional security tag for LSM integration
pub struct Bio {
/// Unique BIO ID for tracking.
pub id: u64,
/// Operation type.
pub op: BioOp,
/// Starting sector (logical block address).
pub sector: u64,
/// Number of sectors (used for Discard operations).
/// For Read/Write, this is derived from vecs.
pub num_sectors: u64,
/// Scatter-gather buffer list.
vecs: AdmittedVec<BioVec>,
/// Completion callback (called when I/O finishes).
completion: Option<BioComplete>,
/// Security context for LSM.
pub sec_tag: Option<SecurityTag>,
/// Device-private data (e.g., virtio descriptor index).
pub private: u64,
/// Timestamp when BIO was created (for latency tracking).
pub timestamp: u64,
}
// Global BIO ID counter
static BIO_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
impl Bio {
/// Create a new BIO for the given operation and starting sector.
///
/// P2-8 FIX: Use fetch_update + checked_add to prevent ID wrapping on u64
/// overflow, following the R105-5 pattern.
pub fn new(op: BioOp, sector: u64) -> Result<Self, BlockError> {
let id = BIO_ID_COUNTER
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
.map_err(|_| BlockError::NoMem)?;
Ok(Self {
id,
op,
sector,
num_sectors: 0,
vecs: AdmittedVec::new(HeapClass::Device),
completion: None,
sec_tag: None,
private: 0,
timestamp: 0, // Will be set by request queue
})
}
/// Create a new Discard BIO with explicit sector count.
pub fn new_discard(sector: u64, num_sectors: u64) -> Result<Self, BlockError> {
let id = BIO_ID_COUNTER
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
.map_err(|_| BlockError::NoMem)?;
Ok(Self {
id,
op: BioOp::Discard,
sector,
num_sectors,
vecs: AdmittedVec::new(HeapClass::Device),
completion: None,
sec_tag: None,
private: 0,
timestamp: 0,
})
}
/// Set the completion callback.
pub fn with_completion(mut self, cb: BioComplete) -> Self {
self.completion = Some(cb);
self
}
/// Set the security tag.
pub fn with_security_tag(mut self, tag: SecurityTag) -> Self {
self.sec_tag = Some(tag);
self
}
/// Add owned storage without allowing payload/count bounds to be bypassed.
pub fn push_vec(&mut self, bv: BioVec) -> Result<(), BlockError> {
if self.vecs.len() >= MAX_BIO_VECS
|| self
.total_len()
.checked_add(bv.len())
.filter(|len| *len <= MAX_BIO_BYTES)
.is_none()
{
return Err(BlockError::TooLarge);
}
self.vecs.try_push(bv).map_err(|_| BlockError::NoMem)
}
pub fn vectors(&self) -> &[BioVec] {
self.vecs.as_slice()
}
pub fn vector_mut(&mut self, index: usize) -> Option<&mut [u8]> {
self.vecs.get_mut(index).map(BioVec::as_mut_slice)
}
/// Private bounded vectors make the total infallible and nonoverflowing.
pub fn total_len(&self) -> usize {
self.vecs.iter().map(BioVec::len).sum()
}
pub fn total_sectors(&self, sector_size: u32) -> Result<u64, BlockError> {
if sector_size == 0 || self.total_len() % sector_size as usize != 0 {
return Err(BlockError::Invalid);
}
Ok((self.total_len() / sector_size as usize) as u64)
}
/// Validate the BIO against device constraints.
///
/// # Arguments
/// * `sector_size` - Device sector size in bytes
/// * `max_sectors` - Maximum sectors per BIO
/// * `device_capacity` - Total device capacity in sectors (for bounds check)
pub fn validate(
&self,
sector_size: u32,
max_sectors: u32,
device_capacity: u64,
) -> Result<(), BlockError> {
let geometry = BlockGeometry::from_logical(sector_size, device_capacity)?;
if self.op == BioOp::Flush {
return if self.vecs.is_empty() && self.num_sectors == 0 {
Ok(())
} else {
Err(BlockError::Invalid)
};
}
if self.op == BioOp::Discard {
if !self.vecs.is_empty() || self.num_sectors == 0 {
return Err(BlockError::Invalid);
}
if self.num_sectors > u64::from(max_sectors) {
return Err(BlockError::TooLarge);
}
let end = self
.sector
.checked_add(self.num_sectors)
.ok_or(BlockError::Invalid)?;
return if end <= geometry.capacity_sectors() {
Ok(())
} else {
Err(BlockError::Invalid)
};
}
if self.num_sectors != 0
|| self.vecs.is_empty()
|| self
.vecs
.iter()
.any(|v| v.is_empty() || !v.is_aligned(sector_size))
{
return Err(BlockError::Invalid);
}
if self.total_sectors(sector_size)? > u64::from(max_sectors) {
return Err(BlockError::TooLarge);
}
geometry
.request_start(self.sector, self.total_len())
.map(|_| ())
}
/// Transfer this completed request to its callback after driver locks drop.
/// Unsubmitted BIO drop does not invoke completion.
pub fn complete(mut self, result: BioResult) {
if let Some(cb) = self.completion.take() {
cb(result, self);
}
}
/// Check if this is a read operation.
#[inline]
pub fn is_read(&self) -> bool {
self.op == BioOp::Read
}
/// Check if this is a write operation.
#[inline]
pub fn is_write(&self) -> bool {
self.op == BioOp::Write
}
}
impl fmt::Debug for Bio {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Bio")
.field("id", &self.id)
.field("op", &self.op)
.field("sector", &self.sector)
.field("vecs", &self.vecs.len())
.field("total_len", &self.total_len())
.field("has_completion", &self.completion.is_some())
.field("sec_tag", &self.sec_tag)
.finish()
}
}
// ============================================================================
// Block Device Trait
// ============================================================================
/// Block device abstraction trait.
///
/// All block device drivers must implement this trait. It provides the
/// interface for submitting I/O requests and querying device properties.
pub trait BlockDevice: Send + Sync {
/// Get the device name (e.g., "vda", "sda").
fn name(&self) -> &str;
/// Get the logical sector size in bytes.
fn sector_size(&self) -> u32 {
DEFAULT_SECTOR_SIZE
}
/// Get the maximum sectors per BIO for this device.
fn max_sectors_per_bio(&self) -> u32 {
MAX_BIO_SECTORS
}
/// Total capacity in logical sectors of `sector_size()` bytes.
fn capacity_sectors(&self) -> u64;
/// Checked immutable geometry used by byte-oriented consumers.
fn geometry(&self) -> Result<BlockGeometry, BlockError> {
BlockGeometry::from_logical(self.sector_size(), self.capacity_sectors())
}
/// Check if the device is read-only.
fn is_read_only(&self) -> bool {
false
}
/// Submit a BIO for asynchronous processing.
///
/// Implementations may complete synchronously. Every terminal path calls
/// `bio.complete(result)` exactly once after releasing driver locks. A driver
/// must retire DMA or keep it pinned without caller access before completion.
fn submit_bio(&self, bio: Bio) -> Result<(), BlockError>;
/// Synchronously read sectors from the device.
///
/// This is a convenience method that creates a BIO and waits for completion.
/// Not all devices support synchronous I/O.
fn read_sync(&self, sector: u64, buf: &mut [u8]) -> Result<usize, BlockError> {
let _ = (sector, buf);
Err(BlockError::NotSupported)
}
/// Synchronously write sectors to the device.
///
/// This is a convenience method that creates a BIO and waits for completion.
/// Not all devices support synchronous I/O.
fn write_sync(&self, sector: u64, buf: &[u8]) -> Result<usize, BlockError> {
let _ = (sector, buf);
Err(BlockError::NotSupported)
}
/// Flush the device write cache.
fn flush(&self) -> Result<(), BlockError> {
Err(BlockError::NotSupported)
}
/// Quiesce a newly probed device whose publication transaction failed.
///
/// The caller must invoke this only before the device becomes reachable by
/// I/O clients. DMA-capable implementations must prove that the device can
/// no longer access owned buffers before returning `Ok(())`. Returning an
/// error requests quarantine: the caller must retain the final `Arc` and
/// all DMA ownership rather than releasing potentially live memory.
fn rollback_unpublished(&self) -> Result<(), BlockError> {
Ok(())
}
}
// ============================================================================
// Request Queue
// ============================================================================
/// Per-device request queue with FIFO scheduling.
///
/// The request queue provides:
/// - Thread-safe BIO enqueueing
/// - FIFO scheduling (simple but fair)
/// - Optional request merging (future enhancement)
/// - Back-pressure through queue depth limits
///
/// # Completion Semantics
///
/// On enqueue failure, the BIO's completion callback is automatically invoked
/// with the error. Pop transfers completion responsibility to the consumer;
/// dropping the queue completes remaining requests with `Offline`.
pub struct RequestQueue {
/// Queued BIOs waiting for processing (VecDeque for O(1) pop).
queue: Mutex<AdmittedDeque<Bio>>,
/// Maximum queue depth.
max_depth: usize,
/// Sector size for validation.
sector_size: u32,
/// Maximum sectors per BIO.
max_sectors: u32,
/// Device capacity in sectors (for bounds checking).
device_capacity: u64,
/// Statistics: total BIOs submitted.
stats_submitted: AtomicU64,
/// Statistics: total BIOs completed.
stats_completed: AtomicU64,
/// Statistics: total bytes transferred.
stats_bytes: AtomicU64,
/// Statistics: total BIOs rejected.
stats_rejected: AtomicU64,
}
impl RequestQueue {
/// Create a new request queue with the given parameters.
pub fn new(
sector_size: u32,
max_sectors: u32,
max_depth: usize,
device_capacity: u64,
) -> Result<Self, BlockError> {
BlockGeometry::from_logical(sector_size, device_capacity)?;
let mut queue = AdmittedDeque::new(HeapClass::Device);
queue
.try_reserve_exact(max_depth)
.map_err(|_| BlockError::NoMem)?;
Ok(Self {
queue: Mutex::new(queue),
max_depth,
sector_size,
max_sectors,
device_capacity,
stats_submitted: AtomicU64::new(0),
stats_completed: AtomicU64::new(0),
stats_bytes: AtomicU64::new(0),
stats_rejected: AtomicU64::new(0),
})
}
/// Enqueue a BIO for processing.
///
/// On failure, the BIO's completion callback is invoked with the error.
/// Returns `Err(BlockError::Busy)` if the queue is full.
pub fn enqueue(&self, bio: Bio) -> Result<(), BlockError> {
// Validate the BIO first
if let Err(e) = bio.validate(self.sector_size, self.max_sectors, self.device_capacity) {
self.stats_rejected.fetch_add(1, Ordering::Relaxed);
// Invoke completion with error so caller doesn't hang
bio.complete(Err(e));
return Err(e);
}
let mut q = self.queue.lock();
if q.len() >= self.max_depth {
self.stats_rejected.fetch_add(1, Ordering::Relaxed);
// Invoke completion with error so caller doesn't hang
drop(q);
bio.complete(Err(BlockError::Busy));
return Err(BlockError::Busy);
}
if let Err(bio) = q.push_back_reserved(bio) {
drop(q);
self.stats_rejected.fetch_add(1, Ordering::Relaxed);
bio.complete(Err(BlockError::NoMem));
return Err(BlockError::NoMem);
}
self.stats_submitted.fetch_add(1, Ordering::Relaxed);
Ok(())
}
/// Pop the next BIO from the queue (FIFO order, O(1)).
pub fn pop(&self) -> Option<Bio> {
self.queue.lock().pop_front_retaining_capacity()
}
/// Get the current queue depth.
#[inline]
pub fn len(&self) -> usize {
self.queue.lock().len()
}
/// Check if the queue is empty.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Check if the queue is full.
#[inline]
pub fn is_full(&self) -> bool {
self.len() >= self.max_depth
}
/// Record a completed BIO (for statistics).
pub fn record_completion(&self, bytes: usize) {
self.stats_completed.fetch_add(1, Ordering::Relaxed);
self.stats_bytes.fetch_add(bytes as u64, Ordering::Relaxed);
}
/// Get queue statistics.
pub fn stats(&self) -> RequestQueueStats {
RequestQueueStats {
submitted: self.stats_submitted.load(Ordering::Relaxed),
completed: self.stats_completed.load(Ordering::Relaxed),
rejected: self.stats_rejected.load(Ordering::Relaxed),
bytes_transferred: self.stats_bytes.load(Ordering::Relaxed),
current_depth: self.len(),
max_depth: self.max_depth,
}
}
}
impl Drop for RequestQueue {
fn drop(&mut self) {
// Exclusive ownership: no mutex guard or queue lock crosses callbacks.
while let Some(bio) = self.queue.get_mut().pop_front_retaining_capacity() {
bio.complete(Err(BlockError::Offline));
}
}
}
/// Request queue statistics.
#[derive(Debug, Clone, Copy)]
pub struct RequestQueueStats {
/// Total BIOs submitted successfully.
pub submitted: u64,
/// Total BIOs completed.
pub completed: u64,
/// Total BIOs rejected (validation failed or queue full).
pub rejected: u64,
/// Total bytes transferred.
pub bytes_transferred: u64,
/// Current queue depth.
pub current_depth: usize,
/// Maximum queue depth.
pub max_depth: usize,
}
// ============================================================================
// Block Device Registry
// ============================================================================
/// Registered block device entry.
struct RegisteredDevice {
/// Device instance.
device: Arc<dyn BlockDevice>,
/// Minor device number.
minor: u32,
}
/// Global block device registry.
///
/// Provides device registration, lookup by name/minor number,
/// and integration with devfs.
pub struct BlockDeviceRegistry {
/// Registered devices. Fixed storage makes publication allocation-free;
/// device names remain owned by the device itself.
devices: RwLock<[Option<RegisteredDevice>; MAX_BLOCK_DEVICES]>,
/// Next minor number to assign.
next_minor: AtomicU64,
}
impl BlockDeviceRegistry {
/// Create a new registry.
pub const fn new() -> Self {
Self {
devices: RwLock::new([const { None }; MAX_BLOCK_DEVICES]),
next_minor: AtomicU64::new(0),
}
}
/// Register a new block device.
///
/// Returns the assigned minor number on success.
pub fn register(&self, device: Arc<dyn BlockDevice>) -> Result<u32, BlockError> {
// R180-27 FIX: fixed slots and device-owned names make the complete
// registry mutation allocation-free after DRIVER_OK.
let mut devices = self.devices.write();
// Check for duplicate name
if devices
.iter()
.flatten()
.any(|registered| registered.device.name() == device.name())
{
return Err(BlockError::Invalid);
}
let slot = devices
.iter()
.position(Option::is_none)
.ok_or(BlockError::NoMem)?;
// P2-8 FIX: Use fetch_update + checked_add to prevent minor number
// wrapping on overflow, following the R105-5 pattern.
let minor = self
.next_minor
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |id| {
(id <= u32::MAX as u64).then(|| id + 1)
})
.map_err(|_| BlockError::NoMem)?;
let minor = u32::try_from(minor).map_err(|_| BlockError::NoMem)?;
devices[slot] = Some(RegisteredDevice { device, minor });
Ok(minor)
}
/// Unregister a block device by name.
pub fn unregister(&self, name: &str) -> Result<(), BlockError> {
let mut devices = self.devices.write();
let pos = devices
.iter()
.position(|entry| {
entry
.as_ref()
.is_some_and(|registered| registered.device.name() == name)
})
.ok_or(BlockError::NotFound)?;
devices[pos] = None;
Ok(())
}
/// Look up a device by name.
pub fn get_by_name(&self, name: &str) -> Option<Arc<dyn BlockDevice>> {
let devices = self.devices.read();
devices
.iter()
.flatten()
.find(|registered| registered.device.name() == name)
.map(|registered| Arc::clone(®istered.device))
}
/// Look up a device by minor number.
pub fn get_by_minor(&self, minor: u32) -> Option<Arc<dyn BlockDevice>> {
let devices = self.devices.read();
devices
.iter()
.flatten()
.find(|registered| registered.minor == minor)
.map(|registered| Arc::clone(®istered.device))
}
/// Get list of all registered device names.
pub fn list_devices(&self) -> Result<Vec<String>, BlockError> {
let devices = self.devices.read();
let mut names = Vec::new();
let count = devices.iter().flatten().count();
names
.try_reserve_exact(count)
.map_err(|_| BlockError::NoMem)?;
for registered in devices.iter().flatten() {
let source_name = registered.device.name();
let mut name = String::new();
name.try_reserve_exact(source_name.len())
.map_err(|_| BlockError::NoMem)?;
name.push_str(source_name);
names.push(name);
}
Ok(names)
}
/// Get the number of registered devices.
pub fn count(&self) -> usize {
self.devices.read().iter().flatten().count()
}
}
// Global registry instance
lazy_static::lazy_static! {
/// Global block device registry.
pub static ref BLOCK_REGISTRY: BlockDeviceRegistry = BlockDeviceRegistry::new();
}
// ============================================================================
// Public API
// ============================================================================
/// Register a block device.
pub fn register_device(device: Arc<dyn BlockDevice>) -> Result<u32, BlockError> {
let geometry = device.geometry()?;
let minor = BLOCK_REGISTRY.register(device.clone())?;
klog!(
Info,
" Block device registered: {} (minor={}, capacity={}MB)",
device.name(),
minor,
geometry.capacity_bytes() / (1024 * 1024)
);
Ok(minor)
}
/// Unregister a block device.
pub fn unregister_device(name: &str) -> Result<(), BlockError> {
BLOCK_REGISTRY.unregister(name)
}
/// Get a block device by name.
pub fn get_device(name: &str) -> Option<Arc<dyn BlockDevice>> {
BLOCK_REGISTRY.get_by_name(name)
}
/// Get a block device by minor number.
pub fn get_device_by_minor(minor: u32) -> Option<Arc<dyn BlockDevice>> {
BLOCK_REGISTRY.get_by_minor(minor)
}
/// List all registered block devices.
pub fn list_devices() -> Result<Vec<String>, BlockError> {
BLOCK_REGISTRY.list_devices()
}
/// A ready VirtIO block device that has not completed kernel publication.
///
/// Dropping this guard rolls back `DRIVER_OK`. If hardware quiescence cannot be
/// proven, the final Arc is deliberately quarantined so DMA-owned memory is
/// never returned to the allocator. `commit` is the only way to disarm it.
pub struct ProbedBlockDevice {
pending: Option<(Arc<dyn BlockDevice>, &'static str)>,
mmio_mapping: Option<BlockPciMmioMapping>,
}
impl ProbedBlockDevice {
fn new(device: Arc<dyn BlockDevice>, name: &'static str) -> Self {
Self {
pending: Some((device, name)),
mmio_mapping: None,
}
}
fn new_pci(
device: Arc<dyn BlockDevice>,
name: &'static str,
mmio_mapping: BlockPciMmioMapping,
) -> Self {
Self {
pending: Some((device, name)),
mmio_mapping: Some(mmio_mapping),
}
}
pub fn name(&self) -> &'static str {
self.pending
.as_ref()
.map(|(_, name)| *name)
.expect("probed block device already committed")
}
pub fn device(&self) -> Arc<dyn BlockDevice> {
Arc::clone(
&self
.pending
.as_ref()
.expect("probed block device already committed")
.0,
)
}
/// Finish publication after every registry has committed successfully.
pub fn commit(mut self) -> (Arc<dyn BlockDevice>, &'static str) {
if let Some(mapping) = self.mmio_mapping.take() {
mapping.commit();
}
self.pending
.take()
.expect("probed block device committed twice")
}
}
impl Drop for ProbedBlockDevice {
fn drop(&mut self) {
let Some((device, name)) = self.pending.take() else {
return;
};
if let Err(error) = device.rollback_unpublished() {
#[cfg(not(test))]
klog_force!(
"R180-27: /dev/{} publication rollback could not prove DMA quiescence: {:?}; quarantining device ownership",
name,
error
);
#[cfg(test)]
let _ = (name, error);
core::mem::forget(device);
if let Some(mapping) = self.mmio_mapping.take() {
// Quarantine the VA reservation/mapping with the device whose
// quiescence could not be proven. Reusing it would let a later
// device inherit an alias still associated with failed hardware.
mapping.quarantine();
}
}
}
}
// ============================================================================
// Initialization
// ============================================================================
/// Initialize the block layer subsystem.
pub fn init() {
klog_always!(" Block layer initialized");
klog_always!(" Max BIO size: {} KB", MAX_BIO_BYTES / 1024);
klog_always!(" Default sector size: {} bytes", DEFAULT_SECTOR_SIZE);
}
// ============================================================================
// High Address MMIO Mapping
// ============================================================================
/// Base virtual address for mapping MMIO regions above 4GB.
/// This is in the kernel's higher-half address space, separate from the kernel image.
const HIGH_MMIO_VIRT_BASE: u64 = 0xffff_ffff_4000_0000;
/// Maximum size of the high MMIO virtual address region (256 MB).
const HIGH_MMIO_VIRT_SIZE: u64 = 256 * 1024 * 1024;
/// Serialized VA allocator. Its guard remains held until the probed block
/// device either commits publication or rolls back, making the bump rewindable.
static HIGH_MMIO_OFFSET: Mutex<u64> = Mutex::new(0);
#[derive(Clone, Copy, Debug, Default)]
struct BlockMmioWindow {
phys: u64,
len: usize,
}
struct BlockPciMmioMapping {
allocator: Option<spin::MutexGuard<'static, u64>>,
reservation_start: u64,
phys_anchor: u64,