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().is_multiple_of(size) || 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).is_multiple_of(4)
263            || !(end as usize).is_multiple_of(4)
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.saturating_sub(1)))
320            || other_range.contains(&region_range.start)
321            || other_range.contains(&(region_range.end.saturating_sub(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
896// `MPU` is an unsafe trait, and with this implementation we guarantee
897// that we adhere to the semantics documented on that trait and its
898// associated types and methods.
899unsafe impl<const MAX_REGIONS: usize, P: TORUserPMP<MAX_REGIONS> + 'static>
900    kernel::platform::mpu::MPU for PMPUserMPU<MAX_REGIONS, P>
901{
902    type MpuConfig = PMPUserMPUConfig<MAX_REGIONS>;
903
904    fn enable_app_mpu(&self) {
905        // TODO: This operation may fail when the PMP is not exclusively used
906        // for userspace. Instead of panicing, we should handle this case more
907        // gracefully and return an error in the `MPU` trait. Process
908        // infrastructure can then attempt to re-schedule the process later on,
909        // try to revoke some optional shared memory regions, or suspend the
910        // process.
911        self.pmp.enable_user_pmp().unwrap()
912    }
913
914    unsafe fn disable_app_mpu(&self) {
915        self.pmp.disable_user_pmp()
916    }
917
918    fn number_total_regions(&self) -> usize {
919        self.pmp.available_regions()
920    }
921
922    fn new_config(&self) -> Option<Self::MpuConfig> {
923        let id = self.config_count.get();
924        self.config_count.set(id.checked_add(1)?);
925
926        Some(PMPUserMPUConfig {
927            id,
928            regions: [(
929                TORUserPMPCFG::OFF,
930                core::ptr::null::<u8>(),
931                core::ptr::null::<u8>(),
932            ); MAX_REGIONS],
933            is_dirty: Cell::new(true),
934            app_memory_region: OptionalCell::empty(),
935        })
936    }
937
938    fn reset_config(&self, config: &mut Self::MpuConfig) {
939        config.regions.iter_mut().for_each(|region| {
940            *region = (
941                TORUserPMPCFG::OFF,
942                core::ptr::null::<u8>(),
943                core::ptr::null::<u8>(),
944            )
945        });
946        config.app_memory_region.clear();
947        config.is_dirty.set(true);
948    }
949
950    fn allocate_region(
951        &self,
952        unallocated_memory_start: *const u8,
953        unallocated_memory_size: usize,
954        min_region_size: usize,
955        permissions: mpu::Permissions,
956        config: &mut Self::MpuConfig,
957    ) -> Option<mpu::Region> {
958        // Find a free region slot. If we don't have one, abort early:
959        let region_num = config
960            .regions
961            .iter()
962            .enumerate()
963            .find(|(_i, (pmpcfg, _, _))| *pmpcfg == TORUserPMPCFG::OFF)
964            .map(|(i, _)| i)?;
965
966        // Now, meet the PMP TOR region constraints. For this, start with the
967        // provided start address and size, transform them to meet the
968        // constraints, and then check that we're still within the bounds of the
969        // provided values:
970        let mut start = unallocated_memory_start as usize;
971        let mut size = min_region_size;
972
973        // Region start always has to align to 4 bytes. Round up to a 4 byte
974        // boundary if required:
975        start = start.next_multiple_of(4);
976
977        // Region size always has to align to 4 bytes. Round up to a 4 byte
978        // boundary if required:
979        size = size.next_multiple_of(4);
980
981        // Regions must be at least 4 bytes in size.
982        if size < 4 {
983            size = 4;
984        }
985
986        // Now, check to see whether the adjusted start and size still meet the
987        // allocation constraints, namely ensure that
988        //
989        //     start + size <= unallocated_memory_start + unallocated_memory_size
990        if start + size > (unallocated_memory_start as usize) + unallocated_memory_size {
991            // We're overflowing the provided memory region, can't make
992            // allocation. Normally, we'd abort here.
993            //
994            // However, a previous implementation of this code was incorrect in
995            // that performed this check before adjusting the requested region
996            // size to meet PMP region layout constraints (4 byte alignment for
997            // start and end address). Existing applications whose end-address
998            // is aligned on a less than 4-byte bondary would thus be given
999            // access to additional memory which should be inaccessible.
1000            // Unfortunately, we can't fix this without breaking existing
1001            // applications. Thus, we perform the same insecure hack here, and
1002            // give the apps at most an extra 3 bytes of memory, as long as the
1003            // requested region as no write privileges.
1004            //
1005            // TODO: Remove this logic with as part of
1006            // https://github.com/tock/tock/issues/3544
1007            let writeable = match permissions {
1008                mpu::Permissions::ReadWriteExecute => true,
1009                mpu::Permissions::ReadWriteOnly => true,
1010                mpu::Permissions::ReadExecuteOnly => false,
1011                mpu::Permissions::ReadOnly => false,
1012                mpu::Permissions::ExecuteOnly => false,
1013            };
1014
1015            if writeable
1016                || (start + size
1017                    > (unallocated_memory_start as usize) + unallocated_memory_size + 3)
1018            {
1019                return None;
1020            }
1021        }
1022
1023        // Finally, check that this new region does not overlap with any
1024        // existing configured userspace region:
1025        for region in config.regions.iter() {
1026            if region.0 != TORUserPMPCFG::OFF && region_overlaps(region, start as *const u8, size) {
1027                return None;
1028            }
1029        }
1030
1031        // All checks passed, store region allocation and mark config as dirty:
1032        config.regions[region_num] = (
1033            permissions.into(),
1034            start as *const u8,
1035            (start + size) as *const u8,
1036        );
1037        config.is_dirty.set(true);
1038
1039        Some(mpu::Region::new(start as *const u8, size))
1040    }
1041
1042    fn remove_memory_region(
1043        &self,
1044        region: mpu::Region,
1045        config: &mut Self::MpuConfig,
1046    ) -> Result<(), ()> {
1047        let index = config
1048            .regions
1049            .iter()
1050            .enumerate()
1051            .find(|(_i, r)| {
1052                // `start as usize + size` in lieu of a safe pointer offset method
1053                r.0 != TORUserPMPCFG::OFF
1054                    && core::ptr::eq(r.1, region.start_address())
1055                    && core::ptr::eq(
1056                        r.2,
1057                        (region.start_address() as usize + region.size()) as *const u8,
1058                    )
1059            })
1060            .map(|(i, _)| i)
1061            .ok_or(())?;
1062
1063        config.regions[index].0 = TORUserPMPCFG::OFF;
1064        config.is_dirty.set(true);
1065
1066        Ok(())
1067    }
1068
1069    fn allocate_app_memory_region(
1070        &self,
1071        unallocated_memory_start: *const u8,
1072        unallocated_memory_size: usize,
1073        min_memory_size: usize,
1074        initial_app_memory_size: usize,
1075        initial_kernel_memory_size: usize,
1076        permissions: mpu::Permissions,
1077        config: &mut Self::MpuConfig,
1078    ) -> Option<(*const u8, usize)> {
1079        // An app memory region can only be allocated once per `MpuConfig`.
1080        // If we already have one, abort:
1081        if config.app_memory_region.is_some() {
1082            return None;
1083        }
1084
1085        // Find a free region slot. If we don't have one, abort early:
1086        let region_num = config
1087            .regions
1088            .iter()
1089            .enumerate()
1090            .find(|(_i, (pmpcfg, _, _))| *pmpcfg == TORUserPMPCFG::OFF)
1091            .map(|(i, _)| i)?;
1092
1093        // Now, meet the PMP TOR region constraints for the region specified by
1094        // `initial_app_memory_size` (which is the part of the region actually
1095        // protected by the PMP). For this, start with the provided start
1096        // address and size, transform them to meet the constraints, and then
1097        // check that we're still within the bounds of the provided values:
1098        let mut start = unallocated_memory_start as usize;
1099        let mut pmp_region_size = initial_app_memory_size;
1100
1101        // Region start always has to align to 4 bytes. Round up to a 4 byte
1102        // boundary if required:
1103        start = start.next_multiple_of(4);
1104
1105        // Region size always has to align to 4 bytes. Round up to a 4 byte
1106        // boundary if required:
1107        pmp_region_size = pmp_region_size.next_multiple_of(4);
1108
1109        // Regions must be at least 4 bytes in size.
1110        if pmp_region_size < 4 {
1111            pmp_region_size = 4;
1112        }
1113
1114        // We need to provide a memory block that fits both the initial app and
1115        // kernel memory sections, and is `min_memory_size` bytes
1116        // long. Calculate the length of this block with our new PMP-aliged
1117        // size:
1118        let memory_block_size = cmp::max(
1119            min_memory_size,
1120            pmp_region_size + initial_kernel_memory_size,
1121        );
1122
1123        // Now, check to see whether the adjusted start and size still meet the
1124        // allocation constraints, namely ensure that
1125        //
1126        //     start + memory_block_size
1127        //         <= unallocated_memory_start + unallocated_memory_size
1128        //
1129        // , which ensures the PMP constraints didn't push us over the bounds of
1130        // the provided memory region, and we can fit the entire allocation as
1131        // requested by the kernel:
1132        if start + memory_block_size > (unallocated_memory_start as usize) + unallocated_memory_size
1133        {
1134            // Overflowing the provided memory region, can't make allocation:
1135            return None;
1136        }
1137
1138        // Finally, check that this new region does not overlap with any
1139        // existing configured userspace region:
1140        for region in config.regions.iter() {
1141            if region.0 != TORUserPMPCFG::OFF
1142                && region_overlaps(region, start as *const u8, memory_block_size)
1143            {
1144                return None;
1145            }
1146        }
1147
1148        // All checks passed, store region allocation, indicate the
1149        // app_memory_region, and mark config as dirty:
1150        config.regions[region_num] = (
1151            permissions.into(),
1152            start as *const u8,
1153            (start + pmp_region_size) as *const u8,
1154        );
1155        config.is_dirty.set(true);
1156        config.app_memory_region.replace(region_num);
1157
1158        Some((start as *const u8, memory_block_size))
1159    }
1160
1161    fn update_app_memory_region(
1162        &self,
1163        app_memory_break: *const u8,
1164        kernel_memory_break: *const u8,
1165        permissions: mpu::Permissions,
1166        config: &mut Self::MpuConfig,
1167    ) -> Result<(), ()> {
1168        let region_num = config.app_memory_region.get().ok_or(())?;
1169
1170        let mut app_memory_break = app_memory_break as usize;
1171        let kernel_memory_break = kernel_memory_break as usize;
1172
1173        // Ensure that the requested app_memory_break complies with PMP
1174        // alignment constraints, namely that the region's end address is 4 byte
1175        // aligned:
1176        app_memory_break = app_memory_break.next_multiple_of(4);
1177
1178        // Check if the app has run out of memory:
1179        if app_memory_break > kernel_memory_break {
1180            return Err(());
1181        }
1182
1183        // If we're not out of memory, update the region configuration
1184        // accordingly:
1185        config.regions[region_num].0 = permissions.into();
1186        config.regions[region_num].2 = app_memory_break as *const u8;
1187        config.is_dirty.set(true);
1188
1189        Ok(())
1190    }
1191
1192    unsafe fn configure_mpu(&self, config: &Self::MpuConfig) {
1193        if !self.last_configured_for.contains(&config.id) || config.is_dirty.get() {
1194            self.pmp.configure_pmp(&config.regions).unwrap();
1195            config.is_dirty.set(false);
1196            self.last_configured_for.set(config.id);
1197        }
1198    }
1199}
1200
1201#[cfg(test)]
1202pub mod tor_user_pmp_test {
1203    use super::{TORUserPMP, TORUserPMPCFG};
1204
1205    struct MockTORUserPMP;
1206    impl<const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS> for MockTORUserPMP {
1207        // Don't require any const-assertions in the MockTORUserPMP.
1208        const CONST_ASSERT_CHECK: () = ();
1209
1210        fn available_regions(&self) -> usize {
1211            // For the MockTORUserPMP, we always assume to have the full number
1212            // of MPU_REGIONS available. More advanced tests may want to return
1213            // a different number here (to simulate kernel memory protection)
1214            // and make the configuration fail at runtime, for instance.
1215            MPU_REGIONS
1216        }
1217
1218        fn configure_pmp(
1219            &self,
1220            _regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
1221        ) -> Result<(), ()> {
1222            Ok(())
1223        }
1224
1225        fn enable_user_pmp(&self) -> Result<(), ()> {
1226            Ok(())
1227        } // The kernel's MPU trait requires
1228
1229        fn disable_user_pmp(&self) {}
1230    }
1231
1232    // TODO: implement more test cases, such as:
1233    //
1234    // - Try to update the app memory break with an invalid pointer below its
1235    //   allocation's start address.
1236
1237    #[test]
1238    fn test_mpu_region_no_overlap() {
1239        use crate::pmp::PMPUserMPU;
1240        use kernel::platform::mpu::{Permissions, MPU};
1241
1242        let mpu: PMPUserMPU<8, MockTORUserPMP> = PMPUserMPU::new(MockTORUserPMP);
1243        let mut config = mpu
1244            .new_config()
1245            .expect("Failed to allocate the first MPU config");
1246
1247        // Allocate a region which spans from 0x40000000 to 0x80000000 (this
1248        // meets PMP alignment constraints and will work on 32-bit and 64-bit
1249        // systems)
1250        let region_0 = mpu
1251            .allocate_region(
1252                0x40000000 as *const u8,
1253                0x40000000,
1254                0x40000000,
1255                Permissions::ReadWriteOnly,
1256                &mut config,
1257            )
1258            .expect(
1259                "Failed to allocate a well-aligned R/W MPU region with \
1260                 unallocated_memory_size == min_region_size",
1261            );
1262        assert!(region_0.start_address() == 0x40000000 as *const u8);
1263        assert!(region_0.size() == 0x40000000);
1264
1265        // Try to allocate a region adjacent to `region_0`. This should work:
1266        let region_1 = mpu
1267            .allocate_region(
1268                0x80000000 as *const u8,
1269                0x10000000,
1270                0x10000000,
1271                Permissions::ReadExecuteOnly,
1272                &mut config,
1273            )
1274            .expect(
1275                "Failed to allocate a well-aligned R/W MPU region adjacent to \
1276                 another region",
1277            );
1278        assert!(region_1.start_address() == 0x80000000 as *const u8);
1279        assert!(region_1.size() == 0x10000000);
1280
1281        // Remove the previously allocated `region_1`:
1282        mpu.remove_memory_region(region_1, &mut config)
1283            .expect("Failed to remove valid MPU region allocation");
1284
1285        // Allocate another region which spans from 0xc0000000 to 0xd0000000
1286        // (this meets PMP alignment constraints and will work on 32-bit and
1287        // 64-bit systems), but this time allocate it using the
1288        // `allocate_app_memory_region` method. We want a region of `0x20000000`
1289        // bytes, but only the first `0x10000000` should be accessible to the
1290        // app.
1291        let (region_2_start, region_2_size) = mpu
1292            .allocate_app_memory_region(
1293                0xc0000000 as *const u8,
1294                0x20000000,
1295                0x20000000,
1296                0x10000000,
1297                0x08000000,
1298                Permissions::ReadWriteOnly,
1299                &mut config,
1300            )
1301            .expect(
1302                "Failed to allocate a well-aligned R/W app memory MPU region \
1303                 with unallocated_memory_size == min_region_size",
1304            );
1305        assert!(region_2_start == 0xc0000000 as *const u8);
1306        assert!(region_2_size == 0x20000000);
1307
1308        // --> General overlap tests involving both regions
1309
1310        // Now, try to allocate another region that spans over both memory
1311        // regions. This should fail.
1312        assert!(mpu
1313            .allocate_region(
1314                0x40000000 as *const u8,
1315                0xc0000000,
1316                0xc0000000,
1317                Permissions::ReadOnly,
1318                &mut config,
1319            )
1320            .is_none());
1321
1322        // Try to allocate a region that spans over parts of both memory
1323        // regions. This should fail.
1324        assert!(mpu
1325            .allocate_region(
1326                0x48000000 as *const u8,
1327                0x80000000,
1328                0x80000000,
1329                Permissions::ReadOnly,
1330                &mut config,
1331            )
1332            .is_none());
1333
1334        // --> Overlap tests involving a single region (region_0)
1335        //
1336        // We define these in an array, such that we can run the tests with the
1337        // `region_0` defined (to confirm that the allocations are indeed
1338        // refused), and with `region_0` removed (to make sure they would work
1339        // in general).
1340        let overlap_region_0_tests = [
1341            (
1342                // Try to allocate a region that is contained within
1343                // `region_0`. This should fail.
1344                0x41000000 as *const u8,
1345                0x01000000,
1346                0x01000000,
1347                Permissions::ReadWriteOnly,
1348            ),
1349            (
1350                // Try to allocate a region that overlaps with `region_0` in the
1351                // front. This should fail.
1352                0x38000000 as *const u8,
1353                0x10000000,
1354                0x10000000,
1355                Permissions::ReadWriteExecute,
1356            ),
1357            (
1358                // Try to allocate a region that overlaps with `region_0` in the
1359                // back. This should fail.
1360                0x48000000 as *const u8,
1361                0x10000000,
1362                0x10000000,
1363                Permissions::ExecuteOnly,
1364            ),
1365            (
1366                // Try to allocate a region that spans over `region_0`. This
1367                // should fail.
1368                0x38000000 as *const u8,
1369                0x20000000,
1370                0x20000000,
1371                Permissions::ReadWriteOnly,
1372            ),
1373        ];
1374
1375        // Make sure that the allocation requests fail with `region_0` defined:
1376        for (memory_start, memory_size, length, perms) in overlap_region_0_tests.iter() {
1377            assert!(mpu
1378                .allocate_region(*memory_start, *memory_size, *length, *perms, &mut config,)
1379                .is_none());
1380        }
1381
1382        // Now, remove `region_0` and re-run the tests. Every test-case should
1383        // succeed now (in isolation, hence removing the successful allocations):
1384        mpu.remove_memory_region(region_0, &mut config)
1385            .expect("Failed to remove valid MPU region allocation");
1386
1387        for region @ (memory_start, memory_size, length, perms) in overlap_region_0_tests.iter() {
1388            let allocation_res =
1389                mpu.allocate_region(*memory_start, *memory_size, *length, *perms, &mut config);
1390
1391            match allocation_res {
1392                Some(region) => {
1393                    mpu.remove_memory_region(region, &mut config)
1394                        .expect("Failed to remove valid MPU region allocation");
1395                }
1396                None => {
1397                    panic!(
1398                        "Failed to allocate region that does not overlap and should meet alignment constraints: {:?}",
1399                        region
1400                    );
1401                }
1402            }
1403        }
1404
1405        // Make sure we can technically allocate a memory region that overlaps
1406        // with the kernel part of the `app_memory_region`.
1407        //
1408        // It is unclear whether this should be supported.
1409        let region_2 = mpu
1410            .allocate_region(
1411                0xd0000000 as *const u8,
1412                0x10000000,
1413                0x10000000,
1414                Permissions::ReadWriteOnly,
1415                &mut config,
1416            )
1417            .unwrap();
1418        assert!(region_2.start_address() == 0xd0000000 as *const u8);
1419        assert!(region_2.size() == 0x10000000);
1420
1421        // Now, we can grow the app memory break into this region:
1422        mpu.update_app_memory_region(
1423            0xd0000004 as *const u8,
1424            0xd8000000 as *const u8,
1425            Permissions::ReadWriteOnly,
1426            &mut config,
1427        )
1428        .expect("Failed to grow the app memory region into an existing other MPU region");
1429
1430        // Now, we have two overlapping MPU regions. Remove `region_2`, and try
1431        // to reallocate it as `region_3`. This should fail now, demonstrating
1432        // that we managed to reach an invalid intermediate state:
1433        mpu.remove_memory_region(region_2, &mut config)
1434            .expect("Failed to remove valid MPU region allocation");
1435        assert!(mpu
1436            .allocate_region(
1437                0xd0000000 as *const u8,
1438                0x10000000,
1439                0x10000000,
1440                Permissions::ReadWriteOnly,
1441                &mut config,
1442            )
1443            .is_none());
1444    }
1445}
1446
1447pub mod simple {
1448    use super::{pmpcfg_octet, TORUserPMP, TORUserPMPCFG};
1449    use crate::csr;
1450    use core::fmt;
1451    use kernel::utilities::registers::{FieldValue, LocalRegisterCopy};
1452
1453    /// A "simple" RISC-V PMP implementation.
1454    ///
1455    /// The SimplePMP does not support locked regions, kernel memory protection,
1456    /// or any ePMP features (using the mseccfg CSR). It is generic over the
1457    /// number of hardware PMP regions available. `AVAILABLE_ENTRIES` is
1458    /// expected to be set to the number of available entries.
1459    ///
1460    /// [`SimplePMP`] implements [`TORUserPMP`] to expose all of its regions as
1461    /// "top of range" (TOR) regions (each taking up two physical PMP entires)
1462    /// for use as a user-mode memory protection mechanism.
1463    ///
1464    /// Notably, [`SimplePMP`] implements `TORUserPMP<MPU_REGIONS>` over a
1465    /// generic `MPU_REGIONS` where `MPU_REGIONS <= (AVAILABLE_ENTRIES / 2)`. As
1466    /// PMP re-configuration can have a significiant runtime overhead, users are
1467    /// free to specify a small `MPU_REGIONS` const-generic parameter to reduce
1468    /// the runtime overhead induced through PMP configuration, at the cost of
1469    /// having less PMP regions available to use for userspace memory
1470    /// protection.
1471    pub struct SimplePMP<const AVAILABLE_ENTRIES: usize>;
1472
1473    impl<const AVAILABLE_ENTRIES: usize> SimplePMP<AVAILABLE_ENTRIES> {
1474        pub unsafe fn new() -> Result<Self, ()> {
1475            // The SimplePMP does not support locked regions, kernel memory
1476            // protection, or any ePMP features (using the mseccfg CSR). Ensure
1477            // that we don't find any locked regions. If we don't have locked
1478            // regions and can still successfully execute code, this means that
1479            // we're not in the ePMP machine-mode lockdown mode, and can treat
1480            // our hardware as a regular PMP.
1481            //
1482            // Furthermore, we test whether we can use each entry (i.e. whether
1483            // it actually exists in HW) by flipping the RWX bits. If we can't
1484            // flip them, then `AVAILABLE_ENTRIES` is incorrect.  However, this
1485            // is not sufficient to check for locked regions, because of the
1486            // ePMP's rule-lock-bypass bit. If a rule is locked, it might be the
1487            // reason why we can execute code or read-write data in machine mode
1488            // right now. Thus, never try to touch a locked region, as we might
1489            // well revoke access to a kernel region!
1490            for i in 0..AVAILABLE_ENTRIES {
1491                // Read the entry's CSR:
1492                let pmpcfg_csr = csr::CSR.pmpconfig_get(i / 4);
1493
1494                // Extract the entry's pmpcfg octet:
1495                let pmpcfg: LocalRegisterCopy<u8, pmpcfg_octet::Register> = LocalRegisterCopy::new(
1496                    pmpcfg_csr.overflowing_shr(((i % 4) * 8) as u32).0 as u8,
1497                );
1498
1499                // As outlined above, we never touch a locked region. Thus, bail
1500                // out if it's locked:
1501                if pmpcfg.is_set(pmpcfg_octet::l) {
1502                    return Err(());
1503                }
1504
1505                // Now that it's not locked, we can be sure that regardless of
1506                // any ePMP bits, this region is either ignored or entirely
1507                // denied for machine-mode access. Hence, we can change it in
1508                // arbitrary ways without breaking our own memory access. Try to
1509                // flip the R/W/X bits:
1510                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr ^ (7 << ((i % 4) * 8)));
1511
1512                // Check if the CSR changed:
1513                if pmpcfg_csr == csr::CSR.pmpconfig_get(i / 4) {
1514                    // Didn't change! This means that this region is not backed
1515                    // by HW. Return an error as `AVAILABLE_ENTRIES` is
1516                    // incorrect:
1517                    return Err(());
1518                }
1519
1520                // Finally, turn the region off:
1521                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr & !(0x18 << ((i % 4) * 8)));
1522            }
1523
1524            // Hardware PMP is verified to be in a compatible mode / state, and
1525            // has at least `AVAILABLE_ENTRIES` entries.
1526            Ok(SimplePMP)
1527        }
1528    }
1529
1530    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS>
1531        for SimplePMP<AVAILABLE_ENTRIES>
1532    {
1533        // Ensure that the MPU_REGIONS (starting at entry, and occupying two
1534        // entries per region) don't overflow the available entires.
1535        const CONST_ASSERT_CHECK: () = assert!(MPU_REGIONS <= (AVAILABLE_ENTRIES / 2));
1536
1537        fn available_regions(&self) -> usize {
1538            // Always assume to have `MPU_REGIONS` usable TOR regions. We don't
1539            // support locked regions, or kernel protection.
1540            MPU_REGIONS
1541        }
1542
1543        // This implementation is specific for 32-bit systems. We use
1544        // `u32::from_be_bytes` and then cast to usize, as it manages to compile
1545        // on 64-bit systems as well. However, this implementation will not work
1546        // on RV64I systems, due to the changed pmpcfgX CSR layout.
1547        fn configure_pmp(
1548            &self,
1549            regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
1550        ) -> Result<(), ()> {
1551            // Could use `iter_array_chunks` once that's stable.
1552            let mut regions_iter = regions.iter();
1553            let mut i = 0;
1554
1555            while let Some(even_region) = regions_iter.next() {
1556                let odd_region_opt = regions_iter.next();
1557
1558                if let Some(odd_region) = odd_region_opt {
1559                    // We can configure two regions at once which, given that we
1560                    // start at index 0 (an even offset), translates to a single
1561                    // CSR write for the pmpcfgX register:
1562                    csr::CSR.pmpconfig_set(
1563                        i / 2,
1564                        u32::from_be_bytes([
1565                            odd_region.0.get(),
1566                            TORUserPMPCFG::OFF.get(),
1567                            even_region.0.get(),
1568                            TORUserPMPCFG::OFF.get(),
1569                        ]) as usize,
1570                    );
1571
1572                    // Now, set the addresses of the respective regions, if they
1573                    // are enabled, respectively:
1574                    if even_region.0 != TORUserPMPCFG::OFF {
1575                        csr::CSR
1576                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1577                        csr::CSR
1578                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1579                    }
1580
1581                    if odd_region.0 != TORUserPMPCFG::OFF {
1582                        csr::CSR
1583                            .pmpaddr_set(i * 2 + 2, (odd_region.1 as usize).overflowing_shr(2).0);
1584                        csr::CSR
1585                            .pmpaddr_set(i * 2 + 3, (odd_region.2 as usize).overflowing_shr(2).0);
1586                    }
1587
1588                    i += 2;
1589                } else {
1590                    // TODO: check overhead of code
1591                    // Modify the first two pmpcfgX octets for this region:
1592                    csr::CSR.pmpconfig_modify(
1593                        i / 2,
1594                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
1595                            0x0000FFFF,
1596                            0,
1597                            u32::from_be_bytes([
1598                                0,
1599                                0,
1600                                even_region.0.get(),
1601                                TORUserPMPCFG::OFF.get(),
1602                            ]) as usize,
1603                        ),
1604                    );
1605
1606                    // Set the addresses if the region is enabled:
1607                    if even_region.0 != TORUserPMPCFG::OFF {
1608                        csr::CSR
1609                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1610                        csr::CSR
1611                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1612                    }
1613
1614                    i += 1;
1615                }
1616            }
1617
1618            Ok(())
1619        }
1620
1621        fn enable_user_pmp(&self) -> Result<(), ()> {
1622            // No-op. The SimplePMP does not have any kernel-enforced regions.
1623            Ok(())
1624        }
1625
1626        fn disable_user_pmp(&self) {
1627            // No-op. The SimplePMP does not have any kernel-enforced regions.
1628        }
1629    }
1630
1631    impl<const AVAILABLE_ENTRIES: usize> fmt::Display for SimplePMP<AVAILABLE_ENTRIES> {
1632        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1633            write!(f, " PMP hardware configuration -- entries: \r\n")?;
1634            unsafe { super::format_pmp_entries::<AVAILABLE_ENTRIES>(f) }
1635        }
1636    }
1637}
1638
1639pub mod kernel_protection {
1640    use super::{pmpcfg_octet, NAPOTRegionSpec, TORRegionSpec, TORUserPMP, TORUserPMPCFG};
1641    use crate::csr;
1642    use core::fmt;
1643    use kernel::utilities::registers::{FieldValue, LocalRegisterCopy};
1644
1645    // ---------- Kernel memory-protection PMP memory region wrapper types -----
1646    //
1647    // These types exist primarily to avoid argument confusion in the
1648    // [`KernelProtectionPMP`] constructor, which accepts the addresses of these
1649    // memory regions as arguments. They further encode whether a region must
1650    // adhere to the `NAPOT` or `TOR` addressing mode constraints:
1651
1652    /// The flash memory region address range.
1653    ///
1654    /// Configured in the PMP as a `NAPOT` region.
1655    #[derive(Copy, Clone, Debug)]
1656    pub struct FlashRegion(pub NAPOTRegionSpec);
1657
1658    /// The RAM region address range.
1659    ///
1660    /// Configured in the PMP as a `NAPOT` region.
1661    #[derive(Copy, Clone, Debug)]
1662    pub struct RAMRegion(pub NAPOTRegionSpec);
1663
1664    /// The MMIO region address range.
1665    ///
1666    /// Configured in the PMP as a `NAPOT` region.
1667    #[derive(Copy, Clone, Debug)]
1668    pub struct MMIORegion(pub NAPOTRegionSpec);
1669
1670    /// The PMP region specification for the kernel `.text` section.
1671    ///
1672    /// This is to be made accessible to machine-mode as read-execute.
1673    /// Configured in the PMP as a `TOR` region.
1674    #[derive(Copy, Clone, Debug)]
1675    pub struct KernelTextRegion(pub TORRegionSpec);
1676
1677    /// A RISC-V PMP implementation which supports machine-mode (kernel) memory
1678    /// protection, with a fixed number of "kernel regions" (such as `.text`,
1679    /// flash, RAM and MMIO).
1680    ///
1681    /// This implementation will configure the PMP in the following way:
1682    ///
1683    ///   ```text
1684    ///   |-------+-----------------------------------------+-------+---+-------|
1685    ///   | ENTRY | REGION / ADDR                           | MODE  | L | PERMS |
1686    ///   |-------+-----------------------------------------+-------+---+-------|
1687    ///   |     0 | /                                     \ | OFF   |   |       |
1688    ///   |     1 | \ Userspace TOR region #0             / | TOR   |   | ????? |
1689    ///   |       |                                         |       |   |       |
1690    ///   |     2 | /                                     \ | OFF   |   |       |
1691    ///   |     3 | \ Userspace TOR region #1             / | TOR   |   | ????? |
1692    ///   |       |                                         |       |   |       |
1693    ///   | 4 ... | /                                     \ |       |   |       |
1694    ///   | n - 8 | \ Userspace TOR region #x             / |       |   |       |
1695    ///   |       |                                         |       |   |       |
1696    ///   | n - 7 | "Deny-all" user-mode rule (all memory)  | NAPOT |   | ----- |
1697    ///   |       |                                         |       |   |       |
1698    ///   | n - 6 | --------------------------------------- | OFF   | X | ----- |
1699    ///   | n - 5 | Kernel .text section                    | TOR   | X | R/X   |
1700    ///   |       |                                         |       |   |       |
1701    ///   | n - 4 | FLASH (spanning kernel & apps)          | NAPOT | X | R     |
1702    ///   |       |                                         |       |   |       |
1703    ///   | n - 3 | RAM (spanning kernel & apps)            | NAPOT | X | R/W   |
1704    ///   |       |                                         |       |   |       |
1705    ///   | n - 2 | MMIO                                    | NAPOT | X | R/W   |
1706    ///   |       |                                         |       |   |       |
1707    ///   | n - 1 | "Deny-all" machine-mode    (all memory) | NAPOT | X | ----- |
1708    ///   |-------+-----------------------------------------+-------+---+-------|
1709    ///   ```
1710    ///
1711    /// This implementation does not use any `mseccfg` protection bits (ePMP
1712    /// functionality). To protect machine-mode (kernel) memory regions, regions
1713    /// must be marked as locked. However, locked regions apply to both user-
1714    /// and machine-mode. Thus, region `n - 7` serves as a "deny-all" user-mode
1715    /// rule, which prohibits all accesses not explicitly allowed through rules
1716    /// `< n - 7`. Kernel memory is made accessible underneath this "deny-all"
1717    /// region, which does not apply to machine-mode.
1718    ///
1719    /// This PMP implementation supports the [`TORUserPMP`] interface with
1720    /// `MPU_REGIONS <= ((AVAILABLE_ENTRIES - 7) / 2)`, to leave sufficient
1721    /// space for the "deny-all" and kernel regions. This constraint is enforced
1722    /// through the [`KernelProtectionPMP::CONST_ASSERT_CHECK`] associated
1723    /// constant, which MUST be evaluated by the consumer of the [`TORUserPMP`]
1724    /// trait (usually the [`PMPUserMPU`](super::PMPUserMPU) implementation).
1725    pub struct KernelProtectionPMP<const AVAILABLE_ENTRIES: usize>;
1726
1727    impl<const AVAILABLE_ENTRIES: usize> KernelProtectionPMP<AVAILABLE_ENTRIES> {
1728        pub unsafe fn new(
1729            flash: FlashRegion,
1730            ram: RAMRegion,
1731            mmio: MMIORegion,
1732            kernel_text: KernelTextRegion,
1733        ) -> Result<Self, ()> {
1734            for i in 0..AVAILABLE_ENTRIES {
1735                // Read the entry's CSR:
1736                let pmpcfg_csr = csr::CSR.pmpconfig_get(i / 4);
1737
1738                // Extract the entry's pmpcfg octet:
1739                let pmpcfg: LocalRegisterCopy<u8, pmpcfg_octet::Register> = LocalRegisterCopy::new(
1740                    pmpcfg_csr.overflowing_shr(((i % 4) * 8) as u32).0 as u8,
1741                );
1742
1743                // As outlined above, we never touch a locked region. Thus, bail
1744                // out if it's locked:
1745                if pmpcfg.is_set(pmpcfg_octet::l) {
1746                    return Err(());
1747                }
1748
1749                // Now that it's not locked, we can be sure that regardless of
1750                // any ePMP bits, this region is either ignored or entirely
1751                // denied for machine-mode access. Hence, we can change it in
1752                // arbitrary ways without breaking our own memory access. Try to
1753                // flip the R/W/X bits:
1754                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr ^ (7 << ((i % 4) * 8)));
1755
1756                // Check if the CSR changed:
1757                if pmpcfg_csr == csr::CSR.pmpconfig_get(i / 4) {
1758                    // Didn't change! This means that this region is not backed
1759                    // by HW. Return an error as `AVAILABLE_ENTRIES` is
1760                    // incorrect:
1761                    return Err(());
1762                }
1763
1764                // Finally, turn the region off:
1765                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr & !(0x18 << ((i % 4) * 8)));
1766            }
1767
1768            // -----------------------------------------------------------------
1769            // Hardware PMP is verified to be in a compatible mode & state, and
1770            // has at least `AVAILABLE_ENTRIES` entries.
1771            // -----------------------------------------------------------------
1772
1773            // Now we need to set up the various kernel memory protection
1774            // regions, and the deny-all userspace region (n - 8), never
1775            // modified.
1776
1777            // Helper to modify an arbitrary PMP entry. Because we don't know
1778            // AVAILABLE_ENTRIES in advance, there's no good way to
1779            // optimize this further.
1780            fn write_pmpaddr_pmpcfg(i: usize, pmpcfg: u8, pmpaddr: usize) {
1781                csr::CSR.pmpaddr_set(i, pmpaddr);
1782                csr::CSR.pmpconfig_modify(
1783                    i / 4,
1784                    FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
1785                        0x000000FF_usize,
1786                        (i % 4) * 8,
1787                        u32::from_be_bytes([0, 0, 0, pmpcfg]) as usize,
1788                    ),
1789                );
1790            }
1791
1792            // Set the kernel `.text`, flash, RAM and MMIO regions, in no
1793            // particular order, with the exception of `.text` and flash:
1794            // `.text` must precede flash, as otherwise we'd be revoking execute
1795            // permissions temporarily. Given that we can currently execute
1796            // code, this should not have any impact on our accessible memory,
1797            // assuming that the provided regions are not otherwise aliased.
1798
1799            // MMIO at n - 2:
1800            write_pmpaddr_pmpcfg(
1801                AVAILABLE_ENTRIES - 2,
1802                (pmpcfg_octet::a::NAPOT
1803                    + pmpcfg_octet::r::SET
1804                    + pmpcfg_octet::w::SET
1805                    + pmpcfg_octet::x::CLEAR
1806                    + pmpcfg_octet::l::SET)
1807                    .into(),
1808                mmio.0.pmpaddr(),
1809            );
1810
1811            // RAM at n - 3:
1812            write_pmpaddr_pmpcfg(
1813                AVAILABLE_ENTRIES - 3,
1814                (pmpcfg_octet::a::NAPOT
1815                    + pmpcfg_octet::r::SET
1816                    + pmpcfg_octet::w::SET
1817                    + pmpcfg_octet::x::CLEAR
1818                    + pmpcfg_octet::l::SET)
1819                    .into(),
1820                ram.0.pmpaddr(),
1821            );
1822
1823            // `.text` at n - 6 and n - 5 (TOR region):
1824            write_pmpaddr_pmpcfg(
1825                AVAILABLE_ENTRIES - 6,
1826                (pmpcfg_octet::a::OFF
1827                    + pmpcfg_octet::r::CLEAR
1828                    + pmpcfg_octet::w::CLEAR
1829                    + pmpcfg_octet::x::CLEAR
1830                    + pmpcfg_octet::l::SET)
1831                    .into(),
1832                kernel_text.0.pmpaddr_a(),
1833            );
1834            write_pmpaddr_pmpcfg(
1835                AVAILABLE_ENTRIES - 5,
1836                (pmpcfg_octet::a::TOR
1837                    + pmpcfg_octet::r::SET
1838                    + pmpcfg_octet::w::CLEAR
1839                    + pmpcfg_octet::x::SET
1840                    + pmpcfg_octet::l::SET)
1841                    .into(),
1842                kernel_text.0.pmpaddr_b(),
1843            );
1844
1845            // flash at n - 4:
1846            write_pmpaddr_pmpcfg(
1847                AVAILABLE_ENTRIES - 4,
1848                (pmpcfg_octet::a::NAPOT
1849                    + pmpcfg_octet::r::SET
1850                    + pmpcfg_octet::w::CLEAR
1851                    + pmpcfg_octet::x::CLEAR
1852                    + pmpcfg_octet::l::SET)
1853                    .into(),
1854                flash.0.pmpaddr(),
1855            );
1856
1857            // Now that the kernel has explicit region definitions for any
1858            // memory that it needs to have access to, we can deny other memory
1859            // accesses in our very last rule (n - 1):
1860            write_pmpaddr_pmpcfg(
1861                AVAILABLE_ENTRIES - 1,
1862                (pmpcfg_octet::a::NAPOT
1863                    + pmpcfg_octet::r::CLEAR
1864                    + pmpcfg_octet::w::CLEAR
1865                    + pmpcfg_octet::x::CLEAR
1866                    + pmpcfg_octet::l::SET)
1867                    .into(),
1868                // the entire address space:
1869                0x7FFFFFFF,
1870            );
1871
1872            // Finally, we configure the non-locked user-mode deny all
1873            // rule. This must never be removed, or otherwise usermode will be
1874            // able to access all locked regions (which are supposed to be
1875            // exclusively accessible to kernel-mode):
1876            write_pmpaddr_pmpcfg(
1877                AVAILABLE_ENTRIES - 7,
1878                (pmpcfg_octet::a::NAPOT
1879                    + pmpcfg_octet::r::CLEAR
1880                    + pmpcfg_octet::w::CLEAR
1881                    + pmpcfg_octet::x::CLEAR
1882                    + pmpcfg_octet::l::CLEAR)
1883                    .into(),
1884                // the entire address space:
1885                0x7FFFFFFF,
1886            );
1887
1888            // Setup complete
1889            Ok(KernelProtectionPMP)
1890        }
1891    }
1892
1893    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS>
1894        for KernelProtectionPMP<AVAILABLE_ENTRIES>
1895    {
1896        /// Ensure that the MPU_REGIONS (starting at entry, and occupying two
1897        /// entries per region) don't overflow the available entires, excluding
1898        /// the 7 entires used for implementing the kernel memory protection.
1899        const CONST_ASSERT_CHECK: () = assert!(MPU_REGIONS <= ((AVAILABLE_ENTRIES - 7) / 2));
1900
1901        fn available_regions(&self) -> usize {
1902            // Always assume to have `MPU_REGIONS` usable TOR regions. We don't
1903            // support locking additional regions at runtime.
1904            MPU_REGIONS
1905        }
1906
1907        // This implementation is specific for 32-bit systems. We use
1908        // `u32::from_be_bytes` and then cast to usize, as it manages to compile
1909        // on 64-bit systems as well. However, this implementation will not work
1910        // on RV64I systems, due to the changed pmpcfgX CSR layout.
1911        fn configure_pmp(
1912            &self,
1913            regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
1914        ) -> Result<(), ()> {
1915            // Could use `iter_array_chunks` once that's stable.
1916            let mut regions_iter = regions.iter();
1917            let mut i = 0;
1918
1919            while let Some(even_region) = regions_iter.next() {
1920                let odd_region_opt = regions_iter.next();
1921
1922                if let Some(odd_region) = odd_region_opt {
1923                    // We can configure two regions at once which, given that we
1924                    // start at index 0 (an even offset), translates to a single
1925                    // CSR write for the pmpcfgX register:
1926                    csr::CSR.pmpconfig_set(
1927                        i / 2,
1928                        u32::from_be_bytes([
1929                            odd_region.0.get(),
1930                            TORUserPMPCFG::OFF.get(),
1931                            even_region.0.get(),
1932                            TORUserPMPCFG::OFF.get(),
1933                        ]) as usize,
1934                    );
1935
1936                    // Now, set the addresses of the respective regions, if they
1937                    // are enabled, respectively:
1938                    if even_region.0 != TORUserPMPCFG::OFF {
1939                        csr::CSR
1940                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1941                        csr::CSR
1942                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1943                    }
1944
1945                    if odd_region.0 != TORUserPMPCFG::OFF {
1946                        csr::CSR
1947                            .pmpaddr_set(i * 2 + 2, (odd_region.1 as usize).overflowing_shr(2).0);
1948                        csr::CSR
1949                            .pmpaddr_set(i * 2 + 3, (odd_region.2 as usize).overflowing_shr(2).0);
1950                    }
1951
1952                    i += 2;
1953                } else {
1954                    // Modify the first two pmpcfgX octets for this region:
1955                    csr::CSR.pmpconfig_modify(
1956                        i / 2,
1957                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
1958                            0x0000FFFF,
1959                            0,
1960                            u32::from_be_bytes([
1961                                0,
1962                                0,
1963                                even_region.0.get(),
1964                                TORUserPMPCFG::OFF.get(),
1965                            ]) as usize,
1966                        ),
1967                    );
1968
1969                    // Set the addresses if the region is enabled:
1970                    if even_region.0 != TORUserPMPCFG::OFF {
1971                        csr::CSR
1972                            .pmpaddr_set(i * 2 + 0, (even_region.1 as usize).overflowing_shr(2).0);
1973                        csr::CSR
1974                            .pmpaddr_set(i * 2 + 1, (even_region.2 as usize).overflowing_shr(2).0);
1975                    }
1976
1977                    i += 1;
1978                }
1979            }
1980
1981            Ok(())
1982        }
1983
1984        fn enable_user_pmp(&self) -> Result<(), ()> {
1985            // No-op. User-mode regions are never enforced in machine-mode, and
1986            // thus can be configured direct and may stay enabled in
1987            // machine-mode.
1988            Ok(())
1989        }
1990
1991        fn disable_user_pmp(&self) {
1992            // No-op. User-mode regions are never enforced in machine-mode, and
1993            // thus can be configured direct and may stay enabled in
1994            // machine-mode.
1995        }
1996    }
1997
1998    impl<const AVAILABLE_ENTRIES: usize> fmt::Display for KernelProtectionPMP<AVAILABLE_ENTRIES> {
1999        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2000            write!(f, " PMP hardware configuration -- entries: \r\n")?;
2001            unsafe { super::format_pmp_entries::<AVAILABLE_ENTRIES>(f) }
2002        }
2003    }
2004}
2005
2006pub mod kernel_protection_mml_epmp {
2007    use super::{pmpcfg_octet, NAPOTRegionSpec, TORRegionSpec, TORUserPMP, TORUserPMPCFG};
2008    use crate::csr;
2009    use core::cell::Cell;
2010    use core::fmt;
2011    use kernel::platform::mpu;
2012    use kernel::utilities::registers::interfaces::{Readable, Writeable};
2013    use kernel::utilities::registers::{FieldValue, LocalRegisterCopy};
2014
2015    // ---------- Kernel memory-protection PMP memory region wrapper types -----
2016    //
2017    // These types exist primarily to avoid argument confusion in the
2018    // [`KernelProtectionMMLEPMP`] constructor, which accepts the addresses of
2019    // these memory regions as arguments. They further encode whether a region
2020    // must adhere to the `NAPOT` or `TOR` addressing mode constraints:
2021
2022    /// The flash memory region address range.
2023    ///
2024    /// Configured in the PMP as a `NAPOT` region.
2025    #[derive(Copy, Clone, Debug)]
2026    pub struct FlashRegion(pub NAPOTRegionSpec);
2027
2028    /// The RAM region address range.
2029    ///
2030    /// Configured in the PMP as a `NAPOT` region.
2031    #[derive(Copy, Clone, Debug)]
2032    pub struct RAMRegion(pub NAPOTRegionSpec);
2033
2034    /// The MMIO region address range.
2035    ///
2036    /// Configured in the PMP as a `NAPOT` region.
2037    #[derive(Copy, Clone, Debug)]
2038    pub struct MMIORegion(pub NAPOTRegionSpec);
2039
2040    /// The PMP region specification for the kernel `.text` section.
2041    ///
2042    /// This is to be made accessible to machine-mode as read-execute.
2043    /// Configured in the PMP as a `TOR` region.
2044    #[derive(Copy, Clone, Debug)]
2045    pub struct KernelTextRegion(pub TORRegionSpec);
2046
2047    /// A RISC-V ePMP implementation.
2048    ///
2049    /// Supports machine-mode (kernel) memory protection by using the
2050    /// machine-mode lockdown mode (MML), with a fixed number of
2051    /// "kernel regions" (such as `.text`, flash, RAM and MMIO).
2052    ///
2053    /// This implementation will configure the ePMP in the following way:
2054    ///
2055    /// - `mseccfg` CSR:
2056    ///   ```text
2057    ///   |-------------+-----------------------------------------------+-------|
2058    ///   | MSECCFG BIT | LABEL                                         | STATE |
2059    ///   |-------------+-----------------------------------------------+-------|
2060    ///   |           0 | Machine-Mode Lockdown (MML)                   |     1 |
2061    ///   |           1 | Machine-Mode Whitelist Policy (MMWP)          |     1 |
2062    ///   |           2 | Rule-Lock Bypass (RLB)                        |     0 |
2063    ///   |-------------+-----------------------------------------------+-------|
2064    ///   ```
2065    ///
2066    /// - `pmpaddrX` / `pmpcfgX` CSRs:
2067    ///   ```text
2068    ///   |-------+-----------------------------------------+-------+---+-------|
2069    ///   | ENTRY | REGION / ADDR                           | MODE  | L | PERMS |
2070    ///   |-------+-----------------------------------------+-------+---+-------|
2071    ///   |     0 | --------------------------------------- | OFF   | X | ----- |
2072    ///   |     1 | Kernel .text section                    | TOR   | X | R/X   |
2073    ///   |       |                                         |       |   |       |
2074    ///   |     2 | /                                     \ | OFF   |   |       |
2075    ///   |     3 | \ Userspace TOR region #0             / | TOR   |   | ????? |
2076    ///   |       |                                         |       |   |       |
2077    ///   |     4 | /                                     \ | OFF   |   |       |
2078    ///   |     5 | \ Userspace TOR region #1             / | TOR   |   | ????? |
2079    ///   |       |                                         |       |   |       |
2080    ///   | 6 ... | /                                     \ |       |   |       |
2081    ///   | n - 4 | \ Userspace TOR region #x             / |       |   |       |
2082    ///   |       |                                         |       |   |       |
2083    ///   | n - 3 | FLASH (spanning kernel & apps)          | NAPOT | X | R     |
2084    ///   |       |                                         |       |   |       |
2085    ///   | n - 2 | RAM (spanning kernel & apps)            | NAPOT | X | R/W   |
2086    ///   |       |                                         |       |   |       |
2087    ///   | n - 1 | MMIO                                    | NAPOT | X | R/W   |
2088    ///   |-------+-----------------------------------------+-------+---+-------|
2089    ///   ```
2090    ///
2091    /// Crucially, this implementation relies on an unconfigured hardware PMP
2092    /// implementing the ePMP (`mseccfg` CSR) extension, providing the Machine
2093    /// Lockdown Mode (MML) security bit. This bit is required to ensure that
2094    /// any machine-mode (kernel) protection regions (lock bit set) are only
2095    /// accessible to kernel mode.
2096    pub struct KernelProtectionMMLEPMP<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> {
2097        user_pmp_enabled: Cell<bool>,
2098        shadow_user_pmpcfgs: [Cell<TORUserPMPCFG>; MPU_REGIONS],
2099    }
2100
2101    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize>
2102        KernelProtectionMMLEPMP<AVAILABLE_ENTRIES, MPU_REGIONS>
2103    {
2104        // Start user-mode TOR regions after the first kernel .text region:
2105        const TOR_REGIONS_OFFSET: usize = 1;
2106
2107        pub unsafe fn new(
2108            flash: FlashRegion,
2109            ram: RAMRegion,
2110            mmio: MMIORegion,
2111            kernel_text: KernelTextRegion,
2112        ) -> Result<Self, ()> {
2113            for i in 0..AVAILABLE_ENTRIES {
2114                // Read the entry's CSR:
2115                let pmpcfg_csr = csr::CSR.pmpconfig_get(i / 4);
2116
2117                // Extract the entry's pmpcfg octet:
2118                let pmpcfg: LocalRegisterCopy<u8, pmpcfg_octet::Register> = LocalRegisterCopy::new(
2119                    pmpcfg_csr.overflowing_shr(((i % 4) * 8) as u32).0 as u8,
2120                );
2121
2122                // As outlined above, we never touch a locked region. Thus, bail
2123                // out if it's locked:
2124                if pmpcfg.is_set(pmpcfg_octet::l) {
2125                    return Err(());
2126                }
2127
2128                // Now that it's not locked, we can be sure that regardless of
2129                // any ePMP bits, this region is either ignored or entirely
2130                // denied for machine-mode access. Hence, we can change it in
2131                // arbitrary ways without breaking our own memory access. Try to
2132                // flip the R/W/X bits:
2133                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr ^ (7 << ((i % 4) * 8)));
2134
2135                // Check if the CSR changed:
2136                if pmpcfg_csr == csr::CSR.pmpconfig_get(i / 4) {
2137                    // Didn't change! This means that this region is not backed
2138                    // by HW. Return an error as `AVAILABLE_ENTRIES` is
2139                    // incorrect:
2140                    return Err(());
2141                }
2142
2143                // Finally, turn the region off:
2144                csr::CSR.pmpconfig_set(i / 4, pmpcfg_csr & !(0x18 << ((i % 4) * 8)));
2145            }
2146
2147            // -----------------------------------------------------------------
2148            // Hardware PMP is verified to be in a compatible mode & state, and
2149            // has at least `AVAILABLE_ENTRIES` entries. We have not yet checked
2150            // whether the PMP is actually an _e_PMP. However, we don't want to
2151            // produce a gadget to set RLB, and so the only safe way to test
2152            // this is to set up the PMP regions and then try to enable the
2153            // mseccfg bits.
2154            // -----------------------------------------------------------------
2155
2156            // Helper to modify an arbitrary PMP entry. Because we don't know
2157            // AVAILABLE_ENTRIES in advance, there's no good way to
2158            // optimize this further.
2159            fn write_pmpaddr_pmpcfg(i: usize, pmpcfg: u8, pmpaddr: usize) {
2160                // Important to set the address first. Locking the pmpcfg
2161                // register will also lock the adress register!
2162                csr::CSR.pmpaddr_set(i, pmpaddr);
2163                csr::CSR.pmpconfig_modify(
2164                    i / 4,
2165                    FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2166                        0x000000FF_usize,
2167                        (i % 4) * 8,
2168                        u32::from_be_bytes([0, 0, 0, pmpcfg]) as usize,
2169                    ),
2170                );
2171            }
2172
2173            // Set the kernel `.text`, flash, RAM and MMIO regions, in no
2174            // particular order, with the exception of `.text` and flash:
2175            // `.text` must precede flash, as otherwise we'd be revoking execute
2176            // permissions temporarily. Given that we can currently execute
2177            // code, this should not have any impact on our accessible memory,
2178            // assuming that the provided regions are not otherwise aliased.
2179
2180            // `.text` at n - 5 and n - 4 (TOR region):
2181            write_pmpaddr_pmpcfg(
2182                0,
2183                (pmpcfg_octet::a::OFF
2184                    + pmpcfg_octet::r::CLEAR
2185                    + pmpcfg_octet::w::CLEAR
2186                    + pmpcfg_octet::x::CLEAR
2187                    + pmpcfg_octet::l::SET)
2188                    .into(),
2189                kernel_text.0.pmpaddr_a(),
2190            );
2191            write_pmpaddr_pmpcfg(
2192                1,
2193                (pmpcfg_octet::a::TOR
2194                    + pmpcfg_octet::r::SET
2195                    + pmpcfg_octet::w::CLEAR
2196                    + pmpcfg_octet::x::SET
2197                    + pmpcfg_octet::l::SET)
2198                    .into(),
2199                kernel_text.0.pmpaddr_b(),
2200            );
2201
2202            // MMIO at n - 1:
2203            write_pmpaddr_pmpcfg(
2204                AVAILABLE_ENTRIES - 1,
2205                (pmpcfg_octet::a::NAPOT
2206                    + pmpcfg_octet::r::SET
2207                    + pmpcfg_octet::w::SET
2208                    + pmpcfg_octet::x::CLEAR
2209                    + pmpcfg_octet::l::SET)
2210                    .into(),
2211                mmio.0.pmpaddr(),
2212            );
2213
2214            // RAM at n - 2:
2215            write_pmpaddr_pmpcfg(
2216                AVAILABLE_ENTRIES - 2,
2217                (pmpcfg_octet::a::NAPOT
2218                    + pmpcfg_octet::r::SET
2219                    + pmpcfg_octet::w::SET
2220                    + pmpcfg_octet::x::CLEAR
2221                    + pmpcfg_octet::l::SET)
2222                    .into(),
2223                ram.0.pmpaddr(),
2224            );
2225
2226            // flash at n - 3:
2227            write_pmpaddr_pmpcfg(
2228                AVAILABLE_ENTRIES - 3,
2229                (pmpcfg_octet::a::NAPOT
2230                    + pmpcfg_octet::r::SET
2231                    + pmpcfg_octet::w::CLEAR
2232                    + pmpcfg_octet::x::CLEAR
2233                    + pmpcfg_octet::l::SET)
2234                    .into(),
2235                flash.0.pmpaddr(),
2236            );
2237
2238            // Finally, attempt to enable the MSECCFG security bits, and verify
2239            // that they have been set correctly. If they have not been set to
2240            // the written value, this means that this hardware either does not
2241            // support ePMP, or it was in some invalid state otherwise. We don't
2242            // need to read back the above regions, as we previous verified that
2243            // none of their entries were locked -- so writing to them must work
2244            // even without RLB set.
2245            //
2246            // Set RLB(2) = 0, MMWP(1) = 1, MML(0) = 1
2247            csr::CSR.mseccfg.set(0x00000003);
2248
2249            // Read back the MSECCFG CSR to ensure that the machine's security
2250            // configuration was set properly. If this fails, we have set up the
2251            // PMP in a way that would give userspace access to kernel
2252            // space. The caller of this method must appropriately handle this
2253            // error condition by ensuring that the platform will never execute
2254            // userspace code!
2255            if csr::CSR.mseccfg.get() != 0x00000003 {
2256                return Err(());
2257            }
2258
2259            // Setup complete
2260            Ok(KernelProtectionMMLEPMP {
2261                user_pmp_enabled: Cell::new(false),
2262                shadow_user_pmpcfgs: [const { Cell::new(TORUserPMPCFG::OFF) }; MPU_REGIONS],
2263            })
2264        }
2265    }
2266
2267    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> TORUserPMP<MPU_REGIONS>
2268        for KernelProtectionMMLEPMP<AVAILABLE_ENTRIES, MPU_REGIONS>
2269    {
2270        // Ensure that the MPU_REGIONS (starting at entry, and occupying two
2271        // entries per region) don't overflow the available entires, excluding
2272        // the 7 entries used for implementing the kernel memory protection:
2273        const CONST_ASSERT_CHECK: () = assert!(MPU_REGIONS <= ((AVAILABLE_ENTRIES - 5) / 2));
2274
2275        fn available_regions(&self) -> usize {
2276            // Always assume to have `MPU_REGIONS` usable TOR regions. We don't
2277            // support locking additional regions at runtime.
2278            MPU_REGIONS
2279        }
2280
2281        // This implementation is specific for 32-bit systems. We use
2282        // `u32::from_be_bytes` and then cast to usize, as it manages to compile
2283        // on 64-bit systems as well. However, this implementation will not work
2284        // on RV64I systems, due to the changed pmpcfgX CSR layout.
2285        fn configure_pmp(
2286            &self,
2287            regions: &[(TORUserPMPCFG, *const u8, *const u8); MPU_REGIONS],
2288        ) -> Result<(), ()> {
2289            // Configure all of the regions' addresses and store their pmpcfg octets
2290            // in our shadow storage. If the user PMP is already enabled, we further
2291            // apply this configuration (set the pmpcfgX CSRs) by running
2292            // `enable_user_pmp`:
2293            for (i, (region, shadow_user_pmpcfg)) in regions
2294                .iter()
2295                .zip(self.shadow_user_pmpcfgs.iter())
2296                .enumerate()
2297            {
2298                // The ePMP in MML mode does not support read-write-execute
2299                // regions. If such a region is to be configured, abort. As this
2300                // loop here only modifies the shadow state, we can simply abort and
2301                // return an error. We don't make any promises about the ePMP state
2302                // if the configuration files, but it is still being activated with
2303                // `enable_user_pmp`:
2304                if region.0.get()
2305                    == <TORUserPMPCFG as From<mpu::Permissions>>::from(
2306                        mpu::Permissions::ReadWriteExecute,
2307                    )
2308                    .get()
2309                {
2310                    return Err(());
2311                }
2312
2313                // Set the CSR addresses for this region (if its not OFF, in which
2314                // case the hardware-configured addresses are irrelevant):
2315                if region.0 != TORUserPMPCFG::OFF {
2316                    csr::CSR.pmpaddr_set(
2317                        (i + Self::TOR_REGIONS_OFFSET) * 2 + 0,
2318                        (region.1 as usize).overflowing_shr(2).0,
2319                    );
2320                    csr::CSR.pmpaddr_set(
2321                        (i + Self::TOR_REGIONS_OFFSET) * 2 + 1,
2322                        (region.2 as usize).overflowing_shr(2).0,
2323                    );
2324                }
2325
2326                // Store the region's pmpcfg octet:
2327                shadow_user_pmpcfg.set(region.0);
2328            }
2329
2330            // If the PMP is currently active, apply the changes to the CSRs:
2331            if self.user_pmp_enabled.get() {
2332                self.enable_user_pmp()?;
2333            }
2334
2335            Ok(())
2336        }
2337
2338        fn enable_user_pmp(&self) -> Result<(), ()> {
2339            // We store the "enabled" PMPCFG octets of user regions in the
2340            // `shadow_user_pmpcfg` field, such that we can re-enable the PMP
2341            // without a call to `configure_pmp` (where the `TORUserPMPCFG`s are
2342            // provided by the caller).
2343
2344            // Could use `iter_array_chunks` once that's stable.
2345            let mut shadow_user_pmpcfgs_iter = self.shadow_user_pmpcfgs.iter();
2346            let mut i = Self::TOR_REGIONS_OFFSET;
2347
2348            while let Some(first_region_pmpcfg) = shadow_user_pmpcfgs_iter.next() {
2349                // If we're at a "region" offset divisible by two (where "region" =
2350                // 2 PMP "entries"), then we can configure an entire `pmpcfgX` CSR
2351                // in one operation. As CSR writes are expensive, this is an
2352                // operation worth making:
2353                let second_region_opt = if i % 2 == 0 {
2354                    shadow_user_pmpcfgs_iter.next()
2355                } else {
2356                    None
2357                };
2358
2359                if let Some(second_region_pmpcfg) = second_region_opt {
2360                    // We're at an even index and have two regions to configure, so
2361                    // do that with a single CSR write:
2362                    csr::CSR.pmpconfig_set(
2363                        i / 2,
2364                        u32::from_be_bytes([
2365                            second_region_pmpcfg.get().get(),
2366                            TORUserPMPCFG::OFF.get(),
2367                            first_region_pmpcfg.get().get(),
2368                            TORUserPMPCFG::OFF.get(),
2369                        ]) as usize,
2370                    );
2371
2372                    i += 2;
2373                } else if i % 2 == 0 {
2374                    // This is a single region at an even index. Thus, modify the
2375                    // first two pmpcfgX octets for this region.
2376                    csr::CSR.pmpconfig_modify(
2377                        i / 2,
2378                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2379                            0x0000FFFF,
2380                            0, // lower two octets
2381                            u32::from_be_bytes([
2382                                0,
2383                                0,
2384                                first_region_pmpcfg.get().get(),
2385                                TORUserPMPCFG::OFF.get(),
2386                            ]) as usize,
2387                        ),
2388                    );
2389
2390                    i += 1;
2391                } else {
2392                    // This is a single region at an odd index. Thus, modify the
2393                    // latter two pmpcfgX octets for this region.
2394                    csr::CSR.pmpconfig_modify(
2395                        i / 2,
2396                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2397                            0x0000FFFF,
2398                            16, // higher two octets
2399                            u32::from_be_bytes([
2400                                0,
2401                                0,
2402                                first_region_pmpcfg.get().get(),
2403                                TORUserPMPCFG::OFF.get(),
2404                            ]) as usize,
2405                        ),
2406                    );
2407
2408                    i += 1;
2409                }
2410            }
2411
2412            self.user_pmp_enabled.set(true);
2413
2414            Ok(())
2415        }
2416
2417        fn disable_user_pmp(&self) {
2418            // Simply set all of the user-region pmpcfg octets to OFF:
2419
2420            let mut user_region_pmpcfg_octet_pairs =
2421                (Self::TOR_REGIONS_OFFSET)..(Self::TOR_REGIONS_OFFSET + MPU_REGIONS);
2422            while let Some(first_region_idx) = user_region_pmpcfg_octet_pairs.next() {
2423                let second_region_opt = if first_region_idx % 2 == 0 {
2424                    user_region_pmpcfg_octet_pairs.next()
2425                } else {
2426                    None
2427                };
2428
2429                if let Some(_second_region_idx) = second_region_opt {
2430                    // We're at an even index and have two regions to configure, so
2431                    // do that with a single CSR write:
2432                    csr::CSR.pmpconfig_set(
2433                        first_region_idx / 2,
2434                        u32::from_be_bytes([
2435                            TORUserPMPCFG::OFF.get(),
2436                            TORUserPMPCFG::OFF.get(),
2437                            TORUserPMPCFG::OFF.get(),
2438                            TORUserPMPCFG::OFF.get(),
2439                        ]) as usize,
2440                    );
2441                } else if first_region_idx % 2 == 0 {
2442                    // This is a single region at an even index. Thus, modify the
2443                    // first two pmpcfgX octets for this region.
2444                    csr::CSR.pmpconfig_modify(
2445                        first_region_idx / 2,
2446                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2447                            0x0000FFFF,
2448                            0, // lower two octets
2449                            u32::from_be_bytes([
2450                                0,
2451                                0,
2452                                TORUserPMPCFG::OFF.get(),
2453                                TORUserPMPCFG::OFF.get(),
2454                            ]) as usize,
2455                        ),
2456                    );
2457                } else {
2458                    // This is a single region at an odd index. Thus, modify the
2459                    // latter two pmpcfgX octets for this region.
2460                    csr::CSR.pmpconfig_modify(
2461                        first_region_idx / 2,
2462                        FieldValue::<usize, csr::pmpconfig::pmpcfg::Register>::new(
2463                            0x0000FFFF,
2464                            16, // higher two octets
2465                            u32::from_be_bytes([
2466                                0,
2467                                0,
2468                                TORUserPMPCFG::OFF.get(),
2469                                TORUserPMPCFG::OFF.get(),
2470                            ]) as usize,
2471                        ),
2472                    );
2473                }
2474            }
2475
2476            self.user_pmp_enabled.set(false);
2477        }
2478    }
2479
2480    impl<const AVAILABLE_ENTRIES: usize, const MPU_REGIONS: usize> fmt::Display
2481        for KernelProtectionMMLEPMP<AVAILABLE_ENTRIES, MPU_REGIONS>
2482    {
2483        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2484            write!(
2485                f,
2486                " ePMP configuration:\r\n  mseccfg: {:#08X}, user-mode PMP active: {:?}, entries:\r\n",
2487                csr::CSR.mseccfg.get(),
2488                self.user_pmp_enabled.get()
2489            )?;
2490            unsafe { super::format_pmp_entries::<AVAILABLE_ENTRIES>(f) }?;
2491
2492            write!(f, "  Shadow PMP entries for user-mode:\r\n")?;
2493            for (i, shadowed_pmpcfg) in self.shadow_user_pmpcfgs.iter().enumerate() {
2494                let (start_pmpaddr_label, startaddr_pmpaddr, endaddr, mode) =
2495                    if shadowed_pmpcfg.get() == TORUserPMPCFG::OFF {
2496                        (
2497                            "pmpaddr",
2498                            csr::CSR.pmpaddr_get((i + Self::TOR_REGIONS_OFFSET) * 2),
2499                            0,
2500                            "OFF",
2501                        )
2502                    } else {
2503                        (
2504                            "  start",
2505                            csr::CSR
2506                                .pmpaddr_get((i + Self::TOR_REGIONS_OFFSET) * 2)
2507                                .overflowing_shl(2)
2508                                .0,
2509                            csr::CSR
2510                                .pmpaddr_get((i + Self::TOR_REGIONS_OFFSET) * 2 + 1)
2511                                .overflowing_shl(2)
2512                                .0
2513                                | 0b11,
2514                            "TOR",
2515                        )
2516                    };
2517
2518                write!(
2519                    f,
2520                    "  [{:02}]: {}={:#010X}, end={:#010X}, cfg={:#04X} ({}  ) ({}{}{}{})\r\n",
2521                    (i + Self::TOR_REGIONS_OFFSET) * 2 + 1,
2522                    start_pmpaddr_label,
2523                    startaddr_pmpaddr,
2524                    endaddr,
2525                    shadowed_pmpcfg.get().get(),
2526                    mode,
2527                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::l) {
2528                        "l"
2529                    } else {
2530                        "-"
2531                    },
2532                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::r) {
2533                        "r"
2534                    } else {
2535                        "-"
2536                    },
2537                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::w) {
2538                        "w"
2539                    } else {
2540                        "-"
2541                    },
2542                    if shadowed_pmpcfg.get().get_reg().is_set(pmpcfg_octet::x) {
2543                        "x"
2544                    } else {
2545                        "-"
2546                    },
2547                )?;
2548            }
2549
2550            Ok(())
2551        }
2552    }
2553}