arm-tzc 0.2.1

Arm TrustZone Address Space Controller
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
// SPDX-FileCopyrightText: Copyright The arm-tzc Contributors.
// SPDX-License-Identifier: MIT OR Apache-2.0

use bitflags::bitflags;
use safe_mmio::{SharedMmioPointer, UniqueMmioPointer, field, field_shared, fields::ReadPureWrite};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

use crate::{
    for_in_slice,
    utils::{concatenate_address_parts, get_bit, set_bit, split_address},
};

const REGION_ALIGNMENT_MASK: u64 = 0xfff;

/// Controls access to a region from the secure world.
#[derive(Debug, Clone, Copy, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)]
#[repr(transparent)]
pub struct SecureAccess(u32);

bitflags! {
    impl SecureAccess: u32 {
        /// Denies all access from secure world.
        const NONE = 0;

        /// Enables read access from secure world.
        const R = 1 << 30;

        /// Enables write access from secure world.
        const W = 1 << 31;

        /// Enables read-write access from secure world.
        const RW = Self::R.bits() | Self::W.bits();
    }
}

#[derive(Debug, Clone, Copy, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)]
/// Each region has a region attributes register which controls the permissions for Region 0 and,
/// for all other regions, the permissions and target filter region enables.
#[repr(transparent)]
pub struct RegionAttributes(u32);

impl RegionAttributes {
    /// Creates a fresh value for a `RegionAttributes`.
    ///
    /// - `secure_access`: controls read/write access from the Secure World.
    /// - `filters`: the id of the filters to enable for this region.
    pub const fn new(secure_access: SecureAccess, filters: &[usize]) -> Self {
        let mut s = Self(secure_access.bits());

        for_in_slice! {
            f in filters,
            s.set_filter_status(*f, true)
        }

        s
    }

    /// Gets secure access attributes of the region.
    pub const fn secure_access(&self) -> SecureAccess {
        SecureAccess::from_bits_truncate(self.0)
    }

    /// Sets secure access attributes of the region.
    pub const fn set_secure_access(&mut self, secure_access: SecureAccess) {
        self.0 &= !SecureAccess::RW.bits();
        self.0 |= secure_access.bits();
    }

    /// Whether the filter `index` is enabled for this region.
    pub const fn is_filter_enabled(&self, index: usize) -> bool {
        assert!(index < 4);
        get_bit(self.0, index)
    }

    /// Independently disables/enables the filter `index` for this region.
    ///
    /// When set HIGH, it enables the use of the current region programming for the associated
    /// filter. For Region 0 all bits are set HIGH and cannot be modified.
    pub const fn set_filter_status(&mut self, index: usize, enabled: bool) {
        assert!(index < 4);
        set_bit(&mut self.0, index, enabled);
    }
}

#[derive(Debug, Clone, Copy, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)]
/// Each region has a region id access register which controls the Non-secure access based on the
/// NSAID inputs.
#[repr(transparent)]
pub struct RegionIDAccess(u32);

impl RegionIDAccess {
    /// Denies non-secure access to the region.
    pub const NONE: Self = Self::new(&[], &[]);

    /// Creates a new instance of `RegionIDAccess`.
    ///
    /// - `writes`: all the NSA indexes that should be allowed to write into this region.
    /// - `reads`: all the NSA indexes that should be allowed to read into this region.
    pub const fn new(writes: &[usize], reads: &[usize]) -> Self {
        let mut s = Self(0);

        for_in_slice! {
            w in writes,
            s.set_write_enabled(*w, true)
        }

        for_in_slice! {
            r in reads,
            s.set_read_enabled(*r, true)
        }

        s
    }

    /// Whether Non-secure write access with an the associated `NSAIDW<index>` are allowed to
    /// progress.
    pub const fn is_write_enabled(&self, index: usize) -> bool {
        assert!(index < 16);
        get_bit(self.0, index + 16)
    }

    /// Permits Non-secure write access to any access with the associated `NSAIDW<index>` value.
    pub const fn set_write_enabled(&mut self, index: usize, enabled: bool) {
        assert!(index < 16);
        set_bit(&mut self.0, index + 16, enabled);
    }

    /// Whether Non-secure read access with an the associated `NSAIDW<index>` are allowed to
    /// progress.
    pub const fn is_read_enabled(&self, index: usize) -> bool {
        assert!(index < 16);
        get_bit(self.0, index)
    }

    /// Permits Non-secure read access to any access with the associated `NSAIDW<index>` value.
    pub const fn set_read_enabled(&mut self, index: usize, enabled: bool) {
        assert!(index < 16);
        set_bit(&mut self.0, index, enabled);
    }
}

#[derive(Debug, Clone, Eq, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq)]
#[repr(C, align(4))]
pub(crate) struct RegionRegisters {
    /// 0x100 + (0x20 * n): Region base address low register.
    region_base_low: ReadPureWrite<u32>,
    /// 0x104 + (0x20 * n): Region base address high register.
    region_base_high: ReadPureWrite<u32>,
    /// 0x108 + (0x20 * n): Region top address low register.
    region_top_low: ReadPureWrite<u32>,
    /// 0x10C + (0x20 * n): Region top address high register.
    region_top_high: ReadPureWrite<u32>,
    /// 0x110 + (0x20 * n): Region attributes register.
    region_attributes: ReadPureWrite<RegionAttributes>,
    /// 0x114 + (0x20 * n): Region ID access register.
    region_id_access: ReadPureWrite<RegionIDAccess>,
    /// 0x118 + (0x20 * n) - 0x120 + (0x20 * n): reserved.
    reserved: [u32; 2],
}

/// Wrapper structure to allow reading registers for a region. See also
/// [`Tzc::region`][crate::Tzc::region].
pub struct TzcRegion<'regs> {
    pub(crate) regs: SharedMmioPointer<'regs, RegionRegisters>,
    pub(crate) address_width_mask: u64,
}

impl<'a> TzcRegion<'a> {
    /// Returns the base address for this region.
    ///
    /// The address' bit-width will be contained within the width specified by the TZC in the
    /// [`build_configuration`][crate::Tzc::build_configuration] register and the 12 LSBs are be 0
    /// as the regions size are 4KB-aligned and this address must point to their first byte.
    pub fn region_base_address(&self) -> u64 {
        concatenate_address_parts(
            field_shared!(self.regs, region_base_low).read(),
            field_shared!(self.regs, region_base_high).read(),
        ) & self.address_width_mask // The mask is applied since the [63:N] first bits (N is address width) may be non-zero.
    }

    /// Returns the top address for this region.
    ///
    /// The address' bit-width will be contained within the width specified by the TZC in the
    /// [`build_configuration`][crate::Tzc::build_configuration] register and the 12 LSBs are be 1
    /// as the regions size are 4KB-aligned and this address must point to their last byte.
    pub fn region_top_address(&self) -> u64 {
        concatenate_address_parts(
            field_shared!(self.regs, region_top_low).read(),
            field_shared!(self.regs, region_top_high).read(),
        ) & self.address_width_mask // The mask is applied since the [63:N] first bits (N is address width) may be non-zero.
    }

    /// Return the [`RegionAttributes`] for this region.
    pub fn region_attributes(&self) -> RegionAttributes {
        field_shared!(self.regs, region_attributes).read()
    }

    /// Return the [`RegionIDAccess`] for this region.
    pub fn region_id_access(&self) -> RegionIDAccess {
        field_shared!(self.regs, region_id_access).read()
    }
}

macro_rules! redeclare_fn {
    ($name:ident, $ret:ty) => {
        #[doc=concat!("See [TzcRegion::", stringify!($name), "].")]
        pub fn $name(&self) -> $ret {
            self.as_shared().$name()
        }
    };
}

/// Wrapper structure to allow reading and writing registers for a region. See also
/// [`Tzc::region_mut`][crate::Tzc::region_mut].
pub struct TzcRegionMut<'regs> {
    pub(crate) regs: UniqueMmioPointer<'regs, RegionRegisters>,
    pub(crate) addresses_writable: bool,
    pub(crate) address_width_mask: u64,
}

impl<'a> TzcRegionMut<'a> {
    #[inline(always)]
    fn as_shared(&self) -> TzcRegion<'a> {
        TzcRegion {
            regs: *self.regs,
            address_width_mask: self.address_width_mask,
        }
    }

    redeclare_fn!(region_base_address, u64);
    redeclare_fn!(region_top_address, u64);
    redeclare_fn!(region_attributes, RegionAttributes);
    redeclare_fn!(region_id_access, RegionIDAccess);

    /// Sets the base address for this region.
    ///
    /// The address' bit-width must be contained within the width specified by the TZC in the
    /// [`build_configuration`][crate::Tzc::build_configuration] register and the 12 LSBs must be 0
    /// as the regions size are 4KB-aligned and this address must point to their first byte.
    ///
    /// This value cannot be written for Region 0, any call of this function with `index == 0` will
    /// result in an error.
    pub fn set_region_base_address(&mut self, address: u64) {
        assert_eq!(address & self.address_width_mask, address);
        assert_eq!(address & REGION_ALIGNMENT_MASK, 0);
        assert!(self.addresses_writable);

        let (low, high) = split_address(address);
        field!(self.regs, region_base_low).write(low);
        field!(self.regs, region_base_high).write(high);
    }

    /// Sets the top address for this region.
    ///
    /// The address' bit-width must be contained within the width specified by the TZC in the
    /// [`build_configuration`][crate::Tzc::build_configuration] register and the 12 LSBs must be 1
    /// as the regions size are 4KB-aligned and this address must point to their last byte.
    ///
    /// This value cannot be written for Region 0 and attempting it will return an error.
    pub fn set_region_top_address(&mut self, address: u64) {
        assert_eq!(address & self.address_width_mask, address);
        assert_eq!(address & REGION_ALIGNMENT_MASK, REGION_ALIGNMENT_MASK);
        assert!(self.addresses_writable);

        let (low, high) = split_address(address);
        field!(self.regs, region_top_low).write(low);
        field!(self.regs, region_top_high).write(high);
    }

    /// Sets the [`RegionAttributes`] for the region `index`.
    pub fn set_region_attributes(&mut self, value: RegionAttributes) {
        field!(self.regs, region_attributes).write(value);
    }

    /// Sets the [`RegionIDAccess`] for the region `index`.
    pub fn set_region_id_access(&mut self, value: RegionIDAccess) {
        field!(self.regs, region_id_access).write(value);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{region::REGION_ALIGNMENT_MASK, tests::FakeTZCRegisters};

    #[test]
    fn region_0_address() {
        let mut regs = FakeTZCRegisters::new();
        regs.reg_write(0x100, 0xbeef_0000);
        regs.reg_write(0x104, 0xdead);
        regs.reg_write(0x108, 0xdaed_0000);
        regs.reg_write(0x10c, 0xfeeb);

        let tzc = regs.tzc_for_test();
        assert_eq!(
            tzc.region(0).unwrap().region_base_address(),
            0xdead_beef_0000
        );
        assert_eq!(
            tzc.region(0).unwrap().region_top_address(),
            0xfeeb_daed_0000
        );
    }

    #[test]
    fn region_n_address() {
        let mut regs = FakeTZCRegisters::new();
        for i in 1..=8 {
            regs.reg_write(0x100 + i * 0x20, 0xabcd_0000);
            regs.reg_write(0x104 + i * 0x20, i as u32);
            regs.reg_write(0x108 + i * 0x20, 0xeffe_0000);
            regs.reg_write(0x10c + i * 0x20, i as u32 + 8);
        }

        let tzc = regs.tzc_for_test();
        for i in 1..=8 {
            assert_eq!(
                tzc.region(i).unwrap().region_base_address(),
                (i as u64) << 32 | 0xabcd_0000
            );
            assert_eq!(
                tzc.region(i).unwrap().region_top_address(),
                (i as u64 + 8) << 32 | 0xeffe_0000
            );
        }
    }

    #[test]
    fn region_n_address_mask() {
        let mut regs = FakeTZCRegisters::new();
        regs.reg_write(0x120, 0xffff_f000);
        regs.reg_write(0x124, u32::MAX);
        regs.reg_write(0x128, u32::MAX);
        regs.reg_write(0x12c, u32::MAX);
        let tzc = regs.tzc_for_test();

        assert_eq!(
            tzc.region(1).unwrap().region_base_address(),
            0x0000_ffff_ffff_f000
        );
        assert_eq!(
            tzc.region(1).unwrap().region_top_address(),
            0x0000_ffff_ffff_ffff
        );
    }

    #[test]
    fn region_n_write_address() {
        let mut regs = FakeTZCRegisters::new();
        let mut tzc = regs.tzc_for_test();
        for i in 1..=8 {
            let mut reg = tzc.region_mut(i).unwrap();

            reg.set_region_base_address((i << 32 | (i << 16)) as u64);

            reg.set_region_top_address((i << 36 | (i << 24)) as u64 | REGION_ALIGNMENT_MASK);
        }

        for i in 1..=8 {
            assert_eq!(regs.reg_read(0x100 + i * 0x20), (i as u32) << 16);
            assert_eq!(regs.reg_read(0x104 + i * 0x20), i as u32);
            assert_eq!(
                regs.reg_read(0x108 + i * 0x20),
                (i as u32) << 24 | (REGION_ALIGNMENT_MASK as u32)
            );
            assert_eq!(regs.reg_read(0x10c + i * 0x20), (i << 4) as u32);
        }
    }

    #[test]
    #[should_panic]
    fn region_0_write_base_address() {
        let mut regs = FakeTZCRegisters::new();
        let mut tzc = regs.tzc_for_test();

        tzc.region_mut(0)
            .unwrap()
            .set_region_base_address(0xdead_beef_0000);
    }

    #[test]
    #[should_panic]
    fn region_0_write_top_address() {
        let mut regs = FakeTZCRegisters::new();
        let mut tzc = regs.tzc_for_test();

        tzc.region_mut(0)
            .unwrap()
            .set_region_top_address(0xdead_beef_0000);
    }

    #[test]
    fn region_attributes() {
        let mut regs = FakeTZCRegisters::new();
        regs.reg_write(0x110, 0b0000_0000_0000_0000_0000_0000_0000_0101);
        regs.reg_write(0x130, 0b0100_0000_0000_0000_0000_0000_0000_0010);
        regs.reg_write(0x150, 0b1000_0000_0000_0000_0000_0000_0000_1111);
        regs.reg_write(0x170, 0b1100_0000_0000_0000_0000_0000_0000_0000);

        let tzc = regs.tzc_for_test();
        let att0 = tzc.region(0).unwrap().region_attributes();
        let att1 = tzc.region(1).unwrap().region_attributes();
        let att2 = tzc.region(2).unwrap().region_attributes();
        let att3 = tzc.region(3).unwrap().region_attributes();

        assert_eq!(SecureAccess::NONE, att0.secure_access());
        assert!(att0.is_filter_enabled(0));
        assert!(!att0.is_filter_enabled(1));
        assert!(att0.is_filter_enabled(2));
        assert!(!att0.is_filter_enabled(3));

        assert_eq!(SecureAccess::R, att1.secure_access());
        assert!(!att1.is_filter_enabled(0));
        assert!(att1.is_filter_enabled(1));
        assert!(!att1.is_filter_enabled(2));
        assert!(!att1.is_filter_enabled(3));

        assert_eq!(SecureAccess::W, att2.secure_access());
        assert!(att2.is_filter_enabled(0));
        assert!(att2.is_filter_enabled(1));
        assert!(att2.is_filter_enabled(2));
        assert!(att2.is_filter_enabled(3));

        assert_eq!(SecureAccess::RW, att3.secure_access());
        assert!(!att3.is_filter_enabled(0));
        assert!(!att3.is_filter_enabled(1));
        assert!(!att3.is_filter_enabled(2));
        assert!(!att3.is_filter_enabled(3));
    }

    #[test]
    fn set_region_attributes() {
        let mut regs = FakeTZCRegisters::new();
        regs.reg_write(0x110, 0b0000_0000_0000_0000_0000_0000_0000_0101);
        regs.reg_write(0x130, 0b0100_0000_0000_0000_0000_0000_0000_0010);

        let mut tzc = regs.tzc_for_test();

        let mut reg0 = tzc.region_mut(0).unwrap();
        let mut att0 = reg0.region_attributes();
        att0.set_secure_access(SecureAccess::W);
        att0.set_filter_status(0, false);
        reg0.set_region_attributes(att0);

        let mut reg1 = tzc.region_mut(1).unwrap();
        let mut att1 = reg1.region_attributes();
        att1.set_secure_access(SecureAccess::NONE);
        att1.set_filter_status(1, false);
        reg1.set_region_attributes(att1);

        let att2 = RegionAttributes::new(SecureAccess::RW, &[0, 1, 2, 3]);
        tzc.region_mut(2).unwrap().set_region_attributes(att2);
        assert_eq!(
            regs.reg_read(0x110),
            0b1000_0000_0000_0000_0000_0000_0000_0100
        );
        assert_eq!(
            regs.reg_read(0x130),
            0b0000_0000_0000_0000_0000_0000_0000_0000
        );
        assert_eq!(
            regs.reg_read(0x150),
            0b1100_0000_0000_0000_0000_0000_0000_1111
        );
    }

    #[test]
    fn region_id_access() {
        let mut regs = FakeTZCRegisters::new();
        regs.reg_write(0x114, 0b1000_0000_0000_0001_0000_0000_0011_1000);
        regs.reg_write(0x134, 0b1111_1111_1111_1111_0000_0000_0000_0000);

        let tzc = regs.tzc_for_test();

        let rid0 = tzc.region(0).unwrap().region_id_access();
        let rid1 = tzc.region(1).unwrap().region_id_access();

        for i in 0..16 {
            assert_eq!(rid0.is_read_enabled(i), (3..=5).contains(&i));
            assert_eq!(rid0.is_write_enabled(i), [0, 15].contains(&i));
            assert!(!rid1.is_read_enabled(i));
            assert!(rid1.is_write_enabled(i));
        }
    }

    #[test]
    fn set_region_id_access() {
        let mut regs = FakeTZCRegisters::new();
        regs.reg_write(0x134, 0b1000_0000_0000_0001_0000_0000_0011_1000);
        let mut tzc = regs.tzc_for_test();

        let mut rid0 = tzc.region(0).unwrap().region_id_access();
        rid0.set_read_enabled(13, true);
        rid0.set_read_enabled(14, true);
        rid0.set_read_enabled(15, true);
        rid0.set_write_enabled(0, true);
        rid0.set_write_enabled(1, true);
        tzc.region_mut(0).unwrap().set_region_id_access(rid0);

        let mut rid1 = tzc.region(1).unwrap().region_id_access();
        rid1.set_read_enabled(3, false);
        rid1.set_read_enabled(4, false);
        rid1.set_read_enabled(6, true);
        rid1.set_write_enabled(0, false);
        tzc.region_mut(1).unwrap().set_region_id_access(rid1);

        let rid2 = RegionIDAccess::new(&[1, 2, 3], &[14, 15]);
        tzc.region_mut(2).unwrap().set_region_id_access(rid2);

        assert_eq!(
            regs.reg_read(0x114),
            0b0000_0000_0000_0011_1110_0000_0000_0000
        );

        assert_eq!(
            regs.reg_read(0x134),
            0b1000_0000_0000_0000_0000_0000_0110_0000
        );

        assert_eq!(
            regs.reg_read(0x154),
            0b0000_0000_0000_1110_1100_0000_0000_0000,
        );
    }

    #[test]
    #[should_panic]
    fn region_attributes_oob_filter_read() {
        let mut regs = FakeTZCRegisters::new();
        let tzc = regs.tzc_for_test();

        tzc.region(0)
            .unwrap()
            .region_attributes()
            .is_filter_enabled(4);
    }

    #[test]
    #[should_panic]
    fn region_attributes_oob_filter_write() {
        let mut regs = FakeTZCRegisters::new();
        let tzc = regs.tzc_for_test();

        tzc.region(0)
            .unwrap()
            .region_attributes()
            .set_filter_status(4, true);
    }

    #[test]
    #[should_panic]
    fn region_id_access_oob_get_read() {
        let mut regs = FakeTZCRegisters::new();
        let tzc = regs.tzc_for_test();

        tzc.region(0)
            .unwrap()
            .region_id_access()
            .is_read_enabled(17);
    }

    #[test]
    #[should_panic]
    fn region_id_access_oob_set_read() {
        let mut regs = FakeTZCRegisters::new();
        let tzc = regs.tzc_for_test();

        tzc.region(0)
            .unwrap()
            .region_id_access()
            .set_read_enabled(17, false);
    }

    #[test]
    #[should_panic]
    fn region_id_access_oob_get_write() {
        let mut regs = FakeTZCRegisters::new();
        let tzc = regs.tzc_for_test();

        tzc.region(0)
            .unwrap()
            .region_id_access()
            .is_write_enabled(17);
    }

    #[test]
    #[should_panic]
    fn region_id_access_oob_set_write() {
        let mut regs = FakeTZCRegisters::new();
        let tzc = regs.tzc_for_test();

        tzc.region(0)
            .unwrap()
            .region_id_access()
            .set_write_enabled(17, false);
    }
}