Software APIs
bootstrap.c
1 // Copyright lowRISC contributors (OpenTitan project).
2 // Licensed under the Apache License, Version 2.0, see LICENSE for details.
3 // SPDX-License-Identifier: Apache-2.0
4 
5 #include "sw/device/silicon_creator/lib/bootstrap.h"
6 
7 #include <assert.h>
8 #include <stdalign.h>
9 #include <stdint.h>
10 
13 #include "sw/device/silicon_creator/lib/drivers/flash_ctrl.h"
14 #include "sw/device/silicon_creator/lib/drivers/rstmgr.h"
15 #include "sw/device/silicon_creator/lib/drivers/spi_device.h"
16 #include "sw/device/silicon_creator/lib/error.h"
17 #include "sw/device/silicon_creator/lib/stack_utilization.h"
18 
19 #include "flash_ctrl_regs.h"
20 
21 enum {
22  /*
23  * Maximum flash address, exclusive.
24  */
25  kMaxAddress =
26  FLASH_CTRL_PARAM_BYTES_PER_BANK * FLASH_CTRL_PARAM_REG_NUM_BANKS,
27 };
28 
29 static_assert(FLASH_CTRL_PARAM_REG_NUM_BANKS == 2, "Flash must have 2 banks");
30 
31 /**
32  * Bootstrap states.
33  *
34  * OpenTitan bootstrap consists of three states between which the chip
35  * transitions sequentially.
36  *
37  * Encoding generated with
38  * $ ./util/design/sparse-fsm-encode.py -d 5 -m 3 -n 32 \
39  * -s 375382971 --language=c
40  *
41  * Minimum Hamming distance: 17
42  * Maximum Hamming distance: 19
43  * Minimum Hamming weight: 16
44  * Maximum Hamming weight: 19
45  */
46 typedef enum bootstrap_state {
47  /**
48  * Initial bootstrap state where the chip waits for a SECTOR_ERASE or
49  * CHIP_ERASE command.
50  */
51  kBootstrapStateErase = 0xd4576543,
52  /**
53  * Second bootstrap state where the chip verifies that all data banks have
54  * been erased.
55  */
56  kBootstrapStateEraseVerify = 0xf3c71bac,
57  /**
58  * Final bootstrap state. This is the main program loop where the chip handles
59  * erase, program, and reset commands.
60  */
61  kBootstrapStateProgram = 0xbdd8ca60,
62 } bootstrap_state_t;
63 
64 /**
65  * Handles access permissions and erases a 4 KiB region in the data partition of
66  * the embedded flash.
67  *
68  * Since OpenTitan's flash page size is 2 KiB, this function erases two
69  * consecutive pages.
70  *
71  * @param addr Address that falls within the 4 KiB region being deleted.
72  * @return Result of the operation.
73  */
75 static rom_error_t bootstrap_sector_erase(uint32_t addr) {
76  static_assert(FLASH_CTRL_PARAM_BYTES_PER_PAGE == 2048,
77  "Page size must be 2 KiB");
78  enum {
79  /**
80  * Mask for truncating `addr` to the lower 4 KiB aligned address.
81  */
82  kPageAddrMask = ~UINT32_C(4096) + 1,
83  };
84 
85  if (addr >= kMaxAddress) {
86  return kErrorBootstrapEraseAddress;
87  }
88  addr &= kPageAddrMask;
89 
90  flash_ctrl_data_default_perms_set((flash_ctrl_perms_t){
91  .read = kMultiBitBool4False,
92  .write = kMultiBitBool4False,
93  .erase = kMultiBitBool4True,
94  });
95  rom_error_t err_0 = flash_ctrl_data_erase(addr, kFlashCtrlEraseTypePage);
96  rom_error_t err_1 = flash_ctrl_data_erase(
97  addr + FLASH_CTRL_PARAM_BYTES_PER_PAGE, kFlashCtrlEraseTypePage);
98  flash_ctrl_data_default_perms_set((flash_ctrl_perms_t){
99  .read = kMultiBitBool4False,
100  .write = kMultiBitBool4False,
101  .erase = kMultiBitBool4False,
102  });
103 
104  HARDENED_RETURN_IF_ERROR(err_0);
105  return err_1;
106 }
107 
108 /**
109  * Handles access permissions and programs up to 256 bytes of flash memory
110  * starting at `addr`.
111  *
112  * If `byte_count` is not a multiple of flash word size, it's rounded up to next
113  * flash word and missing bytes in `data` are set to `0xff`.
114  *
115  * @param addr Address to write to, must be flash word aligned.
116  * @param byte_count Number of bytes to write. Rounded up to next flash word if
117  * not a multiple of flash word size. Missing bytes in `data` are set to `0xff`.
118  * @param data Data to write, must be word aligned. If `byte_count` is not a
119  * multiple of flash word size, `data` must have enough space until the next
120  * flash word.
121  * @return Result of the operation.
122  */
124 static rom_error_t bootstrap_page_program(uint32_t addr, size_t byte_count,
125  uint8_t *data) {
126  static_assert(__builtin_popcount(FLASH_CTRL_PARAM_BYTES_PER_WORD) == 1,
127  "Bytes per flash word must be a power of two.");
128  enum {
129  /**
130  * Mask for checking that `addr` is flash word aligned.
131  */
132  kFlashWordMask = FLASH_CTRL_PARAM_BYTES_PER_WORD - 1,
133  /**
134  * SPI flash programming page size in bytes.
135  */
136  kFlashProgPageSize = 256,
137  /**
138  * Mask for checking whether `addr` is flash programming page aligned.
139  *
140  * Flash programming page size is 256 bytes, writes that start at an `addr`
141  * with a non-zero LSB wrap to the start of the 256 byte region.
142  */
143  kFlashProgPageMask = kFlashProgPageSize - 1,
144  };
145 
146  if (addr & kFlashWordMask || addr >= kMaxAddress) {
147  return kErrorBootstrapProgramAddress;
148  }
149 
150  // Round up to next flash word and fill missing bytes with `0xff`.
151  size_t flash_word_misalignment = byte_count & kFlashWordMask;
152  if (flash_word_misalignment > 0) {
153  size_t padding_byte_count =
154  FLASH_CTRL_PARAM_BYTES_PER_WORD - flash_word_misalignment;
155  for (size_t i = 0; i < padding_byte_count; ++i) {
156  data[byte_count++] = 0xff;
157  }
158  }
159  size_t rem_word_count = byte_count / sizeof(uint32_t);
160 
161  flash_ctrl_data_default_perms_set((flash_ctrl_perms_t){
162  .read = kMultiBitBool4False,
163  .write = kMultiBitBool4True,
164  .erase = kMultiBitBool4False,
165  });
166  // Perform two writes if the start address is not page-aligned (256 bytes).
167  // Note: Address is flash-word-aligned (8 bytes) due to the check above.
168  rom_error_t err_0 = kErrorOk;
169  size_t prog_page_misalignment = addr & kFlashProgPageMask;
170  if (prog_page_misalignment > 0) {
171  size_t word_count =
172  (kFlashProgPageSize - prog_page_misalignment) / sizeof(uint32_t);
173  if (word_count > rem_word_count) {
174  word_count = rem_word_count;
175  }
176  err_0 = flash_ctrl_data_write(addr, word_count, data);
177  rem_word_count -= word_count;
178  data += word_count * sizeof(uint32_t);
179  // Wrap to the beginning of the current page since PAGE_PROGRAM modifies
180  // a single page only.
181  addr &= ~(uint32_t)kFlashProgPageMask;
182  }
183  rom_error_t err_1 = kErrorOk;
184  if (rem_word_count > 0) {
185  err_1 = flash_ctrl_data_write(addr, rem_word_count, data);
186  }
187  flash_ctrl_data_default_perms_set((flash_ctrl_perms_t){
188  .read = kMultiBitBool4False,
189  .write = kMultiBitBool4False,
190  .erase = kMultiBitBool4False,
191  });
192 
193  HARDENED_RETURN_IF_ERROR(err_0);
194  return err_1;
195 }
196 
197 /**
198  * Bootstrap state 1: Wait for an erase command and erase the data
199  * partition.
200  *
201  * This function erases both data banks of the flash regardless of the type of
202  * the erase command (CHIP_ERASE or SECTOR_ERASE).
203  *
204  * @param state Bootstrap state.
205  * @return Result of the operation.
206  */
208 static rom_error_t bootstrap_handle_erase(bootstrap_state_t *state) {
209  HARDENED_CHECK_EQ(*state, kBootstrapStateErase);
210 
211  spi_device_cmd_t cmd;
212  RETURN_IF_ERROR(spi_device_cmd_get(&cmd));
213  // Erase requires WREN, ignore if WEL is not set.
214  if (!bitfield_bit32_read(spi_device_flash_status_get(), kSpiDeviceWelBit)) {
215  return kErrorOk;
216  }
217 
218  rom_error_t error = kErrorUnknown;
219  switch (cmd.opcode) {
220  case kSpiDeviceOpcodeChipErase:
221  case kSpiDeviceOpcodeSectorErase:
222  error = bootstrap_chip_erase();
223  HARDENED_RETURN_IF_ERROR(error);
224  *state = kBootstrapStateEraseVerify;
225  // Note: We clear WIP and WEN bits in `bootstrap_handle_erase_verify()`
226  // after checking that both data banks have been erased.
227  break;
228  default:
229  // Ignore any other command, e.g. PAGE_PROGRAM, RESET, and clear WIP and
230  // WEN bits right away.
231  spi_device_flash_status_clear();
232  error = kErrorOk;
233  }
234 
235  return error;
236 }
237 
238 /**
239  * Bootstrap state 2: Verify that all data banks have been erased.
240  *
241  * This function also clears the WIP and WEN bits of the flash status register.
242  *
243  * @param state Bootstrap state.
244  * @return Result of the operation.
245  */
247 static rom_error_t bootstrap_handle_erase_verify(bootstrap_state_t *state) {
248  HARDENED_CHECK_EQ(*state, kBootstrapStateEraseVerify);
249 
250  const rom_error_t err = bootstrap_erase_verify();
251  HARDENED_RETURN_IF_ERROR(err);
252 
253  spi_device_flash_status_clear();
254 
255  *state = kBootstrapStateProgram;
256  return err;
257 }
258 
259 /**
260  * Bootstrap state 3: (Erase/)Program loop.
261  *
262  * @param state Bootstrap state.
263  * @return Result of the operation.
264  */
266 static rom_error_t bootstrap_handle_program(bootstrap_state_t *state) {
267  static_assert(alignof(spi_device_cmd_t) >= sizeof(uint32_t) &&
268  offsetof(spi_device_cmd_t, payload) >= sizeof(uint32_t),
269  "Payload must be word aligned.");
270  static_assert(
271  sizeof((spi_device_cmd_t){0}.payload) % FLASH_CTRL_PARAM_BYTES_PER_WORD ==
272  0,
273  "Payload size must be a multiple of flash word size.");
274 
275  HARDENED_CHECK_EQ(*state, kBootstrapStateProgram);
276 
277  spi_device_cmd_t cmd;
278  RETURN_IF_ERROR(spi_device_cmd_get(&cmd));
279  // Erase and program require WREN, ignore if WEL is not set.
280  if (cmd.opcode != kSpiDeviceOpcodeReset &&
281  !bitfield_bit32_read(spi_device_flash_status_get(), kSpiDeviceWelBit)) {
282  return kErrorOk;
283  }
284 
285  rom_error_t error = kErrorUnknown;
286  switch (cmd.opcode) {
287  case kSpiDeviceOpcodeChipErase:
288  error = bootstrap_chip_erase();
289  break;
290  case kSpiDeviceOpcodeSectorErase:
291  error = bootstrap_sector_erase(cmd.address);
292  break;
293  case kSpiDeviceOpcodePageProgram:
294  error = bootstrap_page_program(cmd.address, cmd.payload_byte_count,
295  cmd.payload);
296  break;
297  case kSpiDeviceOpcodeReset:
298  // In a normal build, this function inlines to nothing.
299  stack_utilization_print();
300  rstmgr_reset();
301 #ifdef OT_PLATFORM_RV32
302  HARDENED_TRAP();
303 #else
304  // If this is an off-target test, return `kErrorUnknown` to be able to
305  // test without requiring EXPECT_DEATH.
306  error = kErrorUnknown;
307 #endif
308  break;
309  default:
310  // We don't expect any other commands but we can potentially end up
311  // here with a 0x0 opcode due to glitches on SPI or strap lines (see
312  // #11871).
313  error = kErrorOk;
314  }
315  HARDENED_RETURN_IF_ERROR(error);
316 
317  spi_device_flash_status_clear();
318  return error;
319 }
320 
321 rom_error_t enter_bootstrap(void) {
322  spi_device_init();
323 
324  // Bootstrap event loop.
325  bootstrap_state_t state = kBootstrapStateErase;
326  rom_error_t error = kErrorUnknown;
327  while (true) {
328  switch (launder32(state)) {
329  case kBootstrapStateErase:
330  HARDENED_CHECK_EQ(state, kBootstrapStateErase);
331  error = bootstrap_handle_erase(&state);
332  break;
333  case kBootstrapStateEraseVerify:
334  HARDENED_CHECK_EQ(state, kBootstrapStateEraseVerify);
335  error = bootstrap_handle_erase_verify(&state);
336  break;
337  case kBootstrapStateProgram:
338  HARDENED_CHECK_EQ(state, kBootstrapStateProgram);
339  error = bootstrap_handle_program(&state);
340  break;
341  default:
342  error = kErrorBootstrapInvalidState;
343  }
344  HARDENED_RETURN_IF_ERROR(error);
345  }
346  HARDENED_TRAP();
347 }