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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use anyhow::Result;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use serde::{Deserialize, Serialize};
use serde_annotate::Annotate;
use std::io::{Read, Write};

use super::misc::{TlvHeader, TlvTag};
use crate::chip::boolean::MultiBitBool4;

/// Describes the proprerties of a flash region.
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, Annotate)]
pub struct FlashFlags {
    /// Read operations are allowed in this region.
    #[serde(default)]
    pub read: bool,
    /// Program operations are allowed in this region.
    #[serde(default)]
    pub program: bool,
    /// Erase operations are allowed in this region.
    #[serde(default)]
    pub erase: bool,
    /// Scrambling is enabled in this region.
    #[serde(default)]
    pub scramble: bool,
    /// ECC memory correction is enabled in this region.
    #[serde(default)]
    pub ecc: bool,
    /// The high endurance feature is enabled in this region.
    #[serde(default)]
    pub high_endurance: bool,
    /// Forbid program and erase operations when in the primary flash side.
    #[serde(default)]
    pub protect_when_primary: bool,
    /// Lock the configuration of this region.
    #[serde(default)]
    pub lock: bool,
}

impl FlashFlags {
    const TRUE: u64 = MultiBitBool4::True.0 as u64;
    const FALSE: u64 = MultiBitBool4::False.0 as u64;

    /// A basic set of flash properties.
    pub fn basic() -> Self {
        FlashFlags {
            read: true,
            program: true,
            erase: true,
            scramble: true,
            ecc: true,
            high_endurance: true,
            ..Default::default()
        }
    }

    /// A set of flash properties appropriate for the ROM_EXT region.
    pub fn rom_ext() -> Self {
        Self {
            read: true,
            program: true,
            erase: true,
            protect_when_primary: true,
            ..Default::default()
        }
    }

    /// A set of flash properties appropriate for the owner firmware region.
    pub fn firmware() -> Self {
        Self {
            read: true,
            program: true,
            erase: true,
            scramble: true,
            ecc: true,
            protect_when_primary: true,
            ..Default::default()
        }
    }

    /// A set of flash properties appropriate for the owner filesystem region.
    pub fn filesystem() -> Self {
        Self {
            read: true,
            program: true,
            erase: true,
            high_endurance: true,
            ..Default::default()
        }
    }

    /// A set of flash properties appropriate for owner info pages.
    pub fn info_page() -> Self {
        Self {
            read: true,
            program: true,
            erase: true,
            scramble: true,
            ecc: true,
            ..Default::default()
        }
    }
}

impl From<u64> for FlashFlags {
    fn from(flags: u64) -> Self {
        #[rustfmt::skip]
        let value = Self {
            // First 32-bit word: access/protection flags.
            read:                 flags & 0xF == Self::TRUE,
            program:              (flags >> 4) & 0xF == Self::TRUE,
            erase:                (flags >> 8) & 0xF == Self::TRUE,
            protect_when_primary: (flags >> 24) & 0xF == Self::TRUE,
            lock:                 (flags >> 28) & 0xF == Self::TRUE,

            // Second 32-bit word: flash properties.
            scramble:             (flags >> 32) & 0xF == Self::TRUE,
            ecc:                  (flags >> 36) & 0xF == Self::TRUE,
            high_endurance:       (flags >> 40) & 0xF == Self::TRUE,
        };
        value
    }
}

impl From<FlashFlags> for u64 {
    fn from(flags: FlashFlags) -> u64 {
        #[rustfmt::skip]
        let value =
            // First 32-bit word: access/protection flags.
            if flags.read                 { FlashFlags::TRUE } else { FlashFlags::FALSE } |
            if flags.program              { FlashFlags::TRUE } else { FlashFlags::FALSE } << 4 |
            if flags.erase                { FlashFlags::TRUE } else { FlashFlags::FALSE } << 8 |
            if flags.protect_when_primary { FlashFlags::TRUE } else { FlashFlags::FALSE } << 24 |
            if flags.lock                 { FlashFlags::TRUE } else { FlashFlags::FALSE } << 28 |

            // Second 32-bit word: flash properties.
            if flags.scramble             { FlashFlags::TRUE } else { FlashFlags::FALSE } << 32 |
            if flags.ecc                  { FlashFlags::TRUE } else { FlashFlags::FALSE } << 36 |
            if flags.high_endurance       { FlashFlags::TRUE } else { FlashFlags::FALSE } << 40 ;
        value
    }
}

/// Describes a region to which a set of flags apply.
#[derive(Debug, Default, Serialize, Deserialize, Annotate)]
pub struct OwnerFlashRegion {
    /// The start of the region (in pages).
    pub start: u16,
    /// The size of the region (in pages).
    pub size: u16,
    #[serde(flatten)]
    pub flags: FlashFlags,
}

impl OwnerFlashRegion {
    const SIZE: usize = 12;
    pub fn new(start: u16, size: u16, flags: FlashFlags) -> Self {
        Self { start, size, flags }
    }
    pub fn read(src: &mut impl Read, crypt: u64) -> Result<Self> {
        let start = src.read_u16::<LittleEndian>()?;
        let size = src.read_u16::<LittleEndian>()?;
        let flags = FlashFlags::from(src.read_u64::<LittleEndian>()? ^ crypt);
        Ok(Self { start, size, flags })
    }
    pub fn write(&self, dest: &mut impl Write, crypt: u64) -> Result<()> {
        dest.write_u16::<LittleEndian>(self.start)?;
        dest.write_u16::<LittleEndian>(self.size)?;
        dest.write_u64::<LittleEndian>(u64::from(self.flags) ^ crypt)?;
        Ok(())
    }
}

/// Describes the overall flash configuration for data pages.
#[derive(Debug, Serialize, Deserialize, Annotate)]
pub struct OwnerFlashConfig {
    /// Header identifying this struct.
    #[serde(default)]
    pub header: TlvHeader,
    /// A list of flash region configurations.
    pub config: Vec<OwnerFlashRegion>,
}

impl Default for OwnerFlashConfig {
    fn default() -> Self {
        Self {
            header: TlvHeader::new(TlvTag::FlashConfig, 0),
            config: Vec::new(),
        }
    }
}

impl OwnerFlashConfig {
    const BASE_SIZE: usize = 8;
    pub fn basic() -> Self {
        Self {
            header: TlvHeader::new(TlvTag::FlashConfig, 0),
            config: vec![
                OwnerFlashRegion::new(0, 32, FlashFlags::rom_ext()),
                OwnerFlashRegion::new(32, 192, FlashFlags::firmware()),
                OwnerFlashRegion::new(224, 32, FlashFlags::filesystem()),
                OwnerFlashRegion::new(256, 32, FlashFlags::rom_ext()),
                OwnerFlashRegion::new(256 + 32, 192, FlashFlags::firmware()),
                OwnerFlashRegion::new(256 + 224, 32, FlashFlags::filesystem()),
            ],
        }
    }
    pub fn read(src: &mut impl Read, header: TlvHeader) -> Result<Self> {
        let config_len = (header.length - Self::BASE_SIZE) / OwnerFlashRegion::SIZE;
        let mut config = Vec::new();
        for i in 0..config_len {
            let crypt = 0x1111_1111_1111_1111u64 * (i as u64);
            config.push(OwnerFlashRegion::read(src, crypt)?)
        }
        Ok(Self { header, config })
    }
    pub fn write(&self, dest: &mut impl Write) -> Result<()> {
        let header = TlvHeader::new(
            TlvTag::FlashConfig,
            Self::BASE_SIZE + self.config.len() * OwnerFlashRegion::SIZE,
        );
        header.write(dest)?;
        for (i, config) in self.config.iter().enumerate() {
            let crypt = 0x1111_1111_1111_1111u64 * (i as u64);
            config.write(dest, crypt)?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::util::hexdump::{hexdump_parse, hexdump_string};

    #[rustfmt::skip]
    const OWNER_FLASH_CONFIG_BIN: &str =
r#"00000000: 46 4c 53 48 2c 00 00 00 00 00 00 00 96 09 00 99  FLSH,...........
00000010: 69 09 00 00 01 00 02 00 77 18 11 88 88 18 11 11  i.......w.......
00000020: 03 00 05 00 44 24 22 bb 44 24 22 22              ....D$".D$""
"#;

    const OWNER_FLASH_CONFIG_JSON: &str = r#"{
  header: {
    identifier: "FlashConfig",
    length: 44
  },
  config: [
    {
      start: 0,
      size: 0,
      read: true,
      program: false,
      erase: false,
      scramble: false,
      ecc: true,
      high_endurance: false,
      protect_when_primary: false,
      lock: false
    },
    {
      start: 1,
      size: 2,
      read: true,
      program: true,
      erase: false,
      scramble: false,
      ecc: false,
      high_endurance: false,
      protect_when_primary: false,
      lock: false
    },
    {
      start: 3,
      size: 5,
      read: true,
      program: true,
      erase: true,
      scramble: true,
      ecc: true,
      high_endurance: true,
      protect_when_primary: false,
      lock: false
    }
  ]
}"#;

    #[test]
    fn test_owner_flash_config_write() -> Result<()> {
        let ofr = OwnerFlashConfig {
            header: TlvHeader::default(),
            config: vec![
                OwnerFlashRegion::new(
                    0,
                    0,
                    FlashFlags {
                        read: true,
                        ecc: true,
                        ..Default::default()
                    },
                ),
                OwnerFlashRegion::new(
                    1,
                    2,
                    FlashFlags {
                        read: true,
                        program: true,
                        ..Default::default()
                    },
                ),
                OwnerFlashRegion::new(3, 5, FlashFlags::basic()),
            ],
        };
        let mut bin = Vec::new();
        ofr.write(&mut bin)?;
        eprintln!("{}", hexdump_string(&bin)?);
        assert_eq!(hexdump_string(&bin)?, OWNER_FLASH_CONFIG_BIN);
        Ok(())
    }

    #[test]
    fn test_owner_flash_config_read() -> Result<()> {
        let buf = hexdump_parse(OWNER_FLASH_CONFIG_BIN)?;
        let mut cur = std::io::Cursor::new(&buf);
        let header = TlvHeader::read(&mut cur)?;
        let ofr = OwnerFlashConfig::read(&mut cur, header)?;
        let doc = serde_annotate::serialize(&ofr)?.to_json5().to_string();
        assert_eq!(doc, OWNER_FLASH_CONFIG_JSON);
        Ok(())
    }
}