smmu 1.6.5

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
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
//! Page Entry structures for ARM SMMU v3
//!
//! This module defines the PageEntry and PagePermissions structures used for
//! page table entries in address translation. All implementations are safe
//! with zero unsafe code.

use super::{AccessType, SecurityState, PA};

/// Page access permissions structure
///
/// Defines read/write/execute permissions for memory pages following ARM
/// architecture memory permissions model. This structure uses a packed bitfield
/// representation for optimal cache efficiency (1 byte total).
///
/// # Memory Layout
///
/// Packed into a single byte with bits:
/// - Bit 0: Read permission
/// - Bit 1: Write permission
/// - Bit 2: Execute permission
/// - Bit 3: Privileged-only access (GAP-2: STE.STRW privilege check)
/// - Bits 4-7: Reserved (future use)
///
/// # Examples
///
/// ```
/// use smmu::types::PagePermissions;
///
/// // Create read-only permissions
/// let read_only = PagePermissions::read_only();
/// assert!(read_only.read());
/// assert!(!read_only.write());
///
/// // Create read-write permissions
/// let read_write = PagePermissions::read_write();
/// assert!(read_write.read() && read_write.write());
///
/// // Create privileged-only read permissions
/// let priv_read = PagePermissions::read_only_privileged();
/// assert!(priv_read.read());
/// assert!(priv_read.privileged_only());
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PagePermissions(u8);

impl PagePermissions {
    /// Bitfield constants
    const READ: u8 = 0b0001;
    const WRITE: u8 = 0b0010;
    const EXEC: u8 = 0b0100;
    /// Bit 3: privileged-only access restriction (GAP-2 STE.STRW)
    const PRIV_ONLY: u8 = 0b1000;

    /// Creates new PagePermissions with explicit flags
    ///
    /// # Arguments
    ///
    /// * `read` - Read permission
    /// * `write` - Write permission
    /// * `execute` - Execute permission
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::PagePermissions;
    ///
    /// let perms = PagePermissions::new(true, false, false);
    /// assert!(perms.read());
    /// ```
    #[must_use]
    #[inline]
    pub const fn new(read: bool, write: bool, execute: bool) -> Self {
        let mut bits = 0u8;
        if read {
            bits |= Self::READ;
        }
        if write {
            bits |= Self::WRITE;
        }
        if execute {
            bits |= Self::EXEC;
        }
        Self(bits)
    }

    /// Creates permissions with no access allowed
    #[must_use]
    #[inline]
    pub const fn none() -> Self {
        Self::new(false, false, false)
    }

    /// Creates read-only permissions
    #[must_use]
    #[inline]
    pub const fn read_only() -> Self {
        Self::new(true, false, false)
    }

    /// Creates read-only privileged-only permissions (GAP-2: STE.STRW)
    ///
    /// Access is restricted to privileged callers unless STRW=EL2 or STRW=EL3
    /// suppresses the privilege check.
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::PagePermissions;
    ///
    /// let perms = PagePermissions::read_only_privileged();
    /// assert!(perms.read());
    /// assert!(!perms.write());
    /// assert!(perms.privileged_only());
    /// ```
    #[must_use]
    #[inline]
    pub const fn read_only_privileged() -> Self {
        Self(Self::READ | Self::PRIV_ONLY)
    }

    /// Returns a new `PagePermissions` with the `privileged_only` bit set or cleared.
    ///
    /// When `true`, the page is only accessible to privileged accesses unless
    /// STRW=EL2 or STRW=EL3 suppresses the check (ARM §5.2 STE.STRW, GAP-2).
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::PagePermissions;
    ///
    /// let perms = PagePermissions::read_write().with_privileged_only(true);
    /// assert!(perms.privileged_only());
    /// let perms2 = perms.with_privileged_only(false);
    /// assert!(!perms2.privileged_only());
    /// ```
    #[must_use]
    #[inline]
    pub const fn with_privileged_only(self, priv_only: bool) -> Self {
        if priv_only {
            Self(self.0 | Self::PRIV_ONLY)
        } else {
            Self(self.0 & !Self::PRIV_ONLY)
        }
    }

    /// Creates write-only permissions
    #[must_use]
    #[inline]
    pub const fn write_only() -> Self {
        Self::new(false, true, false)
    }

    /// Creates execute-only permissions
    #[must_use]
    #[inline]
    pub const fn execute_only() -> Self {
        Self::new(false, false, true)
    }

    /// Creates read-write permissions
    #[must_use]
    #[inline]
    pub const fn read_write() -> Self {
        Self::new(true, true, false)
    }

    /// Creates read-execute permissions
    #[must_use]
    #[inline]
    pub const fn read_execute() -> Self {
        Self::new(true, false, true)
    }

    /// Creates all permissions (read, write, execute)
    #[must_use]
    #[inline]
    pub const fn all() -> Self {
        Self::new(true, true, true)
    }

    /// Returns true if read permission is allowed
    #[must_use]
    #[inline(always)]
    pub const fn read(self) -> bool {
        (self.0 & Self::READ) != 0
    }

    /// Returns true if write permission is allowed
    #[must_use]
    #[inline(always)]
    pub const fn write(self) -> bool {
        (self.0 & Self::WRITE) != 0
    }

    /// Returns true if execute permission is allowed
    #[must_use]
    #[inline(always)]
    pub const fn execute(self) -> bool {
        (self.0 & Self::EXEC) != 0
    }

    /// Returns true if access is restricted to privileged callers (GAP-2: STE.STRW)
    ///
    /// When `true`, the stream context's STRW field determines whether to enforce
    /// or suppress this restriction: STRW=EL2 and STRW=EL3 suppress the check.
    ///
    /// Note: The [`allows()`](Self::allows) method does NOT check this flag; it is
    /// evaluated separately at the stream-context translate level.
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::PagePermissions;
    ///
    /// assert!(!PagePermissions::read_only().privileged_only());
    /// assert!(PagePermissions::read_only_privileged().privileged_only());
    /// ```
    #[must_use]
    #[inline(always)]
    pub const fn privileged_only(self) -> bool {
        (self.0 & Self::PRIV_ONLY) != 0
    }

    /// Checks if the given access type is allowed
    ///
    /// # Arguments
    ///
    /// * `access` - The access type to check
    ///
    /// # Returns
    ///
    /// `true` if the access is allowed, `false` otherwise
    #[must_use]
    #[inline]
    pub const fn allows(self, access: AccessType) -> bool {
        match access {
            AccessType::None => true, // No access required, always allowed
            AccessType::Read => self.read(),
            AccessType::Write => self.write(),
            AccessType::Execute => self.execute(),
            AccessType::ReadWrite => self.read() && self.write(),
            AccessType::ReadExecute => self.read() && self.execute(),
            AccessType::WriteExecute => self.write() && self.execute(),
            AccessType::ReadWriteExecute => self.read() && self.write() && self.execute(),
            // Bug-4 fix: privileged variants — privilege bit does not affect R/W/X permission check;
            // the privilege level is handled separately by the UWXN/PRIVCFG path.
            AccessType::ReadPrivileged => self.read(),
            AccessType::WritePrivileged => self.write(),
            AccessType::ReadWritePrivileged => self.read() && self.write(),
            AccessType::ExecutePrivileged => self.execute(),
            // BUG-RUST-5 fix: compound-execute privileged variants (bit-3 set; R/W/X same as unprivileged equivalents).
            AccessType::ReadExecutePrivileged => self.read() && self.execute(),
            AccessType::WriteExecutePrivileged => self.write() && self.execute(),
            AccessType::ReadWriteExecutePrivileged => self.read() && self.write() && self.execute(),
        }
    }

    /// Returns the union of two permission sets
    ///
    /// # Arguments
    ///
    /// * `other` - The other permission set
    ///
    /// # Returns
    ///
    /// A new PagePermissions with permissions from both sets
    #[must_use]
    #[inline]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Returns the intersection of two permission sets
    ///
    /// For R/W/X bits the intersection uses AND (both must allow).
    /// For the `privileged_only` bit the intersection uses OR: if either
    /// permission set restricts access to privileged callers the result
    /// also restricts it (ARM §3.3.1, GAP-2).
    ///
    /// # Arguments
    ///
    /// * `other` - The other permission set
    ///
    /// # Returns
    ///
    /// A new PagePermissions with only R/W/X permissions present in both sets,
    /// and `privileged_only` set if either set has it.
    #[must_use]
    #[inline]
    pub const fn intersection(self, other: Self) -> Self {
        // R/W/X: AND (both must allow); privileged_only: OR (union of restrictions)
        let rwx = self.0 & other.0 & 0b0111;
        let priv_bit = (self.0 | other.0) & Self::PRIV_ONLY;
        Self(rwx | priv_bit)
    }

    /// Checks if this permission set is a subset of another
    ///
    /// # Arguments
    ///
    /// * `other` - The other permission set
    ///
    /// # Returns
    ///
    /// `true` if all permissions in `self` are also in `other`
    #[must_use]
    #[inline]
    pub const fn is_subset_of(self, other: &Self) -> bool {
        (self.0 & !other.0) == 0
    }
}

impl Default for PagePermissions {
    /// Creates PagePermissions with no access allowed (secure default)
    #[inline]
    fn default() -> Self {
        Self::none()
    }
}

/// Page table entry structure
///
/// Represents a single page table entry containing physical address mapping,
/// permissions, security state, and memory attributes. This structure follows
/// ARM SMMU v3 specification requirements.
///
/// # Memory Safety
///
/// This structure uses zero unsafe code and leverages Rust's ownership system
/// for safe memory management.
///
/// # Examples
///
/// ```
/// use smmu::types::{PageEntry, PagePermissions, PA, SecurityState};
///
/// let pa = PA::new(0x1000).unwrap();
/// let perms = PagePermissions::read_write();
/// let entry = PageEntry::new(pa, perms);
///
/// assert!(entry.is_valid());
/// assert_eq!(entry.physical_address(), pa);
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PageEntry {
    /// Physical address mapping
    physical_address: PA,
    /// Page permissions
    permissions: PagePermissions,
    /// Entry validity flag
    valid: bool,
    /// Security state
    security_state: SecurityState,
    /// Cacheable attribute
    cacheable: bool,
    /// Shareable attribute
    shareable: bool,
    /// Device memory attribute
    device_memory: bool,
    /// Hardware Access Flag (CD.HA bit 43) — set on first access when HA=1
    access_flag: bool,
    /// Hardware Dirty State (CD.HD bit 42) — set on first write when HD=1
    dirty: bool,
}

impl PageEntry {
    /// Creates a new valid PageEntry with physical address and permissions
    ///
    /// Security state defaults to NonSecure, and memory attributes default to
    /// normal memory (cacheable, shareable, not device memory).
    ///
    /// # Arguments
    ///
    /// * `physical_address` - Physical address for this entry
    /// * `permissions` - Access permissions
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::{PageEntry, PagePermissions, PA};
    ///
    /// let pa = PA::new(0x1000).unwrap();
    /// let entry = PageEntry::new(pa, PagePermissions::read_only());
    /// assert!(entry.is_valid());
    /// ```
    #[must_use]
    pub const fn new(physical_address: PA, permissions: PagePermissions) -> Self {
        Self {
            physical_address,
            permissions,
            valid: true,
            security_state: SecurityState::NonSecure,
            cacheable: true,
            shareable: true,
            device_memory: false,
            access_flag: false,
            dirty: false,
        }
    }

    /// Creates a new PageEntry with explicit security state
    ///
    /// # Arguments
    ///
    /// * `physical_address` - Physical address for this entry
    /// * `permissions` - Access permissions
    /// * `security_state` - Security state (Secure/NonSecure/Realm)
    #[must_use]
    pub const fn with_security_state(
        physical_address: PA,
        permissions: PagePermissions,
        security_state: SecurityState,
    ) -> Self {
        Self {
            physical_address,
            permissions,
            valid: true,
            security_state,
            cacheable: true,
            shareable: true,
            device_memory: false,
            access_flag: false,
            dirty: false,
        }
    }

    /// Creates a builder for constructing PageEntry
    #[must_use]
    pub const fn builder() -> PageEntryBuilder {
        PageEntryBuilder::new()
    }

    /// Returns the physical address
    #[must_use]
    #[inline]
    pub const fn physical_address(&self) -> PA {
        self.physical_address
    }

    /// Returns the permissions
    #[must_use]
    #[inline]
    pub const fn permissions(&self) -> PagePermissions {
        self.permissions
    }

    /// Returns the security state
    #[must_use]
    #[inline]
    pub const fn security_state(&self) -> SecurityState {
        self.security_state
    }

    /// Returns true if entry is valid
    #[must_use]
    #[inline]
    pub const fn is_valid(&self) -> bool {
        self.valid
    }

    /// Returns true if entry is cacheable
    #[must_use]
    #[inline]
    pub const fn is_cacheable(&self) -> bool {
        self.cacheable
    }

    /// Returns true if entry is shareable
    #[must_use]
    #[inline]
    pub const fn is_shareable(&self) -> bool {
        self.shareable
    }

    /// Returns true if entry represents device memory
    #[must_use]
    #[inline]
    pub const fn is_device_memory(&self) -> bool {
        self.device_memory
    }

    /// Marks the entry as valid
    #[must_use]
    pub const fn mark_valid(mut self) -> Self {
        self.valid = true;
        self
    }

    /// Marks the entry as invalid
    #[must_use]
    pub const fn mark_invalid(mut self) -> Self {
        self.valid = false;
        self
    }

    /// Sets the cacheable attribute
    #[must_use]
    pub const fn with_cacheable(mut self, cacheable: bool) -> Self {
        self.cacheable = cacheable;
        // Device memory cannot be cacheable
        if self.device_memory && cacheable {
            self.cacheable = false;
        }
        self
    }

    /// Sets the shareable attribute
    #[must_use]
    pub const fn with_shareable(mut self, shareable: bool) -> Self {
        self.shareable = shareable;
        self
    }

    /// Sets the device memory attribute
    #[must_use]
    pub const fn with_device_memory(mut self, device_memory: bool) -> Self {
        self.device_memory = device_memory;
        // Device memory cannot be cacheable
        if device_memory {
            self.cacheable = false;
        }
        self
    }

    /// Updates the permissions
    #[must_use]
    pub const fn with_permissions(mut self, permissions: PagePermissions) -> Self {
        self.permissions = permissions;
        self
    }

    /// Returns true if the hardware Access Flag is set (CD.HA bit 43, ARM SMMU v3 §3.13)
    ///
    /// When CD.HA=1, the SMMU sets this flag on the first access to a page.
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::{PageEntry, PagePermissions, PA};
    ///
    /// let pa = PA::new(0x1000).unwrap();
    /// let entry = PageEntry::new(pa, PagePermissions::read_write());
    /// assert!(!entry.is_access_flag_set());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_access_flag_set(&self) -> bool {
        self.access_flag
    }

    /// Returns true if the hardware Dirty State bit is set (CD.HD bit 42, ARM SMMU v3 §3.13)
    ///
    /// When CD.HD=1, the SMMU sets this flag on the first write to a page.
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::{PageEntry, PagePermissions, PA};
    ///
    /// let pa = PA::new(0x1000).unwrap();
    /// let entry = PageEntry::new(pa, PagePermissions::read_write());
    /// assert!(!entry.is_dirty());
    /// ```
    #[must_use]
    #[inline]
    pub const fn is_dirty(&self) -> bool {
        self.dirty
    }

    /// Sets the Access Flag state (CD.HA simulation, ARM SMMU v3 §3.13)
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::{PageEntry, PagePermissions, PA};
    ///
    /// let pa = PA::new(0x1000).unwrap();
    /// let entry = PageEntry::new(pa, PagePermissions::read_write()).with_access_flag(true);
    /// assert!(entry.is_access_flag_set());
    /// ```
    #[must_use]
    pub const fn with_access_flag(mut self, v: bool) -> Self {
        self.access_flag = v;
        self
    }

    /// Sets the Dirty State bit (CD.HD simulation, ARM SMMU v3 §3.13)
    ///
    /// # Examples
    ///
    /// ```
    /// use smmu::types::{PageEntry, PagePermissions, PA};
    ///
    /// let pa = PA::new(0x1000).unwrap();
    /// let entry = PageEntry::new(pa, PagePermissions::read_write()).with_dirty(true);
    /// assert!(entry.is_dirty());
    /// ```
    #[must_use]
    pub const fn with_dirty(mut self, v: bool) -> Self {
        self.dirty = v;
        self
    }
}

impl Default for PageEntry {
    /// Creates an invalid PageEntry with zero physical address
    fn default() -> Self {
        Self {
            physical_address: PA::new(0).unwrap_or_else(|_| unreachable!()),
            permissions: PagePermissions::default(),
            valid: false,
            security_state: SecurityState::NonSecure,
            cacheable: false,
            shareable: false,
            device_memory: false,
            access_flag: false,
            dirty: false,
        }
    }
}

/// Builder for PageEntry with compile-time validation
///
/// Provides a fluent interface for constructing PageEntry instances.
///
/// # Examples
///
/// ```
/// use smmu::types::{PageEntry, PagePermissions, PA, SecurityState};
///
/// let pa = PA::new(0x2000).unwrap();
/// let entry = PageEntry::builder()
///     .physical_address(pa)
///     .permissions(PagePermissions::read_execute())
///     .security_state(SecurityState::Secure)
///     .cacheable(true)
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct PageEntryBuilder {
    physical_address: Option<PA>,
    permissions: PagePermissions,
    security_state: SecurityState,
    cacheable: bool,
    shareable: bool,
    device_memory: bool,
    access_flag: bool,
    dirty: bool,
}

impl PageEntryBuilder {
    /// Creates a new builder with default values
    #[must_use]
    const fn new() -> Self {
        Self {
            physical_address: None,
            permissions: PagePermissions::none(),
            security_state: SecurityState::NonSecure,
            cacheable: true,
            shareable: true,
            device_memory: false,
            access_flag: false,
            dirty: false,
        }
    }

    /// Sets the physical address
    #[must_use]
    pub const fn physical_address(mut self, pa: PA) -> Self {
        self.physical_address = Some(pa);
        self
    }

    /// Sets the permissions
    #[must_use]
    pub const fn permissions(mut self, perms: PagePermissions) -> Self {
        self.permissions = perms;
        self
    }

    /// Sets the security state
    #[must_use]
    pub const fn security_state(mut self, state: SecurityState) -> Self {
        self.security_state = state;
        self
    }

    /// Sets the cacheable attribute
    #[must_use]
    pub const fn cacheable(mut self, cacheable: bool) -> Self {
        self.cacheable = cacheable;
        self
    }

    /// Sets the shareable attribute
    #[must_use]
    pub const fn shareable(mut self, shareable: bool) -> Self {
        self.shareable = shareable;
        self
    }

    /// Sets the device memory attribute
    #[must_use]
    pub const fn device_memory(mut self, device_memory: bool) -> Self {
        self.device_memory = device_memory;
        self
    }

    /// Sets the Access Flag (CD.HA simulation, ARM SMMU v3 §3.13)
    #[must_use]
    pub const fn access_flag(mut self, v: bool) -> Self {
        self.access_flag = v;
        self
    }

    /// Sets the Dirty State bit (CD.HD simulation, ARM SMMU v3 §3.13)
    #[must_use]
    pub const fn dirty(mut self, v: bool) -> Self {
        self.dirty = v;
        self
    }

    /// Builds the PageEntry
    ///
    /// # Panics
    ///
    /// Panics if physical address was not set
    #[must_use]
    pub fn build(self) -> PageEntry {
        let physical_address = self.physical_address.expect("Physical address must be set");

        let mut entry = PageEntry {
            physical_address,
            permissions: self.permissions,
            valid: true,
            security_state: self.security_state,
            cacheable: self.cacheable,
            shareable: self.shareable,
            device_memory: self.device_memory,
            access_flag: self.access_flag,
            dirty: self.dirty,
        };

        // Enforce device memory constraints
        if entry.device_memory {
            entry.cacheable = false;
        }

        entry
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ========================================================================
    // TDD tests for FINDING-M-04: Access Flag and Dirty State simulation
    // These tests will FAIL before implementation.
    // ========================================================================

    #[test]
    fn test_page_entry_access_flag_default_false() {
        let pa = PA::new(0x1000).unwrap();
        let entry = PageEntry::new(pa, PagePermissions::read_write());
        assert!(!entry.is_access_flag_set());
    }

    #[test]
    fn test_page_entry_dirty_default_false() {
        let pa = PA::new(0x1000).unwrap();
        let entry = PageEntry::new(pa, PagePermissions::read_write());
        assert!(!entry.is_dirty());
    }

    #[test]
    fn test_page_entry_with_access_flag() {
        let pa = PA::new(0x1000).unwrap();
        let entry = PageEntry::new(pa, PagePermissions::read_write()).with_access_flag(true);
        assert!(entry.is_access_flag_set());
    }

    #[test]
    fn test_page_entry_with_dirty() {
        let pa = PA::new(0x1000).unwrap();
        let entry = PageEntry::new(pa, PagePermissions::read_write()).with_dirty(true);
        assert!(entry.is_dirty());
    }

    #[test]
    fn test_page_permissions_basic() {
        let perms = PagePermissions::new(true, false, true);
        assert!(perms.read());
        assert!(!perms.write());
        assert!(perms.execute());
    }

    #[test]
    fn test_page_entry_basic() {
        let pa = PA::new(0x1000).unwrap();
        let perms = PagePermissions::read_write();
        let entry = PageEntry::new(pa, perms);

        assert!(entry.is_valid());
        assert_eq!(entry.physical_address(), pa);
        assert_eq!(entry.permissions(), perms);
    }

    #[test]
    fn test_device_memory_not_cacheable() {
        let pa = PA::new(0x2000).unwrap();
        let entry = PageEntry::new(pa, PagePermissions::default())
            .with_device_memory(true)
            .with_cacheable(true);

        assert!(entry.is_device_memory());
        assert!(!entry.is_cacheable(), "Device memory should not be cacheable");
    }
}