blob: 27262bd846556b21b892732e35d66a2cff941a97 [file] [log] [blame] [view]
David Brown17e20d12017-09-12 11:53:20 -06001<!--
David Brownaac71112020-02-03 16:13:42 -07002 - SPDX-License-Identifier: Apache-2.0
David Brown17e20d12017-09-12 11:53:20 -06003
David Vinczee574f2d2020-07-10 11:42:03 +02004 - Copyright (c) 2017-2020 Linaro LTD
David Brownaac71112020-02-03 16:13:42 -07005 - Copyright (c) 2017-2019 JUUL Labs
Roland Mikhel206b9142023-02-23 15:28:52 +01006 - Copyright (c) 2019-2023 Arm Limited
David Brownaac71112020-02-03 16:13:42 -07007
8 - Original license:
9
10 - Licensed to the Apache Software Foundation (ASF) under one
11 - or more contributor license agreements. See the NOTICE file
12 - distributed with this work for additional information
13 - regarding copyright ownership. The ASF licenses this file
14 - to you under the Apache License, Version 2.0 (the
15 - "License"); you may not use this file except in compliance
16 - with the License. You may obtain a copy of the License at
17
18 - http://www.apache.org/licenses/LICENSE-2.0
19
20 - Unless required by applicable law or agreed to in writing,
21 - software distributed under the License is distributed on an
22 - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
23 - KIND, either express or implied. See the License for the
24 - specific language governing permissions and limitations
25 - under the License.
David Vinczeba3bd602019-06-17 16:01:43 +020026-->
27
Francesco Servidio482921f2021-10-20 15:42:59 +020028# Bootloader
David Brown17e20d12017-09-12 11:53:20 -060029
Fabio Utzigd37d8772019-12-03 10:32:18 -030030## [Summary](#summary)
Christopher Collins92ea77f2016-12-12 15:59:26 -080031
Francesco Servidio4ff0c182021-10-20 15:27:16 +020032MCUboot comprises two packages:
Christopher Collins92ea77f2016-12-12 15:59:26 -080033
David Brown17e20d12017-09-12 11:53:20 -060034* The bootutil library (boot/bootutil)
35* The boot application (each port has its own at boot/<port>)
Christopher Collins92ea77f2016-12-12 15:59:26 -080036
Francesco Servidio482921f2021-10-20 15:42:59 +020037The bootutil library performs most of the functions of a bootloader. In
Christopher Collins92ea77f2016-12-12 15:59:26 -080038particular, the piece that is missing is the final step of actually jumping to
39the main image. This last step is instead implemented by the boot application.
Francesco Servidio482921f2021-10-20 15:42:59 +020040Bootloader functionality is separated in this manner to enable unit testing of
41the bootloader. A library can be unit tested, but an application can't.
Christopher Collins92ea77f2016-12-12 15:59:26 -080042Therefore, functionality is delegated to the bootutil library when possible.
43
Fabio Utzigd37d8772019-12-03 10:32:18 -030044## [Limitations](#limitations)
Christopher Collins92ea77f2016-12-12 15:59:26 -080045
Francesco Servidio482921f2021-10-20 15:42:59 +020046The bootloader currently only supports images with the following
Christopher Collins92ea77f2016-12-12 15:59:26 -080047characteristics:
David Brown17e20d12017-09-12 11:53:20 -060048* Built to run from flash.
49* Built to run from a fixed location (i.e., not position-independent).
Christopher Collins92ea77f2016-12-12 15:59:26 -080050
Francesco Servidio5bc98322021-11-03 13:19:22 +010051## [Image format](#image-format)
Christopher Collins92ea77f2016-12-12 15:59:26 -080052
53The following definitions describe the image format.
54
David Brown17e20d12017-09-12 11:53:20 -060055``` c
Fabio Utzigea422c22017-09-11 11:02:47 -030056#define IMAGE_MAGIC 0x96f3b83d
Christopher Collins92ea77f2016-12-12 15:59:26 -080057
58#define IMAGE_HEADER_SIZE 32
59
60struct image_version {
61 uint8_t iv_major;
62 uint8_t iv_minor;
63 uint16_t iv_revision;
64 uint32_t iv_build_num;
65};
66
67/** Image header. All fields are in little endian byte order. */
68struct image_header {
69 uint32_t ih_magic;
Fabio Utzigea422c22017-09-11 11:02:47 -030070 uint32_t ih_load_addr;
David Vinczee32483f2019-06-13 10:46:24 +020071 uint16_t ih_hdr_size; /* Size of image header (bytes). */
72 uint16_t ih_protect_tlv_size; /* Size of protected TLV area (bytes). */
73 uint32_t ih_img_size; /* Does not include header. */
74 uint32_t ih_flags; /* IMAGE_F_[...]. */
Christopher Collins92ea77f2016-12-12 15:59:26 -080075 struct image_version ih_ver;
David Vinczee32483f2019-06-13 10:46:24 +020076 uint32_t _pad1;
Christopher Collins92ea77f2016-12-12 15:59:26 -080077};
78
Fabio Utzigfd140ec2019-09-12 14:37:48 -030079#define IMAGE_TLV_INFO_MAGIC 0x6907
80#define IMAGE_TLV_PROT_INFO_MAGIC 0x6908
81
Fabio Utzigea422c22017-09-11 11:02:47 -030082/** Image TLV header. All fields in little endian. */
83struct image_tlv_info {
84 uint16_t it_magic;
85 uint16_t it_tlv_tot; /* size of TLV area (including tlv_info header) */
86};
87
Christopher Collins92ea77f2016-12-12 15:59:26 -080088/** Image trailer TLV format. All fields in little endian. */
89struct image_tlv {
90 uint8_t it_type; /* IMAGE_TLV_[...]. */
91 uint8_t _pad;
Marti Bolivar49b29172017-08-04 14:50:51 -040092 uint16_t it_len; /* Data length (not including TLV header). */
Christopher Collins92ea77f2016-12-12 15:59:26 -080093};
94
95/*
96 * Image header flags.
97 */
Marti Bolivar7c057e92017-08-04 14:46:39 -040098#define IMAGE_F_PIC 0x00000001 /* Not supported. */
Salome Thirot0f641972021-05-14 11:19:55 +010099#define IMAGE_F_ENCRYPTED_AES128 0x00000004 /* Encrypted using AES128. */
100#define IMAGE_F_ENCRYPTED_AES256 0x00000008 /* Encrypted using AES256. */
Marti Bolivar7c057e92017-08-04 14:46:39 -0400101#define IMAGE_F_NON_BOOTABLE 0x00000010 /* Split image app. */
Fabio Utzigea422c22017-09-11 11:02:47 -0300102#define IMAGE_F_RAM_LOAD 0x00000020
Christopher Collins92ea77f2016-12-12 15:59:26 -0800103
104/*
105 * Image trailer TLV types.
106 */
Fabio Utzigea422c22017-09-11 11:02:47 -0300107#define IMAGE_TLV_KEYHASH 0x01 /* hash of the public key */
David Brown27648b82017-08-31 10:40:29 -0600108#define IMAGE_TLV_SHA256 0x10 /* SHA256 of image hdr and body */
Marko Kiiskila8dd56f32017-08-22 21:40:49 -0700109#define IMAGE_TLV_RSA2048_PSS 0x20 /* RSA2048 of hash output */
Roland Mikhel206b9142023-02-23 15:28:52 +0100110#define IMAGE_TLV_ECDSA224 0x21 /* ECDSA of hash output - Not supported anymore */
David Vincze4395b802023-04-27 16:11:49 +0200111#define IMAGE_TLV_ECDSA_SIG 0x22 /* ECDSA of hash output */
Fabio Utzig3501c012019-05-13 15:07:25 -0700112#define IMAGE_TLV_RSA3072_PSS 0x23 /* RSA3072 of hash output */
Fabio Utzig195411f2019-06-28 07:48:21 -0300113#define IMAGE_TLV_ED25519 0x24 /* ED25519 of hash output */
David Vinczee32483f2019-06-13 10:46:24 +0200114#define IMAGE_TLV_ENC_RSA2048 0x30 /* Key encrypted with RSA-OAEP-2048 */
Salome Thirot0f641972021-05-14 11:19:55 +0100115#define IMAGE_TLV_ENC_KW 0x31 /* Key encrypted with AES-KW-128 or
116 256 */
Fabio Utzig5eaa5762020-04-02 13:30:43 -0300117#define IMAGE_TLV_ENC_EC256 0x32 /* Key encrypted with ECIES-P256 */
118#define IMAGE_TLV_ENC_X25519 0x33 /* Key encrypted with ECIES-X25519 */
David Vinczee32483f2019-06-13 10:46:24 +0200119#define IMAGE_TLV_DEPENDENCY 0x40 /* Image depends on other image */
David Vinczec3084132020-02-18 14:50:47 +0100120#define IMAGE_TLV_SEC_CNT 0x50 /* security counter */
David Brown17e20d12017-09-12 11:53:20 -0600121```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800122
123Optional type-length-value records (TLVs) containing image metadata are placed
124after the end of the image.
125
David Vinczee32483f2019-06-13 10:46:24 +0200126The `ih_protect_tlv_size` field indicates the length of the protected TLV area.
Fabio Utzigfd140ec2019-09-12 14:37:48 -0300127If protected TLVs are present then a TLV info header with magic equal to
128`IMAGE_TLV_PROT_INFO_MAGIC` must be present and the protected TLVs (plus the
129info header itself) have to be included in the hash calculation. Otherwise the
130hash is only calculated over the image header and the image itself. In this
David Vinczee32483f2019-06-13 10:46:24 +0200131case the value of the `ih_protect_tlv_size` field is 0.
132
David Brown17e20d12017-09-12 11:53:20 -0600133The `ih_hdr_size` field indicates the length of the header, and therefore the
Christopher Collins92ea77f2016-12-12 15:59:26 -0800134offset of the image itself. This field provides for backwards compatibility in
135case of changes to the format of the image header.
136
Francesco Servidio5bc98322021-11-03 13:19:22 +0100137## [Flash map](#flash-map)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800138
Fabio Utzigac834962017-07-20 13:20:48 -0300139A device's flash is partitioned according to its _flash map_. At a high
Christopher Collins92ea77f2016-12-12 15:59:26 -0800140level, the flash map maps numeric IDs to _flash areas_. A flash area is a
141region of disk with the following properties:
David Brown17e20d12017-09-12 11:53:20 -06001421. An area can be fully erased without affecting any other areas.
1432. A write to one area does not restrict writes to other areas.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800144
Francesco Servidio482921f2021-10-20 15:42:59 +0200145The bootloader uses the following flash area IDs:
David Vinczeb75c12a2019-03-22 14:58:33 +0100146```c
147/* Independent from multiple image boot */
David Vincze2d736ad2019-02-18 11:50:22 +0100148#define FLASH_AREA_BOOTLOADER 0
David Vinczeb75c12a2019-03-22 14:58:33 +0100149#define FLASH_AREA_IMAGE_SCRATCH 3
150```
151```c
Francesco Servidio482921f2021-10-20 15:42:59 +0200152/* If the bootloader is working with the first image */
David Vincze2d736ad2019-02-18 11:50:22 +0100153#define FLASH_AREA_IMAGE_PRIMARY 1
154#define FLASH_AREA_IMAGE_SECONDARY 2
David Vinczeb75c12a2019-03-22 14:58:33 +0100155```
156```c
Francesco Servidio482921f2021-10-20 15:42:59 +0200157/* If the bootloader is working with the second image */
David Vinczeb75c12a2019-03-22 14:58:33 +0100158#define FLASH_AREA_IMAGE_PRIMARY 5
159#define FLASH_AREA_IMAGE_SECONDARY 6
David Brown17e20d12017-09-12 11:53:20 -0600160```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800161
Marti Bolivar4e64d562017-08-04 14:53:33 -0400162The bootloader area contains the bootloader image itself. The other areas are
David Vinczeb75c12a2019-03-22 14:58:33 +0100163described in subsequent sections. The flash could contain multiple executable
164images therefore the flash area IDs of primary and secondary areas are mapped
165based on the number of the active image (on which the bootloader is currently
166working).
Marti Bolivar4e64d562017-08-04 14:53:33 -0400167
Francesco Servidio5bc98322021-11-03 13:19:22 +0100168## [Image slots](#image-slots)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800169
David Vinczeb75c12a2019-03-22 14:58:33 +0100170A portion of the flash memory can be partitioned into multiple image areas, each
171contains two image slots: a primary slot and a secondary slot.
Francesco Servidio482921f2021-10-20 15:42:59 +0200172Normally, the bootloader will only run an image from the primary slot, so
David Vinczee574f2d2020-07-10 11:42:03 +0200173images must be built such that they can run from that fixed location in flash
Tamas Banfe031092020-09-10 17:32:39 +0200174(the exception to this is the [direct-xip](#direct-xip) and the
Francesco Servidio482921f2021-10-20 15:42:59 +0200175[ram-load](#ram-load) upgrade mode). If the bootloader needs to run the
Tamas Banfe031092020-09-10 17:32:39 +0200176image resident in the secondary slot, it must copy its contents into the primary
177slot before doing so, either by swapping the two images or by overwriting the
178contents of the primary slot. The bootloader supports either swap- or
179overwrite-based image upgrades, but must be configured at build time to choose
180one of these two strategies.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800181
Andrzej Puzdrowski9abda322021-11-29 14:50:46 +0100182### [Swap using scratch](#image-swap-using-scratch)
183
184When swap-using-scratch algorithm is used, in addition to the slots of
185image areas, the bootloader requires a scratch area to allow for reliable
186image swapping. The scratch area must have a size
David Vinczeb75c12a2019-03-22 14:58:33 +0100187that is enough to store at least the largest sector that is going to be swapped.
188Many devices have small equally sized flash sectors, eg 4K, while others have
David Vincze2d736ad2019-02-18 11:50:22 +0100189variable sized sectors where the largest sectors might be 128K or 256K, so the
190scratch must be big enough to store that. The scratch is only ever used when
191swapping firmware, which means only when doing an upgrade. Given that, the main
192reason for using a larger size for the scratch is that flash wear will be more
193evenly distributed, because a single sector would be written twice the number of
194times than using two sectors, for example. To evaluate the ideal size of the
195scratch for your use case the following parameters are relevant:
Fabio Utziga722f5a2017-12-12 14:04:53 -0200196
197* the ratio of image size / scratch size
198* the number of erase cycles supported by the flash hardware
199
200The image size is used (instead of slot size) because only the slot's sectors
201that are actually used for storing the image are copied. The image/scratch ratio
202is the number of times the scratch will be erased on every upgrade. The number
203of erase cycles divided by the image/scratch ratio will give you the number of
204times an upgrade can be performed before the device goes out of spec.
205
206```
207num_upgrades = number_of_erase_cycles / (image_size / scratch_size)
208```
209
210Let's assume, for example, a device with 10000 erase cycles, an image size of
211150K and a scratch of 4K (usual minimum size of 4K sector devices). This would
212result in a total of:
213
214`10000 / (150 / 4) ~ 267`
215
216Increasing the scratch to 16K would give us:
217
218`10000 / (150 / 16) ~ 1067`
219
220There is no *best* ratio, as the right size is use-case dependent. Factors to
221consider include the number of times a device will be upgraded both in the field
David Vincze2d736ad2019-02-18 11:50:22 +0100222and during development, as well as any desired safety margin on the
223manufacturer's specified number of erase cycles. In general, using a ratio that
224allows hundreds to thousands of field upgrades in production is recommended.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800225
Andrzej Puzdrowski9abda322021-11-29 14:50:46 +0100226swap-using scratch algorithm assumes that the primary and the secondary image
227slot areas sizes are equal.
228The maximum image size available for the application
Tamas Ban04efc2e2022-12-08 17:46:26 +0100229will be:
Andrzej Puzdrowski9abda322021-11-29 14:50:46 +0100230```
231maximum-image-size = image-slot-size - image-trailer-size
232```
233
Tamas Ban04efc2e2022-12-08 17:46:26 +0100234Where:
235 `image-slot-size` is the size of the image slot.
Andrzej Puzdrowski961a6102021-11-30 17:34:02 +0100236 `image-trailer-size` is the size of the image trailer.
Andrzej Puzdrowski9abda322021-11-29 14:50:46 +0100237
Andrzej Puzdrowski3c1e6d32021-11-25 09:39:33 +0100238### [Swap without using scratch](#image-swap-no-scratch)
239
240This algorithm is an alternative to the swap-using-scratch algorithm.
241It uses an additional sector in the primary slot to make swap possible.
242The algorithm works as follows:
243
Tamas Ban04efc2e2022-12-08 17:46:26 +0100244 1. Moves all sectors of the primary slot up by one sector.
245 Beginning from N=0:
Andrzej Puzdrowski3c1e6d32021-11-25 09:39:33 +0100246 2. Copies the N-th sector from the secondary slot to the N-th sector of the
247 primary slot.
248 3. Copies the (N+1)-th sector from the primary slot to the N-th sector of the
249 secondary slot.
250 4. Repeats steps 2. and 3. until all the slots' sectors are swapped.
251
252This algorithm is designed so that the higher sector of the primary slot is
253used only for allowing sectors to move up. Therefore the most
254memory-size-effective slot layout is when the primary slot is exactly one sector
255larger than the secondary slot, although same-sized slots are allowed as well.
256The algorithm is limited to support sectors of the same
257sector layout. All slot's sectors should be of the same size.
258
259When using this algorithm the maximum image size available for the application
Tamas Ban04efc2e2022-12-08 17:46:26 +0100260will be:
Andrzej Puzdrowski3c1e6d32021-11-25 09:39:33 +0100261```
262maximum-image-size = (N-1) * slot-sector-size - image-trailer-sectors-size
263```
264
Tamas Ban04efc2e2022-12-08 17:46:26 +0100265Where:
266 `N` is the number of sectors in the primary slot.
Andrzej Puzdrowski3c1e6d32021-11-25 09:39:33 +0100267 `image-trailer-sectors-size` is the size of the image trailer rounded up to
268 the total size of sectors its occupied. For instance if the image-trailer-size
269 is equal to 1056 B and the sector size is equal to 1024 B, then
270 `image-trailer-sectors-size` will be equal to 2048 B.
271
272The algorithm does two erase cycles on the primary slot and one on the secondary
273slot during each swap. Assuming that receiving a new image by the DFU
274application requires 1 erase cycle on the secondary slot, this should result in
275leveling the flash wear between the slots.
276
277The algorithm is enabled using the `MCUBOOT_SWAP_USING_MOVE` option.
278
David Vinczee574f2d2020-07-10 11:42:03 +0200279### [Equal slots (direct-xip)](#direct-xip)
280
281When the direct-xip mode is enabled the active image flag is "moved" between the
282slots during image upgrade and in contrast to the above, the bootloader can
283run an image directly from either the primary or the secondary slot (without
284having to move/copy it into the primary slot). Therefore the image update
285client, which downloads the new images must be aware, which slot contains the
286active image and which acts as a staging area and it is responsible for loading
287the proper images into the proper slot. All this requires that the images be
288built to be executed from the corresponding slot. At boot time the bootloader
289first looks for images in the slots and then inspects the version numbers in the
290image headers. It selects the newest image (with the highest version number) and
291then checks its validity (integrity check, signature verification etc.). If the
292image is invalid MCUboot erases its memory slot and starts to validate the other
293image. After a successful validation of the selected image the bootloader
294chain-loads it.
David Vincze505fba22020-10-22 13:53:29 +0200295
296An additional "revert" mechanism is also supported. For more information, please
297read the [corresponding section](#direct-xip-revert).
David Vinczee574f2d2020-07-10 11:42:03 +0200298Handling the primary and secondary slots as equals has its drawbacks. Since the
299images are not moved between the slots, the on-the-fly image
300encryption/decryption can't be supported (it only applies to storing the image
301in an external flash on the device, the transport of encrypted image data is
302still feasible).
303
304The overwrite and the direct-xip upgrade strategies are substantially simpler to
305implement than the image swapping strategy, especially since the bootloader must
306work properly even when it is reset during the middle of an image swap. For this
307reason, the rest of the document describes its behavior when configured to swap
308images during an upgrade.
Marti Bolivara91674f2017-08-04 14:56:08 -0400309
Francesco Servidio5bc98322021-11-03 13:19:22 +0100310### [RAM loading](#ram-load)
Tamas Banfe031092020-09-10 17:32:39 +0200311
312In ram-load mode the slots are equal. Like the direct-xip mode, this mode
313also selects the newest image by reading the image version numbers in the image
314headers. But instead of executing it in place, the newest image is copied to the
315RAM for execution. The load address, the location in RAM where the image is
316copied to, is stored in the image header. The ram-load upgrade mode can be
317useful when there is no internal flash in the SoC, but there is a big enough
318internal RAM to hold the images. Usually in this case the images are stored
319in an external storage device. Execution from external storage has some
320drawbacks (lower execution speed, image is exposed to attacks) therefore the
321image is always copied to the internal RAM before the authentication and
322execution. Ram-load mode requires the image to be built to be executed from
323the RAM address range instead of the storage device address range. If
324ram-load is enabled then platform must define the following parameters:
325
326```c
327#define IMAGE_EXECUTABLE_RAM_START <area_base_addr>
328#define IMAGE_EXECUTABLE_RAM_SIZE <area_size_in_bytes>
329```
330
Mark Horvathccaf7f82021-01-04 18:16:42 +0100331For multiple image load if multiple ram regions are used platform must define
332the `MULTIPLE_EXECUTABLE_RAM_REGIONS` flag instead and implement the following
333function:
334
335```c
336int boot_get_image_exec_ram_info(uint32_t image_id,
337 uint32_t *exec_ram_start,
338 uint32_t *exec_ram_size)
339```
340
Tamas Banfe031092020-09-10 17:32:39 +0200341When ram-load is enabled, the `--load-addr <addr>` option of the `imgtool`
342script must also be used when signing the images. This option set the `RAM_LOAD`
343flag in the image header which indicates that the image should be loaded to the
344RAM and also set the load address in the image header.
345
Hugo L'Hostisdb543e52021-03-09 18:00:31 +0000346When the encryption option is enabled (`MCUBOOT_ENC_IMAGES`) along with ram-load
347the image is checked for encryption. If the image is not encrypted, RAM loading
348happens as described above. If the image is encrypted, it is copied in RAM at
349the provided address and then decrypted. Finally, the decrypted image is
350authenticated in RAM and executed.
Tamas Banfe031092020-09-10 17:32:39 +0200351
Francesco Servidio5bc98322021-11-03 13:19:22 +0100352## [Boot swap types](#boot-swap-types)
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800353
Marti Bolivar048d8d82017-08-04 17:14:24 -0400354When the device first boots under normal circumstances, there is an up-to-date
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200355firmware image in each primary slot, which MCUboot can validate and then
David Vincze2d736ad2019-02-18 11:50:22 +0100356chain-load. In this case, no image swaps are necessary. During device upgrades,
David Vinczeba3bd602019-06-17 16:01:43 +0200357however, new candidate image(s) is present in the secondary slot(s), which
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200358MCUboot must swap into the primary slot(s) before booting as discussed above.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800359
Marti Bolivar048d8d82017-08-04 17:14:24 -0400360Upgrading an old image with a new one by swapping can be a two-step process. In
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200361this process, MCUboot performs a "test" swap of image data in flash and boots
David Vinczeba3bd602019-06-17 16:01:43 +0200362the new image or it will be executed during operation. The new image can then
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200363update the contents of flash at runtime to mark itself "OK", and MCUboot will
David Vinczeba3bd602019-06-17 16:01:43 +0200364then still choose to run it during the next boot. When this happens, the swap is
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200365made "permanent". If this doesn't happen, MCUboot will perform a "revert" swap
David Vinczeba3bd602019-06-17 16:01:43 +0200366during the next boot by swapping the image(s) back into its original location(s)
367, and attempting to boot the old image(s).
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800368
Marti Bolivar048d8d82017-08-04 17:14:24 -0400369Depending on the use case, the first swap can also be made permanent directly.
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200370In this case, MCUboot will never attempt to revert the images on the next reset.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800371
Marti Bolivar048d8d82017-08-04 17:14:24 -0400372Test swaps are supported to provide a rollback mechanism to prevent devices
373from becoming "bricked" by bad firmware. If the device crashes immediately
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200374upon booting a new (bad) image, MCUboot will revert to the old (working) image
Marti Bolivar048d8d82017-08-04 17:14:24 -0400375at the next device reset, rather than booting the bad image again. This allows
376device firmware to make test swaps permanent only after performing a self-test
377routine.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800378
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200379On startup, MCUboot inspects the contents of flash to decide for each images
David Vinczeba3bd602019-06-17 16:01:43 +0200380which of these "swap types" to perform; this decision determines how it
381proceeds.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800382
Marti Bolivar048d8d82017-08-04 17:14:24 -0400383The possible swap types, and their meanings, are:
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800384
David Brown17e20d12017-09-12 11:53:20 -0600385- `BOOT_SWAP_TYPE_NONE`: The "usual" or "no upgrade" case; attempt to boot the
David Vincze2d736ad2019-02-18 11:50:22 +0100386 contents of the primary slot.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800387
David Vincze2d736ad2019-02-18 11:50:22 +0100388- `BOOT_SWAP_TYPE_TEST`: Boot the contents of the secondary slot by swapping
389 images. Unless the swap is made permanent, revert back on the next boot.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800390
David Brown17e20d12017-09-12 11:53:20 -0600391- `BOOT_SWAP_TYPE_PERM`: Permanently swap images, and boot the upgraded image
Marti Bolivar048d8d82017-08-04 17:14:24 -0400392 firmware.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800393
David Vincze2d736ad2019-02-18 11:50:22 +0100394- `BOOT_SWAP_TYPE_REVERT`: A previous test swap was not made permanent;
395 swap back to the old image whose data are now in the secondary slot. If the
396 old image marks itself "OK" when it boots, the next boot will have swap type
397 `BOOT_SWAP_TYPE_NONE`.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800398
David Brown17e20d12017-09-12 11:53:20 -0600399- `BOOT_SWAP_TYPE_FAIL`: Swap failed because image to be run is not valid.
Marti Bolivar048d8d82017-08-04 17:14:24 -0400400
David Brown17e20d12017-09-12 11:53:20 -0600401- `BOOT_SWAP_TYPE_PANIC`: Swapping encountered an unrecoverable error.
Marti Bolivar048d8d82017-08-04 17:14:24 -0400402
403The "swap type" is a high-level representation of the outcome of the
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200404boot. Subsequent sections describe how MCUboot determines the swap type from
Marti Bolivar048d8d82017-08-04 17:14:24 -0400405the bit-level contents of flash.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800406
David Vincze505fba22020-10-22 13:53:29 +0200407### [Revert mechanism in direct-xip mode](#direct-xip-revert)
408
409The direct-xip mode also supports a "revert" mechanism which is the equivalent
David Vincze1c456242021-06-29 15:25:24 +0200410of the swap mode's "revert" swap. When the direct-xip mode is selected it can be
411enabled with the MCUBOOT_DIRECT_XIP_REVERT config option and an image trailer
412must also be added to the signed images (the "--pad" option of the `imgtool`
413script must be used). For more information on this please read the
414[Image Trailer](#image-trailer) section and the [imgtool](imgtool.md)
415documentation. Making the images permanent (marking them as confirmed in
416advance) is also supported just like in swap mode. The individual steps of the
417direct-xip mode's "revert" mechanism are the following:
David Vincze505fba22020-10-22 13:53:29 +0200418
4191. Select the slot which holds the newest potential image.
4202. Was the image previously selected to run (during a previous boot)?
421 + Yes: Did the image mark itself "OK" (was the self-test successful)?
422 + Yes.
423 - Proceed to step 3.
424 + No.
425 - Erase the image from the slot to prevent it from being selected
426 again during the next boot.
427 - Return to step 1 (the bootloader will attempt to select and
428 possibly boot the previous image if there is one).
429 + No.
430 - Mark the image as "selected" (set the copy_done flag in the trailer).
431 - Proceed to step 3.
4323. Proceed to image validation ...
433
Francesco Servidio5bc98322021-11-03 13:19:22 +0100434## [Image trailer](#image-trailer)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800435
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300436For the bootloader to be able to determine the current state and what actions
Marti Bolivar42818032017-08-04 15:45:01 -0400437should be taken during the current boot operation, it uses metadata stored in
438the image flash areas. While swapping, some of this metadata is temporarily
439copied into and out of the scratch area.
440
441This metadata is located at the end of the image flash areas, and is called an
442image trailer. An image trailer has the following structure:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800443
David Brown17e20d12017-09-12 11:53:20 -0600444```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800445 0 1 2 3
446 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
447 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collins92ea77f2016-12-12 15:59:26 -0800448 ~ ~
Fabio Utzig2c05f1b2018-04-04 10:35:17 -0300449 ~ Swap status (BOOT_MAX_IMG_SECTORS * min-write-size * 3) ~
Christopher Collins92ea77f2016-12-12 15:59:26 -0800450 ~ ~
451 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collinsa1c12042019-05-23 14:00:28 -0700452 | Encryption key 0 (16 octets) [*] |
453 | |
Christopher Collins92ea77f2016-12-12 15:59:26 -0800454 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300455 | 0xff padding as needed |
456 | (BOOT_MAX_ALIGN minus 16 octets from Encryption key 0) [*] |
457 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collinsa1c12042019-05-23 14:00:28 -0700458 | Encryption key 1 (16 octets) [*] |
459 | |
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300460 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300461 | 0xff padding as needed |
462 | (BOOT_MAX_ALIGN minus 16 octets from Encryption key 1) [*] |
463 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collinsa1c12042019-05-23 14:00:28 -0700464 | Swap size (4 octets) |
Fabio Utzigea422c22017-09-11 11:02:47 -0300465 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300466 | 0xff padding as needed |
467 | (BOOT_MAX_ALIGN minus 4 octets from Swap size) |
Fabio Utzigea422c22017-09-11 11:02:47 -0300468 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300469 | Swap info | 0xff padding (BOOT_MAX_ALIGN minus 1 octet) |
Christopher Collinsa1c12042019-05-23 14:00:28 -0700470 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300471 | Copy done | 0xff padding (BOOT_MAX_ALIGN minus 1 octet) |
472 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
473 | Image OK | 0xff padding (BOOT_MAX_ALIGN minus 1 octet) |
474 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
475 | 0xff padding as needed |
476 | (BOOT_MAX_ALIGN minus 16 octets from MAGIC) |
Christopher Collinsa1c12042019-05-23 14:00:28 -0700477 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
478 | MAGIC (16 octets) |
479 | |
Christopher Collins92ea77f2016-12-12 15:59:26 -0800480 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
David Brown17e20d12017-09-12 11:53:20 -0600481```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800482
Christopher Collinsa1c12042019-05-23 14:00:28 -0700483[*]: Only present if the encryption option is enabled (`MCUBOOT_ENC_IMAGES`).
484
Marti Bolivar42818032017-08-04 15:45:01 -0400485The offset immediately following such a record represents the start of the next
486flash area.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800487
Francesco Servidio2fe449d2021-10-21 12:38:36 +0200488---
489***Note***
490
491*"min-write-size" is a property of the flash hardware. If the hardware*
492*allows individual bytes to be written at arbitrary addresses, then*
493*min-write-size is 1. If the hardware only allows writes at even addresses,*
494*then min-write-size is 2, and so on.*
495
496---
Christopher Collins92ea77f2016-12-12 15:59:26 -0800497
Marti Bolivar1dcb6852017-08-04 15:59:32 -0400498An image trailer contains the following fields:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800499
Marti Bolivar1dcb6852017-08-04 15:59:32 -04005001. Swap status: A series of records which records the progress of an image
David Vincze2d736ad2019-02-18 11:50:22 +0100501 swap. To swap entire images, data are swapped between the two image areas
502 one or more sectors at a time, like this:
Marti Bolivar1dcb6852017-08-04 15:59:32 -0400503
David Vincze2d736ad2019-02-18 11:50:22 +0100504 - sector data in the primary slot is copied into scratch, then erased
505 - sector data in the secondary slot is copied into the primary slot,
506 then erased
507 - sector data in scratch is copied into the secondary slot
Marti Bolivar1dcb6852017-08-04 15:59:32 -0400508
509As it swaps images, the bootloader updates the swap status field in a way that
510allows it to compute how far this swap operation has progressed for each
511sector. The swap status field can thus used to resume a swap operation if the
512bootloader is halted while a swap operation is ongoing and later reset. The
David Vincze2d736ad2019-02-18 11:50:22 +0100513`BOOT_MAX_IMG_SECTORS` value is the configurable maximum number of sectors
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200514MCUboot supports for each image; its value defaults to 128, but allows for
David Vincze2d736ad2019-02-18 11:50:22 +0100515either decreasing this size, to limit RAM usage, or to increase it in devices
516that have massive amounts of Flash or very small sized sectors and thus require
517a bigger configuration to allow for the handling of all slot's sectors.
iysheng506a16f2021-08-26 06:13:11 +0800518The factor of min-write-size is due to the behavior of flash hardware. The factor
David Vincze2d736ad2019-02-18 11:50:22 +0100519of 3 is explained below.
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300520
Christopher Collinsa1c12042019-05-23 14:00:28 -07005212. Encryption keys: key-encrypting keys (KEKs). These keys are needed for
522 image encryption and decryption. See the
523 [encrypted images](encrypted_images.md) document for more information.
524
5253. Swap size: When beginning a new swap operation, the total size that needs
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +0000526 to be swapped (based on the slot with largest image + TLVs) is written to
David Vincze2d736ad2019-02-18 11:50:22 +0100527 this location for easier recovery in case of a reset while performing the
528 swap.
Fabio Utzigea422c22017-09-11 11:02:47 -0300529
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +00005304. Swap info: A single byte which encodes the following information:
David Vinczee2453472019-06-17 12:31:59 +0200531 - Swap type: Stored in bits 0-3. Indicating the type of swap operation in
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200532 progress. When MCUboot resumes an interrupted swap, it uses this field to
David Vinczee2453472019-06-17 12:31:59 +0200533 determine the type of operation to perform. This field contains one of the
534 following values in the table below.
535 - Image number: Stored in bits 4-7. It has always 0 value at single image
536 boot. In case of multi image boot it indicates, which image was swapped when
537 interrupt happened. The same scratch area is used during in case of all
538 image swap operation. Therefore this field is used to determine which image
539 the trailer belongs to if boot status is found on scratch area when the swap
540 operation is resumed.
Christopher Collinsa1c12042019-05-23 14:00:28 -0700541
542| Name | Value |
543| ------------------------- | ----- |
544| `BOOT_SWAP_TYPE_TEST` | 2 |
545| `BOOT_SWAP_TYPE_PERM` | 3 |
546| `BOOT_SWAP_TYPE_REVERT` | 4 |
547
548
5495. Copy done: A single byte indicating whether the image in this slot is
David Brown17e20d12017-09-12 11:53:20 -0600550 complete (0x01=done; 0xff=not done).
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300551
Christopher Collinsa1c12042019-05-23 14:00:28 -07005526. Image OK: A single byte indicating whether the image in this slot has been
David Brown17e20d12017-09-12 11:53:20 -0600553 confirmed as good by the user (0x01=confirmed; 0xff=not confirmed).
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300554
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -03005557. MAGIC: A 16-byte field identifying the image trailer layout. It may assume
556 distinct values depending on the maximum supported write alignment
557 (`BOOT_MAX_ALIGN`) of the image, as defined by the following construct:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800558
David Brown17e20d12017-09-12 11:53:20 -0600559``` c
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300560union boot_img_magic_t
561{
562 struct {
563 uint16_t align;
564 uint8_t magic[14];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800565 };
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300566 uint8_t val[16];
567};
David Brown17e20d12017-09-12 11:53:20 -0600568```
Gustavo Henrique Nihei41f123c2021-11-22 18:45:48 -0300569 If `BOOT_MAX_ALIGN` is **8 bytes**, then MAGIC contains the following 16 bytes:
570
571``` c
572const union boot_img_magic_t boot_img_magic = {
573 .val = {
574 0x77, 0xc2, 0x95, 0xf3,
575 0x60, 0xd2, 0xef, 0x7f,
576 0x35, 0x52, 0x50, 0x0f,
577 0x2c, 0xb6, 0x79, 0x80
578 }
579};
580```
581
582 In case `BOOT_MAX_ALIGN` is defined to any value different than **8**, then the maximum
583 supported write alignment value is encoded in the MAGIC field, followed by a fixed
584 14-byte pattern:
585
586``` c
587const union boot_img_magic_t boot_img_magic = {
588 .align = BOOT_MAX_ALIGN,
589 .magic = {
590 0x2d, 0xe1,
591 0x5d, 0x29, 0x41, 0x0b,
592 0x8d, 0x77, 0x67, 0x9c,
593 0x11, 0x0f, 0x1f, 0x8a
594 }
595};
596```
597
Andrzej Puzdrowskicd35fef2021-11-25 16:15:08 +0100598---
599***Note***
600Be aware that the image trailers make the ending area of the image slot
601unavailable for carrying the image data. In particular, the swap status size
602could be huge. For example, for 128 slot sectors with a 4-byte alignment,
603it would become 1536 B.
604
605---
Christopher Collins92ea77f2016-12-12 15:59:26 -0800606
Francesco Servidio5bc98322021-11-03 13:19:22 +0100607## [Image trailers](#image-trailers)
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300608
Francesco Servidio482921f2021-10-20 15:42:59 +0200609At startup, the bootloader determines the boot swap type by inspecting the
Marti Bolivar048d8d82017-08-04 17:14:24 -0400610image trailers. When using the term "image trailers" what is meant is the
611aggregate information provided by both image slot's trailers.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300612
Fabio Utzigd37d8772019-12-03 10:32:18 -0300613### [New swaps (non-resumes)](#new-swaps-non-resumes)
Christopher Collinsa1c12042019-05-23 14:00:28 -0700614
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200615For new swaps, MCUboot must inspect a collection of fields to determine which
Christopher Collinsa1c12042019-05-23 14:00:28 -0700616swap operation to perform.
617
David Vincze2d736ad2019-02-18 11:50:22 +0100618The image trailers records are structured around the limitations imposed by
619flash hardware. As a consequence, they do not have a very intuitive design, and
620it is difficult to get a sense of the state of the device just by looking at the
Marti Bolivar048d8d82017-08-04 17:14:24 -0400621image trailers. It is better to map all the possible trailer states to the swap
622types described above via a set of tables. These tables are reproduced below.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300623
Francesco Servidio2fe449d2021-10-21 12:38:36 +0200624---
625***Note***
626
627*An important caveat about the tables described below is that they must*
628*be evaluated in the order presented here. Lower state numbers must have a*
629*higher priority when testing the image trailers.*
630
631---
Christopher Collins92ea77f2016-12-12 15:59:26 -0800632
David Brown17e20d12017-09-12 11:53:20 -0600633```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800634 State I
David Vincze2d736ad2019-02-18 11:50:22 +0100635 | primary slot | secondary slot |
636 -----------------+--------------+----------------|
637 magic | Any | Good |
638 image-ok | Any | Unset |
639 copy-done | Any | Any |
640 -----------------+--------------+----------------'
641 result: BOOT_SWAP_TYPE_TEST |
642 -------------------------------------------------'
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300643
Christopher Collins92ea77f2016-12-12 15:59:26 -0800644
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300645 State II
David Vincze2d736ad2019-02-18 11:50:22 +0100646 | primary slot | secondary slot |
647 -----------------+--------------+----------------|
648 magic | Any | Good |
649 image-ok | Any | 0x01 |
650 copy-done | Any | Any |
651 -----------------+--------------+----------------'
652 result: BOOT_SWAP_TYPE_PERM |
653 -------------------------------------------------'
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300654
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800655
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300656 State III
David Vincze2d736ad2019-02-18 11:50:22 +0100657 | primary slot | secondary slot |
658 -----------------+--------------+----------------|
659 magic | Good | Unset |
660 image-ok | 0xff | Any |
661 copy-done | 0x01 | Any |
662 -----------------+--------------+----------------'
663 result: BOOT_SWAP_TYPE_REVERT |
664 -------------------------------------------------'
David Brown17e20d12017-09-12 11:53:20 -0600665```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800666
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200667Any of the above three states results in MCUboot attempting to swap images.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800668
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200669Otherwise, MCUboot does not attempt to swap images, resulting in one of the
Marti Bolivar048d8d82017-08-04 17:14:24 -0400670other three swap types, as illustrated by State IV.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300671
David Brown17e20d12017-09-12 11:53:20 -0600672```
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300673 State IV
David Vincze2d736ad2019-02-18 11:50:22 +0100674 | primary slot | secondary slot |
675 -----------------+--------------+----------------|
676 magic | Any | Any |
677 image-ok | Any | Any |
678 copy-done | Any | Any |
679 -----------------+--------------+----------------'
680 result: BOOT_SWAP_TYPE_NONE, |
681 BOOT_SWAP_TYPE_FAIL, or |
682 BOOT_SWAP_TYPE_PANIC |
683 -------------------------------------------------'
David Brown17e20d12017-09-12 11:53:20 -0600684```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800685
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200686In State IV, when no errors occur, MCUboot will attempt to boot the contents of
David Vincze2d736ad2019-02-18 11:50:22 +0100687the primary slot directly, and the result is `BOOT_SWAP_TYPE_NONE`. If the image
688in the primary slot is not valid, the result is `BOOT_SWAP_TYPE_FAIL`. If a
689fatal error occurs during boot, the result is `BOOT_SWAP_TYPE_PANIC`. If the
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200690result is either `BOOT_SWAP_TYPE_FAIL` or `BOOT_SWAP_TYPE_PANIC`, MCUboot hangs
David Vincze2d736ad2019-02-18 11:50:22 +0100691rather than booting an invalid or compromised image.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300692
Francesco Servidio2fe449d2021-10-21 12:38:36 +0200693---
694***Note***
695
696*An important caveat to the above is the result when a swap is requested*
697*and the image in the secondary slot fails to validate, due to a hashing or*
698*signing error. This state behaves as State IV with the extra action of*
699*marking the image in the primary slot as "OK", to prevent further attempts*
700*to swap.*
701
702---
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300703
Fabio Utzigd37d8772019-12-03 10:32:18 -0300704### [Resumed swaps](#resumed-swaps)
Christopher Collinsa1c12042019-05-23 14:00:28 -0700705
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200706If MCUboot determines that it is resuming an interrupted swap (i.e., a reset
Christopher Collinsa1c12042019-05-23 14:00:28 -0700707occurred mid-swap), it fully determines the operation to resume by reading the
David Vinczee2453472019-06-17 12:31:59 +0200708`swap info` field from the active trailer and extracting the swap type from bits
7090-3. The set of tables in the previous section are not necessary in the resume
710case.
Christopher Collinsa1c12042019-05-23 14:00:28 -0700711
Francesco Servidio5bc98322021-11-03 13:19:22 +0100712## [High-level operation](#high-level-operation)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800713
Francesco Servidio482921f2021-10-20 15:42:59 +0200714With the terms defined, we can now explore the bootloader's operation. First,
Christopher Collins92ea77f2016-12-12 15:59:26 -0800715a high-level overview of the boot process is presented. Then, the following
716sections describe each step of the process in more detail.
717
718Procedure:
719
David Brown17e20d12017-09-12 11:53:20 -06007201. Inspect swap status region; is an interrupted swap being resumed?
Fabio Utzig75b34412019-09-06 08:30:43 -0300721 + Yes: Complete the partial swap operation; skip to step 3.
722 + No: Proceed to step 2.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800723
David Brown17e20d12017-09-12 11:53:20 -06007242. Inspect image trailers; is a swap requested?
Fabio Utzig75b34412019-09-06 08:30:43 -0300725 + Yes:
726 1. Is the requested image valid (integrity and security check)?
727 + Yes.
728 a. Perform swap operation.
729 b. Persist completion of swap procedure to image trailers.
730 c. Proceed to step 3.
731 + No.
732 a. Erase invalid image.
733 b. Persist failure of swap procedure to image trailers.
734 c. Proceed to step 3.
735
736 + No: Proceed to step 3.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800737
David Vincze2d736ad2019-02-18 11:50:22 +01007383. Boot into image in primary slot.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800739
Francesco Servidio5bc98322021-11-03 13:19:22 +0100740### [Multiple image boot](#multiple-image-boot)
David Vinczeba3bd602019-06-17 16:01:43 +0200741
Francesco Servidio482921f2021-10-20 15:42:59 +0200742When the flash contains multiple executable images the bootloader's operation
David Vinczeba3bd602019-06-17 16:01:43 +0200743is a bit more complex but similar to the previously described procedure with
744one image. Every image can be updated independently therefore the flash is
745partitioned further to arrange two slots for each image.
746```
747+--------------------+
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200748| MCUboot |
David Vinczeba3bd602019-06-17 16:01:43 +0200749+--------------------+
750 ~~~~~ <- memory might be not contiguous
751+--------------------+
752| Image 0 |
753| primary slot |
754+--------------------+
755| Image 0 |
756| secondary slot |
757+--------------------+
758 ~~~~~ <- memory might be not contiguous
759+--------------------+
760| Image N |
761| primary slot |
762+--------------------+
763| Image N |
764| secondary slot |
765+--------------------+
766| Scratch |
767+--------------------+
768```
Francesco Servidio4ff0c182021-10-20 15:27:16 +0200769MCUboot is also capable of handling dependencies between images. For example
David Vinczee32483f2019-06-13 10:46:24 +0200770if an image needs to be reverted it might be necessary to revert another one too
771(e.g. due to API incompatibilities) or simply to prevent from being updated
772because of an unsatisfied dependency. Therefore all aborted swaps have to be
773completed and all the swap types have to be determined for each image before
774the dependency checks. Dependency handling is described in more detail in a
775following section. The multiple image boot procedure is organized in loops which
776iterate over all the firmware images. The high-level overview of the boot
777process is presented below.
David Vinczeba3bd602019-06-17 16:01:43 +0200778
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700779+ Loop 1. Iterate over all images
David Vinczeba3bd602019-06-17 16:01:43 +0200780 1. Inspect swap status region of current image; is an interrupted swap being
781 resumed?
782 + Yes:
783 + Review the validity of previously determined swap types
784 of other images.
785 + Complete the partial swap operation.
786 + Mark the swap type as `None`.
787 + Skip to next image.
788 + No: Proceed to step 2.
789
790 2. Inspect image trailers in the primary and secondary slot; is an image
791 swap requested?
792 + Yes: Review the validity of previously determined swap types of other
793 images. Is the requested image valid (integrity and security
794 check)?
795 + Yes:
796 + Set the previously determined swap type for the current image.
797 + Skip to next image.
798 + No:
799 + Erase invalid image.
800 + Persist failure of swap procedure to image trailers.
801 + Mark the swap type as `Fail`.
802 + Skip to next image.
803 + No:
804 + Mark the swap type as `None`.
805 + Skip to next image.
806
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700807+ Loop 2. Iterate over all images
David Vinczee32483f2019-06-13 10:46:24 +0200808 1. Does the current image depend on other image(s)?
809 + Yes: Are all the image dependencies satisfied?
810 + Yes: Skip to next image.
811 + No:
812 + Modify swap type depending on what the previous type was.
813 + Restart dependency check from the first image.
814 + No: Skip to next image.
David Vinczeba3bd602019-06-17 16:01:43 +0200815
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700816+ Loop 3. Iterate over all images
David Vinczeba3bd602019-06-17 16:01:43 +0200817 1. Is an image swap requested?
818 + Yes:
819 + Perform image update operation.
820 + Persist completion of swap procedure to image trailers.
821 + Skip to next image.
822 + No: Skip to next image.
823
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700824+ Loop 4. Iterate over all images
David Vinczeba3bd602019-06-17 16:01:43 +0200825 1. Validate image in the primary slot (integrity and security check) or
826 at least do a basic sanity check to avoid booting into an empty flash
827 area.
828
829+ Boot into image in the primary slot of the 0th image position\
830 (other image in the boot chain is started by another image).
831
Francesco Servidio5bc98322021-11-03 13:19:22 +0100832### [Multiple image boot for RAM loading and direct-xip](#multiple-image-boot-for-ram-loading-and-direct-xip)
Mark Horvathccaf7f82021-01-04 18:16:42 +0100833
Francesco Servidio482921f2021-10-20 15:42:59 +0200834The operation of the bootloader is different when the ram-load or the
Mark Horvathccaf7f82021-01-04 18:16:42 +0100835direct-xip strategy is chosen. The flash map is very similar to the swap
836strategy but there is no need for Scratch area.
837
838+ Loop 1. Until all images are loaded and all dependencies are satisfied
839 1. Subloop 1. Iterate over all images
840 + Does any of the slots contain an image?
841 + Yes:
842 + Choose the newer image.
843 + Copy it to RAM in case of ram-load strategy.
844 + Validate the image (integrity and security check).
845 + If validation fails delete the image from flash and try the other
846 slot. (Image must be deleted from RAM too in case of ram-load
847 strategy.)
848 + No: Return with failure.
849
850 2. Subloop 2. Iterate over all images
851 + Does the current image depend on other image(s)?
852 + Yes: Are all the image dependencies satisfied?
853 + Yes: Skip to next image.
854 + No:
855 + Delete the image from RAM in case of ram-load strategy, but
856 do not delete it from flash.
857 + Try to load the image from the other slot.
858 + Restart dependency check from the first image.
859 + No: Skip to next image.
860
861+ Loop 2. Iterate over all images
862 + Increase the security counter if needed.
863 + Do the measured boot and the data sharing if needed.
864
865+ Boot the loaded slot of image 0.
866
Francesco Servidio5bc98322021-11-03 13:19:22 +0100867## [Image swapping](#image-swapping)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800868
Francesco Servidio482921f2021-10-20 15:42:59 +0200869The bootloader swaps the contents of the two image slots for two reasons:
Fabio Utzig75b34412019-09-06 08:30:43 -0300870
871 * User has issued a "set pending" operation; the image in the secondary slot
Håkon Øye Amundsen11d91c32020-03-04 08:49:47 +0000872 should be run once (state I) or repeatedly (state II), depending on
Fabio Utzig75b34412019-09-06 08:30:43 -0300873 whether a permanent swap was specified.
Francesco Servidio482921f2021-10-20 15:42:59 +0200874 * Test image rebooted without being confirmed; the bootloader should
Håkon Øye Amundsen11d91c32020-03-04 08:49:47 +0000875 revert to the original image currently in the secondary slot (state III).
Christopher Collins92ea77f2016-12-12 15:59:26 -0800876
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300877If the image trailers indicates that the image in the secondary slot should be
Francesco Servidio482921f2021-10-20 15:42:59 +0200878run, the bootloader needs to copy it to the primary slot. The image currently
Christopher Collins92ea77f2016-12-12 15:59:26 -0800879in the primary slot also needs to be retained in flash so that it can be used
Francesco Servidio482921f2021-10-20 15:42:59 +0200880later. Furthermore, both images need to be recoverable if the bootloader
Christopher Collins92ea77f2016-12-12 15:59:26 -0800881resets in the middle of the swap operation. The two images are swapped
882according to the following procedure:
883
Fabio Utzig60319ac2019-09-06 08:29:50 -03008841. Determine if both slots are compatible enough to have their images swapped.
885 To be compatible, both have to have only sectors that can fit into the
886 scratch area and if one of them has larger sectors than the other, it must
887 be able to entirely fit some rounded number of sectors from the other slot.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300888 In the next steps we'll use the terminology "region" for the total amount of
889 data copied/erased because this can be any amount of sectors depending on
890 how many the scratch is able to fit for some swap operation.
8912. Iterate the list of region indices in descending order (i.e., starting
892 with the greatest index); only regions that are predetermined to be part of
Fabio Utzig60319ac2019-09-06 08:29:50 -0300893 the image are copied; current element = "index".
894 + a. Erase scratch area.
895 + b. Copy secondary_slot[index] to scratch area.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300896 - If this is the last region in the slot, scratch area has a temporary
Fabio Utzig60319ac2019-09-06 08:29:50 -0300897 status area initialized to store the initial state, because the
Fabio Utzigc28005b2019-09-10 12:18:29 -0300898 primary slot's last region will have to be erased. In this case,
Fabio Utzig60319ac2019-09-06 08:29:50 -0300899 only the data that was calculated to amount to the image is copied.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300900 - Else if this is the first swapped region but not the last region in
Fabio Utzig60319ac2019-09-06 08:29:50 -0300901 the slot, initialize the status area in primary slot and copy the
Fabio Utzigc28005b2019-09-10 12:18:29 -0300902 full region contents.
903 - Else, copy entire region contents.
Fabio Utzig60319ac2019-09-06 08:29:50 -0300904 + c. Write updated swap status (i).
905 + d. Erase secondary_slot[index]
906 + e. Copy primary_slot[index] to secondary_slot[index] according to amount
907 previosly copied at step b.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300908 - If this is not the last region in the slot, erase the trailer in the
Fabio Utzig60319ac2019-09-06 08:29:50 -0300909 secondary slot, to always use the one in the primary slot.
910 + f. Write updated swap status (ii).
911 + g. Erase primary_slot[index].
912 + h. Copy scratch area to primary_slot[index] according to amount
913 previously copied at step b.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300914 - If this is the last region in the slot, the status is read from
Fabio Utzig60319ac2019-09-06 08:29:50 -0300915 scratch (where it was stored temporarily) and written anew in the
916 primary slot.
917 + i. Write updated swap status (iii).
9183. Persist completion of swap procedure to the primary slot image trailer.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800919
David Vincze2d736ad2019-02-18 11:50:22 +0100920The additional caveats in step 2f are necessary so that the secondary slot image
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800921trailer can be written by the user at a later time. With the image trailer
David Vincze2d736ad2019-02-18 11:50:22 +0100922unwritten, the user can test the image in the secondary slot
Håkon Øye Amundsen11d91c32020-03-04 08:49:47 +0000923(i.e., transition to state I).
Christopher Collins92ea77f2016-12-12 15:59:26 -0800924
Francesco Servidio2fe449d2021-10-21 12:38:36 +0200925---
926***Note***
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300927
Francesco Servidio2fe449d2021-10-21 12:38:36 +0200928*If the region being copied contains the last sector, then swap status is*
929*temporarily maintained on scratch for the duration of this operation, always*
930*using the primary slot's area otherwise.*
931
932---
933***Note***
934
935*The bootloader tries to copy only used sectors (based on largest image*
936*installed on any of the slots), minimizing the amount of sectors copied and*
937*reducing the amount of time required for a swap operation.*
938
939---
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300940
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800941The particulars of step 3 vary depending on whether an image is being tested,
David Vincze2d736ad2019-02-18 11:50:22 +0100942permanently used, reverted or a validation failure of the secondary slot
943happened when a swap was requested:
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300944
Christopher Collins92ea77f2016-12-12 15:59:26 -0800945 * test:
David Vincze2d736ad2019-02-18 11:50:22 +0100946 o Write primary_slot.copy_done = 1
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800947 (swap caused the following values to be written:
David Vincze2d736ad2019-02-18 11:50:22 +0100948 primary_slot.magic = BOOT_MAGIC
Håkon Øye Amundsencdf94c22020-03-04 08:52:31 +0000949 secondary_slot.magic = UNSET
David Vincze2d736ad2019-02-18 11:50:22 +0100950 primary_slot.image_ok = Unset)
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800951
952 * permanent:
David Vincze2d736ad2019-02-18 11:50:22 +0100953 o Write primary_slot.copy_done = 1
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800954 (swap caused the following values to be written:
David Vincze2d736ad2019-02-18 11:50:22 +0100955 primary_slot.magic = BOOT_MAGIC
Håkon Øye Amundsencdf94c22020-03-04 08:52:31 +0000956 secondary_slot.magic = UNSET
David Vincze2d736ad2019-02-18 11:50:22 +0100957 primary_slot.image_ok = 0x01)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800958
959 * revert:
David Vincze2d736ad2019-02-18 11:50:22 +0100960 o Write primary_slot.copy_done = 1
961 o Write primary_slot.image_ok = 1
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300962 (swap caused the following values to be written:
David Vincze2d736ad2019-02-18 11:50:22 +0100963 primary_slot.magic = BOOT_MAGIC)
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300964
David Vincze2d736ad2019-02-18 11:50:22 +0100965 * failure to validate the secondary slot:
966 o Write primary_slot.image_ok = 1
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300967
David Vincze2d736ad2019-02-18 11:50:22 +0100968After completing the operations as described above the image in the primary slot
969should be booted.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800970
Francesco Servidio5bc98322021-11-03 13:19:22 +0100971## [Swap status](#swap-status)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800972
Francesco Servidio482921f2021-10-20 15:42:59 +0200973The swap status region allows the bootloader to recover in case it restarts in
Christopher Collins92ea77f2016-12-12 15:59:26 -0800974the middle of an image swap operation. The swap status region consists of a
975series of single-byte records. These records are written independently, and
976therefore must be padded according to the minimum write size imposed by the
977flash hardware. In the below figure, a min-write-size of 1 is assumed for
978simplicity. The structure of the swap status region is illustrated below. In
979this figure, a min-write-size of 1 is assumed for simplicity.
980
David Brown17e20d12017-09-12 11:53:20 -0600981```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800982 0 1 2 3
983 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
984 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
985 |sec127,state 0 |sec127,state 1 |sec127,state 2 |sec126,state 0 |
986 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
987 |sec126,state 1 |sec126,state 2 |sec125,state 0 |sec125,state 1 |
988 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
989 |sec125,state 2 | |
990 +-+-+-+-+-+-+-+-+ +
991 ~ ~
992 ~ [Records for indices 124 through 1 ~
993 ~ ~
994 ~ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
995 ~ |sec000,state 0 |sec000,state 1 |sec000,state 2 |
996 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
David Brown17e20d12017-09-12 11:53:20 -0600997```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800998
999The above is probably not helpful at all; here is a description in English.
1000
1001Each image slot is partitioned into a sequence of flash sectors. If we were to
1002enumerate the sectors in a single slot, starting at 0, we would have a list of
1003sector indices. Since there are two image slots, each sector index would
1004correspond to a pair of sectors. For example, sector index 0 corresponds to
David Vincze2d736ad2019-02-18 11:50:22 +01001005the first sector in the primary slot and the first sector in the secondary slot.
1006Finally, reverse the list of indices such that the list starts with index
1007`BOOT_MAX_IMG_SECTORS - 1` and ends with 0. The swap status region is a
1008representation of this reversed list.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001009
1010During a swap operation, each sector index transitions through four separate
1011states:
David Brown17e20d12017-09-12 11:53:20 -06001012```
David Vincze2d736ad2019-02-18 11:50:22 +010010130. primary slot: image 0, secondary slot: image 1, scratch: N/A
10141. primary slot: image 0, secondary slot: N/A, scratch: image 1 (1->s, erase 1)
10152. primary slot: N/A, secondary slot: image 0, scratch: image 1 (0->1, erase 0)
10163. primary slot: image 1, secondary slot: image 0, scratch: N/A (s->0)
David Brown17e20d12017-09-12 11:53:20 -06001017```
Christopher Collins92ea77f2016-12-12 15:59:26 -08001018
Francesco Servidio482921f2021-10-20 15:42:59 +02001019Each time a sector index transitions to a new state, the bootloader writes a
1020record to the swap status region. Logically, the bootloader only needs one
Christopher Collins92ea77f2016-12-12 15:59:26 -08001021record per sector index to keep track of the current swap state. However, due
1022to limitations imposed by flash hardware, a record cannot be overwritten when
Francesco Servidio482921f2021-10-20 15:42:59 +02001023an index's state changes. To solve this problem, the bootloader uses three
Christopher Collins92ea77f2016-12-12 15:59:26 -08001024records per sector index rather than just one.
1025
1026Each sector-state pair is represented as a set of three records. The record
1027values map to the above four states as follows
1028
David Brown17e20d12017-09-12 11:53:20 -06001029```
Christopher Collins92ea77f2016-12-12 15:59:26 -08001030 | rec0 | rec1 | rec2
1031 --------+------+------+------
1032 state 0 | 0xff | 0xff | 0xff
1033 state 1 | 0x01 | 0xff | 0xff
1034 state 2 | 0x01 | 0x02 | 0xff
1035 state 3 | 0x01 | 0x02 | 0x03
David Brown17e20d12017-09-12 11:53:20 -06001036```
Christopher Collins92ea77f2016-12-12 15:59:26 -08001037
Fabio Utzig2c05f1b2018-04-04 10:35:17 -03001038The swap status region can accommodate `BOOT_MAX_IMG_SECTORS` sector indices.
David Vincze2d736ad2019-02-18 11:50:22 +01001039Hence, the size of the region, in bytes, is
1040`BOOT_MAX_IMG_SECTORS * min-write-size * 3`. The only requirement for the index
1041count is that it is great enough to account for a maximum-sized image
1042(i.e., at least as great as the total sector count in an image slot). If a
1043device's image slots have been configured with `BOOT_MAX_IMG_SECTORS: 128` and
1044use less than 128 sectors, the first record that gets written will be somewhere
1045in the middle of the region. For example, if a slot uses 64 sectors, the first
1046sector index that gets swapped is 63, which corresponds to the exact halfway
1047point within the region.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001048
Francesco Servidio2fe449d2021-10-21 12:38:36 +02001049---
1050***Note***
1051
1052*Since the scratch area only ever needs to record swapping of the last*
1053*sector, it uses at most min-write-size * 3 bytes for its own status area.*
1054
1055---
Fabio Utzig5bd4e582017-07-20 08:55:38 -03001056
Francesco Servidio5bc98322021-11-03 13:19:22 +01001057## [Reset recovery](#reset-recovery)
Christopher Collins92ea77f2016-12-12 15:59:26 -08001058
Francesco Servidio482921f2021-10-20 15:42:59 +02001059If the bootloader resets in the middle of a swap operation, the two images may
Christopher Collins92ea77f2016-12-12 15:59:26 -08001060be discontiguous in flash. Bootutil recovers from this condition by using the
Fabio Utzig86fe4b22017-07-28 18:56:29 -03001061image trailers to determine how the image parts are distributed in flash.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001062
1063The first step is determine where the relevant swap status region is located.
1064Because this region is embedded within the image slots, its location in flash
Fabio Utzig86fe4b22017-07-28 18:56:29 -03001065changes during a swap operation. The below set of tables map image trailers
Christopher Collins92ea77f2016-12-12 15:59:26 -08001066contents to swap status location. In these tables, the "source" field
David Vinczeba3bd602019-06-17 16:01:43 +02001067indicates where the swap status region is located. In case of multi image boot
1068the images primary area and the single scratch area is always examined in pairs.
1069If swap status found on scratch area then it might not belong to the current
1070image. The swap_info field of swap status stores the corresponding image number.
1071If it does not match then "source: none" is returned.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001072
David Brown17e20d12017-09-12 11:53:20 -06001073```
David Vincze2d736ad2019-02-18 11:50:22 +01001074 | primary slot | scratch |
1075 ----------+--------------+--------------|
1076 magic | Good | Any |
1077 copy-done | 0x01 | N/A |
1078 ----------+--------------+--------------'
1079 source: none |
1080 ----------------------------------------'
Marti Bolivar49b29172017-08-04 14:50:51 -04001081
David Vincze2d736ad2019-02-18 11:50:22 +01001082 | primary slot | scratch |
1083 ----------+--------------+--------------|
1084 magic | Good | Any |
1085 copy-done | 0xff | N/A |
1086 ----------+--------------+--------------'
1087 source: primary slot |
1088 ----------------------------------------'
Marti Bolivar49b29172017-08-04 14:50:51 -04001089
David Vincze2d736ad2019-02-18 11:50:22 +01001090 | primary slot | scratch |
1091 ----------+--------------+--------------|
1092 magic | Any | Good |
1093 copy-done | Any | N/A |
1094 ----------+--------------+--------------'
1095 source: scratch |
1096 ----------------------------------------'
Marti Bolivar49b29172017-08-04 14:50:51 -04001097
David Vincze2d736ad2019-02-18 11:50:22 +01001098 | primary slot | scratch |
1099 ----------+--------------+--------------|
1100 magic | Unset | Any |
1101 copy-done | 0xff | N/A |
1102 ----------+--------------+--------------|
1103 source: primary slot |
1104 ----------------------------------------+------------------------------+
1105 This represents one of two cases: |
1106 o No swaps ever (no status to read, so no harm in checking). |
1107 o Mid-revert; status in the primary slot. |
1108 For this reason we assume the primary slot as source, to trigger a |
1109 check of the status area and find out if there was swapping under way. |
1110 -----------------------------------------------------------------------'
David Brown17e20d12017-09-12 11:53:20 -06001111```
Christopher Collins92ea77f2016-12-12 15:59:26 -08001112
Francesco Servidio4ff0c182021-10-20 15:27:16 +02001113If the swap status region indicates that the images are not contiguous, MCUboot
Christopher Collinsa1c12042019-05-23 14:00:28 -07001114determines the type of swap operation that was interrupted by reading the `swap
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +00001115info` field in the active image trailer and extracting the swap type from bits
David Vinczee2453472019-06-17 12:31:59 +020011160-3 then resumes the operation. In other words, it applies the procedure defined
1117in the previous section, moving image 1 into the primary slot and image 0 into
1118the secondary slot. If the boot status indicates that an image part is present
1119in the scratch area, this part is copied into the correct location by starting
1120at step e or step h in the area-swap procedure, depending on whether the part
1121belongs to image 0 or image 1.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001122
Francesco Servidio482921f2021-10-20 15:42:59 +02001123After the swap operation has been completed, the bootloader proceeds as though
Christopher Collins92ea77f2016-12-12 15:59:26 -08001124it had just been started.
1125
Francesco Servidio5bc98322021-11-03 13:19:22 +01001126## [Integrity check](#integrity-check)
Christopher Collins92ea77f2016-12-12 15:59:26 -08001127
1128An image is checked for integrity immediately before it gets copied into the
Francesco Servidio482921f2021-10-20 15:42:59 +02001129primary slot. If the bootloader doesn't perform an image swap, then it can
David Vincze2d736ad2019-02-18 11:50:22 +01001130perform an optional integrity check of the image in the primary slot if
1131`MCUBOOT_VALIDATE_PRIMARY_SLOT` is set, otherwise it doesn't perform an
1132integrity check.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001133
Francesco Servidio482921f2021-10-20 15:42:59 +02001134During the integrity check, the bootloader verifies the following aspects of
Christopher Collins92ea77f2016-12-12 15:59:26 -08001135an image:
Fabio Utzig75b34412019-09-06 08:30:43 -03001136
Fabio Utzigfd140ec2019-09-12 14:37:48 -03001137 * 32-bit magic number must be correct (`IMAGE_MAGIC`).
Fabio Utzig75b34412019-09-06 08:30:43 -03001138 * Image must contain an `image_tlv_info` struct, identified by its magic
Fabio Utzigfd140ec2019-09-12 14:37:48 -03001139 (`IMAGE_TLV_PROT_INFO_MAGIC` or `IMAGE_TLV_INFO_MAGIC`) exactly following
1140 the firmware (`hdr_size` + `img_size`). If `IMAGE_TLV_PROT_INFO_MAGIC` is
1141 found then after `ih_protect_tlv_size` bytes, another `image_tlv_info`
1142 with magic equal to `IMAGE_TLV_INFO_MAGIC` must be present.
Fabio Utzig75b34412019-09-06 08:30:43 -03001143 * Image must contain a SHA256 TLV.
1144 * Calculated SHA256 must match SHA256 TLV contents.
1145 * Image *may* contain a signature TLV. If it does, it must also have a
1146 KEYHASH TLV with the hash of the key that was used to sign. The list of
1147 keys will then be iterated over looking for the matching key, which then
1148 will then be used to verify the image contents.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001149
Wouter Cappellebb7a39d2021-05-03 16:44:44 +02001150For low performance MCU's where the validation is a heavy process at boot
1151(~1-2 seconds on a arm-cortex-M0), the `MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE`
1152could be used. This option will cache the validation result as described above
1153into the magic area of the primary slot. The next boot, the validation will be
1154skipped if the previous validation was succesfull. This option is reducing the
1155security level since if an attacker could modify the contents of the flash after
1156a good image has been validated, the attacker could run his own image without
1157running validation again. Enabling this option should be done with care.
1158
Fabio Utzigd37d8772019-12-03 10:32:18 -03001159## [Security](#security)
Christopher Collins92ea77f2016-12-12 15:59:26 -08001160
1161As indicated above, the final step of the integrity check is signature
Francesco Servidio482921f2021-10-20 15:42:59 +02001162verification. The bootloader can have one or more public keys embedded in it
1163at build time. During signature verification, the bootloader verifies that an
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +00001164image was signed with a private key that corresponds to the embedded KEYHASH
Fabio Utzigea422c22017-09-11 11:02:47 -03001165TLV.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001166
Francesco Servidio482921f2021-10-20 15:42:59 +02001167For information on embedding public keys in the bootloader, as well as
Fabio Utzig4dce6aa2018-02-12 15:31:32 -02001168producing signed images, see: [signed_images](signed_images.md).
Fabio Utzigcdfa11a2018-10-01 09:45:54 -03001169
1170If you want to enable and use encrypted images, see:
1171[encrypted_images](encrypted_images.md).
David Vinczee32483f2019-06-13 10:46:24 +02001172
Francesco Servidio2fe449d2021-10-21 12:38:36 +02001173---
1174***Note***
1175
1176*Image encryption is not supported when the direct-xip upgrade strategy*
1177*is selected.*
1178
1179---
David Vinczee574f2d2020-07-10 11:42:03 +02001180
Francesco Servidio5bc98322021-11-03 13:19:22 +01001181### [Using hardware keys for verification](#hw-key-support)
David Vincze25459bf2020-04-21 17:11:20 +02001182
1183By default, the whole public key is embedded in the bootloader code and its
1184hash is added to the image manifest as a KEYHASH TLV entry. As an alternative
1185the bootloader can be made independent of the keys by setting the
1186`MCUBOOT_HW_KEY` option. In this case the hash of the public key must be
Francesco Servidio4ff0c182021-10-20 15:27:16 +02001187provisioned to the target device and MCUboot must be able to retrieve the
David Vincze25459bf2020-04-21 17:11:20 +02001188key-hash from there. For this reason the target must provide a definition
1189for the `boot_retrieve_public_key_hash()` function which is declared in
1190`boot/bootutil/include/bootutil/sign_key.h`. It is also required to use
1191the `full` option for the `--public-key-format` imgtool argument in order to
1192add the whole public key (PUBKEY TLV) to the image manifest instead of its
1193hash (KEYHASH TLV). During boot the public key is validated before using it for
Francesco Servidio4ff0c182021-10-20 15:27:16 +02001194signature verification, MCUboot calculates the hash of the public key from the
David Vincze25459bf2020-04-21 17:11:20 +02001195TLV area and compares it with the key-hash that was retrieved from the device.
Francesco Servidio4ff0c182021-10-20 15:27:16 +02001196This way MCUboot is independent from the public key(s). The key(s) can be
David Vincze25459bf2020-04-21 17:11:20 +02001197provisioned any time and by different parties.
1198
Fabio Utzigd37d8772019-12-03 10:32:18 -03001199## [Protected TLVs](#protected-tlvs)
Fabio Utzigfd140ec2019-09-12 14:37:48 -03001200
1201If the TLV area contains protected TLV entries, by beginning with a `struct
1202image_tlv_info` with a magic value of `IMAGE_TLV_PROT_INFO_MAGIC` then the
1203data of those TLVs must also be integrity and authenticity protected. Beyond
1204the full size of the protected TLVs being stored in the `image_tlv_info`,
1205the size of the protected TLVs together with the size of the `image_tlv_info`
1206struct itself are also saved in the `ih_protected_size` field inside the
1207header.
1208
1209Whenever an image has protected TLVs the SHA256 has to be calculated over
1210not just the image header and the image but also the TLV info header and the
1211protected TLVs.
1212
1213```
1214A +---------------------+
1215 | Header | <- struct image_header
1216 +---------------------+
1217 | Payload |
1218 +---------------------+
1219 | TLV area |
1220 | +-----------------+ | struct image_tlv_info with
1221 | | TLV area header | | <- IMAGE_TLV_PROT_INFO_MAGIC (optional)
1222 | +-----------------+ |
1223 | | Protected TLVs | | <- Protected TLVs (struct image_tlv)
1224B | +-----------------+ |
1225 | | TLV area header | | <- struct image_tlv_info with IMAGE_TLV_INFO_MAGIC
1226C | +-----------------+ |
1227 | | SHA256 hash | | <- hash from A - B (struct image_tlv)
1228D | +-----------------+ |
1229 | | Keyhash | | <- indicates which pub. key for sig (struct image_tlv)
1230 | +-----------------+ |
1231 | | Signature | | <- signature from C - D (struct image_tlv), only hash
1232 | +-----------------+ |
1233 +---------------------+
1234```
1235
Francesco Servidio5bc98322021-11-03 13:19:22 +01001236## [Dependency check](#dependency-check)
David Vinczee32483f2019-06-13 10:46:24 +02001237
Francesco Servidio4ff0c182021-10-20 15:27:16 +02001238MCUboot can handle multiple firmware images. It is possible to update them
David Vinczee32483f2019-06-13 10:46:24 +02001239independently but in many cases it can be desired to be able to describe
1240dependencies between the images (e.g. to ensure API compliance and avoid
1241interoperability issues).
1242
1243The dependencies between images can be described with additional TLV entries in
Fabio Utzigfd140ec2019-09-12 14:37:48 -03001244the protected TLV area after the end of an image. There can be more than one
1245dependency entry, but in practice if the platform only supports two individual
1246images then there can be maximum one entry which reflects to the other image.
David Vinczee32483f2019-06-13 10:46:24 +02001247
David Vinczee32483f2019-06-13 10:46:24 +02001248At the phase of dependency check all aborted swaps are finalized if there were
Francesco Servidio482921f2021-10-20 15:42:59 +02001249any. During the dependency check the bootloader verifies whether the image
David Vinczee32483f2019-06-13 10:46:24 +02001250dependencies are all satisfied. If at least one of the dependencies of an image
1251is not fulfilled then the swap type of that image has to be modified
1252accordingly and the dependency check needs to be restarted. This way the number
1253of unsatisfied dependencies will decrease or remain the same. There is always at
1254least 1 valid configuration. In worst case, the system returns to the initial
1255state after dependency check.
1256
1257For more information on adding dependency entries to an image,
1258see: [imgtool](imgtool.md).
Håkon Øye Amundsen2d1bac12020-01-03 13:08:09 +00001259
Francesco Servidio5bc98322021-11-03 13:19:22 +01001260## [Downgrade prevention](#downgrade-prevention)
Håkon Øye Amundsen2d1bac12020-01-03 13:08:09 +00001261
1262Downgrade prevention is a feature which enforces that the new image must have a
David Vinczec3084132020-02-18 14:50:47 +01001263higher version/security counter number than the image it is replacing, thus
1264preventing the malicious downgrading of the device to an older and possibly
1265vulnerable version of its firmware.
1266
Francesco Servidio5bc98322021-11-03 13:19:22 +01001267### [Software-based downgrade prevention](#sw-downgrade-prevention)
David Vinczec3084132020-02-18 14:50:47 +01001268
1269During the software based downgrade prevention the image version numbers are
1270compared. This feature is enabled with the `MCUBOOT_DOWNGRADE_PREVENTION`
1271option. In this case downgrade prevention is only available when the
1272overwrite-based image update strategy is used (i.e. `MCUBOOT_OVERWRITE_ONLY`
1273is set).
1274
Francesco Servidio5bc98322021-11-03 13:19:22 +01001275### [Hardware-based downgrade prevention](#hw-downgrade-prevention)
David Vinczec3084132020-02-18 14:50:47 +01001276
David Vincze25459bf2020-04-21 17:11:20 +02001277Each signed image can contain a security counter in its protected TLV area, which
1278can be added to the image using the `-s` option of the [imgtool](imgtool.md) script.
David Vinczec3084132020-02-18 14:50:47 +01001279During the hardware based downgrade prevention (alias rollback protection) the
1280new image's security counter will be compared with the currently active security
1281counter value which must be stored in a non-volatile and trusted component of
David Vincze25459bf2020-04-21 17:11:20 +02001282the device. It is beneficial to handle this counter independently from image
1283version number:
David Vinczec3084132020-02-18 14:50:47 +01001284
1285 * It does not need to increase with each software release,
1286 * It makes it possible to do software downgrade to some extent: if the
1287 security counter has the same value in the older image then it is accepted.
David Vincze25459bf2020-04-21 17:11:20 +02001288
1289It is an optional step of the image validation process and can be enabled with
1290the `MCUBOOT_HW_ROLLBACK_PROT` config option. When enabled, the target must
1291provide an implementation of the security counter interface defined in
1292`boot/bootutil/include/security_cnt.h`.
1293
1294## [Measured boot and data sharing](#boot-data-sharing)
1295
Francesco Servidio4ff0c182021-10-20 15:27:16 +02001296MCUboot defines a mechanism for sharing boot status information (also known as
David Vincze25459bf2020-04-21 17:11:20 +02001297measured boot) and an interface for sharing application specific information
1298with the runtime software. If any of these are enabled the target must provide
1299a shared data area between the bootloader and runtime firmware and define the
1300following parameters:
1301
1302```c
1303#define MCUBOOT_SHARED_DATA_BASE <area_base_addr>
1304#define MCUBOOT_SHARED_DATA_SIZE <area_size_in_bytes>
1305```
1306
1307In the shared memory area all data entries are stored in a type-length-value
1308(TLV) format. Before adding the first data entry, the whole area is overwritten
1309with zeros and a TLV header is added at the beginning of the area during an
1310initialization phase. This TLV header contains a `tlv_magic` field with a value
1311of `SHARED_DATA_TLV_INFO_MAGIC` and a `tlv_tot_len` field which is indicating
1312the total length of shared TLV area including this header. The header is
1313followed by the the data TLV entries which are composed from a
1314`shared_data_tlv_entry` header and the data itself. In the data header there is
1315a `tlv_type` field which identifies the consumer of the entry (in the runtime
1316software) and specifies the subtype of that data item. More information about
1317the `tlv_type` field and data types can be found in the
1318`boot/bootutil/include/bootutil/boot_status.h` file. The type is followed by a
1319`tlv_len` field which indicates the size of the data entry in bytes, not
1320including the entry header. After this header structure comes the actual data.
1321
1322```c
1323/** Shared data TLV header. All fields in little endian. */
1324struct shared_data_tlv_header {
1325 uint16_t tlv_magic;
1326 uint16_t tlv_tot_len; /* size of whole TLV area (including this header) */
1327};
1328
1329/** Shared data TLV entry header format. All fields in little endian. */
1330struct shared_data_tlv_entry {
1331 uint16_t tlv_type;
1332 uint16_t tlv_len; /* TLV data length (not including this header). */
1333};
1334```
1335
1336The measured boot can be enabled with the `MCUBOOT_MEASURED_BOOT` config option.
1337When enabled, the `--boot_record` argument of the imgtool script must also be
1338used during the image signing process to add a BOOT_RECORD TLV to the image
1339manifest. This TLV contains the following attributes/measurements of the
1340image in CBOR encoded format:
1341
1342 * Software type (role of the software component)
1343 * Software version
1344 * Signer ID (identifies the signing authority)
1345 * Measurement value (hash of the image)
1346 * Measurement type (algorithm used to calculate the measurement value)
1347
1348The `sw_type` string that is passed as the `--boot_record` option's parameter
1349will be the value of the "Software type" attribute in the generated BOOT_RECORD
1350TLV. The target must also define the `MAX_BOOT_RECORD_SZ` macro which indicates
1351the maximum size of the CBOR encoded boot record in bytes.
Francesco Servidio4ff0c182021-10-20 15:27:16 +02001352During boot, MCUboot will look for these TLVs (in case of multiple images) in
David Vincze25459bf2020-04-21 17:11:20 +02001353the manifests of the active images (the latest and validated) and copy the CBOR
1354encoded binary data to the shared data area. Preserving all these image
1355attributes from the boot stage for use by later runtime services (such as an
1356attestation service) is known as a measured boot.
1357
1358Setting the `MCUBOOT_DATA_SHARING` option enables the sharing of application
1359specific data using the same shared data area as for the measured boot. For
1360this, the target must provide a definition for the `boot_save_shared_data()`
1361function which is declared in `boot/bootutil/include/bootutil/boot_record.h`.
1362The `boot_add_data_to_shared_area()` function can be used for adding new TLV
Jamie McCrae88b28652023-08-03 15:58:58 +01001363entries to the shared data area. Alternatively, setting the
1364`MCUBOOT_DATA_SHARING_BOOTINFO` option will provide a default function for
1365this which saves information such as the maximum application size, bootloader
1366version (if available), running slot number, if recovery is part of MCUboot
1367and the signature type. Details of the TLVs for this information can be found
1368in `boot/bootutil/include/bootutil/boot_status.h` with `BLINFO_` prefixes.
Mate Toth-Palcbf9d392020-11-09 16:47:49 +01001369
1370## [Testing in CI](#testing-in-ci)
1371
1372### [Testing Fault Injection Hardening (FIH)](#testing-fih)
1373
1374The CI currently tests the Fault Injection Hardening feature of MCUboot by
1375executing instruction skip during execution, and looking at whether a corrupted
1376image was booted by the bootloader or not.
1377
1378The main idea is that instruction skipping can be automated by scripting a
1379debugger to automatically execute the following steps:
1380
1381- Set breakpoint at specified address.
1382- Continue execution.
1383- On breakpoint hit increase the Program Counter.
1384- Continue execution.
1385- Detach from target after a timeout reached.
1386
1387Whether or not the corrupted image was booted or not can be decided by looking
1388for certain entries in the log.
1389
1390As MCUboot is deployed on a microcontroller, testing FI would not make much
1391sense in the simulator environment running on a host machine with different
1392architecture than the MCU's, as the degree of hardening depends on compiler
1393behavior. For example, (a bit counterintuitively) the code produced by gcc
1394with `-O0` optimisation is more resilient against FI attacks than the code
1395generated with `-O3` or `-Os` optimizations.
1396
1397To run on a desired architecture in the CI, the tests need to be executed on an
1398emulator (as real devices are not available in the CI environment). For this
1399implementation QEMU is selected.
1400
1401For the tests MCUboot needs a set of drivers and an implementation of a main
1402function. For the purpose of this test Trusted-Firmware-M has been selected as
1403it supports Armv8-M platforms that are also emulated by QEMU.
1404
1405The tests run in a docker container inside the CI VMs, to make it more easy to
1406deploy build and test environment (QEMU, compilers, interpreters). The CI VMs
1407seems to be using quite old Ubuntu (16.04).
1408
1409The sequence of the testing is the following (pseudo code):
1410
1411```sh
1412fn main()
1413 # Implemented in ci/fih-tests_install.sh
1414 generate_docker_image(Dockerfile)
1415
1416 # See details below. Implemented in ci/fih-tests_run.sh.
1417 # Calling the function with different parameters is done by Travis CI based on
1418 # the values provided in the .travis.yaml
1419 start_docker_image(skip_sizes, build_type, damage_type, fih_level)
1420
1421fn start_docker_image(skip_sizes, build_type, damage_type, fih_level)
1422 # implemented in ci/fih_test_docker/execute_test.sh
1423 compile_mcuboot(build_type)
1424
1425 # implemented in ci/fih_test_docker/damage_image.py
1426 damage_image(damage_type)
1427
1428 # implemented in ci/fih_test_docker/run_fi_test.sh
1429 ranges = generate_address_ranges()
1430 for s in skip_sizes
1431 for r in ranges
1432 do_skip_in_qemu(s, r) # See details below
1433 evaluate_logs()
1434
1435fn do_skip_in_qemu(size, range)
1436 for a in r
1437 run_qemu(a, size) # See details below
1438
1439# this part is implemented in ci/fih_test_docker/fi_tester_gdb.sh
1440fn run_qemu(a, size)
1441 script = create_debugger_script(a, size)
1442 start_qemu_in_bacground() # logs serial out to a file
1443 gdb_attach_to_qemu(script)
1444 kill_qemu()
1445
1446 # This checks the debugger and the quemu logs, and decides whether the tets
1447 # was executed successfully, and whether the image is booted or not. Then
1448 # emits a yaml fragment on the standard out to be processed by the caller
1449 # script
1450 evaluate_run(qemu_log_file)
1451```
1452
1453Further notes:
1454
1455- The image is corrupted by changing its signature.
1456- MCUBOOT_FIH_PROFILE_MAX is not tested as it requires TRNG, and the AN521
1457platform has no support for it. However this profile adds the random
1458execution delay to the code, so should not affect the instruction skip results
1459too much, because break point is placed at exact address. But in practice this
1460makes harder the accurate timing of the attack.
1461- The test cases defined in .travis.yml always return `passed`, if they were
1462executed successfully. A yaml file is created during test execution with the
1463details of the test execution results. A summary of the collected results is
1464printed in the log at the end of the test.
1465
1466An advantage of having the tests running in a docker image is that it is
1467possible to run the tests on a local machine that has git and docker, without
1468installing any additional software.
1469
1470So, running the test on the host looks like the following (The commands below
1471are issued from the MCUboot source directory):
1472
1473```sh
Sherry Zhang3c4f69c2021-09-16 14:20:04 +08001474$ mkdir docker
Mate Toth-Palcbf9d392020-11-09 16:47:49 +01001475$ ./ci/fih-tests_install.sh
Tamas Ban04efc2e2022-12-08 17:46:26 +01001476$ FIH_LEVEL=MEDIUM BUILD_TYPE=RELEASE SKIP_SIZE=2 DAMAGE_TYPE=SIGNATURE \
1477 ./ci/fih-tests_run.sh
Mate Toth-Palcbf9d392020-11-09 16:47:49 +01001478```
1479On the travis CI the environment variables in the last command are set based on
1480the configs provided in the `.travis.yaml`
1481
1482This starts the tests, however the shell that it is running in is not
1483interactive, it is not possible to examine the results of the test run. To have
1484an interactive shell where the results can be examined, the following can be
1485done:
1486
1487- The docker image needs to be built with `ci/fih-tests_install.sh` as described
1488 above.
1489- Start the docker image with the following command:
1490 `docker run -i -t mcuboot/fih-test`.
1491- Execute the test with a command similar to the following:
1492 `/root/execute_test.sh 8 RELEASE SIGNATURE MEDIUM`. After the test finishes,
1493 the shell returns, and it is possible to investigate the results. It is also
1494 possible to stop the test with _Ctrl+c_. The parameters to the
1495 `execute_test.sh` are `SKIP_SIZE`, `BUILD_TYPE`, `DAMAGE_TYPE`, `FIH_LEVEL` in
Salome Thirot0f641972021-05-14 11:19:55 +01001496 order.