blob: 52602b85dfbea5422eeaf5a5019a16b536d1c21c [file] [log] [blame]
Tamas Banf70ef8c2017-12-19 15:35:09 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
Tamas Ban581034a2017-12-19 19:54:37 +000020/*
Tamas Ban4fb8e9d2018-02-23 14:22:03 +000021 * Original code taken from mcuboot project at:
22 * https://github.com/runtimeco/mcuboot
Tamas Ban5b647472019-01-05 08:59:30 +000023 * Modifications are Copyright (c) 2018-2019 Arm Limited.
Tamas Ban581034a2017-12-19 19:54:37 +000024 */
25
Tamas Banf70ef8c2017-12-19 15:35:09 +000026/**
27 * This file provides an interface to the boot loader. Functions defined in
28 * this file should only be called while the boot loader is running.
29 */
30
31#include <assert.h>
32#include <stddef.h>
33#include <stdbool.h>
34#include <inttypes.h>
35#include <stdlib.h>
36#include <string.h>
Tamas Banc3828852018-02-01 12:24:16 +000037#include "flash_map/flash_map.h"
Tamas Banf70ef8c2017-12-19 15:35:09 +000038#include "bootutil/bootutil.h"
39#include "bootutil/image.h"
40#include "bootutil_priv.h"
Tamas Bana9de4a62018-09-18 08:09:45 +010041#include "bl2/include/tfm_boot_status.h"
42#include "bl2/include/boot_record.h"
Tamas Banf70ef8c2017-12-19 15:35:09 +000043
44#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
45#include "bootutil/bootutil_log.h"
46
Tamas Banf70ef8c2017-12-19 15:35:09 +000047static struct boot_loader_state boot_data;
48
Oliver Swedef9982442018-08-24 18:37:44 +010049#if !defined(MCUBOOT_NO_SWAP) && !defined(MCUBOOT_RAM_LOADING)
Tamas Banf70ef8c2017-12-19 15:35:09 +000050struct boot_status_table {
51 /**
52 * For each field, a value of 0 means "any".
53 */
54 uint8_t bst_magic_slot0;
55 uint8_t bst_magic_scratch;
56 uint8_t bst_copy_done_slot0;
57 uint8_t bst_status_source;
58};
59
60/**
61 * This set of tables maps swap state contents to boot status location.
62 * When searching for a match, these tables must be iterated in order.
63 */
64static const struct boot_status_table boot_status_tables[] = {
65 {
66 /* | slot-0 | scratch |
67 * ----------+------------+------------|
68 * magic | Good | Any |
69 * copy-done | 0x01 | N/A |
70 * ----------+------------+------------'
71 * source: none |
72 * ------------------------------------'
73 */
74 .bst_magic_slot0 = BOOT_MAGIC_GOOD,
75 .bst_magic_scratch = 0,
76 .bst_copy_done_slot0 = 0x01,
77 .bst_status_source = BOOT_STATUS_SOURCE_NONE,
78 },
79
80 {
81 /* | slot-0 | scratch |
82 * ----------+------------+------------|
83 * magic | Good | Any |
84 * copy-done | 0xff | N/A |
85 * ----------+------------+------------'
86 * source: slot 0 |
87 * ------------------------------------'
88 */
89 .bst_magic_slot0 = BOOT_MAGIC_GOOD,
90 .bst_magic_scratch = 0,
91 .bst_copy_done_slot0 = 0xff,
92 .bst_status_source = BOOT_STATUS_SOURCE_SLOT0,
93 },
94
95 {
96 /* | slot-0 | scratch |
97 * ----------+------------+------------|
98 * magic | Any | Good |
99 * copy-done | Any | N/A |
100 * ----------+------------+------------'
101 * source: scratch |
102 * ------------------------------------'
103 */
104 .bst_magic_slot0 = 0,
105 .bst_magic_scratch = BOOT_MAGIC_GOOD,
106 .bst_copy_done_slot0 = 0,
107 .bst_status_source = BOOT_STATUS_SOURCE_SCRATCH,
108 },
109
110 {
111 /* | slot-0 | scratch |
112 * ----------+------------+------------|
113 * magic | Unset | Any |
114 * copy-done | 0xff | N/A |
115 * ----------+------------+------------|
116 * source: varies |
117 * ------------------------------------+------------------------------+
118 * This represents one of two cases: |
119 * o No swaps ever (no status to read, so no harm in checking). |
120 * o Mid-revert; status in slot 0. |
121 * -------------------------------------------------------------------'
122 */
123 .bst_magic_slot0 = BOOT_MAGIC_UNSET,
124 .bst_magic_scratch = 0,
125 .bst_copy_done_slot0 = 0xff,
126 .bst_status_source = BOOT_STATUS_SOURCE_SLOT0,
127 },
128};
129
130#define BOOT_STATUS_TABLES_COUNT \
Tamas Ban581034a2017-12-19 19:54:37 +0000131 (sizeof(boot_status_tables) / sizeof(boot_status_tables[0]))
Tamas Banf70ef8c2017-12-19 15:35:09 +0000132
133#define BOOT_LOG_SWAP_STATE(area, state) \
Tamas Ban4fb8e9d2018-02-23 14:22:03 +0000134 BOOT_LOG_INF("%s: magic=%5s, copy_done=0x%x, image_ok=0x%x", \
Tamas Banf70ef8c2017-12-19 15:35:09 +0000135 (area), \
136 ((state)->magic == BOOT_MAGIC_GOOD ? "good" : \
137 (state)->magic == BOOT_MAGIC_UNSET ? "unset" : \
138 "bad"), \
139 (state)->copy_done, \
140 (state)->image_ok)
Oliver Swedef9982442018-08-24 18:37:44 +0100141#endif /* !MCUBOOT_NO_SWAP && !MCUBOOT_RAM_LOADING */
Tamas Banf70ef8c2017-12-19 15:35:09 +0000142
Tamas Ban4fb8e9d2018-02-23 14:22:03 +0000143
144static int
145boot_read_image_header(int slot, struct image_header *out_hdr)
146{
147 const struct flash_area *fap = NULL;
148 int area_id;
149 int rc;
150
151 area_id = flash_area_id_from_image_slot(slot);
152 rc = flash_area_open(area_id, &fap);
153 if (rc != 0) {
154 rc = BOOT_EFLASH;
155 goto done;
156 }
157
158 rc = flash_area_read(fap, 0, out_hdr, sizeof(*out_hdr));
159 if (rc != 0) {
160 rc = BOOT_EFLASH;
161 goto done;
162 }
163
164 rc = 0;
165
166done:
167 flash_area_close(fap);
168 return rc;
169}
170
171static int
172boot_read_image_headers(void)
173{
174 int rc;
175 int i;
176
177 for (i = 0; i < BOOT_NUM_SLOTS; i++) {
178 rc = boot_read_image_header(i, boot_img_hdr(&boot_data, i));
179 if (rc != 0) {
180 /* If at least the first slot's header was read successfully, then
181 * the boot loader can attempt a boot. Failure to read any headers
182 * is a fatal error.
183 */
184 if (i > 0) {
185 return 0;
186 } else {
187 return rc;
188 }
189 }
190 }
191
192 return 0;
193}
194
195static uint8_t
196boot_write_sz(void)
197{
198 const struct flash_area *fap;
199 uint8_t elem_sz;
200 uint8_t align;
201 int rc;
202
203 /* Figure out what size to write update status update as. The size depends
204 * on what the minimum write size is for scratch area, active image slot.
205 * We need to use the bigger of those 2 values.
206 */
207 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
208 assert(rc == 0);
209 elem_sz = flash_area_align(fap);
210 flash_area_close(fap);
211
212 rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
213 assert(rc == 0);
214 align = flash_area_align(fap);
215 flash_area_close(fap);
216
217 if (align > elem_sz) {
218 elem_sz = align;
219 }
220
221 return elem_sz;
222}
223
224/**
225 * Determines the sector layout of both image slots and the scratch area.
226 * This information is necessary for calculating the number of bytes to erase
227 * and copy during an image swap. The information collected during this
228 * function is used to populate the boot_data global.
229 */
230static int
231boot_read_sectors(void)
232{
233 int rc;
234
235 rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_0);
236 if (rc != 0) {
237 return BOOT_EFLASH;
238 }
239
240 rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_1);
241 if (rc != 0) {
242 return BOOT_EFLASH;
243 }
244
245 BOOT_WRITE_SZ(&boot_data) = boot_write_sz();
246
247 return 0;
248}
249
250/*
251 * Validate image hash/signature in a slot.
252 */
253static int
Tamas Ban0e8ab302019-01-17 11:45:31 +0000254boot_image_check(struct image_header *hdr, const struct flash_area *fap)
Tamas Ban4fb8e9d2018-02-23 14:22:03 +0000255{
256 static uint8_t tmpbuf[BOOT_TMPBUF_SZ];
257
258 if (bootutil_img_validate(hdr, fap, tmpbuf, BOOT_TMPBUF_SZ,
Tamas Ban0e8ab302019-01-17 11:45:31 +0000259 NULL, 0, NULL)) {
Tamas Ban4fb8e9d2018-02-23 14:22:03 +0000260 return BOOT_EBADIMAGE;
261 }
262 return 0;
263}
264
265static int
266boot_validate_slot(int slot)
267{
268 const struct flash_area *fap;
269 struct image_header *hdr;
270 int rc;
271
272 hdr = boot_img_hdr(&boot_data, slot);
273 if (hdr->ih_magic == 0xffffffff || hdr->ih_flags & IMAGE_F_NON_BOOTABLE) {
274 /* No bootable image in slot; continue booting from slot 0. */
275 return -1;
276 }
277
278 rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
279 if (rc != 0) {
280 return BOOT_EFLASH;
281 }
282
Tamas Bana9de4a62018-09-18 08:09:45 +0100283 if ((hdr->ih_magic != IMAGE_MAGIC ||
Tamas Ban0e8ab302019-01-17 11:45:31 +0000284 boot_image_check(hdr, fap) != 0)) {
Tamas Ban4fb8e9d2018-02-23 14:22:03 +0000285 if (slot != 0) {
David Vincze26e8c8a2018-08-28 16:59:41 +0200286 rc = flash_area_erase(fap, 0, fap->fa_size);
287 if(rc != 0) {
288 flash_area_close(fap);
289 return BOOT_EFLASH;
290 }
Tamas Ban4fb8e9d2018-02-23 14:22:03 +0000291 /* Image in slot 1 is invalid. Erase the image and
292 * continue booting from slot 0.
293 */
294 }
295 BOOT_LOG_ERR("Authentication failed! Image in slot %d is not valid.",
296 slot);
297 return -1;
298 }
299
300 flash_area_close(fap);
301
302 /* Image in slot 1 is valid. */
303 return 0;
304}
305
Oliver Swedef9982442018-08-24 18:37:44 +0100306#if !defined(MCUBOOT_NO_SWAP) && !defined(MCUBOOT_OVERWRITE_ONLY)
307/*
308 * Compute the total size of the given image. Includes the size of
309 * the TLVs.
310 */
311static int
312boot_read_image_size(int slot, struct image_header *hdr, uint32_t *size)
313{
314 const struct flash_area *fap = NULL;
315 struct image_tlv_info info;
316 int area_id;
317 int rc;
318
319 area_id = flash_area_id_from_image_slot(slot);
320 rc = flash_area_open(area_id, &fap);
321 if (rc != 0) {
322 rc = BOOT_EFLASH;
323 goto done;
324 }
325
326 rc = flash_area_read(fap, hdr->ih_hdr_size + hdr->ih_img_size,
327 &info, sizeof(info));
328 if (rc != 0) {
329 rc = BOOT_EFLASH;
330 goto done;
331 }
332 if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
333 rc = BOOT_EBADIMAGE;
334 goto done;
335 }
336 *size = hdr->ih_hdr_size + hdr->ih_img_size + info.it_tlv_tot;
337 rc = 0;
338
339done:
340 flash_area_close(fap);
341 return rc;
342}
343#endif /* !MCUBOOT_NO_SWAP && !MCUBOOT_OVERWRITE_ONLY */
344
345#if !defined(MCUBOOT_NO_SWAP) && !defined(MCUBOOT_RAM_LOADING)
Tamas Banf70ef8c2017-12-19 15:35:09 +0000346/**
Tamas Ban581034a2017-12-19 19:54:37 +0000347 * Determines where in flash the most recent boot status is stored. The boot
Tamas Banf70ef8c2017-12-19 15:35:09 +0000348 * status is necessary for completing a swap that was interrupted by a boot
349 * loader reset.
350 *
Tamas Ban581034a2017-12-19 19:54:37 +0000351 * @return BOOT_STATUS_SOURCE_[...] code indicating where
352 * status should be read from.
Tamas Banf70ef8c2017-12-19 15:35:09 +0000353 */
354static int
355boot_status_source(void)
356{
357 const struct boot_status_table *table;
358 struct boot_swap_state state_scratch;
359 struct boot_swap_state state_slot0;
360 int rc;
361 int i;
362 uint8_t source;
363
364 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &state_slot0);
365 assert(rc == 0);
366
367 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH, &state_scratch);
368 assert(rc == 0);
369
370 BOOT_LOG_SWAP_STATE("Image 0", &state_slot0);
371 BOOT_LOG_SWAP_STATE("Scratch", &state_scratch);
372
373 for (i = 0; i < BOOT_STATUS_TABLES_COUNT; i++) {
374 table = &boot_status_tables[i];
375
376 if ((table->bst_magic_slot0 == 0 ||
377 table->bst_magic_slot0 == state_slot0.magic) &&
378 (table->bst_magic_scratch == 0 ||
379 table->bst_magic_scratch == state_scratch.magic) &&
380 (table->bst_copy_done_slot0 == 0 ||
381 table->bst_copy_done_slot0 == state_slot0.copy_done)) {
382 source = table->bst_status_source;
383 BOOT_LOG_INF("Boot source: %s",
384 source == BOOT_STATUS_SOURCE_NONE ? "none" :
385 source == BOOT_STATUS_SOURCE_SCRATCH ? "scratch" :
386 source == BOOT_STATUS_SOURCE_SLOT0 ? "slot 0" :
387 "BUG; can't happen");
388 return source;
389 }
390 }
391
392 BOOT_LOG_INF("Boot source: none");
393 return BOOT_STATUS_SOURCE_NONE;
394}
395
396/**
397 * Calculates the type of swap that just completed.
398 *
399 * This is used when a swap is interrupted by an external event. After
400 * finishing the swap operation determines what the initial request was.
401 */
402static int
403boot_previous_swap_type(void)
404{
405 int post_swap_type;
406
407 post_swap_type = boot_swap_type();
408
409 switch (post_swap_type) {
Tamas Ban581034a2017-12-19 19:54:37 +0000410 case BOOT_SWAP_TYPE_NONE: return BOOT_SWAP_TYPE_PERM;
411 case BOOT_SWAP_TYPE_REVERT: return BOOT_SWAP_TYPE_TEST;
412 case BOOT_SWAP_TYPE_PANIC: return BOOT_SWAP_TYPE_PANIC;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000413 }
414
415 return BOOT_SWAP_TYPE_FAIL;
416}
417
Tamas Banf70ef8c2017-12-19 15:35:09 +0000418static int
Tamas Banf70ef8c2017-12-19 15:35:09 +0000419boot_slots_compatible(void)
420{
421 size_t num_sectors_0 = boot_img_num_sectors(&boot_data, 0);
422 size_t num_sectors_1 = boot_img_num_sectors(&boot_data, 1);
423 size_t size_0, size_1;
424 size_t i;
425
426 /* Ensure both image slots have identical sector layouts. */
427 if (num_sectors_0 != num_sectors_1) {
428 return 0;
429 }
430 for (i = 0; i < num_sectors_0; i++) {
431 size_0 = boot_img_sector_size(&boot_data, 0, i);
432 size_1 = boot_img_sector_size(&boot_data, 1, i);
433 if (size_0 != size_1) {
434 return 0;
435 }
436 }
437
438 return 1;
439}
440
Tamas Banf70ef8c2017-12-19 15:35:09 +0000441
442static uint32_t
443boot_status_internal_off(int idx, int state, int elem_sz)
444{
445 int idx_sz;
446
447 idx_sz = elem_sz * BOOT_STATUS_STATE_COUNT;
448
449 return idx * idx_sz + state * elem_sz;
450}
451
452/**
453 * Reads the status of a partially-completed swap, if any. This is necessary
454 * to recover in case the boot lodaer was reset in the middle of a swap
455 * operation.
456 */
457static int
458boot_read_status_bytes(const struct flash_area *fap, struct boot_status *bs)
459{
460 uint32_t off;
461 uint8_t status;
462 int max_entries;
463 int found;
464 int rc;
465 int i;
466
467 off = boot_status_off(fap);
468 max_entries = boot_status_entries(fap);
469
470 found = 0;
471 for (i = 0; i < max_entries; i++) {
472 rc = flash_area_read(fap, off + i * BOOT_WRITE_SZ(&boot_data),
473 &status, 1);
474 if (rc != 0) {
475 return BOOT_EFLASH;
476 }
477
478 if (status == 0xff) {
479 if (found) {
480 break;
481 }
482 } else if (!found) {
483 found = 1;
484 }
485 }
486
487 if (found) {
488 i--;
489 bs->idx = i / BOOT_STATUS_STATE_COUNT;
490 bs->state = i % BOOT_STATUS_STATE_COUNT;
491 }
492
493 return 0;
494}
495
496/**
497 * Reads the boot status from the flash. The boot status contains
498 * the current state of an interrupted image copy operation. If the boot
499 * status is not present, or it indicates that previous copy finished,
500 * there is no operation in progress.
501 */
502static int
503boot_read_status(struct boot_status *bs)
504{
505 const struct flash_area *fap;
506 int status_loc;
507 int area_id;
508 int rc;
509
Tamas Ban581034a2017-12-19 19:54:37 +0000510 memset(bs, 0, sizeof(*bs));
Tamas Banf70ef8c2017-12-19 15:35:09 +0000511
512 status_loc = boot_status_source();
513 switch (status_loc) {
514 case BOOT_STATUS_SOURCE_NONE:
515 return 0;
516
517 case BOOT_STATUS_SOURCE_SCRATCH:
518 area_id = FLASH_AREA_IMAGE_SCRATCH;
519 break;
520
521 case BOOT_STATUS_SOURCE_SLOT0:
522 area_id = FLASH_AREA_IMAGE_0;
523 break;
524
525 default:
526 assert(0);
527 return BOOT_EBADARGS;
528 }
529
530 rc = flash_area_open(area_id, &fap);
531 if (rc != 0) {
532 return BOOT_EFLASH;
533 }
534
535 rc = boot_read_status_bytes(fap, bs);
536
537 flash_area_close(fap);
538 return rc;
539}
540
541/**
542 * Writes the supplied boot status to the flash file system. The boot status
543 * contains the current state of an in-progress image copy operation.
544 *
545 * @param bs The boot status to write.
546 *
547 * @return 0 on success; nonzero on failure.
548 */
549int
550boot_write_status(struct boot_status *bs)
551{
Tamas Ban581034a2017-12-19 19:54:37 +0000552 const struct flash_area *fap = NULL;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000553 uint32_t off;
554 int area_id;
555 int rc;
556 uint8_t buf[BOOT_MAX_ALIGN];
557 uint8_t align;
558
559 /* NOTE: The first sector copied (that is the last sector on slot) contains
560 * the trailer. Since in the last step SLOT 0 is erased, the first
561 * two status writes go to the scratch which will be copied to SLOT 0!
562 */
563
564 if (bs->use_scratch) {
565 /* Write to scratch. */
566 area_id = FLASH_AREA_IMAGE_SCRATCH;
567 } else {
568 /* Write to slot 0. */
569 area_id = FLASH_AREA_IMAGE_0;
570 }
571
572 rc = flash_area_open(area_id, &fap);
573 if (rc != 0) {
574 rc = BOOT_EFLASH;
575 goto done;
576 }
577
578 off = boot_status_off(fap) +
579 boot_status_internal_off(bs->idx, bs->state,
580 BOOT_WRITE_SZ(&boot_data));
581
Tamas Banc3828852018-02-01 12:24:16 +0000582 align = flash_area_align(fap);
Tamas Banf70ef8c2017-12-19 15:35:09 +0000583 memset(buf, 0xFF, BOOT_MAX_ALIGN);
584 buf[0] = bs->state;
585
586 rc = flash_area_write(fap, off, buf, align);
587 if (rc != 0) {
588 rc = BOOT_EFLASH;
589 goto done;
590 }
591
592 rc = 0;
593
594done:
595 flash_area_close(fap);
596 return rc;
597}
598
Tamas Banf70ef8c2017-12-19 15:35:09 +0000599/**
600 * Determines which swap operation to perform, if any. If it is determined
601 * that a swap operation is required, the image in the second slot is checked
602 * for validity. If the image in the second slot is invalid, it is erased, and
603 * a swap type of "none" is indicated.
604 *
605 * @return The type of swap to perform (BOOT_SWAP_TYPE...)
606 */
607static int
608boot_validated_swap_type(void)
609{
610 int swap_type;
611
612 swap_type = boot_swap_type();
613 switch (swap_type) {
614 case BOOT_SWAP_TYPE_TEST:
615 case BOOT_SWAP_TYPE_PERM:
616 case BOOT_SWAP_TYPE_REVERT:
617 /* Boot loader wants to switch to slot 1. Ensure image is valid. */
618 if (boot_validate_slot(1) != 0) {
619 swap_type = BOOT_SWAP_TYPE_FAIL;
620 }
621 }
622
623 return swap_type;
624}
625
626/**
627 * Calculates the number of sectors the scratch area can contain. A "last"
628 * source sector is specified because images are copied backwards in flash
629 * (final index to index number 0).
630 *
631 * @param last_sector_idx The index of the last source sector
632 * (inclusive).
633 * @param out_first_sector_idx The index of the first source sector
634 * (inclusive) gets written here.
635 *
636 * @return The number of bytes comprised by the
637 * [first-sector, last-sector] range.
638 */
639#ifndef MCUBOOT_OVERWRITE_ONLY
640static uint32_t
641boot_copy_sz(int last_sector_idx, int *out_first_sector_idx)
642{
643 size_t scratch_sz;
644 uint32_t new_sz;
645 uint32_t sz;
646 int i;
647
648 sz = 0;
649
650 scratch_sz = boot_scratch_area_size(&boot_data);
651 for (i = last_sector_idx; i >= 0; i--) {
652 new_sz = sz + boot_img_sector_size(&boot_data, 0, i);
653 if (new_sz > scratch_sz) {
654 break;
655 }
656 sz = new_sz;
657 }
658
659 /* i currently refers to a sector that doesn't fit or it is -1 because all
660 * sectors have been processed. In both cases, exclude sector i.
661 */
662 *out_first_sector_idx = i + 1;
663 return sz;
664}
665#endif /* !MCUBOOT_OVERWRITE_ONLY */
666
667/**
David Vinczef7641fa2018-09-04 18:29:46 +0200668 * Erases a region of flash.
669 *
670 * @param flash_area_idx The ID of the flash area containing the region
671 * to erase.
672 * @param off The offset within the flash area to start the
673 * erase.
674 * @param sz The number of bytes to erase.
675 *
676 * @return 0 on success; nonzero on failure.
677 */
678static int
679boot_erase_sector(int flash_area_id, uint32_t off, uint32_t sz)
680{
681 const struct flash_area *fap = NULL;
682 int rc;
683
684 rc = flash_area_open(flash_area_id, &fap);
685 if (rc != 0) {
686 rc = BOOT_EFLASH;
687 goto done;
688 }
689
690 rc = flash_area_erase(fap, off, sz);
691 if (rc != 0) {
692 rc = BOOT_EFLASH;
693 goto done;
694 }
695
696 rc = 0;
697
698done:
699 flash_area_close(fap);
700 return rc;
701}
702
703/**
Tamas Banf70ef8c2017-12-19 15:35:09 +0000704 * Copies the contents of one flash region to another. You must erase the
705 * destination region prior to calling this function.
706 *
707 * @param flash_area_id_src The ID of the source flash area.
708 * @param flash_area_id_dst The ID of the destination flash area.
709 * @param off_src The offset within the source flash area to
710 * copy from.
711 * @param off_dst The offset within the destination flash area to
712 * copy to.
713 * @param sz The number of bytes to copy.
714 *
715 * @return 0 on success; nonzero on failure.
716 */
717static int
718boot_copy_sector(int flash_area_id_src, int flash_area_id_dst,
719 uint32_t off_src, uint32_t off_dst, uint32_t sz)
720{
721 const struct flash_area *fap_src;
722 const struct flash_area *fap_dst;
723 uint32_t bytes_copied;
724 int chunk_sz;
725 int rc;
726
727 static uint8_t buf[1024];
728
729 fap_src = NULL;
730 fap_dst = NULL;
731
732 rc = flash_area_open(flash_area_id_src, &fap_src);
733 if (rc != 0) {
734 rc = BOOT_EFLASH;
735 goto done;
736 }
737
738 rc = flash_area_open(flash_area_id_dst, &fap_dst);
739 if (rc != 0) {
740 rc = BOOT_EFLASH;
741 goto done;
742 }
743
744 bytes_copied = 0;
745 while (bytes_copied < sz) {
Tamas Ban581034a2017-12-19 19:54:37 +0000746 if (sz - bytes_copied > sizeof(buf)) {
747 chunk_sz = sizeof(buf);
Tamas Banf70ef8c2017-12-19 15:35:09 +0000748 } else {
749 chunk_sz = sz - bytes_copied;
750 }
751
752 rc = flash_area_read(fap_src, off_src + bytes_copied, buf, chunk_sz);
753 if (rc != 0) {
754 rc = BOOT_EFLASH;
755 goto done;
756 }
757
758 rc = flash_area_write(fap_dst, off_dst + bytes_copied, buf, chunk_sz);
759 if (rc != 0) {
760 rc = BOOT_EFLASH;
761 goto done;
762 }
763
764 bytes_copied += chunk_sz;
765 }
766
767 rc = 0;
768
769done:
770 if (fap_src) {
771 flash_area_close(fap_src);
772 }
773 if (fap_dst) {
774 flash_area_close(fap_dst);
775 }
776 return rc;
777}
778
779#ifndef MCUBOOT_OVERWRITE_ONLY
780static inline int
781boot_status_init_by_id(int flash_area_id, const struct boot_status *bs)
782{
783 const struct flash_area *fap;
784 struct boot_swap_state swap_state;
785 int rc;
786
787 rc = flash_area_open(flash_area_id, &fap);
788 assert(rc == 0);
789
790 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &swap_state);
791 assert(rc == 0);
792
793 if (swap_state.image_ok == BOOT_FLAG_SET) {
794 rc = boot_write_image_ok(fap);
795 assert(rc == 0);
796 }
797
798 rc = boot_write_swap_size(fap, bs->swap_size);
799 assert(rc == 0);
800
801 rc = boot_write_magic(fap);
802 assert(rc == 0);
803
804 flash_area_close(fap);
805
806 return 0;
807}
David Vinczef7641fa2018-09-04 18:29:46 +0200808
809static int
810boot_erase_last_sector_by_id(int flash_area_id)
811{
812 uint8_t slot;
813 uint32_t last_sector;
814 int rc;
815
816 switch (flash_area_id) {
817 case FLASH_AREA_IMAGE_0:
818 slot = 0;
819 break;
820 case FLASH_AREA_IMAGE_1:
821 slot = 1;
822 break;
823 default:
824 return BOOT_EFLASH;
825 }
826
827 last_sector = boot_img_num_sectors(&boot_data, slot) - 1;
828 rc = boot_erase_sector(flash_area_id,
829 boot_img_sector_off(&boot_data, slot, last_sector),
830 boot_img_sector_size(&boot_data, slot, last_sector));
831 assert(rc == 0);
832
833 return rc;
834}
835#endif /* !MCUBOOT_OVERWRITE_ONLY */
Tamas Banf70ef8c2017-12-19 15:35:09 +0000836
Tamas Banf70ef8c2017-12-19 15:35:09 +0000837/**
838 * Swaps the contents of two flash regions within the two image slots.
839 *
840 * @param idx The index of the first sector in the range of
841 * sectors being swapped.
842 * @param sz The number of bytes to swap.
843 * @param bs The current boot status. This struct gets
844 * updated according to the outcome.
845 *
846 * @return 0 on success; nonzero on failure.
847 */
848#ifndef MCUBOOT_OVERWRITE_ONLY
849static void
850boot_swap_sectors(int idx, uint32_t sz, struct boot_status *bs)
851{
852 const struct flash_area *fap;
853 uint32_t copy_sz;
854 uint32_t trailer_sz;
855 uint32_t img_off;
856 uint32_t scratch_trailer_off;
857 struct boot_swap_state swap_state;
858 size_t last_sector;
859 int rc;
860
861 /* Calculate offset from start of image area. */
862 img_off = boot_img_sector_off(&boot_data, 0, idx);
863
864 copy_sz = sz;
865 trailer_sz = boot_slots_trailer_sz(BOOT_WRITE_SZ(&boot_data));
866
867 /* sz in this function is always is always sized on a multiple of the
868 * sector size. The check against the start offset of the last sector
869 * is to determine if we're swapping the last sector. The last sector
870 * needs special handling because it's where the trailer lives. If we're
871 * copying it, we need to use scratch to write the trailer temporarily.
872 *
873 * NOTE: `use_scratch` is a temporary flag (never written to flash) which
874 * controls if special handling is needed (swapping last sector).
875 */
876 last_sector = boot_img_num_sectors(&boot_data, 0) - 1;
877 if (img_off + sz > boot_img_sector_off(&boot_data, 0, last_sector)) {
878 copy_sz -= trailer_sz;
879 }
880
881 bs->use_scratch = (bs->idx == 0 && copy_sz != sz);
882
883 if (bs->state == 0) {
884 rc = boot_erase_sector(FLASH_AREA_IMAGE_SCRATCH, 0, sz);
885 assert(rc == 0);
886
887 rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_SCRATCH,
888 img_off, 0, copy_sz);
889 assert(rc == 0);
890
891 if (bs->idx == 0) {
892 if (bs->use_scratch) {
893 boot_status_init_by_id(FLASH_AREA_IMAGE_SCRATCH, bs);
894 } else {
895 /* Prepare the status area... here it is known that the
896 * last sector is not being used by the image data so it's
897 * safe to erase.
898 */
899 rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_0);
900 assert(rc == 0);
901
902 boot_status_init_by_id(FLASH_AREA_IMAGE_0, bs);
903 }
904 }
905
906 bs->state = 1;
907 rc = boot_write_status(bs);
908 assert(rc == 0);
909 }
910
911 if (bs->state == 1) {
912 rc = boot_erase_sector(FLASH_AREA_IMAGE_1, img_off, sz);
913 assert(rc == 0);
914
915 rc = boot_copy_sector(FLASH_AREA_IMAGE_0, FLASH_AREA_IMAGE_1,
916 img_off, img_off, copy_sz);
917 assert(rc == 0);
918
919 if (bs->idx == 0 && !bs->use_scratch) {
920 /* If not all sectors of the slot are being swapped,
921 * guarantee here that only slot0 will have the state.
922 */
923 rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_1);
924 assert(rc == 0);
925 }
926
927 bs->state = 2;
928 rc = boot_write_status(bs);
929 assert(rc == 0);
930 }
931
932 if (bs->state == 2) {
933 rc = boot_erase_sector(FLASH_AREA_IMAGE_0, img_off, sz);
934 assert(rc == 0);
935
936 /* NOTE: also copy trailer from scratch (has status info) */
937 rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
938 0, img_off, copy_sz);
939 assert(rc == 0);
940
941 if (bs->use_scratch) {
942 rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
943 assert(rc == 0);
944
945 scratch_trailer_off = boot_status_off(fap);
946
947 flash_area_close(fap);
948
949 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
950 assert(rc == 0);
951
952 /* copy current status that is being maintained in scratch */
953 rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
954 scratch_trailer_off,
955 img_off + copy_sz,
956 BOOT_STATUS_STATE_COUNT * BOOT_WRITE_SZ(&boot_data));
957 assert(rc == 0);
958
959 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH,
960 &swap_state);
961 assert(rc == 0);
962
963 if (swap_state.image_ok == BOOT_FLAG_SET) {
964 rc = boot_write_image_ok(fap);
965 assert(rc == 0);
966 }
967
968 rc = boot_write_swap_size(fap, bs->swap_size);
969 assert(rc == 0);
970
971 rc = boot_write_magic(fap);
972 assert(rc == 0);
973
974 flash_area_close(fap);
975 }
976
977 bs->idx++;
978 bs->state = 0;
979 bs->use_scratch = 0;
980 rc = boot_write_status(bs);
981 assert(rc == 0);
982 }
983}
984#endif /* !MCUBOOT_OVERWRITE_ONLY */
985
986/**
987 * Swaps the two images in flash. If a prior copy operation was interrupted
988 * by a system reset, this function completes that operation.
989 *
990 * @param bs The current boot status. This function reads
991 * this struct to determine if it is resuming
992 * an interrupted swap operation. This
993 * function writes the updated status to this
994 * function on return.
995 *
996 * @return 0 on success; nonzero on failure.
997 */
998#ifdef MCUBOOT_OVERWRITE_ONLY
999static int
1000boot_copy_image(struct boot_status *bs)
1001{
1002 size_t sect_count;
1003 size_t sect;
1004 int rc;
1005 size_t size = 0;
1006 size_t this_size;
1007
1008 BOOT_LOG_INF("Image upgrade slot1 -> slot0");
1009 BOOT_LOG_INF("Erasing slot0");
1010
1011 sect_count = boot_img_num_sectors(&boot_data, 0);
1012 for (sect = 0; sect < sect_count; sect++) {
1013 this_size = boot_img_sector_size(&boot_data, 0, sect);
1014 rc = boot_erase_sector(FLASH_AREA_IMAGE_0,
1015 size,
1016 this_size);
1017 assert(rc == 0);
1018
1019 size += this_size;
1020 }
1021
1022 BOOT_LOG_INF("Copying slot 1 to slot 0: 0x%lx bytes", size);
1023 rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_0,
1024 0, 0, size);
1025
1026 /* Erase slot 1 so that we don't do the upgrade on every boot.
1027 * TODO: Perhaps verify slot 0's signature again? */
1028 rc = boot_erase_sector(FLASH_AREA_IMAGE_1,
1029 0, boot_img_sector_size(&boot_data, 1, 0));
1030 assert(rc == 0);
1031
1032 return 0;
1033}
1034#else
1035static int
1036boot_copy_image(struct boot_status *bs)
1037{
1038 uint32_t sz;
1039 int first_sector_idx;
1040 int last_sector_idx;
1041 int swap_idx;
1042 struct image_header *hdr;
1043 uint32_t size;
1044 uint32_t copy_size;
1045 int rc;
1046
1047 /* FIXME: just do this if asked by user? */
1048
1049 size = copy_size = 0;
1050
1051 if (bs->idx == 0 && bs->state == 0) {
1052 /*
1053 * No swap ever happened, so need to find the largest image which
1054 * will be used to determine the amount of sectors to swap.
1055 */
1056 hdr = boot_img_hdr(&boot_data, 0);
1057 if (hdr->ih_magic == IMAGE_MAGIC) {
1058 rc = boot_read_image_size(0, hdr, &copy_size);
1059 assert(rc == 0);
1060 }
1061
1062 hdr = boot_img_hdr(&boot_data, 1);
1063 if (hdr->ih_magic == IMAGE_MAGIC) {
1064 rc = boot_read_image_size(1, hdr, &size);
1065 assert(rc == 0);
1066 }
1067
1068 if (size > copy_size) {
1069 copy_size = size;
1070 }
1071
1072 bs->swap_size = copy_size;
1073 } else {
1074 /*
1075 * If a swap was under way, the swap_size should already be present
1076 * in the trailer...
1077 */
1078 rc = boot_read_swap_size(&bs->swap_size);
1079 assert(rc == 0);
1080
1081 copy_size = bs->swap_size;
1082 }
1083
1084 size = 0;
1085 last_sector_idx = 0;
1086 while (1) {
1087 size += boot_img_sector_size(&boot_data, 0, last_sector_idx);
1088 if (size >= copy_size) {
1089 break;
1090 }
1091 last_sector_idx++;
1092 }
1093
1094 swap_idx = 0;
1095 while (last_sector_idx >= 0) {
1096 sz = boot_copy_sz(last_sector_idx, &first_sector_idx);
1097 if (swap_idx >= bs->idx) {
1098 boot_swap_sectors(first_sector_idx, sz, bs);
1099 }
1100
1101 last_sector_idx = first_sector_idx - 1;
1102 swap_idx++;
1103 }
1104
1105 return 0;
1106}
1107#endif
1108
1109/**
1110 * Marks the image in slot 0 as fully copied.
1111 */
1112#ifndef MCUBOOT_OVERWRITE_ONLY
1113static int
1114boot_set_copy_done(void)
1115{
1116 const struct flash_area *fap;
1117 int rc;
1118
1119 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
1120 if (rc != 0) {
1121 return BOOT_EFLASH;
1122 }
1123
1124 rc = boot_write_copy_done(fap);
1125 flash_area_close(fap);
1126 return rc;
1127}
1128#endif /* !MCUBOOT_OVERWRITE_ONLY */
1129
1130/**
1131 * Marks a reverted image in slot 0 as confirmed. This is necessary to ensure
1132 * the status bytes from the image revert operation don't get processed on a
1133 * subsequent boot.
1134 *
1135 * NOTE: image_ok is tested before writing because if there's a valid permanent
1136 * image installed on slot0 and the new image to be upgrade to has a bad sig,
1137 * image_ok would be overwritten.
1138 */
1139#ifndef MCUBOOT_OVERWRITE_ONLY
1140static int
1141boot_set_image_ok(void)
1142{
1143 const struct flash_area *fap;
1144 struct boot_swap_state state;
1145 int rc;
1146
1147 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
1148 if (rc != 0) {
1149 return BOOT_EFLASH;
1150 }
1151
1152 rc = boot_read_swap_state(fap, &state);
1153 if (rc != 0) {
1154 rc = BOOT_EFLASH;
1155 goto out;
1156 }
1157
1158 if (state.image_ok == BOOT_FLAG_UNSET) {
1159 rc = boot_write_image_ok(fap);
1160 }
1161
1162out:
1163 flash_area_close(fap);
1164 return rc;
1165}
1166#endif /* !MCUBOOT_OVERWRITE_ONLY */
1167
1168/**
1169 * Performs an image swap if one is required.
1170 *
1171 * @param out_swap_type On success, the type of swap performed gets
1172 * written here.
1173 *
1174 * @return 0 on success; nonzero on failure.
1175 */
1176static int
1177boot_swap_if_needed(int *out_swap_type)
1178{
1179 struct boot_status bs;
1180 int swap_type;
1181 int rc;
1182
1183 /* Determine if we rebooted in the middle of an image swap
1184 * operation.
1185 */
1186 rc = boot_read_status(&bs);
1187 assert(rc == 0);
1188 if (rc != 0) {
1189 return rc;
1190 }
1191
1192 /* If a partial swap was detected, complete it. */
1193 if (bs.idx != 0 || bs.state != 0) {
1194 rc = boot_copy_image(&bs);
1195 assert(rc == 0);
1196
1197 /* NOTE: here we have finished a swap resume. The initial request
1198 * was either a TEST or PERM swap, which now after the completed
1199 * swap will be determined to be respectively REVERT (was TEST)
1200 * or NONE (was PERM).
1201 */
1202
1203 /* Extrapolate the type of the partial swap. We need this
1204 * information to know how to mark the swap complete in flash.
1205 */
1206 swap_type = boot_previous_swap_type();
1207 } else {
1208 swap_type = boot_validated_swap_type();
1209 switch (swap_type) {
1210 case BOOT_SWAP_TYPE_TEST:
1211 case BOOT_SWAP_TYPE_PERM:
1212 case BOOT_SWAP_TYPE_REVERT:
1213 rc = boot_copy_image(&bs);
1214 assert(rc == 0);
1215 break;
1216 }
1217 }
1218
1219 *out_swap_type = swap_type;
1220 return 0;
1221}
1222
1223/**
1224 * Prepares the booting process. This function moves images around in flash as
1225 * appropriate, and tells you what address to boot from.
1226 *
1227 * @param rsp On success, indicates how booting should occur.
1228 *
1229 * @return 0 on success; nonzero on failure.
1230 */
1231int
1232boot_go(struct boot_rsp *rsp)
1233{
1234 int swap_type;
1235 size_t slot;
1236 int rc;
1237 int fa_id;
1238 bool reload_headers = false;
1239
1240 /* The array of slot sectors are defined here (as opposed to file scope) so
1241 * that they don't get allocated for non-boot-loader apps. This is
1242 * necessary because the gcc option "-fdata-sections" doesn't seem to have
1243 * any effect in older gcc versions (e.g., 4.8.4).
1244 */
1245 static boot_sector_t slot0_sectors[BOOT_MAX_IMG_SECTORS];
1246 static boot_sector_t slot1_sectors[BOOT_MAX_IMG_SECTORS];
Tamas Ban581034a2017-12-19 19:54:37 +00001247
Tamas Banf70ef8c2017-12-19 15:35:09 +00001248 boot_data.imgs[0].sectors = slot0_sectors;
1249 boot_data.imgs[1].sectors = slot1_sectors;
1250
1251 /* Open boot_data image areas for the duration of this call. */
1252 for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
1253 fa_id = flash_area_id_from_image_slot(slot);
1254 rc = flash_area_open(fa_id, &BOOT_IMG_AREA(&boot_data, slot));
1255 assert(rc == 0);
1256 }
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001257
Tamas Banf70ef8c2017-12-19 15:35:09 +00001258 rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH,
1259 &BOOT_SCRATCH_AREA(&boot_data));
1260 assert(rc == 0);
1261
1262 /* Determine the sector layout of the image slots and scratch area. */
1263 rc = boot_read_sectors();
1264 if (rc != 0) {
1265 goto out;
1266 }
1267
1268 /* Attempt to read an image header from each slot. */
1269 rc = boot_read_image_headers();
1270 if (rc != 0) {
1271 goto out;
1272 }
1273
1274 /* If the image slots aren't compatible, no swap is possible. Just boot
1275 * into slot 0.
1276 */
1277 if (boot_slots_compatible()) {
1278 rc = boot_swap_if_needed(&swap_type);
1279 assert(rc == 0);
1280 if (rc != 0) {
1281 goto out;
1282 }
1283
1284 /*
1285 * The following states need image_ok be explicitly set after the
1286 * swap was finished to avoid a new revert.
1287 */
Tamas Ban581034a2017-12-19 19:54:37 +00001288 if (swap_type == BOOT_SWAP_TYPE_REVERT ||
1289 swap_type == BOOT_SWAP_TYPE_FAIL) {
Tamas Banf70ef8c2017-12-19 15:35:09 +00001290#ifndef MCUBOOT_OVERWRITE_ONLY
1291 rc = boot_set_image_ok();
1292 if (rc != 0) {
1293 swap_type = BOOT_SWAP_TYPE_PANIC;
1294 }
1295#endif /* !MCUBOOT_OVERWRITE_ONLY */
1296 }
1297 } else {
1298 swap_type = BOOT_SWAP_TYPE_NONE;
1299 }
1300
1301 switch (swap_type) {
1302 case BOOT_SWAP_TYPE_NONE:
1303 slot = 0;
1304 break;
1305
1306 case BOOT_SWAP_TYPE_TEST: /* fallthrough */
1307 case BOOT_SWAP_TYPE_PERM: /* fallthrough */
1308 case BOOT_SWAP_TYPE_REVERT:
1309 slot = 1;
1310 reload_headers = true;
1311#ifndef MCUBOOT_OVERWRITE_ONLY
1312 rc = boot_set_copy_done();
1313 if (rc != 0) {
1314 swap_type = BOOT_SWAP_TYPE_PANIC;
1315 }
1316#endif /* !MCUBOOT_OVERWRITE_ONLY */
1317 break;
1318
1319 case BOOT_SWAP_TYPE_FAIL:
1320 /* The image in slot 1 was invalid and is now erased. Ensure we don't
1321 * try to boot into it again on the next reboot. Do this by pretending
1322 * we just reverted back to slot 0.
1323 */
1324 slot = 0;
1325 reload_headers = true;
1326 break;
1327
1328 default:
1329 swap_type = BOOT_SWAP_TYPE_PANIC;
1330 }
1331
1332 if (swap_type == BOOT_SWAP_TYPE_PANIC) {
1333 BOOT_LOG_ERR("panic!");
1334 assert(0);
1335
1336 /* Loop forever... */
Tamas Ban581034a2017-12-19 19:54:37 +00001337 while (1)
1338 ;
Tamas Banf70ef8c2017-12-19 15:35:09 +00001339 }
1340
1341#ifdef MCUBOOT_VALIDATE_SLOT0
1342 if (reload_headers) {
1343 rc = boot_read_image_headers();
1344 if (rc != 0) {
1345 goto out;
1346 }
1347 /* Since headers were reloaded, it can be assumed we just performed a
1348 * swap or overwrite. Now the header info that should be used to
1349 * provide the data for the bootstrap, which previously was at Slot 1,
1350 * was updated to Slot 0.
1351 */
1352 slot = 0;
1353 }
1354
1355 rc = boot_validate_slot(0);
1356 assert(rc == 0);
1357 if (rc != 0) {
1358 rc = BOOT_EBADIMAGE;
1359 goto out;
1360 }
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001361#else /* MCUBOOT_VALIDATE_SLOT0 */
Tamas Banf70ef8c2017-12-19 15:35:09 +00001362 (void)reload_headers;
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001363#endif /* MCUBOOT_VALIDATE_SLOT0 */
Tamas Banf70ef8c2017-12-19 15:35:09 +00001364
1365 /* Always boot from the primary slot. */
1366 rsp->br_flash_dev_id = boot_img_fa_device_id(&boot_data, 0);
1367 rsp->br_image_off = boot_img_slot_off(&boot_data, 0);
1368 rsp->br_hdr = boot_img_hdr(&boot_data, slot);
1369
Tamas Ban0e8ab302019-01-17 11:45:31 +00001370 /* Save boot status to shared memory area */
1371 rc = boot_save_boot_status(SW_S_NS,
1372 rsp->br_hdr,
1373 BOOT_IMG_AREA(&boot_data, slot));
1374 if (rc) {
1375 BOOT_LOG_ERR("Failed to add data to shared area");
1376 }
1377
Tamas Banf70ef8c2017-12-19 15:35:09 +00001378 out:
1379 flash_area_close(BOOT_SCRATCH_AREA(&boot_data));
1380 for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
1381 flash_area_close(BOOT_IMG_AREA(&boot_data, BOOT_NUM_SLOTS - 1 - slot));
1382 }
1383 return rc;
1384}
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001385
Oliver Swedef9982442018-08-24 18:37:44 +01001386#else /* MCUBOOT_NO_SWAP || MCUBOOT_RAM_LOADING */
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001387
1388#define BOOT_LOG_IMAGE_INFO(area, hdr, state) \
1389 BOOT_LOG_INF("Image %"PRIu32": version=%"PRIu8".%"PRIu8".%"PRIu16"" \
1390 ".%"PRIu32", magic=%5s, image_ok=0x%x", \
1391 (area), \
1392 (hdr)->ih_ver.iv_major, \
1393 (hdr)->ih_ver.iv_minor, \
1394 (hdr)->ih_ver.iv_revision, \
1395 (hdr)->ih_ver.iv_build_num, \
1396 ((state)->magic == BOOT_MAGIC_GOOD ? "good" : \
1397 (state)->magic == BOOT_MAGIC_UNSET ? "unset" : \
1398 "bad"), \
1399 (state)->image_ok)
1400
1401struct image_slot_version {
1402 uint64_t version;
1403 uint32_t slot_number;
1404};
1405
1406/**
1407 * Extract the version number from the image header. This function must be
1408 * ported if version number format has changed in the image header.
1409 *
1410 * @param hdr Pointer to an image header structure
1411 *
Oliver Swedef9982442018-08-24 18:37:44 +01001412 * @return Version number casted to uint64_t
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001413 */
1414static uint64_t
1415boot_get_version_number(struct image_header *hdr)
1416{
Oliver Swedef9982442018-08-24 18:37:44 +01001417 uint64_t version = 0;
1418 version |= (uint64_t)hdr->ih_ver.iv_major << (IMAGE_VER_MINOR_LENGTH
1419 + IMAGE_VER_REVISION_LENGTH
1420 + IMAGE_VER_BUILD_NUM_LENGTH);
1421 version |= (uint64_t)hdr->ih_ver.iv_minor << (IMAGE_VER_REVISION_LENGTH
1422 + IMAGE_VER_BUILD_NUM_LENGTH);
1423 version |= (uint64_t)hdr->ih_ver.iv_revision << IMAGE_VER_BUILD_NUM_LENGTH;
1424 version |= hdr->ih_ver.iv_build_num;
1425 return version;
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001426}
1427
1428/**
1429 * Comparator function for `qsort` to compare version numbers. This function
1430 * must be ported if version number format has changed in the image header.
1431 *
1432 * @param ver1 Pointer to an array element which holds the version number
1433 * @param ver2 Pointer to another array element which holds the version
1434 * number
1435 *
1436 * @return if version1 > version2 -1
1437 * if version1 == version2 0
1438 * if version1 < version2 1
1439 */
1440static int
1441boot_compare_version_numbers(const void *ver1, const void *ver2)
1442{
1443 if (((struct image_slot_version *)ver1)->version <
1444 ((struct image_slot_version *)ver2)->version) {
1445 return 1;
1446 }
1447
1448 if (((struct image_slot_version *)ver1)->version ==
1449 ((struct image_slot_version *)ver2)->version) {
1450 return 0;
1451 }
1452
1453 return -1;
1454}
1455
1456/**
1457 * Sort the available images based on the version number and puts them in
1458 * a list.
1459 *
1460 * @param boot_sequence A pointer to an array, whose aim is to carry
1461 * the boot order of candidate images.
1462 * @param slot_cnt The number of flash areas, which can contains firmware
1463 * images.
1464 *
1465 * @return The number of valid images.
1466 */
1467uint32_t
1468boot_get_boot_sequence(uint32_t *boot_sequence, uint32_t slot_cnt)
1469{
1470 struct boot_swap_state slot_state;
1471 struct image_header *hdr;
1472 struct image_slot_version image_versions[BOOT_NUM_SLOTS] = {{0}};
1473 uint32_t image_cnt = 0;
1474 uint32_t slot;
1475 int32_t rc;
1476 int32_t fa_id;
1477
1478 for (slot = 0; slot < slot_cnt; slot++) {
1479 hdr = boot_img_hdr(&boot_data, slot);
1480 fa_id = flash_area_id_from_image_slot(slot);
1481 rc = boot_read_swap_state_by_id(fa_id, &slot_state);
1482 if (rc != 0) {
1483 BOOT_LOG_ERR("Error during reading image trailer from slot:"
1484 " %"PRIu32"", slot);
1485 continue;
1486 }
1487
1488 if (hdr->ih_magic == IMAGE_MAGIC) {
1489 if (slot_state.magic == BOOT_MAGIC_GOOD ||
1490 slot_state.image_ok == 0x01) {
1491 /* Valid cases:
1492 * - Test mode: magic is OK in image trailer
1493 * - Permanent mode: image_ok flag has previously set
1494 */
1495 image_versions[slot].slot_number = slot;
1496 image_versions[slot].version = boot_get_version_number(hdr);
1497 image_cnt++;
1498 }
1499
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001500 BOOT_LOG_IMAGE_INFO(slot, hdr, &slot_state);
1501 } else {
Oliver Swedef9982442018-08-24 18:37:44 +01001502 BOOT_LOG_INF("Image %"PRIu32": No valid image", slot);
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001503 }
1504 }
1505
1506 /* Sort the images based on version number */
1507 qsort(&image_versions[0],
1508 slot_cnt,
1509 sizeof(struct image_slot_version),
1510 boot_compare_version_numbers);
1511
1512 /* Copy the calculated boot sequence to boot_sequence array */
1513 for (slot = 0; slot < slot_cnt; slot++) {
1514 boot_sequence[slot] = image_versions[slot].slot_number;
1515 }
1516
1517 return image_cnt;
1518}
1519
Oliver Swedef9982442018-08-24 18:37:44 +01001520#ifdef MCUBOOT_RAM_LOADING
1521/**
1522 * Copies an image from a slot in the flash to an SRAM address, where the load
1523 * address has already been inserted into the image header by this point and is
1524 * extracted from it within this method. The copying is done sector-by-sector.
1525 *
1526 * @param slot The flash slot of the image to be copied to SRAM.
1527 *
1528 * @param hdr Pointer to the image header structure of the image
1529 * that needs to be copid to SRAM
1530 *
1531 * @return 0 on success; nonzero on failure.
1532 */
1533static int
1534boot_copy_image_to_sram(int slot, struct image_header *hdr)
1535{
1536 int rc;
1537 uint32_t sect_sz;
1538 uint32_t sect = 0;
1539 uint32_t bytes_copied = 0;
1540 const struct flash_area *fap_src = NULL;
1541 uint32_t dst = (uint32_t) hdr->ih_load_addr;
1542 uint32_t img_sz;
1543
1544 if (dst % 4 != 0) {
1545 BOOT_LOG_INF("Cannot copy the image to the SRAM address 0x%"PRIx32" "
1546 "- the load address must be aligned with 4 bytes due to SRAM "
1547 "restrictions", dst);
1548 return BOOT_EBADARGS;
1549 }
1550
1551 rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap_src);
1552 if (rc != 0) {
1553 return BOOT_EFLASH;
1554 }
1555
1556 rc = boot_read_image_size(slot, hdr, &img_sz);
1557 if (rc != 0) {
1558 return BOOT_EFLASH;
1559 }
1560
1561 while (bytes_copied < img_sz) {
1562 sect_sz = boot_img_sector_size(&boot_data, slot, sect);
1563 /*
1564 * Direct copy from where the image sector resides in flash to its new
1565 * location in SRAM
1566 */
1567 rc = flash_area_read(fap_src,
1568 bytes_copied,
1569 (void *)(dst + bytes_copied),
1570 sect_sz);
1571 if (rc != 0) {
1572 BOOT_LOG_INF("Error whilst copying image from Flash to SRAM");
1573 break;
1574 } else {
1575 bytes_copied += sect_sz;
1576 }
1577 sect++;
1578 }
1579
1580 if (fap_src) {
1581 flash_area_close(fap_src);
1582 }
1583 return rc;
1584}
1585#endif /* MCUBOOT_RAM_LOADING */
1586
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001587/**
1588 * Prepares the booting process. This function choose the newer image in flash
1589 * as appropriate, and returns the address to boot from.
1590 *
1591 * @param rsp On success, indicates how booting should occur.
1592 *
1593 * @return 0 on success; nonzero on failure.
1594 */
1595int
1596boot_go(struct boot_rsp *rsp)
1597{
1598 size_t slot = 0;
1599 int32_t i;
1600 int rc;
1601 int fa_id;
1602 uint32_t boot_sequence[BOOT_NUM_SLOTS];
1603 uint32_t img_cnt;
Oliver Swedef9982442018-08-24 18:37:44 +01001604 struct image_header *newest_image_header;
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001605
1606 static boot_sector_t slot0_sectors[BOOT_MAX_IMG_SECTORS];
1607 static boot_sector_t slot1_sectors[BOOT_MAX_IMG_SECTORS];
1608
1609 boot_data.imgs[0].sectors = &slot0_sectors[0];
1610 boot_data.imgs[1].sectors = &slot1_sectors[0];
1611
1612 /* Open boot_data image areas for the duration of this call. */
1613 for (i = 0; i < BOOT_NUM_SLOTS; i++) {
1614 fa_id = flash_area_id_from_image_slot(i);
1615 rc = flash_area_open(fa_id, &BOOT_IMG_AREA(&boot_data, i));
1616 assert(rc == 0);
1617 }
1618
1619 /* Determine the sector layout of the image slots. */
1620 rc = boot_read_sectors();
1621 if (rc != 0) {
1622 goto out;
1623 }
1624
1625 /* Attempt to read an image header from each slot. */
1626 rc = boot_read_image_headers();
1627 if (rc != 0) {
1628 goto out;
1629 }
1630
1631 img_cnt = boot_get_boot_sequence(boot_sequence, BOOT_NUM_SLOTS);
1632 if (img_cnt) {
1633 /* Authenticate images */
1634 for (i = 0; i < img_cnt; i++) {
1635 rc = boot_validate_slot(boot_sequence[i]);
1636 if (rc == 0) {
1637 slot = boot_sequence[i];
1638 break;
1639 }
1640 }
1641 if (rc) {
1642 /* If there was no valid image at all */
1643 rc = BOOT_EBADIMAGE;
1644 goto out;
1645 }
1646
Oliver Swedef9982442018-08-24 18:37:44 +01001647 /* The slot variable now refers to the newest image's slot in flash */
1648 newest_image_header = boot_img_hdr(&boot_data, slot);
1649
1650 #ifdef MCUBOOT_RAM_LOADING
1651 if (newest_image_header->ih_flags & IMAGE_F_RAM_LOAD) {
1652 /* Copy image to the load address from where it
1653 * currently resides in flash */
1654 rc = boot_copy_image_to_sram(slot, newest_image_header);
1655 if (rc != 0) {
1656 rc = BOOT_EBADIMAGE;
1657 BOOT_LOG_INF("Could not copy image from slot 0x%"PRIx32" in "
1658 "the Flash to load address 0x%"PRIx32" in SRAM, "
1659 "aborting..",
1660 slot,
1661 newest_image_header->ih_load_addr);
1662 goto out;
1663 } else {
1664 BOOT_LOG_INF("Image has been copied from slot %d in flash to "
1665 "SRAM address 0x%"PRIx32"",
1666 slot,
1667 newest_image_header->ih_load_addr);
1668 }
1669
1670 /* Validate the image hash in SRAM after the copy was successful */
1671 rc = bootutil_check_hash_after_loading(newest_image_header);
1672 if (rc != 0) {
1673 rc = BOOT_EBADIMAGE;
1674 BOOT_LOG_INF("Cannot validate the hash of the image that was "
1675 "copied to SRAM, aborting..");
1676 goto out;
1677 }
1678
1679 BOOT_LOG_INF("Booting image from SRAM at address 0x%"PRIx32"",
1680 newest_image_header->ih_load_addr);
1681 } else {
1682 BOOT_LOG_INF("Booting image from slot %d", slot);
1683 }
1684 #endif /* MCUBOOT_RAM_LOADING */
1685
1686 rsp->br_hdr = newest_image_header;
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001687 rsp->br_image_off = boot_img_slot_off(&boot_data, slot);
Oliver Swedef9982442018-08-24 18:37:44 +01001688 rsp->br_flash_dev_id = boot_img_fa_device_id(&boot_data, slot);
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001689 } else {
1690 /* No candidate image available */
1691 rc = BOOT_EBADIMAGE;
1692 }
1693
Tamas Ban0e8ab302019-01-17 11:45:31 +00001694 /* Save boot status to shared memory area */
1695 rc = boot_save_boot_status(SW_S_NS,
1696 rsp->br_hdr,
1697 BOOT_IMG_AREA(&boot_data, slot));
1698 if (rc) {
1699 BOOT_LOG_ERR("Failed to add data to shared area");
1700 }
1701
Tamas Ban4fb8e9d2018-02-23 14:22:03 +00001702out:
1703 for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
1704 flash_area_close(BOOT_IMG_AREA(&boot_data, BOOT_NUM_SLOTS - 1 - slot));
1705 }
1706 return rc;
1707}
Oliver Swedef9982442018-08-24 18:37:44 +01001708#endif /* MCUBOOT_NO_SWAP || MCUBOOT_RAM_LOADING */