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