riscv/
pmp.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5use core::cell::Cell;
6use core::num::NonZeroUsize;
7use core::ops::Range;
8use core::{cmp, fmt};
9
10use kernel::platform::mpu;
11use kernel::utilities::cells::OptionalCell;
12use kernel::utilities::registers::{register_bitfields, LocalRegisterCopy};
13
14use crate::csr;
15
16register_bitfields![u8,
17    /// Generic `pmpcfg` octet.
18    ///
19    /// A PMP entry is configured through `pmpaddrX` and `pmpcfgX` CSRs, where a
20    /// single `pmpcfgX` CSRs holds multiple octets, each affecting the access
21    /// permission, addressing mode and "lock" attributes of a single `pmpaddrX`
22    /// CSR. This bitfield definition represents a single, `u8`-backed `pmpcfg`
23    /// octet affecting a single `pmpaddr` entry.
24    pub pmpcfg_octet [
25        r OFFSET(0) NUMBITS(1) [],
26        w OFFSET(1) NUMBITS(1) [],
27        x OFFSET(2) NUMBITS(1) [],
28        a OFFSET(3) NUMBITS(2) [
29            OFF = 0,
30            TOR = 1,
31            NA4 = 2,
32            NAPOT = 3
33        ],
34        l OFFSET(7) NUMBITS(1) []
35    ]
36];
37
38/// Mask for valid values of the `pmpaddrX` CSRs on RISCV platforms.
39///
40/// RV64 platforms support only a 56 bit physical address space. For this reason
41/// (and because addresses in `pmpaddrX` CSRs are left-shifted by 2 bit) the
42/// uppermost 10 bits of a `pmpaddrX` CSR are defined as WARL-0. ANDing with
43/// this mask achieves the same effect; thus it can be used to determine whether
44/// a given PMP region spec would be legal and applied before writing it to a
45/// `pmpaddrX` CSR. For RV32 platforms, th whole 32 bit address range is valid.
46///
47/// This mask will have the value `0x003F_FFFF_FFFF_FFFF` on RV64 platforms, and
48/// `0xFFFFFFFF` on RV32 platforms.
49const PMPADDR_MASK: usize = (0x003F_FFFF_FFFF_FFFFu64 & usize::MAX as u64) as usize;
50
51/// A `pmpcfg` octet for a user-mode (non-locked) TOR-addressed PMP region.
52///
53/// This is a wrapper around a [`pmpcfg_octet`] (`u8`) register type, which
54/// guarantees that the wrapped `pmpcfg` octet is always set to be either
55/// [`TORUserPMPCFG::OFF`] (set to `0x00`), or in a non-locked, TOR-addressed
56/// configuration.
57///
58/// By accepting this type, PMP implements can rely on the above properties to
59/// hold by construction and avoid runtime checks. For example, this type is
60/// used in the [`TORUserPMP::configure_pmp`] method.
61#[derive(Copy, Clone, Debug)]
62pub struct TORUserPMPCFG(LocalRegisterCopy<u8, pmpcfg_octet::Register>);
63
64impl TORUserPMPCFG {
65    pub const OFF: TORUserPMPCFG = TORUserPMPCFG(LocalRegisterCopy::new(0));
66
67    /// Extract the `u8` representation of the [`pmpcfg_octet`] register.
68    pub fn get(&self) -> u8 {
69        self.0.get()
70    }
71
72    /// Extract a copy of the contained [`pmpcfg_octet`] register.
73    pub fn get_reg(&self) -> LocalRegisterCopy<u8, pmpcfg_octet::Register> {
74        self.0
75    }
76}
77
78impl PartialEq<TORUserPMPCFG> for TORUserPMPCFG {
79    fn eq(&self, other: &Self) -> bool {
80        self.0.get() == other.0.get()
81    }
82}
83
84impl Eq for TORUserPMPCFG {}
85
86impl From<mpu::Permissions> for TORUserPMPCFG {
87    fn from(p: mpu::Permissions) -> Self {
88        let fv = match p {
89            mpu::Permissions::ReadWriteExecute => {
90                pmpcfg_octet::r::SET + pmpcfg_octet::w::SET + pmpcfg_octet::x::SET
91            }
92            mpu::Permissions::ReadWriteOnly => {
93                pmpcfg_octet::r::SET + pmpcfg_octet::w::SET + pmpcfg_octet::x::CLEAR
94            }
95            mpu::Permissions::ReadExecuteOnly => {
96                pmpcfg_octet::r::SET + pmpcfg_octet::w::CLEAR + pmpcfg_octet::x::SET
97            }
98            mpu::Permissions::ReadOnly => {
99                pmpcfg_octet::r::SET + pmpcfg_octet::w::CLEAR + pmpcfg_octet::x::CLEAR
100            }
101            mpu::Permissions::ExecuteOnly => {
102                pmpcfg_octet::r::CLEAR + pmpcfg_octet::w::CLEAR + pmpcfg_octet::x::SET
103            }
104        };
105
106        TORUserPMPCFG(LocalRegisterCopy::new(
107            (fv + pmpcfg_octet::l::CLEAR + pmpcfg_octet::a::TOR).value,
108        ))
109    }
110}
111
112/// A RISC-V PMP memory region specification, configured in NAPOT mode.
113///
114/// This type checks that the supplied `start` and `size` values meet the RISC-V
115/// NAPOT requirements, namely that
116///
117/// - the region is a power of two bytes in size
118/// - the region's start address is aligned to the region size
119/// - the region is at least 8 bytes long
120///
121/// Finally, RISC-V restricts physical address spaces to 34 bit on RV32, and 56
122/// bit on RV64 platforms. A `NAPOTRegionSpec` must not cover addresses
123/// exceeding this address space, respectively. In practice, this means that on
124/// RV64 platforms `NAPOTRegionSpec`s whose encoded `pmpaddrX` CSR contains any
125/// non-zero bits in the 10 most significant bits will be rejected.
126///
127/// By accepting this type, PMP implementations can rely on these requirements
128/// to be verified. Furthermore, they can use the [`NAPOTRegionSpec::pmpaddr`]
129/// convenience method to retrieve an `pmpaddrX` CSR value encoding this
130/// region's address and length.
131#[derive(Copy, Clone, Debug)]
132pub struct NAPOTRegionSpec {
133    pmpaddr: usize,
134}
135
136impl NAPOTRegionSpec {
137    /// Construct a new [`NAPOTRegionSpec`] from a pmpaddr CSR value.
138    ///
139    /// For an RV32 platform, every single integer in `[0; usize::MAX]` is a
140    /// valid `pmpaddrX` CSR for a region configured in NAPOT mode, and this
141    /// operation is thus effectively infallible.
142    ///
143    /// For RV64 platforms, this operation checks if the range would include any
144    /// address outside of the 56 bit physical address space and, in this case,
145    /// rejects the `pmpaddr` (tests whether any of the 10 most significant bits
146    /// are non-zero).
147    pub fn from_pmpaddr_csr(pmpaddr: usize) -> Option<Self> {
148        // On 64-bit platforms, the 10 most significant bits must be 0
149        // Prevent the `&-masking with zero` lint error in case of RV32
150        // The redundant checks in this case are optimized out by the compiler on any 1-3,z opt-level
151        #[allow(clippy::bad_bit_mask)]
152        (pmpaddr & !PMPADDR_MASK == 0).then_some(NAPOTRegionSpec { pmpaddr })
153    }
154
155    /// Construct a new [`NAPOTRegionSpec`] from a start address and size.
156    ///
157    /// This method accepts a `start` address and a region length. It returns
158    /// `Some(region)` when all constraints specified in the
159    /// [`NAPOTRegionSpec`]'s documentation are satisfied, otherwise `None`.
160    pub fn from_start_size(start: *const u8, size: usize) -> Option<Self> {
161        if !size.is_power_of_two() || start.addr() % size != 0 || size < 8 {
162            return None;
163        }
164
165        Self::from_pmpaddr_csr(
166            (start.addr() + (size - 1).overflowing_shr(1).0)
167                .overflowing_shr(2)
168                .0,
169        )
170    }
171
172    /// Construct a new [`NAPOTRegionSpec`] from a start address and end address.
173    ///
174    /// This method accepts a `start` address (inclusive) and `end` address
175    /// (exclusive). It returns `Some(region)` when all constraints specified in
176    /// the [`NAPOTRegionSpec`]'s documentation are satisfied, otherwise `None`.
177    pub fn from_start_end(start: *const u8, end: *const u8) -> Option<Self> {
178        end.addr()
179            .checked_sub(start.addr())
180            .and_then(|size| Self::from_start_size(start, size))
181    }
182
183    /// Retrieve a `pmpaddrX`-CSR compatible representation of this
184    /// [`NAPOTRegionSpec`]'s address and length. For this value to be valid in
185    /// a `CSR` register, the `pmpcfgX` octet's `A` (address mode) value
186    /// belonging to this `pmpaddrX`-CSR must be set to `NAPOT` (0b11).
187    pub fn pmpaddr(&self) -> usize {
188        self.pmpaddr
189    }
190
191    /// Return the range of physical addresses covered by this PMP region.
192    ///
193    /// This follows the regular Rust range semantics (start inclusive, end
194    /// exclusive). It returns the addresses as u64-integers to ensure that all
195    /// underlying pmpaddrX CSR values can be represented.
196    pub fn address_range(&self) -> core::ops::Range<u64> {
197        let trailing_ones: u64 = self.pmpaddr.trailing_ones() as u64;
198        let size = 0b1000_u64 << trailing_ones;
199        let base_addr: u64 =
200            (self.pmpaddr as u64 & !((1_u64 << trailing_ones).saturating_sub(1))) << 2;
201        base_addr..(base_addr.saturating_add(size))
202    }
203}
204
205/// A RISC-V PMP memory region specification, configured in TOR mode.
206///
207/// This type checks that the supplied `start` and `end` addresses meet the
208/// RISC-V TOR requirements, namely that
209///
210/// - the region's start address is aligned to a 4-byte boundary
211/// - the region's end address is aligned to a 4-byte boundary
212/// - the region is at least 4 bytes long
213///
214/// Finally, RISC-V restricts physical address spaces to 34 bit on RV32, and 56
215/// bit on RV64 platforms. A `TORRegionSpec` must not cover addresses exceeding
216/// this address space, respectively. In practice, this means that on RV64
217/// platforms `TORRegionSpec`s whose encoded `pmpaddrX` CSR contains any
218/// non-zero bits in the 10 most significant bits will be rejected. In
219/// particular, with the `end` pmpaddrX CSR / address being exclusive, the
220/// region cannot span the last 4 bytes of the 56-bit address space on RV64, or
221/// the last 4 bytes of the 34-bit address space on RV32.
222///
223/// By accepting this type, PMP implementations can rely on these requirements
224/// to be verified.
225#[derive(Copy, Clone, Debug)]
226pub struct TORRegionSpec {
227    pmpaddr_a: usize,
228    pmpaddr_b: usize,
229}
230
231impl TORRegionSpec {
232    /// Construct a new [`TORRegionSpec`] from a pair of pmpaddrX CSR values.
233    ///
234    /// This method accepts two `pmpaddrX` CSR values that together are
235    /// configured to describe a single TOR memory region. The second `pmpaddr_b`
236    /// must be strictly greater than `pmpaddr_a`, which translates into a
237    /// minimum region size of 4 bytes. Otherwise this function returns `None`.
238    ///
239    /// For RV64 platforms, this operation also checks if the range would
240    /// include any address outside of the 56 bit physical address space and, in
241    /// this case, returns `None` (tests whether any of the 10 most significant
242    /// bits of either `pmpaddr` are non-zero).
243    pub fn from_pmpaddr_csrs(pmpaddr_a: usize, pmpaddr_b: usize) -> Option<TORRegionSpec> {
244        // Prevent the `&-masking with zero` lint error in case of RV32
245        // The redundant checks in this case are optimized out by the compiler on any 1-3,z opt-level
246        #[allow(clippy::bad_bit_mask)]
247        ((pmpaddr_a < pmpaddr_b)
248            && (pmpaddr_a & !PMPADDR_MASK == 0)
249            && (pmpaddr_b & !PMPADDR_MASK == 0))
250            .then_some(TORRegionSpec {
251                pmpaddr_a,
252                pmpaddr_b,
253            })
254    }
255
256    /// Construct a new [`TORRegionSpec`] from a range of addresses.
257    ///
258    /// This method accepts a `start` and `end` address. It returns
259    /// `Some(region)` when all constraints specified in the [`TORRegionSpec`]'s
260    /// documentation are satisfied, otherwise `None`.
261    pub fn from_start_end(start: *const u8, end: *const u8) -> Option<Self> {
262        if (start as usize) % 4 != 0
263            || (end as usize) % 4 != 0
264            || (end as usize)
265                .checked_sub(start as usize)
266                .is_none_or(|size| size < 4)
267        {
268            return None;
269        }
270
271        Self::from_pmpaddr_csrs(start.addr() >> 2, end.addr() >> 2)
272    }
273
274    /// Get the first `pmpaddrX` CSR value that this TORRegionSpec encodes.
275    pub fn pmpaddr_a(&self) -> usize {
276        self.pmpaddr_a
277    }
278
279    pub fn pmpaddr_b(&self) -> usize {
280        self.pmpaddr_b
281    }
282}
283
284/// Helper method to check if a [`PMPUserMPUConfig`] region overlaps with a
285/// region specified by `other_start` and `other_size`.
286///
287/// Matching the RISC-V spec this checks `pmpaddr[i-i] <= y < pmpaddr[i]` for TOR
288/// ranges.
289fn region_overlaps(
290    region: &(TORUserPMPCFG, *const u8, *const u8),
291    other_start: *const u8,
292    other_size: usize,
293) -> bool {
294    // PMP TOR regions are not inclusive on the high end, that is
295    //     pmpaddr[i-i] <= y < pmpaddr[i].
296    //
297    // This happens to coincide with the definition of the Rust half-open Range
298    // type, which provides a convenient `.contains()` method:
299    let region_range = Range {
300        start: region.1 as usize,
301        end: region.2 as usize,
302    };
303
304    let other_range = Range {
305        start: other_start as usize,
306        end: other_start as usize + other_size,
307    };
308
309    // For a range A to overlap with a range B, either B's first or B's last
310    // element must be contained in A, or A's first or A's last element must be
311    // contained in B. As we deal with half-open ranges, ensure that neither
312    // range is empty.
313    //
314    // This implementation is simple and stupid, and can be optimized. We leave
315    // that as an exercise to the compiler.
316    !region_range.is_empty()
317        && !other_range.is_empty()
318        && (region_range.contains(&other_range.start)
319            || region_range.contains(&(other_range.end - 1))
320            || other_range.contains(&region_range.start)
321            || other_range.contains(&(region_range.end - 1)))
322}
323
324#[cfg(test)]
325pub mod misc_pmp_test {
326    #[test]
327    fn test_napot_region_spec_from_pmpaddr_csr() {
328        use super::NAPOTRegionSpec;
329
330        // Unfortunatly, we can't run these unit tests for different platforms,
331        // with arbitrary bit-widths (at least when using `usize` in the
332        // `TORRegionSpec` internally.
333        //
334        // For now, we check whatever word-size our host-platform has and
335        // generate our test vectors according to those expectations.
336        let pmpaddr_max: usize = if core::mem::size_of::<usize>() == 8 {
337            // This deliberately does not re-use the `PMPADDR_RV64_MASK`
338            // constant which should be equal to this value:
339            0x003F_FFFF_FFFF_FFFF_u64.try_into().unwrap()
340        } else {
341            usize::MAX
342        };
343
344        for (valid, pmpaddr, start, end) in [
345            // Basic sanity checks:
346            (true, 0b0000, 0b0000_0000, 0b0000_1000),
347            (true, 0b0001, 0b0000_0000, 0b0001_0000),
348            (true, 0b0010, 0b0000_1000, 0b0001_0000),
349            (true, 0b0011, 0b0000_0000, 0b0010_0000),
350            (true, 0b0101, 0b0001_0000, 0b0010_0000),
351            (true, 0b1011, 0b0010_0000, 0b0100_0000),
352            // Can span the whole address space (up to 34 bit on RV32, and 5
353            // bit on RV64, 2^{XLEN + 3) byte NAPOT range).
354            (
355                true,
356                pmpaddr_max,
357                0,
358                if core::mem::size_of::<usize>() == 8 {
359                    0x0200_0000_0000_0000
360                } else {
361                    0x0000_0008_0000_0000
362                },
363            ),
364            // Cannot create region larger than `pmpaddr_max`:
365            (
366                core::mem::size_of::<usize>() != 8,
367                pmpaddr_max.saturating_add(1),
368                0,
369                if core::mem::size_of::<usize>() == 8 {
370                    // Doesn't matter, operation should fail:
371                    0
372                } else {
373                    0x0000_0008_0000_0000
374                },
375            ),
376        ] {
377            match (valid, NAPOTRegionSpec::from_pmpaddr_csr(pmpaddr)) {
378                (true, Some(region)) => {
379                    assert_eq!(
380                        region.pmpaddr(),
381                        pmpaddr,
382                        "NAPOTRegionSpec::from_pmpaddr_csr yields wrong CSR value (0x{:x?} vs. 0x{:x?})",
383                        pmpaddr,
384                        region.pmpaddr()
385                    );
386                    assert_eq!(
387                        region.address_range(),
388                        start..end,
389                        "NAPOTRegionSpec::from_pmpaddr_csr yields wrong address range value for CSR 0x{:x?} (0x{:x?}..0x{:x?} vs. 0x{:x?}..0x{:x?})",
390                        pmpaddr,
391                        region.address_range().start,
392                        region.address_range().end,
393                        start,
394                        end
395                    );
396                }
397
398                (true, None) => {
399                    panic!(
400                        "Failed to create NAPOT region over pmpaddr CSR ({:x?}), but has to succeed!",
401                        pmpaddr,
402                    );
403                }
404
405                (false, Some(region)) => {
406                    panic!(
407                        "Creation of TOR region over pmpaddr CSR {:x?} must fail, but succeeded: {:?}",
408                        pmpaddr, region,
409                    );
410                }
411
412                (false, None) => {
413                    // Good, nothing to do here.
414                }
415            }
416        }
417    }
418
419    #[test]
420    fn test_tor_region_spec_from_pmpaddr_csrs() {
421        use super::TORRegionSpec;
422        // Unfortunatly, we can't run these unit tests for different platforms,
423        // with arbitrary bit-widths (at least when using `usize` in the
424        // `TORRegionSpec` internally.
425        //
426        // For now, we check whatever word-size our host-platform has and
427        // generate our test vectors according to those expectations.
428        let pmpaddr_max: usize = if core::mem::size_of::<usize>() == 8 {
429            // This deliberately does not re-use the `PMPADDR_RV64_MASK`
430            // constant which should be equal to this value:
431            0x003F_FFFF_FFFF_FFFF_u64.try_into().unwrap()
432        } else {
433            usize::MAX
434        };
435
436        for (valid, pmpaddr_a, pmpaddr_b) in [
437            // Can span the whole address space (up to 34 bit on RV32, and 56
438            // bit on RV64):
439            (true, 0, 1),
440            (true, 0x8badf00d, 0xdeadbeef),
441            (true, pmpaddr_max - 1, pmpaddr_max),
442            (true, 0, pmpaddr_max),
443            // Cannot create region smaller than 4 bytes:
444            (false, 0, 0),
445            (false, 0xdeadbeef, 0xdeadbeef),
446            (false, pmpaddr_max, pmpaddr_max),
447            // On 64-bit systems, cannot create region that exceeds 56 bit:
448            (
449                core::mem::size_of::<usize>() != 8,
450                0,
451                pmpaddr_max.saturating_add(1),
452            ),
453            // Cannot create region with end before start:
454            (false, 1, 0),
455            (false, 0xdeadbeef, 0x8badf00d),
456            (false, pmpaddr_max, 0),
457        ] {
458            match (
459                valid,
460                TORRegionSpec::from_pmpaddr_csrs(pmpaddr_a, pmpaddr_b),
461            ) {
462                (true, Some(region)) => {
463                    assert_eq!(region.pmpaddr_a(), pmpaddr_a);
464                    assert_eq!(region.pmpaddr_b(), pmpaddr_b);
465                }
466
467                (true, None) => {
468                    panic!(
469                        "Failed to create TOR region over pmpaddr CSRS ({:x?}, {:x?}), but has to succeed!",
470                        pmpaddr_a, pmpaddr_b,
471                    );
472                }
473
474                (false, Some(region)) => {
475                    panic!(
476                        "Creation of TOR region over pmpaddr CSRs ({:x?}, {:x?}) must fail, but succeeded: {:?}",
477                        pmpaddr_a, pmpaddr_b, region
478                    );
479                }
480
481                (false, None) => {
482                    // Good, nothing to do here.
483                }
484            }
485        }
486    }
487
488    #[test]
489    fn test_tor_region_spec_from_start_end_addrs() {
490        use super::TORRegionSpec;
491
492        fn panicing_shr_2(i: usize) -> usize {
493            assert_eq!(i & 0b11, 0);
494            i >> 2
495        }
496
497        // Unfortunatly, we can't run these unit tests for different platforms,
498        // with arbitrary bit-widths (at least when using `usize` in the
499        // `TORRegionSpec` internally.
500        //
501        // For now, we check whatever word-size our host-platform has and
502        // generate our test vectors according to those expectations.
503        let last_addr: usize = if core::mem::size_of::<usize>() == 8 {
504            0x03F_FFFF_FFFF_FFFC_u64.try_into().unwrap()
505        } else {
506            // For 32-bit platforms, this cannot actually cover the whole
507            // 32-bit address space. We must exclude the last 4 bytes.
508            usize::MAX & (!0b11)
509        };
510
511        for (valid, start, end) in [
512            // Can span the whole address space (up to 34 bit on RV32, and 56
513            // bit on RV64):
514            (true, 0, 4),
515            (true, 0x13374200, 0xdead10cc),
516            (true, last_addr - 4, last_addr),
517            (true, 0, last_addr),
518            // Cannot create region with start and end address not aligned on
519            // 4-byte boundary:
520            (false, 4, 5),
521            (false, 4, 6),
522            (false, 4, 7),
523            (false, 5, 8),
524            (false, 6, 8),
525            (false, 7, 8),
526            // Cannot create region smaller than 4 bytes:
527            (false, 0, 0),
528            (false, 0x13374200, 0x13374200),
529            (false, 0x13374200, 0x13374201),
530            (false, 0x13374200, 0x13374202),
531            (false, 0x13374200, 0x13374203),
532            (false, last_addr, last_addr),
533            // On 64-bit systems, cannot create region that exceeds 56 or covers
534            // the last 4 bytes of this address space. On 32-bit, cannot cover
535            // the full address space (excluding the last 4 bytes of the address
536            // space):
537            (false, 0, last_addr.checked_add(1).unwrap()),
538            // Cannot create region with end before start:
539            (false, 4, 0),
540            (false, 0xdeadbeef, 0x8badf00d),
541            (false, last_addr, 0),
542        ] {
543            match (
544                valid,
545                TORRegionSpec::from_start_end(start as *const u8, end as *const u8),
546            ) {
547                (true, Some(region)) => {
548                    assert_eq!(region.pmpaddr_a(), panicing_shr_2(start));
549                    assert_eq!(region.pmpaddr_b(), panicing_shr_2(end));
550                }
551
552                (true, None) => {
553                    panic!(
554                        "Failed to create TOR region from address range [{:x?}, {:x?}), but has to succeed!",
555                        start, end,
556                    );
557                }
558
559                (false, Some(region)) => {
560                    panic!(
561                        "Creation of TOR region from address range [{:x?}, {:x?}) must fail, but succeeded: {:?}",
562                        start, end, region
563                    );
564                }
565
566                (false, None) => {
567                    // Good, nothing to do here.
568                }
569            }
570        }
571    }
572}
573
574/// Print a table of the configured PMP regions, read from  the HW CSRs.
575///
576/// # Safety
577///
578/// This function is unsafe, as it relies on the PMP CSRs to be accessible, and
579/// the hardware to feature `PHYSICAL_ENTRIES` PMP CSR entries. If these
580/// conditions are not met, calling this function can result in undefinied
581/// behavior (e.g., cause a system trap).
582pub unsafe fn format_pmp_entries<const PHYSICAL_ENTRIES: usize>(
583    f: &mut fmt::Formatter<'_>,
584) -> fmt::Result {
585    for i in 0..PHYSICAL_ENTRIES {
586        // Extract the entry's pmpcfgX register value. The pmpcfgX CSRs are
587        // tightly packed and contain 4 octets beloging to individual
588        // entries. Convert this into a u8-wide LocalRegisterCopy<u8,
589        // pmpcfg_octet> as a generic register type, independent of the entry's
590        // offset.
591        let pmpcfg: LocalRegisterCopy<u8, pmpcfg_octet::Register> = LocalRegisterCopy::new(
592            csr::CSR
593                .pmpconfig_get(i / 4)
594                .overflowing_shr(((i % 4) * 8) as u32)
595                .0 as u8,
596        );
597
598        // The address interpretation is different for every mode. Return both a
599        // string indicating the PMP entry's mode, as well as the effective
600        // start and end address (inclusive) affected by the region. For regions
601        // that are OFF, we still want to expose the pmpaddrX register value --
602        // thus return the raw unshifted value as the addr, and 0 as the
603        // region's end.
604        let (start_label, start, end, mode) = match pmpcfg.read_as_enum(pmpcfg_octet::a) {
605            Some(pmpcfg_octet::a::Value::OFF) => {
606                let addr = csr::CSR.pmpaddr_get(i);
607                ("pmpaddr", addr, 0, "OFF  ")
608            }
609
610            Some(pmpcfg_octet::a::Value::TOR) => {
611                let start = if i > 0 {
612                    csr::CSR.pmpaddr_get(i - 1)
613                } else {
614                    0
615                };
616
617                (
618                    "  start",
619                    start.overflowing_shl(2).0,
620                    csr::CSR.pmpaddr_get(i).overflowing_shl(2).0.wrapping_sub(1),
621                    "TOR  ",
622                )
623            }
624
625            Some(pmpcfg_octet::a::Value::NA4) => {
626                let addr = csr::CSR.pmpaddr_get(i).overflowing_shl(2).0;
627                ("  start", addr, addr | 0b11, "NA4  ")
628            }
629
630            Some(pmpcfg_octet::a::Value::NAPOT) => {
631                let pmpaddr = csr::CSR.pmpaddr_get(i);
632                let encoded_size = pmpaddr.trailing_ones();
633                if (encoded_size as usize) < (core::mem::size_of_val(&pmpaddr) * 8 - 1) {
634                    let start = pmpaddr - ((1 << encoded_size) - 1);
635                    let end = start + (1 << (encoded_size + 1)) - 1;
636                    (
637                        "  start",
638                        start.overflowing_shl(2).0,
639                        end.overflowing_shl(2).0 | 0b11,
640                        "NAPOT",
641                    )
642                } else {
643                    ("  start", usize::MIN, usize::MAX, "NAPOT")
644                }
645            }
646
647            None => {
648                // We match on a 2-bit value with 4 variants, so this is
649                // unreachable. However, don't insert a panic in case this
650                // doesn't get optimized away:
651                ("", 0, 0, "")
652            }
653        };
654
655        // Ternary operator shortcut function, to avoid bulky formatting...
656        fn t<T>(cond: bool, a: T, b: T) -> T {
657            if cond {
658                a
659            } else {
660                b
661            }
662        }
663
664        write!(
665            f,
666            "  [{:02}]: {}={:#010X}, end={:#010X}, cfg={:#04X} ({}) ({}{}{}{})\r\n",
667            i,
668            start_label,
669            start,
670            end,
671            pmpcfg.get(),
672            mode,
673            t(pmpcfg.is_set(pmpcfg_octet::l), "l", "-"),
674            t(pmpcfg.is_set(pmpcfg_octet::r), "r", "-"),
675            t(pmpcfg.is_set(pmpcfg_octet::w), "w", "-"),
676            t(pmpcfg.is_set(pmpcfg_octet::x), "x", "-"),
677        )?;
678    }
679
680    Ok(())
681}
682
683/// A RISC-V PMP implementation exposing a number of TOR memory protection
684/// regions to the [`PMPUserMPU`].
685///
686/// The RISC-V PMP is complex and can be used to enforce memory protection in
687/// various modes (Machine, Supervisor and User mode). Depending on the exact
688/// extension set present (e.g., ePMP) and the machine's security configuration
689/// bits, it may expose a vastly different set of constraints and application
690/// semantics.
691///
692/// Because we can't possibly capture all of this in a single readable,
693/// maintainable and efficient implementation, we implement a two-layer system:
694///
695/// - a [`TORUserPMP`] is a simple abstraction over some underlying PMP hardware
696///   implementation, which exposes an interface to configure regions that are
697///   active (enforced) in user-mode and can be configured for arbitrary
698///   addresses on a 4-byte granularity.
699///
700/// - the [`PMPUserMPU`] takes this abstraction and implements the Tock kernel's
701///   [`mpu::MPU`] trait. It worries about re-configuring memory protection when
702///   switching processes, allocating memory regions of an appropriate size,
703///   etc.
704///
705/// Implementors of a chip are free to define their own [`TORUserPMP`]
706/// implementations, adhering to their specific PMP layout & constraints,
707/// provided they implement this trait.
708///
709/// The `MAX_REGIONS` const generic is used to indicate the maximum number of
710/// TOR PMP regions available to the [`PMPUserMPU`]. The PMP implementation may
711/// provide less regions than indicated through `MAX_REGIONS`, for instance when
712/// entries are enforced (locked) in machine mode. The number of available
713/// regions may change at runtime. The current number of regions available to
714/// the [`PMPUserMPU`] is indicated by the [`TORUserPMP::available_regions`]
715/// method. However, when it is known that a number of regions are not available
716/// for userspace protection, `MAX_REGIONS` can be used to reduce the memory
717/// footprint allocated by stored PMP configurations, as well as the
718/// re-configuration overhead.
719pub trait TORUserPMP<const MAX_REGIONS: usize> {
720    /// A placeholder to define const-assertions which are evaluated in
721    /// [`PMPUserMPU::new`]. This can be used to, for instance, assert that the
722    /// number of userspace regions does not exceed the number of hardware
723    /// regions.
724    const CONST_ASSERT_CHECK: ();
725
726    /// The number of TOR regions currently available for userspace memory
727    /// protection. Within `[0; MAX_REGIONS]`.
728    ///
729    /// The PMP implementation may provide less regions than indicated through
730    /// `MAX_REGIONS`, for instance when entries are enforced (locked) in
731    /// machine mode. The number of available regions may change at runtime. The
732    /// implementation is free to map these regions to arbitrary PMP entries
733    /// (and change this mapping at runtime), provided that they are enforced
734    /// when the hart is in user-mode, and other memory regions are generally
735    /// inaccessible when in user-mode.
736    ///
737    /// When allocating regions for kernel-mode protection, and thus reducing
738    /// the number of regions available to userspace, re-configuring the PMP may
739    /// fail. This is allowed behavior. However, the PMP must not remove any
740    /// regions from the user-mode current configuration while it is active
741    /// ([`TORUserPMP::enable_user_pmp`] has been called, and it has not been
742    /// disabled through [`TORUserPMP::disable_user_pmp`]).
743    fn available_regions(&self) -> usize;
744
745    /// Configure the user-mode memory protection.
746    ///
747    /// This method configures the user-mode memory protection, to be enforced
748    /// on a call to [`TORUserPMP::enable_user_pmp`].
749    ///
750    /// PMP implementations where configured regions are only enforced in
751    /// user-mode may re-configure the PMP on this function invocation and
752    /// implement [`TORUserPMP::enable_user_pmp`] as a no-op. If configured
753    /// regions are enforced in machine-mode (for instance when using an ePMP
754    /// with the machine-mode whitelist policy), the new configuration rules
755    /// must not apply until [`TORUserPMP::enable_user_pmp`].
756    ///
757    /// The tuples as passed in the `regions` parameter are defined as follows:
758    ///
759    /// - first value ([`TORUserPMPCFG`]): the memory protection mode as
760    ///   enforced on the region. A `TORUserPMPCFG` can be created from the
761    ///   [`mpu::Permissions`] type. It is in a format compatible to the pmpcfgX
762    ///   register, guaranteed to not have the lock (`L`) bit set, and
763    ///   configured either as a TOR region (`A = 0b01`), or disabled (all bits
764    ///   set to `0`).
765    ///
766    /// - second value (`*const u8`): the region's start addres. As a PMP TOR
767    ///   region has a 4-byte address granularity, this address is rounded down
768    ///   to the next 4-byte boundary.
769    ///
770    /// - third value (`*const u8`): the region's end addres. As a PMP TOR
771    ///   region has a 4-byte address granularity, this address is rounded down
772    ///   to the next 4-byte boundary.
773    ///
774    /// To disable a region, set its configuration to [`TORUserPMPCFG::OFF`]. In
775    /// this case, the start and end addresses are ignored and can be set to
776    /// arbitrary values.
777    fn configure_pmp(
778        &self,
779        regions: &[(TORUserPMPCFG, *const u8, *const u8); MAX_REGIONS],
780    ) -> Result<(), ()>;
781
782    /// Enable the user-mode memory protection.
783    ///
784    /// Enables the memory protection for user-mode, as configured through
785    /// [`TORUserPMP::configure_pmp`]. Enabling the PMP for user-mode may make
786    /// the user-mode accessible regions inaccessible to the kernel. For PMP
787    /// implementations where configured regions are only enforced in user-mode,
788    /// this method may be implemented as a no-op.
789    ///
790    /// If enabling the current configuration is not possible (e.g., because
791    /// regions have been allocated to the kernel), this function must return
792    /// `Err(())`. Otherwise, this function returns `Ok(())`.
793    fn enable_user_pmp(&self) -> Result<(), ()>;
794
795    /// Disable the user-mode memory protection.
796    ///
797    /// Disables the memory protection for user-mode. If enabling the user-mode
798    /// memory protetion made user-mode accessible regions inaccessible to
799    /// machine-mode, this method should make these regions accessible again.
800    ///
801    /// For PMP implementations where configured regions are only enforced in
802    /// user-mode, this method may be implemented as a no-op. This method is not
803    /// responsible for making regions inaccessible to user-mode. If previously
804    /// configured regions must be made inaccessible,
805    /// [`TORUserPMP::configure_pmp`] must be used to re-configure the PMP
806    /// accordingly.
807    fn disable_user_pmp(&self);
808}
809
810/// Struct storing userspace memory protection regions for the [`PMPUserMPU`].
811pub struct PMPUserMPUConfig<const MAX_REGIONS: usize> {
812    /// PMP config identifier, as generated by the issuing PMP implementation.
813    id: NonZeroUsize,
814    /// Indicates if the configuration has changed since the last time it was
815    /// written to hardware.
816    is_dirty: Cell<bool>,
817    /// Array of MPU regions. Each region requires two physical PMP entries.
818    regions: [(TORUserPMPCFG, *const u8, *const u8); MAX_REGIONS],
819    /// Which region index (into the `regions` array above) is used
820    /// for app memory (if it has been configured).
821    app_memory_region: OptionalCell<usize>,
822}
823
824impl<const MAX_REGIONS: usize> fmt::Display for PMPUserMPUConfig<MAX_REGIONS> {
825    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
826        // Ternary operator shortcut function, to avoid bulky formatting...
827        fn t<T>(cond: bool, a: T, b: T) -> T {
828            if cond {
829                a
830            } else {
831                b
832            }
833        }
834
835        write!(
836            f,
837            " PMPUserMPUConfig {{\r\n  id: {},\r\n  is_dirty: {},\r\n  app_memory_region: {:?},\r\n  regions:\r\n",
838            self.id,
839            self.is_dirty.get(),
840            self.app_memory_region.get()
841        )?;
842
843        for (i, (tor_user_pmpcfg, start, end)) in self.regions.iter().enumerate() {
844            let pmpcfg = tor_user_pmpcfg.get_reg();
845            write!(
846                f,
847                "     #{:02}: start={:#010X}, end={:#010X}, cfg={:#04X} ({}) (-{}{}{})\r\n",
848                i,
849                *start as usize,
850                *end as usize,
851                pmpcfg.get(),
852                t(pmpcfg.is_set(pmpcfg_octet::a), "TOR", "OFF"),
853                t(pmpcfg.is_set(pmpcfg_octet::r), "r", "-"),
854                t(pmpcfg.is_set(pmpcfg_octet::w), "w", "-"),
855                t(pmpcfg.is_set(pmpcfg_octet::x), "x", "-"),
856            )?;
857        }
858
859        write!(f, " }}\r\n")?;
860        Ok(())
861    }
862}
863
864/// Adapter from a generic PMP implementation exposing TOR-type regions to the
865/// Tock [`mpu::MPU`] trait. See [`TORUserPMP`].
866pub struct PMPUserMPU<const MAX_REGIONS: usize, P: TORUserPMP<MAX_REGIONS> + 'static> {
867    /// Monotonically increasing counter for allocated configurations, used to
868    /// assign unique IDs to `PMPUserMPUConfig` instances.
869    config_count: Cell<NonZeroUsize>,
870    /// The configuration that the PMP was last configured for. Used (along with
871    /// the `is_dirty` flag) to determine if PMP can skip writing the
872    /// configuration to hardware.
873    last_configured_for: OptionalCell<NonZeroUsize>,
874    /// Underlying hardware PMP implementation, exposing a number (up to
875    /// `P::MAX_REGIONS`) of memory protection regions with a 4-byte enforcement
876    /// granularity.
877    pub pmp: P,
878}
879
880impl<const MAX_REGIONS: usize, P: TORUserPMP<MAX_REGIONS> + 'static> PMPUserMPU<MAX_REGIONS, P> {
881    pub fn new(pmp: P) -> Self {
882        // Assigning this constant here ensures evaluation of the const
883        // expression at compile time, and can thus be used to enforce
884        // compile-time assertions based on the desired PMP configuration.
885        #[allow(clippy::let_unit_value)]
886        let _: () = P::CONST_ASSERT_CHECK;
887
888        PMPUserMPU {
889            config_count: Cell::new(NonZeroUsize::MIN),
890            last_configured_for: OptionalCell::empty(),
891            pmp,
892        }
893    }
894}
895
896impl<const MAX_REGIONS: usize, P: TORUserPMP<MAX_REGIONS> + 'static> kernel::platform::mpu::MPU
897    for PMPUserMPU<MAX_REGIONS, P>
898{
899    type MpuConfig = PMPUserMPUConfig<MAX_REGIONS>;
900
901    fn enable_app_mpu(&self) {
902        // TODO: This operation may fail when the PMP is not exclusively used
903        // for userspace. Instead of panicing, we should handle this case more
904        // gracefully and return an error in the `MPU` trait. Process
905        // infrastructure can then attempt to re-schedule the process later on,
906        // try to revoke some optional shared memory regions, or suspend the
907        // process.
908        self.pmp.enable_user_pmp().unwrap()
909    }
910
911    fn disable_app_mpu(&self) {
912        self.pmp.disable_user_pmp()
913    }
914
915    fn number_total_regions(&self) -> usize {
916        self.pmp.available_regions()
917    }
918
919    fn new_config(&self) -> Option<Self::MpuConfig> {
920        let id = self.config_count.get();
921        self.config_count.set(id.checked_add(1)?);
922
923        Some(PMPUserMPUConfig {
924            id,
925            regions: [(
926                TORUserPMPCFG::OFF,
927                core::ptr::null::<u8>(),
928                core::ptr::null::<u8>(),
929            ); MAX_REGIONS],
930            is_dirty: Cell::new(true),
931            app_memory_region: OptionalCell::empty(),
932        })
933    }
934
935    fn reset_config(&self, config: &mut Self::MpuConfig) {
936        config.regions.iter_mut().for_each(|region| {
937            *region = (
938                TORUserPMPCFG::OFF,
939                core::ptr::null::<u8>(),
940                core::ptr::null::<u8>(),
941            )
942        });
943        config.app_memory_region.clear();
944        config.is_dirty.set(true);
945    }
946
947    fn allocate_region(
948        &self,
949        unallocated_memory_start: *const u8,
950        unallocated_memory_size: usize,
951        min_region_size: usize,
952        permissions: mpu::Permissions,
953        config: &mut Self::MpuConfig,
954    ) -> Option<mpu::Region> {
955        // Find a free region slot. If we don't have one, abort early:
956        let region_num = config
957            .regions
958            .iter()
959            .enumerate()
960            .find(|(_i, (pmpcfg, _, _))| *pmpcfg == TORUserPMPCFG::OFF)
961            .map(|(i, _)| i)?;
962
963        // Now, meet the PMP TOR region constraints. For this, start with the
964        // provided start address and size, transform them to meet the
965        // constraints, and then check that we're still within the bounds of the
966        // provided values:
967        let mut start = unallocated_memory_start as usize;
968        let mut size = min_region_size;
969
970        // Region start always has to align to 4 bytes. Round up to a 4 byte
971        // boundary if required:
972        if start % 4 != 0 {
973            start += 4 - (start % 4);
974        }
975
976        // Region size always has to align to 4 bytes. Round up to a 4 byte
977        // boundary if required:
978        if size % 4 != 0 {
979            size += 4 - (size % 4);
980        }
981
982        // Regions must be at least 4 bytes in size.
983        if size < 4 {
984            size = 4;
985        }
986
987        // Now, check to see whether the adjusted start and size still meet the
988        // allocation constraints, namely ensure that
989        //
990        //     start + size <= unallocated_memory_start + unallocated_memory_size
991        if start + size > (unallocated_memory_start as usize) + unallocated_memory_size {
992            // We're overflowing the provided memory region, can't make
993            // allocation. Normally, we'd abort here.
994            //
995            // However, a previous implementation of this code was incorrect in
996            // that performed this check before adjusting the requested region
997            // size to meet PMP region layout constraints (4 byte alignment for
998            // start and end address). Existing applications whose end-address
999            // is aligned on a less than 4-byte bondary would thus be given
1000            // access to additional memory which should be inaccessible.
1001            // Unfortunately, we can't fix this without breaking existing
1002            // applications. Thus, we perform the same insecure hack here, and
1003            // give the apps at most an extra 3 bytes of memory, as long as the
1004            // requested region as no write privileges.
1005            //
1006            // TODO: Remove this logic with as part of
1007            // https://github.com/tock/tock/issues/3544
1008            let writeable = match permissions {
1009                mpu::Permissions::ReadWriteExecute => true,
1010                mpu::Permissions::ReadWriteOnly => true,
1011                mpu::Permissions::ReadExecuteOnly => false,
1012                mpu::Permissions::ReadOnly => false,
1013                mpu::Permissions::ExecuteOnly => false,
1014            };
1015
1016            if writeable
1017                || (start + size
1018                    > (unallocated_memory_start as usize) + unallocated_memory_size + 3)
1019            {
1020                return None;
1021            }
1022        }
1023
1024        // Finally, check that this new region does not overlap with any
1025        // existing configured userspace region:
1026        for region in config.regions.iter() {
1027            if region.0 != TORUserPMPCFG::OFF && region_overlaps(region, start as *const u8, size) {
1028                return None;
1029            }
1030        }
1031
1032        // All checks passed, store region allocation and mark config as dirty:
1033        config.regions[region_num] = (
1034            permissions.into(),
1035            start as *const u8,
1036            (start + size) as *const u8,
1037        );
1038        config.is_dirty.set(true);
1039
1040        Some(mpu::Region::new(start as *const u8, size))
1041    }
1042
1043    fn remove_memory_region(
1044        &self,
1045        region: mpu::Region,
1046        config: &mut Self::MpuConfig,
1047    ) -> Result<(), ()> {
1048        let index = config
1049            .regions
1050            .iter()
1051            .enumerate()
1052            .find(|(_i, r)| {
1053                // `start as usize + size` in lieu of a safe pointer offset method
1054                r.0 != TORUserPMPCFG::OFF
1055                    && r.1 == region.start_address()
1056                    && r.2 == (region.start_address() as usize + region.size()) as *const u8
1057            })
1058            .map(|(i, _)| i)
1059            .ok_or(())?;
1060
1061        config.regions[index].0 = TORUserPMPCFG::OFF;
1062        config.is_dirty.set(true);
1063
1064        Ok(())
1065    }
1066
1067    fn allocate_app_memory_region(
1068        &self,
1069        unallocated_memory_start: *const u8,
1070        unallocated_memory_size: usize,
1071        min_memory_size: usize,
1072        initial_app_memory_size: usize,
1073        initial_kernel_memory_size: usize,
1074        permissions: mpu::Permissions,
1075        config: &mut Self::MpuConfig,
1076    ) -> Option<(*const u8, usize)> {
1077        // An app memory region can only be allocated once per `MpuConfig`.
1078        // If we already have one, abort:
1079        if config.app_memory_region.is_some() {
1080            return None;
1081        }
1082
1083        // Find a free region slot. If we don't have one, abort early:
1084        let region_num = config
1085            .regions
1086            .iter()
1087            .enumerate()
1088            .find(|(_i, (pmpcfg, _, _))| *pmpcfg == TORUserPMPCFG::OFF)
1089            .map(|(i, _)| i)?;
1090
1091        // Now, meet the PMP TOR region constraints for the region specified by
1092        // `initial_app_memory_size` (which is the part of the region actually
1093        // protected by the PMP). For this, start with the provided start
1094        // address and size, transform them to meet the constraints, and then
1095        // check that we're still within the bounds of the provided values:
1096        let mut start = unallocated_memory_start as usize;
1097        let mut pmp_region_size = initial_app_memory_size;
1098
1099        // Region start always has to align to 4 bytes. Round up to a 4 byte
1100        // boundary if required:
1101        if start % 4 != 0 {
1102            start += 4 - (start % 4);
1103        }
1104
1105        // Region size always has to align to 4 bytes. Round up to a 4 byte
1106        // boundary if required:
1107        if pmp_region_size % 4 != 0 {
1108            pmp_region_size += 4 - (pmp_region_size % 4);
1109        }
1110
1111        // Regions must be at least 4 bytes in size.
1112        if pmp_region_size < 4 {
1113            pmp_region_size = 4;
1114        }
1115
1116        // We need to provide a memory block that fits both the initial app and
1117        // kernel memory sections, and is `min_memory_size` bytes
1118        // long. Calculate the length of this block with our new PMP-aliged
1119        // size:
1120        let memory_block_size = cmp::max(
1121            min_memory_size,
1122            pmp_region_size + initial_kernel_memory_size,
1123        );
1124
1125        // Now, check to see whether the adjusted start and size still meet the
1126        // allocation constraints, namely ensure that
1127        //
1128        //     start + memory_block_size
1129        //         <= unallocated_memory_start + unallocated_memory_size
1130        //
1131        // , which ensures the PMP constraints didn't push us over the bounds of
1132        // the provided memory region, and we can fit the entire allocation as
1133        // requested by the kernel:
1134        if start + memory_block_size > (unallocated_memory_start as usize) + unallocated_memory_size
1135        {
1136            // Overflowing the provided memory region, can't make allocation:
1137            return None;
1138        }
1139
1140        // Finally, check that this new region does not overlap with any
1141        // existing configured userspace region:
1142        for region in config.regions.iter() {
1143            if region.0 != TORUserPMPCFG::OFF
1144                && region_overlaps(region, start as *const u8, memory_block_size)
1145            {
1146                return None;
1147            }
1148        }
1149
1150        // All checks passed, store region allocation, indicate the
1151        // app_memory_region, and mark config as dirty:
1152        config.regions[region_num] = (
1153            permissions.into(),
1154            start as *const u8,
1155            (start + pmp_region_size) as *const u8,
1156        );
1157        config.is_dirty.set(true);
1158        config.app_memory_region.replace(region_num);
1159
1160        Some((start as *const u8, memory_block_size))
1161    }
1162
1163    fn update_app_memory_region(
1164        &self,
1165        app_memory_break: *const u8,
1166        kernel_memory_break: *const u8,
1167        permissions: mpu::Permissions,
1168        config: &mut Self::MpuConfig,
1169    ) -> Result<(), ()> {
1170        let region_num = config.app_memory_region.get().ok_or(())?;
1171
1172        let mut app_memory_break = app_memory_break as usize;
1173        let kernel_memory_break = kernel_memory_break as usize;
1174
1175        // Ensure that the requested app_memory_break complies with PMP
1176        // alignment constraints, namely that the region's end address is 4 byte
1177        // aligned:
1178        if app_memory_break % 4 != 0 {
1179            app_memory_break += 4 - (app_memory_break % 4);
1180        }
1181
1182        // Check if the app has run out of memory:
1183        if app_memory_break > kernel_memory_break {
1184            return Err(());
1185        }
1186
1187        // If we're not out of memory, update the region configuration
1188        // accordingly:
1189        config.regions[region_num].0 = permissions.into();
1190        config.regions[region_num].2 = app_memory_break as *const u8;
1191        config.is_dirty.set(true);
1192
1193        Ok(())
1194    }
1195
1196    fn configure_mpu(&self, config: &Self::MpuConfig) {
1197        if !self.last_configured_for.contains(&config.id) || config.is_dirty.get() {
1198            self.pmp.configure_pmp(&config.regions).unwrap();
1199            config.is_dirty.set(false);
1200            self.last_configured_for.set(config.id);
1201        }
1202    }
1203}
1204
1205#[cfg(test)]
1206pub mod tor_user_pmp_test {
1207    use super::{TORUserPMP, TORUserPMPCFG};
1208
1209    struct MockTORUserPMP;
1210    impl<const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS> for MockTORUserPMP {
1211        // Don't require any const-assertions in the MockTORUserPMP.
1212        const CONST_ASSERT_CHECK: () = ();
1213
1214        fn available_regions(&self) -> usize {
1215            // For the MockTORUserPMP, we always assume to have the full number
1216            // of MPU_REGIONS available. More advanced tests may want to return
1217            // a different number here (to simulate kernel memory protection)
1218            // and make the configuration fail at runtime, for instance.
1219            MPU_REGIONS
1220        }
1221
1222        fn configure_pmp(
1223            &self,
1224            _regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
1225        ) -> Result<(), ()> {
1226            Ok(())
1227        }
1228
1229        fn enable_user_pmp(&self) -> Result<(), ()> {
1230            Ok(())
1231        } // The kernel's MPU trait requires
1232
1233        fn disable_user_pmp(&self) {}
1234    }
1235
1236    // TODO: implement more test cases, such as:
1237    //
1238    // - Try to update the app memory break with an invalid pointer below its
1239    //   allocation's start address.
1240
1241    #[test]
1242    fn test_mpu_region_no_overlap() {
1243        use crate::pmp::PMPUserMPU;
1244        use kernel::platform::mpu::{Permissions, MPU};
1245
1246        let mpu: PMPUserMPU<8, MockTORUserPMP> = PMPUserMPU::new(MockTORUserPMP);
1247        let mut config = mpu
1248            .new_config()
1249            .expect("Failed to allocate the first MPU config");
1250
1251        // Allocate a region which spans from 0x40000000 to 0x80000000 (this
1252        // meets PMP alignment constraints and will work on 32-bit and 64-bit
1253        // systems)
1254        let region_0 = mpu
1255            .allocate_region(
1256                0x40000000 as *const u8,
1257                0x40000000,
1258                0x40000000,
1259                Permissions::ReadWriteOnly,
1260                &mut config,
1261            )
1262            .expect(
1263                "Failed to allocate a well-aligned R/W MPU region with \
1264                 unallocated_memory_size == min_region_size",
1265            );
1266        assert!(region_0.start_address() == 0x40000000 as *const u8);
1267        assert!(region_0.size() == 0x40000000);
1268
1269        // Try to allocate a region adjacent to `region_0`. This should work:
1270        let region_1 = mpu
1271            .allocate_region(
1272                0x80000000 as *const u8,
1273                0x10000000,
1274                0x10000000,
1275                Permissions::ReadExecuteOnly,
1276                &mut config,
1277            )
1278            .expect(
1279                "Failed to allocate a well-aligned R/W MPU region adjacent to \
1280                 another region",
1281            );
1282        assert!(region_1.start_address() == 0x80000000 as *const u8);
1283        assert!(region_1.size() == 0x10000000);
1284
1285        // Remove the previously allocated `region_1`:
1286        mpu.remove_memory_region(region_1, &mut config)
1287            .expect("Failed to remove valid MPU region allocation");
1288
1289        // Allocate another region which spans from 0xc0000000 to 0xd0000000
1290        // (this meets PMP alignment constraints and will work on 32-bit and
1291        // 64-bit systems), but this time allocate it using the
1292        // `allocate_app_memory_region` method. We want a region of `0x20000000`
1293        // bytes, but only the first `0x10000000` should be accessible to the
1294        // app.
1295        let (region_2_start, region_2_size) = mpu
1296            .allocate_app_memory_region(
1297                0xc0000000 as *const u8,
1298                0x20000000,
1299                0x20000000,
1300                0x10000000,
1301                0x08000000,
1302                Permissions::ReadWriteOnly,
1303                &mut config,
1304            )
1305            .expect(
1306                "Failed to allocate a well-aligned R/W app memory MPU region \
1307                 with unallocated_memory_size == min_region_size",
1308            );
1309        assert!(region_2_start == 0xc0000000 as *const u8);
1310        assert!(region_2_size == 0x20000000);
1311
1312        // --> General overlap tests involving both regions
1313
1314        // Now, try to allocate another region that spans over both memory
1315        // regions. This should fail.
1316        assert!(mpu
1317            .allocate_region(
1318                0x40000000 as *const u8,
1319                0xc0000000,
1320                0xc0000000,
1321                Permissions::ReadOnly,
1322                &mut config,
1323            )
1324            .is_none());
1325
1326        // Try to allocate a region that spans over parts of both memory
1327        // regions. This should fail.
1328        assert!(mpu
1329            .allocate_region(
1330                0x48000000 as *const u8,
1331                0x80000000,
1332                0x80000000,
1333                Permissions::ReadOnly,
1334                &mut config,
1335            )
1336            .is_none());
1337
1338        // --> Overlap tests involving a single region (region_0)
1339        //
1340        // We define these in an array, such that we can run the tests with the
1341        // `region_0` defined (to confirm that the allocations are indeed
1342        // refused), and with `region_0` removed (to make sure they would work
1343        // in general).
1344        let overlap_region_0_tests = [
1345            (
1346                // Try to allocate a region that is contained within
1347                // `region_0`. This should fail.
1348                0x41000000 as *const u8,
1349                0x01000000,
1350                0x01000000,
1351                Permissions::ReadWriteOnly,
1352            ),
1353            (
1354                // Try to allocate a region that overlaps with `region_0` in the
1355                // front. This should fail.
1356                0x38000000 as *const u8,
1357                0x10000000,
1358                0x10000000,
1359                Permissions::ReadWriteExecute,
1360            ),
1361            (
1362                // Try to allocate a region that overlaps with `region_0` in the
1363                // back. This should fail.
1364                0x48000000 as *const u8,
1365                0x10000000,
1366                0x10000000,
1367                Permissions::ExecuteOnly,
1368            ),
1369            (
1370                // Try to allocate a region that spans over `region_0`. This
1371                // should fail.
1372                0x38000000 as *const u8,
1373                0x20000000,
1374                0x20000000,
1375                Permissions::ReadWriteOnly,
1376            ),
1377        ];
1378
1379        // Make sure that the allocation requests fail with `region_0` defined:
1380        for (memory_start, memory_size, length, perms) in overlap_region_0_tests.iter() {
1381            assert!(mpu
1382                .allocate_region(*memory_start, *memory_size, *length, *perms, &mut config,)
1383                .is_none());
1384        }
1385
1386        // Now, remove `region_0` and re-run the tests. Every test-case should
1387        // succeed now (in isolation, hence removing the successful allocations):
1388        mpu.remove_memory_region(region_0, &mut config)
1389            .expect("Failed to remove valid MPU region allocation");
1390
1391        for region @ (memory_start, memory_size, length, perms) in overlap_region_0_tests.iter() {
1392            let allocation_res =
1393                mpu.allocate_region(*memory_start, *memory_size, *length, *perms, &mut config);
1394
1395            match allocation_res {
1396                Some(region) => {
1397                    mpu.remove_memory_region(region, &mut config)
1398                        .expect("Failed to remove valid MPU region allocation");
1399                }
1400                None => {
1401                    panic!(
1402                        "Failed to allocate region that does not overlap and should meet alignment constraints: {:?}",
1403                        region
1404                    );
1405                }
1406            }
1407        }
1408
1409        // Make sure we can technically allocate a memory region that overlaps
1410        // with the kernel part of the `app_memory_region`.
1411        //
1412        // It is unclear whether this should be supported.
1413        let region_2 = mpu
1414            .allocate_region(
1415                0xd0000000 as *const u8,
1416                0x10000000,
1417                0x10000000,
1418                Permissions::ReadWriteOnly,
1419                &mut config,
1420            )
1421            .unwrap();
1422        assert!(region_2.start_address() == 0xd0000000 as *const u8);
1423        assert!(region_2.size() == 0x10000000);
1424
1425        // Now, we can grow the app memory break into this region:
1426        mpu.update_app_memory_region(
1427            0xd0000004 as *const u8,
1428            0xd8000000 as *const u8,
1429            Permissions::ReadWriteOnly,
1430            &mut config,
1431        )
1432        .expect("Failed to grow the app memory region into an existing other MPU region");
1433
1434        // Now, we have two overlapping MPU regions. Remove `region_2`, and try
1435        // to reallocate it as `region_3`. This should fail now, demonstrating
1436        // that we managed to reach an invalid intermediate state:
1437        mpu.remove_memory_region(region_2, &mut config)
1438            .expect("Failed to remove valid MPU region allocation");
1439        assert!(mpu
1440            .allocate_region(
1441                0xd0000000 as *const u8,
1442                0x10000000,
1443                0x10000000,
1444                Permissions::ReadWriteOnly,
1445                &mut config,
1446            )
1447            .is_none());
1448    }
1449}
1450
1451pub mod simple {
1452    use super::{pmpcfg_octet, TORUserPMP, TORUserPMPCFG};
1453    use crate::csr;
1454    use core::fmt;
1455    use kernel::utilities::registers::{FieldValue, LocalRegisterCopy};
1456
1457    /// A "simple" RISC-V PMP implementation.
1458    ///
1459    /// The SimplePMP does not support locked regions, kernel memory protection,
1460    /// or any ePMP features (using the mseccfg CSR). It is generic over the
1461    /// number of hardware PMP regions available. `AVAILABLE_ENTRIES` is
1462    /// expected to be set to the number of available entries.
1463    ///
1464    /// [`SimplePMP`] implements [`TORUserPMP`] to expose all of its regions as
1465    /// "top of range" (TOR) regions (each taking up two physical PMP entires)
1466    /// for use as a user-mode memory protection mechanism.
1467    ///
1468    /// Notably, [`SimplePMP`] implements `TORUserPMP<MPU_REGIONS>` over a
1469    /// generic `MPU_REGIONS` where `MPU_REGIONS <= (AVAILABLE_ENTRIES / 2)`. As
1470    /// PMP re-configuration can have a significiant runtime overhead, users are
1471    /// free to specify a small `MPU_REGIONS` const-generic parameter to reduce
1472    /// the runtime overhead induced through PMP configuration, at the cost of
1473    /// having less PMP regions available to use for userspace memory
1474    /// protection.
1475    pub struct SimplePMP<const AVAILABLE_ENTRIES: usize>;
1476
1477    impl<const AVAILABLE_ENTRIES: usize> SimplePMP<AVAILABLE_ENTRIES> {
1478        pub unsafe fn new() -> Result<Self, ()> {
1479            // The SimplePMP does not support locked regions, kernel memory
1480            // protection, or any ePMP features (using the mseccfg CSR). Ensure
1481            // that we don't find any locked regions. If we don't have locked
1482            // regions and can still successfully execute code, this means that
1483            // we're not in the ePMP machine-mode lockdown mode, and can treat
1484            // our hardware as a regular PMP.
1485            //
1486            // Furthermore, we test whether we can use each entry (i.e. whether
1487            // it actually exists in HW) by flipping the RWX bits. If we can't
1488            // flip them, then `AVAILABLE_ENTRIES` is incorrect.  However, this
1489            // is not sufficient to check for locked regions, because of the
1490            // ePMP's rule-lock-bypass bit. If a rule is locked, it might be the
1491            // reason why we can execute code or read-write data in machine mode
1492            // right now. Thus, never try to touch a locked region, as we might
1493            // well revoke access to a kernel region!
1494            for i in 0..AVAILABLE_ENTRIES {
1495                // Read the entry's CSR:
1496                let pmpcfg_csr = csr::CSR.pmpconfig_get(i / 4);
1497
1498                // Extract the entry's pmpcfg octet:
1499                let pmpcfg: LocalRegisterCopy<u8, pmpcfg_octet::Register> = LocalRegisterCopy::new(
1500                    pmpcfg_csr.overflowing_shr(((i % 4) * 8) as u32).0 as u8,
1501                );
1502
1503                // As outlined above, we never touch a locked region. Thus, bail
1504                // out if it's locked:
1505                if pmpcfg.is_set(pmpcfg_octet::l) {
1506                    return Err(());
1507                }
1508
1509                // Now that it's not locked, we can be sure that regardless of
1510                // any ePMP bits, this region is either ignored or entirely
1511                // denied for machine-mode access. Hence, we can change it in
1512                // arbitrary ways without breaking our own memory access. Try to
1513                // flip the R/W/X bits:
1514                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr ^ (7 << ((i % 4) * 8)));
1515
1516                // Check if the CSR changed:
1517                if pmpcfg_csr == csr::CSR.pmpconfig_get(i / 4) {
1518                    // Didn't change! This means that this region is not backed
1519                    // by HW. Return an error as `AVAILABLE_ENTRIES` is
1520                    // incorrect:
1521                    return Err(());
1522                }
1523
1524                // Finally, turn the region off:
1525                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr & !(0x18 << ((i % 4) * 8)));
1526            }
1527
1528            // Hardware PMP is verified to be in a compatible mode / state, and
1529            // has at least `AVAILABLE_ENTRIES` entries.
1530            Ok(SimplePMP)
1531        }
1532    }
1533
1534    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS>
1535        for SimplePMP<AVAILABLE_ENTRIES>
1536    {
1537        // Ensure that the MPU_REGIONS (starting at entry, and occupying two
1538        // entries per region) don't overflow the available entires.
1539        const CONST_ASSERT_CHECK: () = assert!(MPU_REGIONS <= (AVAILABLE_ENTRIES / 2));
1540
1541        fn available_regions(&self) -> usize {
1542            // Always assume to have `MPU_REGIONS` usable TOR regions. We don't
1543            // support locked regions, or kernel protection.
1544            MPU_REGIONS
1545        }
1546
1547        // This implementation is specific for 32-bit systems. We use
1548        // `u32::from_be_bytes` and then cast to usize, as it manages to compile
1549        // on 64-bit systems as well. However, this implementation will not work
1550        // on RV64I systems, due to the changed pmpcfgX CSR layout.
1551        fn configure_pmp(
1552            &self,
1553            regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
1554        ) -> Result<(), ()> {
1555            // Could use `iter_array_chunks` once that's stable.
1556            let mut regions_iter = regions.iter();
1557            let mut i = 0;
1558
1559            while let Some(even_region) = regions_iter.next() {
1560                let odd_region_opt = regions_iter.next();
1561
1562                if let Some(odd_region) = odd_region_opt {
1563                    // We can configure two regions at once which, given that we
1564                    // start at index 0 (an even offset), translates to a single
1565                    // CSR write for the pmpcfgX register:
1566                    csr::CSR.pmpconfig_set(
1567                        i / 2,
1568                        u32::from_be_bytes([
1569                            odd_region.0.get(),
1570                            TORUserPMPCFG::OFF.get(),
1571                            even_region.0.get(),
1572                            TORUserPMPCFG::OFF.get(),
1573                        ]) as usize,
1574                    );
1575
1576                    // Now, set the addresses of the respective regions, if they
1577                    // are enabled, respectively:
1578                    if even_region.0 != TORUserPMPCFG::OFF {
1579                        csr::CSR
1580                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1581                        csr::CSR
1582                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1583                    }
1584
1585                    if odd_region.0 != TORUserPMPCFG::OFF {
1586                        csr::CSR
1587                            .pmpaddr_set(i * 2 + 2, (odd_region.1 as usize).overflowing_shr(2).0);
1588                        csr::CSR
1589                            .pmpaddr_set(i * 2 + 3, (odd_region.2 as usize).overflowing_shr(2).0);
1590                    }
1591
1592                    i += 2;
1593                } else {
1594                    // TODO: check overhead of code
1595                    // Modify the first two pmpcfgX octets for this region:
1596                    csr::CSR.pmpconfig_modify(
1597                        i / 2,
1598                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
1599                            0x0000FFFF,
1600                            0,
1601                            u32::from_be_bytes([
1602                                0,
1603                                0,
1604                                even_region.0.get(),
1605                                TORUserPMPCFG::OFF.get(),
1606                            ]) as usize,
1607                        ),
1608                    );
1609
1610                    // Set the addresses if the region is enabled:
1611                    if even_region.0 != TORUserPMPCFG::OFF {
1612                        csr::CSR
1613                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1614                        csr::CSR
1615                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1616                    }
1617
1618                    i += 1;
1619                }
1620            }
1621
1622            Ok(())
1623        }
1624
1625        fn enable_user_pmp(&self) -> Result<(), ()> {
1626            // No-op. The SimplePMP does not have any kernel-enforced regions.
1627            Ok(())
1628        }
1629
1630        fn disable_user_pmp(&self) {
1631            // No-op. The SimplePMP does not have any kernel-enforced regions.
1632        }
1633    }
1634
1635    impl<const AVAILABLE_ENTRIES: usize> fmt::Display for SimplePMP<AVAILABLE_ENTRIES> {
1636        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1637            write!(f, " PMP hardware configuration -- entries: \r\n")?;
1638            unsafe { super::format_pmp_entries::<AVAILABLE_ENTRIES>(f) }
1639        }
1640    }
1641}
1642
1643pub mod kernel_protection {
1644    use super::{pmpcfg_octet, NAPOTRegionSpec, TORRegionSpec, TORUserPMP, TORUserPMPCFG};
1645    use crate::csr;
1646    use core::fmt;
1647    use kernel::utilities::registers::{FieldValue, LocalRegisterCopy};
1648
1649    // ---------- Kernel memory-protection PMP memory region wrapper types -----
1650    //
1651    // These types exist primarily to avoid argument confusion in the
1652    // [`KernelProtectionPMP`] constructor, which accepts the addresses of these
1653    // memory regions as arguments. They further encode whether a region must
1654    // adhere to the `NAPOT` or `TOR` addressing mode constraints:
1655
1656    /// The flash memory region address range.
1657    ///
1658    /// Configured in the PMP as a `NAPOT` region.
1659    #[derive(Copy, Clone, Debug)]
1660    pub struct FlashRegion(pub NAPOTRegionSpec);
1661
1662    /// The RAM region address range.
1663    ///
1664    /// Configured in the PMP as a `NAPOT` region.
1665    #[derive(Copy, Clone, Debug)]
1666    pub struct RAMRegion(pub NAPOTRegionSpec);
1667
1668    /// The MMIO region address range.
1669    ///
1670    /// Configured in the PMP as a `NAPOT` region.
1671    #[derive(Copy, Clone, Debug)]
1672    pub struct MMIORegion(pub NAPOTRegionSpec);
1673
1674    /// The PMP region specification for the kernel `.text` section.
1675    ///
1676    /// This is to be made accessible to machine-mode as read-execute.
1677    /// Configured in the PMP as a `TOR` region.
1678    #[derive(Copy, Clone, Debug)]
1679    pub struct KernelTextRegion(pub TORRegionSpec);
1680
1681    /// A RISC-V PMP implementation which supports machine-mode (kernel) memory
1682    /// protection, with a fixed number of "kernel regions" (such as `.text`,
1683    /// flash, RAM and MMIO).
1684    ///
1685    /// This implementation will configure the PMP in the following way:
1686    ///
1687    ///   ```text
1688    ///   |-------+-----------------------------------------+-------+---+-------|
1689    ///   | ENTRY | REGION / ADDR                           | MODE  | L | PERMS |
1690    ///   |-------+-----------------------------------------+-------+---+-------|
1691    ///   |     0 | /                                     \ | OFF   |   |       |
1692    ///   |     1 | \ Userspace TOR region #0             / | TOR   |   | ????? |
1693    ///   |       |                                         |       |   |       |
1694    ///   |     2 | /                                     \ | OFF   |   |       |
1695    ///   |     3 | \ Userspace TOR region #1             / | TOR   |   | ????? |
1696    ///   |       |                                         |       |   |       |
1697    ///   | 4 ... | /                                     \ |       |   |       |
1698    ///   | n - 8 | \ Userspace TOR region #x             / |       |   |       |
1699    ///   |       |                                         |       |   |       |
1700    ///   | n - 7 | "Deny-all" user-mode rule (all memory)  | NAPOT |   | ----- |
1701    ///   |       |                                         |       |   |       |
1702    ///   | n - 6 | --------------------------------------- | OFF   | X | ----- |
1703    ///   | n - 5 | Kernel .text section                    | TOR   | X | R/X   |
1704    ///   |       |                                         |       |   |       |
1705    ///   | n - 4 | FLASH (spanning kernel & apps)          | NAPOT | X | R     |
1706    ///   |       |                                         |       |   |       |
1707    ///   | n - 3 | RAM (spanning kernel & apps)            | NAPOT | X | R/W   |
1708    ///   |       |                                         |       |   |       |
1709    ///   | n - 2 | MMIO                                    | NAPOT | X | R/W   |
1710    ///   |       |                                         |       |   |       |
1711    ///   | n - 1 | "Deny-all" machine-mode    (all memory) | NAPOT | X | ----- |
1712    ///   |-------+-----------------------------------------+-------+---+-------|
1713    ///   ```
1714    ///
1715    /// This implementation does not use any `mseccfg` protection bits (ePMP
1716    /// functionality). To protect machine-mode (kernel) memory regions, regions
1717    /// must be marked as locked. However, locked regions apply to both user-
1718    /// and machine-mode. Thus, region `n - 7` serves as a "deny-all" user-mode
1719    /// rule, which prohibits all accesses not explicitly allowed through rules
1720    /// `< n - 7`. Kernel memory is made accessible underneath this "deny-all"
1721    /// region, which does not apply to machine-mode.
1722    ///
1723    /// This PMP implementation supports the [`TORUserPMP`] interface with
1724    /// `MPU_REGIONS <= ((AVAILABLE_ENTRIES - 7) / 2)`, to leave sufficient
1725    /// space for the "deny-all" and kernel regions. This constraint is enforced
1726    /// through the [`KernelProtectionPMP::CONST_ASSERT_CHECK`] associated
1727    /// constant, which MUST be evaluated by the consumer of the [`TORUserPMP`]
1728    /// trait (usually the [`PMPUserMPU`](super::PMPUserMPU) implementation).
1729    pub struct KernelProtectionPMP<const AVAILABLE_ENTRIES: usize>;
1730
1731    impl<const AVAILABLE_ENTRIES: usize> KernelProtectionPMP<AVAILABLE_ENTRIES> {
1732        pub unsafe fn new(
1733            flash: FlashRegion,
1734            ram: RAMRegion,
1735            mmio: MMIORegion,
1736            kernel_text: KernelTextRegion,
1737        ) -> Result<Self, ()> {
1738            for i in 0..AVAILABLE_ENTRIES {
1739                // Read the entry's CSR:
1740                let pmpcfg_csr = csr::CSR.pmpconfig_get(i / 4);
1741
1742                // Extract the entry's pmpcfg octet:
1743                let pmpcfg: LocalRegisterCopy<u8, pmpcfg_octet::Register> = LocalRegisterCopy::new(
1744                    pmpcfg_csr.overflowing_shr(((i % 4) * 8) as u32).0 as u8,
1745                );
1746
1747                // As outlined above, we never touch a locked region. Thus, bail
1748                // out if it's locked:
1749                if pmpcfg.is_set(pmpcfg_octet::l) {
1750                    return Err(());
1751                }
1752
1753                // Now that it's not locked, we can be sure that regardless of
1754                // any ePMP bits, this region is either ignored or entirely
1755                // denied for machine-mode access. Hence, we can change it in
1756                // arbitrary ways without breaking our own memory access. Try to
1757                // flip the R/W/X bits:
1758                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr ^ (7 << ((i % 4) * 8)));
1759
1760                // Check if the CSR changed:
1761                if pmpcfg_csr == csr::CSR.pmpconfig_get(i / 4) {
1762                    // Didn't change! This means that this region is not backed
1763                    // by HW. Return an error as `AVAILABLE_ENTRIES` is
1764                    // incorrect:
1765                    return Err(());
1766                }
1767
1768                // Finally, turn the region off:
1769                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr & !(0x18 << ((i % 4) * 8)));
1770            }
1771
1772            // -----------------------------------------------------------------
1773            // Hardware PMP is verified to be in a compatible mode & state, and
1774            // has at least `AVAILABLE_ENTRIES` entries.
1775            // -----------------------------------------------------------------
1776
1777            // Now we need to set up the various kernel memory protection
1778            // regions, and the deny-all userspace region (n - 8), never
1779            // modified.
1780
1781            // Helper to modify an arbitrary PMP entry. Because we don't know
1782            // AVAILABLE_ENTRIES in advance, there's no good way to
1783            // optimize this further.
1784            fn write_pmpaddr_pmpcfg(i: usize, pmpcfg: u8, pmpaddr: usize) {
1785                csr::CSR.pmpaddr_set(i, pmpaddr);
1786                csr::CSR.pmpconfig_modify(
1787                    i / 4,
1788                    FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
1789                        0x000000FF_usize,
1790                        (i % 4) * 8,
1791                        u32::from_be_bytes([0, 0, 0, pmpcfg]) as usize,
1792                    ),
1793                );
1794            }
1795
1796            // Set the kernel `.text`, flash, RAM and MMIO regions, in no
1797            // particular order, with the exception of `.text` and flash:
1798            // `.text` must precede flash, as otherwise we'd be revoking execute
1799            // permissions temporarily. Given that we can currently execute
1800            // code, this should not have any impact on our accessible memory,
1801            // assuming that the provided regions are not otherwise aliased.
1802
1803            // MMIO at n - 2:
1804            write_pmpaddr_pmpcfg(
1805                AVAILABLE_ENTRIES - 2,
1806                (pmpcfg_octet::a::NAPOT
1807                    + pmpcfg_octet::r::SET
1808                    + pmpcfg_octet::w::SET
1809                    + pmpcfg_octet::x::CLEAR
1810                    + pmpcfg_octet::l::SET)
1811                    .into(),
1812                mmio.0.pmpaddr(),
1813            );
1814
1815            // RAM at n - 3:
1816            write_pmpaddr_pmpcfg(
1817                AVAILABLE_ENTRIES - 3,
1818                (pmpcfg_octet::a::NAPOT
1819                    + pmpcfg_octet::r::SET
1820                    + pmpcfg_octet::w::SET
1821                    + pmpcfg_octet::x::CLEAR
1822                    + pmpcfg_octet::l::SET)
1823                    .into(),
1824                ram.0.pmpaddr(),
1825            );
1826
1827            // `.text` at n - 6 and n - 5 (TOR region):
1828            write_pmpaddr_pmpcfg(
1829                AVAILABLE_ENTRIES - 6,
1830                (pmpcfg_octet::a::OFF
1831                    + pmpcfg_octet::r::CLEAR
1832                    + pmpcfg_octet::w::CLEAR
1833                    + pmpcfg_octet::x::CLEAR
1834                    + pmpcfg_octet::l::SET)
1835                    .into(),
1836                kernel_text.0.pmpaddr_a(),
1837            );
1838            write_pmpaddr_pmpcfg(
1839                AVAILABLE_ENTRIES - 5,
1840                (pmpcfg_octet::a::TOR
1841                    + pmpcfg_octet::r::SET
1842                    + pmpcfg_octet::w::CLEAR
1843                    + pmpcfg_octet::x::SET
1844                    + pmpcfg_octet::l::SET)
1845                    .into(),
1846                kernel_text.0.pmpaddr_b(),
1847            );
1848
1849            // flash at n - 4:
1850            write_pmpaddr_pmpcfg(
1851                AVAILABLE_ENTRIES - 4,
1852                (pmpcfg_octet::a::NAPOT
1853                    + pmpcfg_octet::r::SET
1854                    + pmpcfg_octet::w::CLEAR
1855                    + pmpcfg_octet::x::CLEAR
1856                    + pmpcfg_octet::l::SET)
1857                    .into(),
1858                flash.0.pmpaddr(),
1859            );
1860
1861            // Now that the kernel has explicit region definitions for any
1862            // memory that it needs to have access to, we can deny other memory
1863            // accesses in our very last rule (n - 1):
1864            write_pmpaddr_pmpcfg(
1865                AVAILABLE_ENTRIES - 1,
1866                (pmpcfg_octet::a::NAPOT
1867                    + pmpcfg_octet::r::CLEAR
1868                    + pmpcfg_octet::w::CLEAR
1869                    + pmpcfg_octet::x::CLEAR
1870                    + pmpcfg_octet::l::SET)
1871                    .into(),
1872                // the entire address space:
1873                0x7FFFFFFF,
1874            );
1875
1876            // Finally, we configure the non-locked user-mode deny all
1877            // rule. This must never be removed, or otherwise usermode will be
1878            // able to access all locked regions (which are supposed to be
1879            // exclusively accessible to kernel-mode):
1880            write_pmpaddr_pmpcfg(
1881                AVAILABLE_ENTRIES - 7,
1882                (pmpcfg_octet::a::NAPOT
1883                    + pmpcfg_octet::r::CLEAR
1884                    + pmpcfg_octet::w::CLEAR
1885                    + pmpcfg_octet::x::CLEAR
1886                    + pmpcfg_octet::l::CLEAR)
1887                    .into(),
1888                // the entire address space:
1889                0x7FFFFFFF,
1890            );
1891
1892            // Setup complete
1893            Ok(KernelProtectionPMP)
1894        }
1895    }
1896
1897    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS>
1898        for KernelProtectionPMP<AVAILABLE_ENTRIES>
1899    {
1900        /// Ensure that the MPU_REGIONS (starting at entry, and occupying two
1901        /// entries per region) don't overflow the available entires, excluding
1902        /// the 7 entires used for implementing the kernel memory protection.
1903        const CONST_ASSERT_CHECK: () = assert!(MPU_REGIONS <= ((AVAILABLE_ENTRIES - 7) / 2));
1904
1905        fn available_regions(&self) -> usize {
1906            // Always assume to have `MPU_REGIONS` usable TOR regions. We don't
1907            // support locking additional regions at runtime.
1908            MPU_REGIONS
1909        }
1910
1911        // This implementation is specific for 32-bit systems. We use
1912        // `u32::from_be_bytes` and then cast to usize, as it manages to compile
1913        // on 64-bit systems as well. However, this implementation will not work
1914        // on RV64I systems, due to the changed pmpcfgX CSR layout.
1915        fn configure_pmp(
1916            &self,
1917            regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
1918        ) -> Result<(), ()> {
1919            // Could use `iter_array_chunks` once that's stable.
1920            let mut regions_iter = regions.iter();
1921            let mut i = 0;
1922
1923            while let Some(even_region) = regions_iter.next() {
1924                let odd_region_opt = regions_iter.next();
1925
1926                if let Some(odd_region) = odd_region_opt {
1927                    // We can configure two regions at once which, given that we
1928                    // start at index 0 (an even offset), translates to a single
1929                    // CSR write for the pmpcfgX register:
1930                    csr::CSR.pmpconfig_set(
1931                        i / 2,
1932                        u32::from_be_bytes([
1933                            odd_region.0.get(),
1934                            TORUserPMPCFG::OFF.get(),
1935                            even_region.0.get(),
1936                            TORUserPMPCFG::OFF.get(),
1937                        ]) as usize,
1938                    );
1939
1940                    // Now, set the addresses of the respective regions, if they
1941                    // are enabled, respectively:
1942                    if even_region.0 != TORUserPMPCFG::OFF {
1943                        csr::CSR
1944                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1945                        csr::CSR
1946                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1947                    }
1948
1949                    if odd_region.0 != TORUserPMPCFG::OFF {
1950                        csr::CSR
1951                            .pmpaddr_set(i * 2 + 2, (odd_region.1 as usize).overflowing_shr(2).0);
1952                        csr::CSR
1953                            .pmpaddr_set(i * 2 + 3, (odd_region.2 as usize).overflowing_shr(2).0);
1954                    }
1955
1956                    i += 2;
1957                } else {
1958                    // Modify the first two pmpcfgX octets for this region:
1959                    csr::CSR.pmpconfig_modify(
1960                        i / 2,
1961                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
1962                            0x0000FFFF,
1963                            0,
1964                            u32::from_be_bytes([
1965                                0,
1966                                0,
1967                                even_region.0.get(),
1968                                TORUserPMPCFG::OFF.get(),
1969                            ]) as usize,
1970                        ),
1971                    );
1972
1973                    // Set the addresses if the region is enabled:
1974                    if even_region.0 != TORUserPMPCFG::OFF {
1975                        csr::CSR
1976                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1977                        csr::CSR
1978                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1979                    }
1980
1981                    i += 1;
1982                }
1983            }
1984
1985            Ok(())
1986        }
1987
1988        fn enable_user_pmp(&self) -> Result<(), ()> {
1989            // No-op. User-mode regions are never enforced in machine-mode, and
1990            // thus can be configured direct and may stay enabled in
1991            // machine-mode.
1992            Ok(())
1993        }
1994
1995        fn disable_user_pmp(&self) {
1996            // No-op. User-mode regions are never enforced in machine-mode, and
1997            // thus can be configured direct and may stay enabled in
1998            // machine-mode.
1999        }
2000    }
2001
2002    impl<const AVAILABLE_ENTRIES: usize> fmt::Display for KernelProtectionPMP<AVAILABLE_ENTRIES> {
2003        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2004            write!(f, " PMP hardware configuration -- entries: \r\n")?;
2005            unsafe { super::format_pmp_entries::<AVAILABLE_ENTRIES>(f) }
2006        }
2007    }
2008}
2009
2010pub mod kernel_protection_mml_epmp {
2011    use super::{pmpcfg_octet, NAPOTRegionSpec, TORRegionSpec, TORUserPMP, TORUserPMPCFG};
2012    use crate::csr;
2013    use core::cell::Cell;
2014    use core::fmt;
2015    use kernel::platform::mpu;
2016    use kernel::utilities::registers::interfaces::{Readable, Writeable};
2017    use kernel::utilities::registers::{FieldValue, LocalRegisterCopy};
2018
2019    // ---------- Kernel memory-protection PMP memory region wrapper types -----
2020    //
2021    // These types exist primarily to avoid argument confusion in the
2022    // [`KernelProtectionMMLEPMP`] constructor, which accepts the addresses of
2023    // these memory regions as arguments. They further encode whether a region
2024    // must adhere to the `NAPOT` or `TOR` addressing mode constraints:
2025
2026    /// The flash memory region address range.
2027    ///
2028    /// Configured in the PMP as a `NAPOT` region.
2029    #[derive(Copy, Clone, Debug)]
2030    pub struct FlashRegion(pub NAPOTRegionSpec);
2031
2032    /// The RAM region address range.
2033    ///
2034    /// Configured in the PMP as a `NAPOT` region.
2035    #[derive(Copy, Clone, Debug)]
2036    pub struct RAMRegion(pub NAPOTRegionSpec);
2037
2038    /// The MMIO region address range.
2039    ///
2040    /// Configured in the PMP as a `NAPOT` region.
2041    #[derive(Copy, Clone, Debug)]
2042    pub struct MMIORegion(pub NAPOTRegionSpec);
2043
2044    /// The PMP region specification for the kernel `.text` section.
2045    ///
2046    /// This is to be made accessible to machine-mode as read-execute.
2047    /// Configured in the PMP as a `TOR` region.
2048    #[derive(Copy, Clone, Debug)]
2049    pub struct KernelTextRegion(pub TORRegionSpec);
2050
2051    /// A RISC-V ePMP implementation.
2052    ///
2053    /// Supports machine-mode (kernel) memory protection by using the
2054    /// machine-mode lockdown mode (MML), with a fixed number of
2055    /// "kernel regions" (such as `.text`, flash, RAM and MMIO).
2056    ///
2057    /// This implementation will configure the ePMP in the following way:
2058    ///
2059    /// - `mseccfg` CSR:
2060    ///   ```text
2061    ///   |-------------+-----------------------------------------------+-------|
2062    ///   | MSECCFG BIT | LABEL                                         | STATE |
2063    ///   |-------------+-----------------------------------------------+-------|
2064    ///   |           0 | Machine-Mode Lockdown (MML)                   |     1 |
2065    ///   |           1 | Machine-Mode Whitelist Policy (MMWP)          |     1 |
2066    ///   |           2 | Rule-Lock Bypass (RLB)                        |     0 |
2067    ///   |-------------+-----------------------------------------------+-------|
2068    ///   ```
2069    ///
2070    /// - `pmpaddrX` / `pmpcfgX` CSRs:
2071    ///   ```text
2072    ///   |-------+-----------------------------------------+-------+---+-------|
2073    ///   | ENTRY | REGION / ADDR                           | MODE  | L | PERMS |
2074    ///   |-------+-----------------------------------------+-------+---+-------|
2075    ///   |     0 | --------------------------------------- | OFF   | X | ----- |
2076    ///   |     1 | Kernel .text section                    | TOR   | X | R/X   |
2077    ///   |       |                                         |       |   |       |
2078    ///   |     2 | /                                     \ | OFF   |   |       |
2079    ///   |     3 | \ Userspace TOR region #0             / | TOR   |   | ????? |
2080    ///   |       |                                         |       |   |       |
2081    ///   |     4 | /                                     \ | OFF   |   |       |
2082    ///   |     5 | \ Userspace TOR region #1             / | TOR   |   | ????? |
2083    ///   |       |                                         |       |   |       |
2084    ///   | 6 ... | /                                     \ |       |   |       |
2085    ///   | n - 4 | \ Userspace TOR region #x             / |       |   |       |
2086    ///   |       |                                         |       |   |       |
2087    ///   | n - 3 | FLASH (spanning kernel & apps)          | NAPOT | X | R     |
2088    ///   |       |                                         |       |   |       |
2089    ///   | n - 2 | RAM (spanning kernel & apps)            | NAPOT | X | R/W   |
2090    ///   |       |                                         |       |   |       |
2091    ///   | n - 1 | MMIO                                    | NAPOT | X | R/W   |
2092    ///   |-------+-----------------------------------------+-------+---+-------|
2093    ///   ```
2094    ///
2095    /// Crucially, this implementation relies on an unconfigured hardware PMP
2096    /// implementing the ePMP (`mseccfg` CSR) extension, providing the Machine
2097    /// Lockdown Mode (MML) security bit. This bit is required to ensure that
2098    /// any machine-mode (kernel) protection regions (lock bit set) are only
2099    /// accessible to kernel mode.
2100    pub struct KernelProtectionMMLEPMP<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> {
2101        user_pmp_enabled: Cell<bool>,
2102        shadow_user_pmpcfgs: [Cell<TORUserPMPCFG>; MPU_REGIONS],
2103    }
2104
2105    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize>
2106        KernelProtectionMMLEPMP<AVAILABLE_ENTRIES, MPU_REGIONS>
2107    {
2108        // Start user-mode TOR regions after the first kernel .text region:
2109        const TOR_REGIONS_OFFSET: usize = 1;
2110
2111        pub unsafe fn new(
2112            flash: FlashRegion,
2113            ram: RAMRegion,
2114            mmio: MMIORegion,
2115            kernel_text: KernelTextRegion,
2116        ) -> Result<Self, ()> {
2117            for i in 0..AVAILABLE_ENTRIES {
2118                // Read the entry's CSR:
2119                let pmpcfg_csr = csr::CSR.pmpconfig_get(i / 4);
2120
2121                // Extract the entry's pmpcfg octet:
2122                let pmpcfg: LocalRegisterCopy<u8, pmpcfg_octet::Register> = LocalRegisterCopy::new(
2123                    pmpcfg_csr.overflowing_shr(((i % 4) * 8) as u32).0 as u8,
2124                );
2125
2126                // As outlined above, we never touch a locked region. Thus, bail
2127                // out if it's locked:
2128                if pmpcfg.is_set(pmpcfg_octet::l) {
2129                    return Err(());
2130                }
2131
2132                // Now that it's not locked, we can be sure that regardless of
2133                // any ePMP bits, this region is either ignored or entirely
2134                // denied for machine-mode access. Hence, we can change it in
2135                // arbitrary ways without breaking our own memory access. Try to
2136                // flip the R/W/X bits:
2137                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr ^ (7 << ((i % 4) * 8)));
2138
2139                // Check if the CSR changed:
2140                if pmpcfg_csr == csr::CSR.pmpconfig_get(i / 4) {
2141                    // Didn't change! This means that this region is not backed
2142                    // by HW. Return an error as `AVAILABLE_ENTRIES` is
2143                    // incorrect:
2144                    return Err(());
2145                }
2146
2147                // Finally, turn the region off:
2148                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr & !(0x18 << ((i % 4) * 8)));
2149            }
2150
2151            // -----------------------------------------------------------------
2152            // Hardware PMP is verified to be in a compatible mode & state, and
2153            // has at least `AVAILABLE_ENTRIES` entries. We have not yet checked
2154            // whether the PMP is actually an _e_PMP. However, we don't want to
2155            // produce a gadget to set RLB, and so the only safe way to test
2156            // this is to set up the PMP regions and then try to enable the
2157            // mseccfg bits.
2158            // -----------------------------------------------------------------
2159
2160            // Helper to modify an arbitrary PMP entry. Because we don't know
2161            // AVAILABLE_ENTRIES in advance, there's no good way to
2162            // optimize this further.
2163            fn write_pmpaddr_pmpcfg(i: usize, pmpcfg: u8, pmpaddr: usize) {
2164                // Important to set the address first. Locking the pmpcfg
2165                // register will also lock the adress register!
2166                csr::CSR.pmpaddr_set(i, pmpaddr);
2167                csr::CSR.pmpconfig_modify(
2168                    i / 4,
2169                    FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2170                        0x000000FF_usize,
2171                        (i % 4) * 8,
2172                        u32::from_be_bytes([0, 0, 0, pmpcfg]) as usize,
2173                    ),
2174                );
2175            }
2176
2177            // Set the kernel `.text`, flash, RAM and MMIO regions, in no
2178            // particular order, with the exception of `.text` and flash:
2179            // `.text` must precede flash, as otherwise we'd be revoking execute
2180            // permissions temporarily. Given that we can currently execute
2181            // code, this should not have any impact on our accessible memory,
2182            // assuming that the provided regions are not otherwise aliased.
2183
2184            // `.text` at n - 5 and n - 4 (TOR region):
2185            write_pmpaddr_pmpcfg(
2186                0,
2187                (pmpcfg_octet::a::OFF
2188                    + pmpcfg_octet::r::CLEAR
2189                    + pmpcfg_octet::w::CLEAR
2190                    + pmpcfg_octet::x::CLEAR
2191                    + pmpcfg_octet::l::SET)
2192                    .into(),
2193                kernel_text.0.pmpaddr_a(),
2194            );
2195            write_pmpaddr_pmpcfg(
2196                1,
2197                (pmpcfg_octet::a::TOR
2198                    + pmpcfg_octet::r::SET
2199                    + pmpcfg_octet::w::CLEAR
2200                    + pmpcfg_octet::x::SET
2201                    + pmpcfg_octet::l::SET)
2202                    .into(),
2203                kernel_text.0.pmpaddr_b(),
2204            );
2205
2206            // MMIO at n - 1:
2207            write_pmpaddr_pmpcfg(
2208                AVAILABLE_ENTRIES - 1,
2209                (pmpcfg_octet::a::NAPOT
2210                    + pmpcfg_octet::r::SET
2211                    + pmpcfg_octet::w::SET
2212                    + pmpcfg_octet::x::CLEAR
2213                    + pmpcfg_octet::l::SET)
2214                    .into(),
2215                mmio.0.pmpaddr(),
2216            );
2217
2218            // RAM at n - 2:
2219            write_pmpaddr_pmpcfg(
2220                AVAILABLE_ENTRIES - 2,
2221                (pmpcfg_octet::a::NAPOT
2222                    + pmpcfg_octet::r::SET
2223                    + pmpcfg_octet::w::SET
2224                    + pmpcfg_octet::x::CLEAR
2225                    + pmpcfg_octet::l::SET)
2226                    .into(),
2227                ram.0.pmpaddr(),
2228            );
2229
2230            // flash at n - 3:
2231            write_pmpaddr_pmpcfg(
2232                AVAILABLE_ENTRIES - 3,
2233                (pmpcfg_octet::a::NAPOT
2234                    + pmpcfg_octet::r::SET
2235                    + pmpcfg_octet::w::CLEAR
2236                    + pmpcfg_octet::x::CLEAR
2237                    + pmpcfg_octet::l::SET)
2238                    .into(),
2239                flash.0.pmpaddr(),
2240            );
2241
2242            // Finally, attempt to enable the MSECCFG security bits, and verify
2243            // that they have been set correctly. If they have not been set to
2244            // the written value, this means that this hardware either does not
2245            // support ePMP, or it was in some invalid state otherwise. We don't
2246            // need to read back the above regions, as we previous verified that
2247            // none of their entries were locked -- so writing to them must work
2248            // even without RLB set.
2249            //
2250            // Set RLB(2) = 0, MMWP(1) = 1, MML(0) = 1
2251            csr::CSR.mseccfg.set(0x00000003);
2252
2253            // Read back the MSECCFG CSR to ensure that the machine's security
2254            // configuration was set properly. If this fails, we have set up the
2255            // PMP in a way that would give userspace access to kernel
2256            // space. The caller of this method must appropriately handle this
2257            // error condition by ensuring that the platform will never execute
2258            // userspace code!
2259            if csr::CSR.mseccfg.get() != 0x00000003 {
2260                return Err(());
2261            }
2262
2263            // Setup complete
2264            const DEFAULT_USER_PMPCFG_OCTET: Cell<TORUserPMPCFG> = Cell::new(TORUserPMPCFG::OFF);
2265            Ok(KernelProtectionMMLEPMP {
2266                user_pmp_enabled: Cell::new(false),
2267                shadow_user_pmpcfgs: [DEFAULT_USER_PMPCFG_OCTET; MPU_REGIONS],
2268            })
2269        }
2270    }
2271
2272    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS>
2273        for KernelProtectionMMLEPMP<AVAILABLE_ENTRIES, MPU_REGIONS>
2274    {
2275        // Ensure that the MPU_REGIONS (starting at entry, and occupying two
2276        // entries per region) don't overflow the available entires, excluding
2277        // the 7 entries used for implementing the kernel memory protection:
2278        const CONST_ASSERT_CHECK: () = assert!(MPU_REGIONS <= ((AVAILABLE_ENTRIES - 5) / 2));
2279
2280        fn available_regions(&self) -> usize {
2281            // Always assume to have `MPU_REGIONS` usable TOR regions. We don't
2282            // support locking additional regions at runtime.
2283            MPU_REGIONS
2284        }
2285
2286        // This implementation is specific for 32-bit systems. We use
2287        // `u32::from_be_bytes` and then cast to usize, as it manages to compile
2288        // on 64-bit systems as well. However, this implementation will not work
2289        // on RV64I systems, due to the changed pmpcfgX CSR layout.
2290        fn configure_pmp(
2291            &self,
2292            regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
2293        ) -> Result<(), ()> {
2294            // Configure all of the regions' addresses and store their pmpcfg octets
2295            // in our shadow storage. If the user PMP is already enabled, we further
2296            // apply this configuration (set the pmpcfgX CSRs) by running
2297            // `enable_user_pmp`:
2298            for (i, (region, shadow_user_pmpcfg)) in regions
2299                .iter()
2300                .zip(self.shadow_user_pmpcfgs.iter())
2301                .enumerate()
2302            {
2303                // The ePMP in MML mode does not support read-write-execute
2304                // regions. If such a region is to be configured, abort. As this
2305                // loop here only modifies the shadow state, we can simply abort and
2306                // return an error. We don't make any promises about the ePMP state
2307                // if the configuration files, but it is still being activated with
2308                // `enable_user_pmp`:
2309                if region.0.get()
2310                    == <TORUserPMPCFG as From<mpu::Permissions>>::from(
2311                        mpu::Permissions::ReadWriteExecute,
2312                    )
2313                    .get()
2314                {
2315                    return Err(());
2316                }
2317
2318                // Set the CSR addresses for this region (if its not OFF, in which
2319                // case the hardware-configured addresses are irrelevant):
2320                if region.0 != TORUserPMPCFG::OFF {
2321                    csr::CSR.pmpaddr_set(
2322                        (i + Self::TOR_REGIONS_OFFSET) * 2 + 0,
2323                        (region.1 as usize).overflowing_shr(2).0,
2324                    );
2325                    csr::CSR.pmpaddr_set(
2326                        (i + Self::TOR_REGIONS_OFFSET) * 2 + 1,
2327                        (region.2 as usize).overflowing_shr(2).0,
2328                    );
2329                }
2330
2331                // Store the region's pmpcfg octet:
2332                shadow_user_pmpcfg.set(region.0);
2333            }
2334
2335            // If the PMP is currently active, apply the changes to the CSRs:
2336            if self.user_pmp_enabled.get() {
2337                self.enable_user_pmp()?;
2338            }
2339
2340            Ok(())
2341        }
2342
2343        fn enable_user_pmp(&self) -> Result<(), ()> {
2344            // We store the "enabled" PMPCFG octets of user regions in the
2345            // `shadow_user_pmpcfg` field, such that we can re-enable the PMP
2346            // without a call to `configure_pmp` (where the `TORUserPMPCFG`s are
2347            // provided by the caller).
2348
2349            // Could use `iter_array_chunks` once that's stable.
2350            let mut shadow_user_pmpcfgs_iter = self.shadow_user_pmpcfgs.iter();
2351            let mut i = Self::TOR_REGIONS_OFFSET;
2352
2353            while let Some(first_region_pmpcfg) = shadow_user_pmpcfgs_iter.next() {
2354                // If we're at a "region" offset divisible by two (where "region" =
2355                // 2 PMP "entries"), then we can configure an entire `pmpcfgX` CSR
2356                // in one operation. As CSR writes are expensive, this is an
2357                // operation worth making:
2358                let second_region_opt = if i % 2 == 0 {
2359                    shadow_user_pmpcfgs_iter.next()
2360                } else {
2361                    None
2362                };
2363
2364                if let Some(second_region_pmpcfg) = second_region_opt {
2365                    // We're at an even index and have two regions to configure, so
2366                    // do that with a single CSR write:
2367                    csr::CSR.pmpconfig_set(
2368                        i / 2,
2369                        u32::from_be_bytes([
2370                            second_region_pmpcfg.get().get(),
2371                            TORUserPMPCFG::OFF.get(),
2372                            first_region_pmpcfg.get().get(),
2373                            TORUserPMPCFG::OFF.get(),
2374                        ]) as usize,
2375                    );
2376
2377                    i += 2;
2378                } else if i % 2 == 0 {
2379                    // This is a single region at an even index. Thus, modify the
2380                    // first two pmpcfgX octets for this region.
2381                    csr::CSR.pmpconfig_modify(
2382                        i / 2,
2383                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2384                            0x0000FFFF,
2385                            0, // lower two octets
2386                            u32::from_be_bytes([
2387                                0,
2388                                0,
2389                                first_region_pmpcfg.get().get(),
2390                                TORUserPMPCFG::OFF.get(),
2391                            ]) as usize,
2392                        ),
2393                    );
2394
2395                    i += 1;
2396                } else {
2397                    // This is a single region at an odd index. Thus, modify the
2398                    // latter two pmpcfgX octets for this region.
2399                    csr::CSR.pmpconfig_modify(
2400                        i / 2,
2401                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2402                            0x0000FFFF,
2403                            16, // higher two octets
2404                            u32::from_be_bytes([
2405                                0,
2406                                0,
2407                                first_region_pmpcfg.get().get(),
2408                                TORUserPMPCFG::OFF.get(),
2409                            ]) as usize,
2410                        ),
2411                    );
2412
2413                    i += 1;
2414                }
2415            }
2416
2417            self.user_pmp_enabled.set(true);
2418
2419            Ok(())
2420        }
2421
2422        fn disable_user_pmp(&self) {
2423            // Simply set all of the user-region pmpcfg octets to OFF:
2424
2425            let mut user_region_pmpcfg_octet_pairs =
2426                (Self::TOR_REGIONS_OFFSET)..(Self::TOR_REGIONS_OFFSET + MPU_REGIONS);
2427            while let Some(first_region_idx) = user_region_pmpcfg_octet_pairs.next() {
2428                let second_region_opt = if first_region_idx % 2 == 0 {
2429                    user_region_pmpcfg_octet_pairs.next()
2430                } else {
2431                    None
2432                };
2433
2434                if let Some(_second_region_idx) = second_region_opt {
2435                    // We're at an even index and have two regions to configure, so
2436                    // do that with a single CSR write:
2437                    csr::CSR.pmpconfig_set(
2438                        first_region_idx / 2,
2439                        u32::from_be_bytes([
2440                            TORUserPMPCFG::OFF.get(),
2441                            TORUserPMPCFG::OFF.get(),
2442                            TORUserPMPCFG::OFF.get(),
2443                            TORUserPMPCFG::OFF.get(),
2444                        ]) as usize,
2445                    );
2446                } else if first_region_idx % 2 == 0 {
2447                    // This is a single region at an even index. Thus, modify the
2448                    // first two pmpcfgX octets for this region.
2449                    csr::CSR.pmpconfig_modify(
2450                        first_region_idx / 2,
2451                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2452                            0x0000FFFF,
2453                            0, // lower two octets
2454                            u32::from_be_bytes([
2455                                0,
2456                                0,
2457                                TORUserPMPCFG::OFF.get(),
2458                                TORUserPMPCFG::OFF.get(),
2459                            ]) as usize,
2460                        ),
2461                    );
2462                } else {
2463                    // This is a single region at an odd index. Thus, modify the
2464                    // latter two pmpcfgX octets for this region.
2465                    csr::CSR.pmpconfig_modify(
2466                        first_region_idx / 2,
2467                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2468                            0x0000FFFF,
2469                            16, // higher two octets
2470                            u32::from_be_bytes([
2471                                0,
2472                                0,
2473                                TORUserPMPCFG::OFF.get(),
2474                                TORUserPMPCFG::OFF.get(),
2475                            ]) as usize,
2476                        ),
2477                    );
2478                }
2479            }
2480
2481            self.user_pmp_enabled.set(false);
2482        }
2483    }
2484
2485    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> fmt::Display
2486        for KernelProtectionMMLEPMP<AVAILABLE_ENTRIES, MPU_REGIONS>
2487    {
2488        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2489            write!(
2490                f,
2491                " ePMP configuration:\r\n  mseccfg: {:#08X}, user-mode PMP active: {:?}, entries:\r\n",
2492                csr::CSR.mseccfg.get(),
2493                self.user_pmp_enabled.get()
2494            )?;
2495            unsafe { super::format_pmp_entries::<AVAILABLE_ENTRIES>(f) }?;
2496
2497            write!(f, "  Shadow PMP entries for user-mode:\r\n")?;
2498            for (i, shadowed_pmpcfg) in self.shadow_user_pmpcfgs.iter().enumerate() {
2499                let (start_pmpaddr_label, startaddr_pmpaddr, endaddr, mode) =
2500                    if shadowed_pmpcfg.get() == TORUserPMPCFG::OFF {
2501                        (
2502                            "pmpaddr",
2503                            csr::CSR.pmpaddr_get((i + Self::TOR_REGIONS_OFFSET) * 2),
2504                            0,
2505                            "OFF",
2506                        )
2507                    } else {
2508                        (
2509                            "  start",
2510                            csr::CSR
2511                                .pmpaddr_get((i + Self::TOR_REGIONS_OFFSET) * 2)
2512                                .overflowing_shl(2)
2513                                .0,
2514                            csr::CSR
2515                                .pmpaddr_get((i + Self::TOR_REGIONS_OFFSET) * 2 + 1)
2516                                .overflowing_shl(2)
2517                                .0
2518                                | 0b11,
2519                            "TOR",
2520                        )
2521                    };
2522
2523                write!(
2524                    f,
2525                    "  [{:02}]: {}={:#010X}, end={:#010X}, cfg={:#04X} ({}  ) ({}{}{}{})\r\n",
2526                    (i + Self::TOR_REGIONS_OFFSET) * 2 + 1,
2527                    start_pmpaddr_label,
2528                    startaddr_pmpaddr,
2529                    endaddr,
2530                    shadowed_pmpcfg.get().get(),
2531                    mode,
2532                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::l) {
2533                        "l"
2534                    } else {
2535                        "-"
2536                    },
2537                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::r) {
2538                        "r"
2539                    } else {
2540                        "-"
2541                    },
2542                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::w) {
2543                        "w"
2544                    } else {
2545                        "-"
2546                    },
2547                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::x) {
2548                        "x"
2549                    } else {
2550                        "-"
2551                    },
2552                )?;
2553            }
2554
2555            Ok(())
2556        }
2557    }
2558}