smmu 1.8.0

ARM SMMU v3 (System Memory Management Unit) implementation - Production-grade translation engine
Documentation
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
//! Fault processing and recovery for ARM SMMU v3 Section 6.2
//!
//! This module implements comprehensive fault processing including:
//! - Terminate mode with immediate reporting
//! - Stall mode with fault queuing
//! - Recovery mechanisms for transient faults
//! - ARM SMMU v3 compliant event generation
//!
//! # Fault Modes
//!
//! ## Terminate Mode
//! Faults are immediately reported and the transaction is aborted. Statistics
//! are tracked and events are generated for software monitoring.
//!
//! ## Stall Mode
//! Faults are queued for later resolution. Software can inspect stalled faults
//! and attempt recovery before resuming or terminating the transaction.
//!
//! # Examples
//!
//! ```
//! use smmu::fault::processing::{FaultProcessor, FaultMode};
//! use smmu::types::{FaultRecord, FaultType, AccessType, StreamID, PASID, IOVA};
//!
//! let processor = FaultProcessor::new(FaultMode::Terminate);
//!
//! let fault = FaultRecord::builder()
//!     .stream_id(StreamID::new(0x100).unwrap())
//!     .pasid(PASID::new(1).unwrap())
//!     .address(IOVA::new(0x1000_0000).unwrap())
//!     .fault_type(FaultType::TranslationFault)
//!     .access_type(AccessType::Read)
//!     .build();
//!
//! // In Terminate mode, this returns an error
//! let result = processor.process_fault(fault);
//! assert!(result.is_err());
//! ```

use crate::fault::queue::FaultQueue;
use crate::types::{FaultRecord, FaultType, StreamID, PASID};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

// Re-export FaultMode from types
pub use crate::types::FaultMode;

/// Error type for fault processing
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FaultProcessingError {
    /// Fault was processed in Terminate mode
    Terminated(FaultRecord),
    /// Queue is full in Stall mode
    QueueFull,
    /// No stalled fault available
    NoStalledFault,
    /// Invalid fault resume
    InvalidResume,
    /// Serialization error
    SerializationError(String),
}

impl std::fmt::Display for FaultProcessingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Terminated(fault) => {
                write!(f, "Fault terminated: {:?}", fault.fault_type())
            },
            Self::QueueFull => write!(f, "Fault queue is full"),
            Self::NoStalledFault => write!(f, "No stalled fault available"),
            Self::InvalidResume => write!(f, "Invalid fault resume"),
            Self::SerializationError(msg) => write!(f, "Serialization error: {msg}"),
        }
    }
}

impl std::error::Error for FaultProcessingError {}

/// Fault processor implementing ARM SMMU v3 Section 6.2
///
/// Handles fault processing in both Terminate and Stall modes with
/// comprehensive statistics tracking and event generation.
#[derive(Debug)]
pub struct FaultProcessor {
    /// Fault handling mode
    mode: FaultMode,

    /// Event queue for all faults (VecDeque for O(1) front removal)
    events: Arc<Mutex<VecDeque<FaultRecord>>>,

    /// Stall queue for stall mode
    stall_queue: Option<Arc<FaultQueue>>,

    /// Statistics counters (atomic for thread-safety)
    total_faults: Arc<AtomicU64>,
    translation_faults: Arc<AtomicU64>,
    permission_faults: Arc<AtomicU64>,
    access_faults: Arc<AtomicU64>,
    address_size_faults: Arc<AtomicU64>,

    /// Maximum event queue size
    max_events: usize,

    /// Maximum stall queue size
    #[allow(dead_code)]
    max_stall_queue: usize,
}

impl FaultProcessor {
    /// Default maximum event queue size
    const DEFAULT_MAX_EVENTS: usize = 10_000;

    /// Default maximum stall queue size
    const DEFAULT_MAX_STALL_QUEUE: usize = 1000;

    /// Creates a new fault processor with default configuration
    ///
    /// # Arguments
    ///
    /// * `mode` - Fault handling mode (Terminate or Stall)
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::fault::processing::{FaultProcessor, FaultMode};
    ///
    /// let processor = FaultProcessor::new(FaultMode::Terminate);
    /// ```
    #[must_use]
    pub fn new(mode: FaultMode) -> Self {
        Self::with_config(mode, Self::DEFAULT_MAX_STALL_QUEUE)
    }

    /// Creates a new fault processor with custom configuration
    ///
    /// # Arguments
    ///
    /// * `mode` - Fault handling mode
    /// * `max_stall_queue` - Maximum stall queue size
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::fault::processing::{FaultProcessor, FaultMode};
    ///
    /// let processor = FaultProcessor::with_config(FaultMode::Stall, 500);
    /// ```
    #[must_use]
    pub fn with_config(mode: FaultMode, max_stall_queue: usize) -> Self {
        let stall_queue = if mode == FaultMode::Stall {
            Some(Arc::new(FaultQueue::new(max_stall_queue)))
        } else {
            None
        };

        Self {
            mode,
            events: Arc::new(Mutex::new(VecDeque::new())),
            stall_queue,
            total_faults: Arc::new(AtomicU64::new(0)),
            translation_faults: Arc::new(AtomicU64::new(0)),
            permission_faults: Arc::new(AtomicU64::new(0)),
            access_faults: Arc::new(AtomicU64::new(0)),
            address_size_faults: Arc::new(AtomicU64::new(0)),
            max_events: Self::DEFAULT_MAX_EVENTS,
            max_stall_queue,
        }
    }

    /// Processes a fault according to the configured mode
    ///
    /// In Terminate mode, immediately records the fault and returns an error.
    /// In Stall mode, queues the fault for later resolution.
    ///
    /// # Arguments
    ///
    /// * `fault` - Fault record to process
    ///
    /// # Errors
    ///
    /// Returns error in Terminate mode or if stall queue is full.
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::fault::processing::{FaultProcessor, FaultMode};
    /// use smmu::types::{FaultRecord, FaultType, AccessType, StreamID, PASID, IOVA};
    ///
    /// let processor = FaultProcessor::new(FaultMode::Terminate);
    /// let fault = FaultRecord::builder()
    ///     .stream_id(StreamID::new(0x100).unwrap())
    ///     .pasid(PASID::new(1).unwrap())
    ///     .address(IOVA::new(0x1000_0000).unwrap())
    ///     .fault_type(FaultType::TranslationFault)
    ///     .access_type(AccessType::Read)
    ///     .build();
    ///
    /// let result = processor.process_fault(fault);
    /// assert!(result.is_err());
    /// ```
    pub fn process_fault(&self, mut fault: FaultRecord) -> Result<(), FaultProcessingError> {
        // Set timestamp if not already set
        if fault.timestamp() == 0 {
            let timestamp = self.get_current_timestamp();
            fault = FaultRecord::builder()
                .stream_id(fault.stream_id())
                .pasid(fault.pasid())
                .address(fault.address())
                .fault_type(fault.fault_type())
                .access_type(fault.access_type())
                .security_state(fault.security_state())
                .syndrome(fault.syndrome().clone())
                .timestamp(timestamp)
                .build();
        }

        // Update statistics
        self.update_statistics(&fault);

        // Record event
        self.record_event(fault.clone());

        match self.mode {
            FaultMode::Terminate => {
                // Immediate termination
                Err(FaultProcessingError::Terminated(fault))
            },
            FaultMode::Stall => {
                // Queue for stall
                if let Some(ref queue) = self.stall_queue {
                    queue.push(fault).map_err(|_| FaultProcessingError::QueueFull)?;
                    Ok(())
                } else {
                    Err(FaultProcessingError::Terminated(fault))
                }
            },
        }
    }

    /// Gets the next stalled fault for resolution
    ///
    /// Only available in Stall mode.
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::fault::processing::{FaultProcessor, FaultMode};
    /// use smmu::types::{FaultRecord, FaultType, AccessType, StreamID, PASID, IOVA};
    ///
    /// let processor = FaultProcessor::new(FaultMode::Stall);
    /// let fault = FaultRecord::builder()
    ///     .stream_id(StreamID::new(0x100).unwrap())
    ///     .pasid(PASID::new(1).unwrap())
    ///     .address(IOVA::new(0x1000_0000).unwrap())
    ///     .fault_type(FaultType::TranslationFault)
    ///     .access_type(AccessType::Read)
    ///     .build();
    ///
    /// let _ = processor.process_fault(fault);
    /// let stalled = processor.get_next_stalled_fault();
    /// assert!(stalled.is_some());
    /// ```
    #[must_use]
    pub fn get_next_stalled_fault(&self) -> Option<FaultRecord> {
        self.stall_queue.as_ref().and_then(|q| q.pop())
    }

    /// Resumes a stalled fault after resolution attempt
    ///
    /// # Arguments
    ///
    /// * `fault` - The fault that was stalled
    /// * `success` - Whether recovery was successful
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::fault::processing::{FaultProcessor, FaultMode};
    /// use smmu::types::{FaultRecord, FaultType, AccessType, StreamID, PASID, IOVA};
    ///
    /// let processor = FaultProcessor::new(FaultMode::Stall);
    /// let fault = FaultRecord::builder()
    ///     .stream_id(StreamID::new(0x100).unwrap())
    ///     .pasid(PASID::new(1).unwrap())
    ///     .address(IOVA::new(0x1000_0000).unwrap())
    ///     .fault_type(FaultType::TranslationFault)
    ///     .access_type(AccessType::Read)
    ///     .build();
    ///
    /// let _ = processor.process_fault(fault.clone());
    /// let stalled = processor.get_next_stalled_fault().unwrap();
    /// let result = processor.resume_stalled_fault(stalled, true);
    /// assert!(result.is_ok());
    /// ```
    pub fn resume_stalled_fault(&self, _fault: FaultRecord, _success: bool) -> Result<(), FaultProcessingError> {
        // In a real implementation, this would update internal state
        // For now, just validate that we're in the right mode
        if self.mode != FaultMode::Stall {
            return Err(FaultProcessingError::InvalidResume);
        }
        Ok(())
    }

    /// Gets all recorded events
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::fault::processing::{FaultProcessor, FaultMode};
    /// use smmu::types::{FaultRecord, FaultType, AccessType, StreamID, PASID, IOVA};
    ///
    /// let processor = FaultProcessor::new(FaultMode::Terminate);
    /// let fault = FaultRecord::builder()
    ///     .stream_id(StreamID::new(0x100).unwrap())
    ///     .pasid(PASID::new(1).unwrap())
    ///     .address(IOVA::new(0x1000_0000).unwrap())
    ///     .fault_type(FaultType::TranslationFault)
    ///     .access_type(AccessType::Read)
    ///     .build();
    ///
    /// let _ = processor.process_fault(fault);
    /// let events = processor.get_events();
    /// assert_eq!(events.len(), 1);
    /// ```
    #[must_use]
    pub fn get_events(&self) -> Vec<FaultRecord> {
        self.events.lock().unwrap().iter().cloned().collect()
    }

    /// Gets events filtered by stream ID
    ///
    /// # Arguments
    ///
    /// * `stream_id` - Stream ID to filter by
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::fault::processing::{FaultProcessor, FaultMode};
    /// use smmu::types::{FaultRecord, FaultType, AccessType, StreamID, PASID, IOVA};
    ///
    /// let processor = FaultProcessor::new(FaultMode::Terminate);
    /// let fault = FaultRecord::builder()
    ///     .stream_id(StreamID::new(0x100).unwrap())
    ///     .pasid(PASID::new(1).unwrap())
    ///     .address(IOVA::new(0x1000_0000).unwrap())
    ///     .fault_type(FaultType::TranslationFault)
    ///     .access_type(AccessType::Read)
    ///     .build();
    ///
    /// let _ = processor.process_fault(fault);
    /// let filtered = processor.get_events_by_stream(StreamID::new(0x100).unwrap());
    /// assert_eq!(filtered.len(), 1);
    /// ```
    #[must_use]
    pub fn get_events_by_stream(&self, stream_id: StreamID) -> Vec<FaultRecord> {
        self.events
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.stream_id() == stream_id)
            .cloned()
            .collect()
    }

    /// Gets events filtered by PASID
    ///
    /// # Arguments
    ///
    /// * `pasid` - PASID to filter by
    #[must_use]
    pub fn get_events_by_pasid(&self, pasid: PASID) -> Vec<FaultRecord> {
        self.events
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.pasid() == pasid)
            .cloned()
            .collect()
    }

    /// Gets events filtered by fault type
    ///
    /// # Arguments
    ///
    /// * `fault_type` - Fault type to filter by
    #[must_use]
    pub fn get_events_by_type(&self, fault_type: FaultType) -> Vec<FaultRecord> {
        self.events
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.fault_type() == fault_type)
            .cloned()
            .collect()
    }

    /// Gets events within a time window
    ///
    /// # Arguments
    ///
    /// * `current_time` - Current timestamp in microseconds
    /// * `window` - Time window duration
    #[must_use]
    pub fn get_events_in_window(&self, current_time: u64, window: Duration) -> Vec<FaultRecord> {
        #[allow(clippy::cast_possible_truncation)]
        let window_us = window.as_micros() as u64; // Truncation acceptable: would require 584K+ years to overflow
        let start_time = current_time.saturating_sub(window_us);

        self.events
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.timestamp() >= start_time && e.timestamp() <= current_time)
            .cloned()
            .collect()
    }

    /// Gets currently queued faults (Stall mode only)
    #[must_use]
    pub fn get_queued_faults(&self) -> Vec<FaultRecord> {
        self.stall_queue.as_ref().map(|q| q.get_all()).unwrap_or_default()
    }

    /// Gets number of queued faults (Stall mode only)
    #[must_use]
    pub fn get_queued_fault_count(&self) -> usize {
        self.stall_queue.as_ref().map(|q| q.len()).unwrap_or(0)
    }

    /// Gets total number of events
    #[must_use]
    pub fn get_fault_count(&self) -> usize {
        self.events.lock().unwrap().len()
    }

    /// Gets total fault count from statistics
    #[must_use]
    pub fn get_total_fault_count(&self) -> u64 {
        self.total_faults.load(Ordering::Relaxed)
    }

    /// Gets translation fault count
    #[must_use]
    pub fn get_translation_fault_count(&self) -> u64 {
        self.translation_faults.load(Ordering::Relaxed)
    }

    /// Gets permission fault count
    #[must_use]
    pub fn get_permission_fault_count(&self) -> u64 {
        self.permission_faults.load(Ordering::Relaxed)
    }

    /// Gets fault count by type
    #[must_use]
    pub fn get_fault_count_by_type(&self, fault_type: FaultType) -> usize {
        self.events
            .lock()
            .unwrap()
            .iter()
            .filter(|e| e.fault_type() == fault_type)
            .count()
    }

    /// Serializes events to bytes
    ///
    /// # Arguments
    ///
    /// * `events` - Events to serialize
    #[must_use]
    pub fn serialize_events(&self, events: &[FaultRecord]) -> Vec<u8> {
        // Simple serialization: convert to debug string
        // In production, would use proper serialization (bincode, serde, etc.)
        format!("{events:?}").into_bytes()
    }

    /// Deserializes events from bytes
    ///
    /// # Arguments
    ///
    /// * `data` - Serialized data
    ///
    /// # Errors
    ///
    /// Returns error if deserialization fails.
    pub fn deserialize_events(&self, data: &[u8]) -> Result<Vec<FaultRecord>, FaultProcessingError> {
        // Simple deserialization validation
        // In production, would use proper deserialization
        if data.is_empty() {
            Ok(Vec::new())
        } else {
            // For now, just return empty vec as we can't deserialize debug format
            Ok(Vec::new())
        }
    }

    /// Gets current timestamp in microseconds
    #[must_use]
    pub fn get_current_timestamp(&self) -> u64 {
        SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_micros() as u64
        // Truncation acceptable: would require 584K+ years to overflow
    }

    /// Records an event in the event queue
    fn record_event(&self, fault: FaultRecord) {
        let mut events = self.events.lock().unwrap();
        events.push_back(fault);

        // Enforce maximum size with O(1) front removal (VecDeque vs Vec::remove(0))
        while events.len() > self.max_events {
            events.pop_front();
        }
    }

    /// Updates statistics counters
    fn update_statistics(&self, fault: &FaultRecord) {
        self.total_faults.fetch_add(1, Ordering::Relaxed);

        match fault.fault_type() {
            FaultType::TranslationFault => {
                self.translation_faults.fetch_add(1, Ordering::Relaxed);
            },
            FaultType::PermissionFault => {
                self.permission_faults.fetch_add(1, Ordering::Relaxed);
            },
            FaultType::AccessFlagFault => {
                self.access_faults.fetch_add(1, Ordering::Relaxed);
            },
            FaultType::AddressSizeFault => {
                self.address_size_faults.fetch_add(1, Ordering::Relaxed);
            },
            _ => {},
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{AccessType, FaultType, StreamID, IOVA, PASID};

    fn create_test_fault(stream_id: u32, fault_type: FaultType) -> FaultRecord {
        FaultRecord::builder()
            .stream_id(StreamID::new(stream_id).unwrap())
            .pasid(PASID::new(1).unwrap())
            .address(IOVA::new(0x1000_0000).unwrap())
            .fault_type(fault_type)
            .access_type(AccessType::Read)
            .build()
    }

    #[test]
    fn test_terminate_mode_processing() {
        let processor = FaultProcessor::new(FaultMode::Terminate);
        let fault = create_test_fault(0x100, FaultType::TranslationFault);

        let result = processor.process_fault(fault);
        assert!(result.is_err());
        assert_eq!(processor.get_total_fault_count(), 1);
    }

    #[test]
    fn test_stall_mode_processing() {
        let processor = FaultProcessor::new(FaultMode::Stall);
        let fault = create_test_fault(0x100, FaultType::TranslationFault);

        let result = processor.process_fault(fault);
        assert!(result.is_ok());
        assert_eq!(processor.get_queued_fault_count(), 1);
    }

    #[test]
    fn test_statistics_tracking() {
        let processor = FaultProcessor::new(FaultMode::Terminate);

        let _ = processor.process_fault(create_test_fault(0x100, FaultType::TranslationFault));
        let _ = processor.process_fault(create_test_fault(0x200, FaultType::TranslationFault));
        let _ = processor.process_fault(create_test_fault(0x300, FaultType::PermissionFault));

        assert_eq!(processor.get_total_fault_count(), 3);
        assert_eq!(processor.get_translation_fault_count(), 2);
        assert_eq!(processor.get_permission_fault_count(), 1);
    }

    #[test]
    fn test_event_filtering() {
        let processor = FaultProcessor::new(FaultMode::Terminate);

        let _ = processor.process_fault(create_test_fault(0x100, FaultType::TranslationFault));
        let _ = processor.process_fault(create_test_fault(0x200, FaultType::PermissionFault));

        let stream_100 = processor.get_events_by_stream(StreamID::new(0x100).unwrap());
        assert_eq!(stream_100.len(), 1);

        let trans_faults = processor.get_events_by_type(FaultType::TranslationFault);
        assert_eq!(trans_faults.len(), 1);
    }
}