blob: 29becfa433db72831a12fd5cba375bc721823d67 [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/*
21 Original code taken from mcuboot project at:
22 https://github.com/runtimeco/mcuboot
23 Modifications are Copyright (c) 2018 Arm Limited.
24 */
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 <os/os_malloc.h>
39#include "bootutil/bootutil.h"
40#include "bootutil/image.h"
41#include "bootutil_priv.h"
42
43#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
44#include "bootutil/bootutil_log.h"
45
Tamas Banf70ef8c2017-12-19 15:35:09 +000046static struct boot_loader_state boot_data;
47
48struct 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) \
132 BOOT_LOG_INF("%s: magic=%s, copy_done=0x%x, image_ok=0x%x", \
133 (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)
139
140/**
Tamas Ban581034a2017-12-19 19:54:37 +0000141 * Determines where in flash the most recent boot status is stored. The boot
Tamas Banf70ef8c2017-12-19 15:35:09 +0000142 * status is necessary for completing a swap that was interrupted by a boot
143 * loader reset.
144 *
Tamas Ban581034a2017-12-19 19:54:37 +0000145 * @return BOOT_STATUS_SOURCE_[...] code indicating where
146 * status should be read from.
Tamas Banf70ef8c2017-12-19 15:35:09 +0000147 */
148static int
149boot_status_source(void)
150{
151 const struct boot_status_table *table;
152 struct boot_swap_state state_scratch;
153 struct boot_swap_state state_slot0;
154 int rc;
155 int i;
156 uint8_t source;
157
158 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &state_slot0);
159 assert(rc == 0);
160
161 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH, &state_scratch);
162 assert(rc == 0);
163
164 BOOT_LOG_SWAP_STATE("Image 0", &state_slot0);
165 BOOT_LOG_SWAP_STATE("Scratch", &state_scratch);
166
167 for (i = 0; i < BOOT_STATUS_TABLES_COUNT; i++) {
168 table = &boot_status_tables[i];
169
170 if ((table->bst_magic_slot0 == 0 ||
171 table->bst_magic_slot0 == state_slot0.magic) &&
172 (table->bst_magic_scratch == 0 ||
173 table->bst_magic_scratch == state_scratch.magic) &&
174 (table->bst_copy_done_slot0 == 0 ||
175 table->bst_copy_done_slot0 == state_slot0.copy_done)) {
176 source = table->bst_status_source;
177 BOOT_LOG_INF("Boot source: %s",
178 source == BOOT_STATUS_SOURCE_NONE ? "none" :
179 source == BOOT_STATUS_SOURCE_SCRATCH ? "scratch" :
180 source == BOOT_STATUS_SOURCE_SLOT0 ? "slot 0" :
181 "BUG; can't happen");
182 return source;
183 }
184 }
185
186 BOOT_LOG_INF("Boot source: none");
187 return BOOT_STATUS_SOURCE_NONE;
188}
189
190/**
191 * Calculates the type of swap that just completed.
192 *
193 * This is used when a swap is interrupted by an external event. After
194 * finishing the swap operation determines what the initial request was.
195 */
196static int
197boot_previous_swap_type(void)
198{
199 int post_swap_type;
200
201 post_swap_type = boot_swap_type();
202
203 switch (post_swap_type) {
Tamas Ban581034a2017-12-19 19:54:37 +0000204 case BOOT_SWAP_TYPE_NONE: return BOOT_SWAP_TYPE_PERM;
205 case BOOT_SWAP_TYPE_REVERT: return BOOT_SWAP_TYPE_TEST;
206 case BOOT_SWAP_TYPE_PANIC: return BOOT_SWAP_TYPE_PANIC;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000207 }
208
209 return BOOT_SWAP_TYPE_FAIL;
210}
211
212/*
213 * Compute the total size of the given image. Includes the size of
214 * the TLVs.
215 */
216#ifndef MCUBOOT_OVERWRITE_ONLY
217static int
218boot_read_image_size(int slot, struct image_header *hdr, uint32_t *size)
219{
Tamas Ban581034a2017-12-19 19:54:37 +0000220 const struct flash_area *fap = NULL;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000221 struct image_tlv_info info;
222 int area_id;
223 int rc;
224
225 area_id = flash_area_id_from_image_slot(slot);
226 rc = flash_area_open(area_id, &fap);
227 if (rc != 0) {
228 rc = BOOT_EFLASH;
229 goto done;
230 }
231
232 rc = flash_area_read(fap, hdr->ih_hdr_size + hdr->ih_img_size,
233 &info, sizeof(info));
234 if (rc != 0) {
235 rc = BOOT_EFLASH;
236 goto done;
237 }
238 if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
239 rc = BOOT_EBADIMAGE;
240 goto done;
241 }
242 *size = hdr->ih_hdr_size + hdr->ih_img_size + info.it_tlv_tot;
243 rc = 0;
244
245done:
246 flash_area_close(fap);
247 return rc;
248}
249#endif /* !MCUBOOT_OVERWRITE_ONLY */
250
251static int
252boot_read_image_header(int slot, struct image_header *out_hdr)
253{
Tamas Ban581034a2017-12-19 19:54:37 +0000254 const struct flash_area *fap = NULL;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000255 int area_id;
256 int rc;
257
258 area_id = flash_area_id_from_image_slot(slot);
259 rc = flash_area_open(area_id, &fap);
260 if (rc != 0) {
261 rc = BOOT_EFLASH;
262 goto done;
263 }
264
Tamas Ban581034a2017-12-19 19:54:37 +0000265 rc = flash_area_read(fap, 0, out_hdr, sizeof(*out_hdr));
Tamas Banf70ef8c2017-12-19 15:35:09 +0000266 if (rc != 0) {
267 rc = BOOT_EFLASH;
268 goto done;
269 }
270
271 rc = 0;
272
273done:
274 flash_area_close(fap);
275 return rc;
276}
277
278static int
279boot_read_image_headers(void)
280{
281 int rc;
282 int i;
283
284 for (i = 0; i < BOOT_NUM_SLOTS; i++) {
285 rc = boot_read_image_header(i, boot_img_hdr(&boot_data, i));
286 if (rc != 0) {
287 /* If at least the first slot's header was read successfully, then
288 * the boot loader can attempt a boot. Failure to read any headers
289 * is a fatal error.
290 */
291 if (i > 0) {
292 return 0;
293 } else {
294 return rc;
295 }
296 }
297 }
298
299 return 0;
300}
301
302static uint8_t
303boot_write_sz(void)
304{
Tamas Banc3828852018-02-01 12:24:16 +0000305 const struct flash_area *fap;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000306 uint8_t elem_sz;
307 uint8_t align;
Tamas Banc3828852018-02-01 12:24:16 +0000308 int rc;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000309
310 /* Figure out what size to write update status update as. The size depends
311 * on what the minimum write size is for scratch area, active image slot.
312 * We need to use the bigger of those 2 values.
313 */
Tamas Banc3828852018-02-01 12:24:16 +0000314 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
315 assert(rc == 0);
316 elem_sz = flash_area_align(fap);
317 flash_area_close(fap);
318
319 rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
320 assert(rc == 0);
321 align = flash_area_align(fap);
322 flash_area_close(fap);
323
Tamas Banf70ef8c2017-12-19 15:35:09 +0000324 if (align > elem_sz) {
325 elem_sz = align;
326 }
327
328 return elem_sz;
329}
330
331static int
332boot_slots_compatible(void)
333{
334 size_t num_sectors_0 = boot_img_num_sectors(&boot_data, 0);
335 size_t num_sectors_1 = boot_img_num_sectors(&boot_data, 1);
336 size_t size_0, size_1;
337 size_t i;
338
339 /* Ensure both image slots have identical sector layouts. */
340 if (num_sectors_0 != num_sectors_1) {
341 return 0;
342 }
343 for (i = 0; i < num_sectors_0; i++) {
344 size_0 = boot_img_sector_size(&boot_data, 0, i);
345 size_1 = boot_img_sector_size(&boot_data, 1, i);
346 if (size_0 != size_1) {
347 return 0;
348 }
349 }
350
351 return 1;
352}
353
354/**
355 * Determines the sector layout of both image slots and the scratch area.
356 * This information is necessary for calculating the number of bytes to erase
357 * and copy during an image swap. The information collected during this
358 * function is used to populate the boot_data global.
359 */
360static int
361boot_read_sectors(void)
362{
363 int rc;
364
365 rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_0);
366 if (rc != 0) {
367 return BOOT_EFLASH;
368 }
369
370 rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_1);
371 if (rc != 0) {
372 return BOOT_EFLASH;
373 }
374
375 BOOT_WRITE_SZ(&boot_data) = boot_write_sz();
376
377 return 0;
378}
379
380static uint32_t
381boot_status_internal_off(int idx, int state, int elem_sz)
382{
383 int idx_sz;
384
385 idx_sz = elem_sz * BOOT_STATUS_STATE_COUNT;
386
387 return idx * idx_sz + state * elem_sz;
388}
389
390/**
391 * Reads the status of a partially-completed swap, if any. This is necessary
392 * to recover in case the boot lodaer was reset in the middle of a swap
393 * operation.
394 */
395static int
396boot_read_status_bytes(const struct flash_area *fap, struct boot_status *bs)
397{
398 uint32_t off;
399 uint8_t status;
400 int max_entries;
401 int found;
402 int rc;
403 int i;
404
405 off = boot_status_off(fap);
406 max_entries = boot_status_entries(fap);
407
408 found = 0;
409 for (i = 0; i < max_entries; i++) {
410 rc = flash_area_read(fap, off + i * BOOT_WRITE_SZ(&boot_data),
411 &status, 1);
412 if (rc != 0) {
413 return BOOT_EFLASH;
414 }
415
416 if (status == 0xff) {
417 if (found) {
418 break;
419 }
420 } else if (!found) {
421 found = 1;
422 }
423 }
424
425 if (found) {
426 i--;
427 bs->idx = i / BOOT_STATUS_STATE_COUNT;
428 bs->state = i % BOOT_STATUS_STATE_COUNT;
429 }
430
431 return 0;
432}
433
434/**
435 * Reads the boot status from the flash. The boot status contains
436 * the current state of an interrupted image copy operation. If the boot
437 * status is not present, or it indicates that previous copy finished,
438 * there is no operation in progress.
439 */
440static int
441boot_read_status(struct boot_status *bs)
442{
443 const struct flash_area *fap;
444 int status_loc;
445 int area_id;
446 int rc;
447
Tamas Ban581034a2017-12-19 19:54:37 +0000448 memset(bs, 0, sizeof(*bs));
Tamas Banf70ef8c2017-12-19 15:35:09 +0000449
450 status_loc = boot_status_source();
451 switch (status_loc) {
452 case BOOT_STATUS_SOURCE_NONE:
453 return 0;
454
455 case BOOT_STATUS_SOURCE_SCRATCH:
456 area_id = FLASH_AREA_IMAGE_SCRATCH;
457 break;
458
459 case BOOT_STATUS_SOURCE_SLOT0:
460 area_id = FLASH_AREA_IMAGE_0;
461 break;
462
463 default:
464 assert(0);
465 return BOOT_EBADARGS;
466 }
467
468 rc = flash_area_open(area_id, &fap);
469 if (rc != 0) {
470 return BOOT_EFLASH;
471 }
472
473 rc = boot_read_status_bytes(fap, bs);
474
475 flash_area_close(fap);
476 return rc;
477}
478
479/**
480 * Writes the supplied boot status to the flash file system. The boot status
481 * contains the current state of an in-progress image copy operation.
482 *
483 * @param bs The boot status to write.
484 *
485 * @return 0 on success; nonzero on failure.
486 */
487int
488boot_write_status(struct boot_status *bs)
489{
Tamas Ban581034a2017-12-19 19:54:37 +0000490 const struct flash_area *fap = NULL;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000491 uint32_t off;
492 int area_id;
493 int rc;
494 uint8_t buf[BOOT_MAX_ALIGN];
495 uint8_t align;
496
497 /* NOTE: The first sector copied (that is the last sector on slot) contains
498 * the trailer. Since in the last step SLOT 0 is erased, the first
499 * two status writes go to the scratch which will be copied to SLOT 0!
500 */
501
502 if (bs->use_scratch) {
503 /* Write to scratch. */
504 area_id = FLASH_AREA_IMAGE_SCRATCH;
505 } else {
506 /* Write to slot 0. */
507 area_id = FLASH_AREA_IMAGE_0;
508 }
509
510 rc = flash_area_open(area_id, &fap);
511 if (rc != 0) {
512 rc = BOOT_EFLASH;
513 goto done;
514 }
515
516 off = boot_status_off(fap) +
517 boot_status_internal_off(bs->idx, bs->state,
518 BOOT_WRITE_SZ(&boot_data));
519
Tamas Banc3828852018-02-01 12:24:16 +0000520 align = flash_area_align(fap);
Tamas Banf70ef8c2017-12-19 15:35:09 +0000521 memset(buf, 0xFF, BOOT_MAX_ALIGN);
522 buf[0] = bs->state;
523
524 rc = flash_area_write(fap, off, buf, align);
525 if (rc != 0) {
526 rc = BOOT_EFLASH;
527 goto done;
528 }
529
530 rc = 0;
531
532done:
533 flash_area_close(fap);
534 return rc;
535}
536
537/*
538 * Validate image hash/signature in a slot.
539 */
540static int
541boot_image_check(struct image_header *hdr, const struct flash_area *fap)
542{
543 static uint8_t tmpbuf[BOOT_TMPBUF_SZ];
544
545 if (bootutil_img_validate(hdr, fap, tmpbuf, BOOT_TMPBUF_SZ,
546 NULL, 0, NULL)) {
547 return BOOT_EBADIMAGE;
548 }
549 return 0;
550}
551
552static int
Tamas Banf70ef8c2017-12-19 15:35:09 +0000553boot_validate_slot(int slot)
554{
555 const struct flash_area *fap;
556 struct image_header *hdr;
557 int rc;
558
559 hdr = boot_img_hdr(&boot_data, slot);
560 if (hdr->ih_magic == 0xffffffff || hdr->ih_flags & IMAGE_F_NON_BOOTABLE) {
561 /* No bootable image in slot; continue booting from slot 0. */
562 return -1;
563 }
564
565 rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
566 if (rc != 0) {
567 return BOOT_EFLASH;
568 }
569
570 if ((hdr->ih_magic != IMAGE_MAGIC || boot_image_check(hdr, fap) != 0)) {
571 if (slot != 0) {
572 flash_area_erase(fap, 0, fap->fa_size);
573 /* Image in slot 1 is invalid. Erase the image and
574 * continue booting from slot 0.
575 */
576 }
577 BOOT_LOG_ERR("Image in slot %d is not valid!", slot);
578 return -1;
579 }
580
581 flash_area_close(fap);
582
583 /* Image in slot 1 is valid. */
584 return 0;
585}
586
587/**
588 * Determines which swap operation to perform, if any. If it is determined
589 * that a swap operation is required, the image in the second slot is checked
590 * for validity. If the image in the second slot is invalid, it is erased, and
591 * a swap type of "none" is indicated.
592 *
593 * @return The type of swap to perform (BOOT_SWAP_TYPE...)
594 */
595static int
596boot_validated_swap_type(void)
597{
598 int swap_type;
599
600 swap_type = boot_swap_type();
601 switch (swap_type) {
602 case BOOT_SWAP_TYPE_TEST:
603 case BOOT_SWAP_TYPE_PERM:
604 case BOOT_SWAP_TYPE_REVERT:
605 /* Boot loader wants to switch to slot 1. Ensure image is valid. */
606 if (boot_validate_slot(1) != 0) {
607 swap_type = BOOT_SWAP_TYPE_FAIL;
608 }
609 }
610
611 return swap_type;
612}
613
614/**
615 * Calculates the number of sectors the scratch area can contain. A "last"
616 * source sector is specified because images are copied backwards in flash
617 * (final index to index number 0).
618 *
619 * @param last_sector_idx The index of the last source sector
620 * (inclusive).
621 * @param out_first_sector_idx The index of the first source sector
622 * (inclusive) gets written here.
623 *
624 * @return The number of bytes comprised by the
625 * [first-sector, last-sector] range.
626 */
627#ifndef MCUBOOT_OVERWRITE_ONLY
628static uint32_t
629boot_copy_sz(int last_sector_idx, int *out_first_sector_idx)
630{
631 size_t scratch_sz;
632 uint32_t new_sz;
633 uint32_t sz;
634 int i;
635
636 sz = 0;
637
638 scratch_sz = boot_scratch_area_size(&boot_data);
639 for (i = last_sector_idx; i >= 0; i--) {
640 new_sz = sz + boot_img_sector_size(&boot_data, 0, i);
641 if (new_sz > scratch_sz) {
642 break;
643 }
644 sz = new_sz;
645 }
646
647 /* i currently refers to a sector that doesn't fit or it is -1 because all
648 * sectors have been processed. In both cases, exclude sector i.
649 */
650 *out_first_sector_idx = i + 1;
651 return sz;
652}
653#endif /* !MCUBOOT_OVERWRITE_ONLY */
654
655/**
656 * Erases a region of flash.
657 *
658 * @param flash_area_idx The ID of the flash area containing the region
659 * to erase.
660 * @param off The offset within the flash area to start the
661 * erase.
662 * @param sz The number of bytes to erase.
663 *
664 * @return 0 on success; nonzero on failure.
665 */
666static int
667boot_erase_sector(int flash_area_id, uint32_t off, uint32_t sz)
668{
Tamas Ban581034a2017-12-19 19:54:37 +0000669 const struct flash_area *fap = NULL;
Tamas Banf70ef8c2017-12-19 15:35:09 +0000670 int rc;
671
672 rc = flash_area_open(flash_area_id, &fap);
673 if (rc != 0) {
674 rc = BOOT_EFLASH;
675 goto done;
676 }
677
678 rc = flash_area_erase(fap, off, sz);
679 if (rc != 0) {
680 rc = BOOT_EFLASH;
681 goto done;
682 }
683
684 rc = 0;
685
686done:
687 flash_area_close(fap);
688 return rc;
689}
690
691/**
692 * Copies the contents of one flash region to another. You must erase the
693 * destination region prior to calling this function.
694 *
695 * @param flash_area_id_src The ID of the source flash area.
696 * @param flash_area_id_dst The ID of the destination flash area.
697 * @param off_src The offset within the source flash area to
698 * copy from.
699 * @param off_dst The offset within the destination flash area to
700 * copy to.
701 * @param sz The number of bytes to copy.
702 *
703 * @return 0 on success; nonzero on failure.
704 */
705static int
706boot_copy_sector(int flash_area_id_src, int flash_area_id_dst,
707 uint32_t off_src, uint32_t off_dst, uint32_t sz)
708{
709 const struct flash_area *fap_src;
710 const struct flash_area *fap_dst;
711 uint32_t bytes_copied;
712 int chunk_sz;
713 int rc;
714
715 static uint8_t buf[1024];
716
717 fap_src = NULL;
718 fap_dst = NULL;
719
720 rc = flash_area_open(flash_area_id_src, &fap_src);
721 if (rc != 0) {
722 rc = BOOT_EFLASH;
723 goto done;
724 }
725
726 rc = flash_area_open(flash_area_id_dst, &fap_dst);
727 if (rc != 0) {
728 rc = BOOT_EFLASH;
729 goto done;
730 }
731
732 bytes_copied = 0;
733 while (bytes_copied < sz) {
Tamas Ban581034a2017-12-19 19:54:37 +0000734 if (sz - bytes_copied > sizeof(buf)) {
735 chunk_sz = sizeof(buf);
Tamas Banf70ef8c2017-12-19 15:35:09 +0000736 } else {
737 chunk_sz = sz - bytes_copied;
738 }
739
740 rc = flash_area_read(fap_src, off_src + bytes_copied, buf, chunk_sz);
741 if (rc != 0) {
742 rc = BOOT_EFLASH;
743 goto done;
744 }
745
746 rc = flash_area_write(fap_dst, off_dst + bytes_copied, buf, chunk_sz);
747 if (rc != 0) {
748 rc = BOOT_EFLASH;
749 goto done;
750 }
751
752 bytes_copied += chunk_sz;
753 }
754
755 rc = 0;
756
757done:
758 if (fap_src) {
759 flash_area_close(fap_src);
760 }
761 if (fap_dst) {
762 flash_area_close(fap_dst);
763 }
764 return rc;
765}
766
767#ifndef MCUBOOT_OVERWRITE_ONLY
768static inline int
769boot_status_init_by_id(int flash_area_id, const struct boot_status *bs)
770{
771 const struct flash_area *fap;
772 struct boot_swap_state swap_state;
773 int rc;
774
775 rc = flash_area_open(flash_area_id, &fap);
776 assert(rc == 0);
777
778 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &swap_state);
779 assert(rc == 0);
780
781 if (swap_state.image_ok == BOOT_FLAG_SET) {
782 rc = boot_write_image_ok(fap);
783 assert(rc == 0);
784 }
785
786 rc = boot_write_swap_size(fap, bs->swap_size);
787 assert(rc == 0);
788
789 rc = boot_write_magic(fap);
790 assert(rc == 0);
791
792 flash_area_close(fap);
793
794 return 0;
795}
796#endif
797
798#ifndef MCUBOOT_OVERWRITE_ONLY
799static int
800boot_erase_last_sector_by_id(int flash_area_id)
801{
802 uint8_t slot;
803 uint32_t last_sector;
804 int rc;
805
806 switch (flash_area_id) {
807 case FLASH_AREA_IMAGE_0:
808 slot = 0;
809 break;
810 case FLASH_AREA_IMAGE_1:
811 slot = 1;
812 break;
813 default:
814 return BOOT_EFLASH;
815 }
816
817 last_sector = boot_img_num_sectors(&boot_data, slot) - 1;
818 rc = boot_erase_sector(flash_area_id,
819 boot_img_sector_off(&boot_data, slot, last_sector),
820 boot_img_sector_size(&boot_data, slot, last_sector));
821 assert(rc == 0);
822
823 return rc;
824}
825#endif /* !MCUBOOT_OVERWRITE_ONLY */
826
827/**
828 * Swaps the contents of two flash regions within the two image slots.
829 *
830 * @param idx The index of the first sector in the range of
831 * sectors being swapped.
832 * @param sz The number of bytes to swap.
833 * @param bs The current boot status. This struct gets
834 * updated according to the outcome.
835 *
836 * @return 0 on success; nonzero on failure.
837 */
838#ifndef MCUBOOT_OVERWRITE_ONLY
839static void
840boot_swap_sectors(int idx, uint32_t sz, struct boot_status *bs)
841{
842 const struct flash_area *fap;
843 uint32_t copy_sz;
844 uint32_t trailer_sz;
845 uint32_t img_off;
846 uint32_t scratch_trailer_off;
847 struct boot_swap_state swap_state;
848 size_t last_sector;
849 int rc;
850
851 /* Calculate offset from start of image area. */
852 img_off = boot_img_sector_off(&boot_data, 0, idx);
853
854 copy_sz = sz;
855 trailer_sz = boot_slots_trailer_sz(BOOT_WRITE_SZ(&boot_data));
856
857 /* sz in this function is always is always sized on a multiple of the
858 * sector size. The check against the start offset of the last sector
859 * is to determine if we're swapping the last sector. The last sector
860 * needs special handling because it's where the trailer lives. If we're
861 * copying it, we need to use scratch to write the trailer temporarily.
862 *
863 * NOTE: `use_scratch` is a temporary flag (never written to flash) which
864 * controls if special handling is needed (swapping last sector).
865 */
866 last_sector = boot_img_num_sectors(&boot_data, 0) - 1;
867 if (img_off + sz > boot_img_sector_off(&boot_data, 0, last_sector)) {
868 copy_sz -= trailer_sz;
869 }
870
871 bs->use_scratch = (bs->idx == 0 && copy_sz != sz);
872
873 if (bs->state == 0) {
874 rc = boot_erase_sector(FLASH_AREA_IMAGE_SCRATCH, 0, sz);
875 assert(rc == 0);
876
877 rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_SCRATCH,
878 img_off, 0, copy_sz);
879 assert(rc == 0);
880
881 if (bs->idx == 0) {
882 if (bs->use_scratch) {
883 boot_status_init_by_id(FLASH_AREA_IMAGE_SCRATCH, bs);
884 } else {
885 /* Prepare the status area... here it is known that the
886 * last sector is not being used by the image data so it's
887 * safe to erase.
888 */
889 rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_0);
890 assert(rc == 0);
891
892 boot_status_init_by_id(FLASH_AREA_IMAGE_0, bs);
893 }
894 }
895
896 bs->state = 1;
897 rc = boot_write_status(bs);
898 assert(rc == 0);
899 }
900
901 if (bs->state == 1) {
902 rc = boot_erase_sector(FLASH_AREA_IMAGE_1, img_off, sz);
903 assert(rc == 0);
904
905 rc = boot_copy_sector(FLASH_AREA_IMAGE_0, FLASH_AREA_IMAGE_1,
906 img_off, img_off, copy_sz);
907 assert(rc == 0);
908
909 if (bs->idx == 0 && !bs->use_scratch) {
910 /* If not all sectors of the slot are being swapped,
911 * guarantee here that only slot0 will have the state.
912 */
913 rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_1);
914 assert(rc == 0);
915 }
916
917 bs->state = 2;
918 rc = boot_write_status(bs);
919 assert(rc == 0);
920 }
921
922 if (bs->state == 2) {
923 rc = boot_erase_sector(FLASH_AREA_IMAGE_0, img_off, sz);
924 assert(rc == 0);
925
926 /* NOTE: also copy trailer from scratch (has status info) */
927 rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
928 0, img_off, copy_sz);
929 assert(rc == 0);
930
931 if (bs->use_scratch) {
932 rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
933 assert(rc == 0);
934
935 scratch_trailer_off = boot_status_off(fap);
936
937 flash_area_close(fap);
938
939 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
940 assert(rc == 0);
941
942 /* copy current status that is being maintained in scratch */
943 rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
944 scratch_trailer_off,
945 img_off + copy_sz,
946 BOOT_STATUS_STATE_COUNT * BOOT_WRITE_SZ(&boot_data));
947 assert(rc == 0);
948
949 rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH,
950 &swap_state);
951 assert(rc == 0);
952
953 if (swap_state.image_ok == BOOT_FLAG_SET) {
954 rc = boot_write_image_ok(fap);
955 assert(rc == 0);
956 }
957
958 rc = boot_write_swap_size(fap, bs->swap_size);
959 assert(rc == 0);
960
961 rc = boot_write_magic(fap);
962 assert(rc == 0);
963
964 flash_area_close(fap);
965 }
966
967 bs->idx++;
968 bs->state = 0;
969 bs->use_scratch = 0;
970 rc = boot_write_status(bs);
971 assert(rc == 0);
972 }
973}
974#endif /* !MCUBOOT_OVERWRITE_ONLY */
975
976/**
977 * Swaps the two images in flash. If a prior copy operation was interrupted
978 * by a system reset, this function completes that operation.
979 *
980 * @param bs The current boot status. This function reads
981 * this struct to determine if it is resuming
982 * an interrupted swap operation. This
983 * function writes the updated status to this
984 * function on return.
985 *
986 * @return 0 on success; nonzero on failure.
987 */
988#ifdef MCUBOOT_OVERWRITE_ONLY
989static int
990boot_copy_image(struct boot_status *bs)
991{
992 size_t sect_count;
993 size_t sect;
994 int rc;
995 size_t size = 0;
996 size_t this_size;
997
998 BOOT_LOG_INF("Image upgrade slot1 -> slot0");
999 BOOT_LOG_INF("Erasing slot0");
1000
1001 sect_count = boot_img_num_sectors(&boot_data, 0);
1002 for (sect = 0; sect < sect_count; sect++) {
1003 this_size = boot_img_sector_size(&boot_data, 0, sect);
1004 rc = boot_erase_sector(FLASH_AREA_IMAGE_0,
1005 size,
1006 this_size);
1007 assert(rc == 0);
1008
1009 size += this_size;
1010 }
1011
1012 BOOT_LOG_INF("Copying slot 1 to slot 0: 0x%lx bytes", size);
1013 rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_0,
1014 0, 0, size);
1015
1016 /* Erase slot 1 so that we don't do the upgrade on every boot.
1017 * TODO: Perhaps verify slot 0's signature again? */
1018 rc = boot_erase_sector(FLASH_AREA_IMAGE_1,
1019 0, boot_img_sector_size(&boot_data, 1, 0));
1020 assert(rc == 0);
1021
1022 return 0;
1023}
1024#else
1025static int
1026boot_copy_image(struct boot_status *bs)
1027{
1028 uint32_t sz;
1029 int first_sector_idx;
1030 int last_sector_idx;
1031 int swap_idx;
1032 struct image_header *hdr;
1033 uint32_t size;
1034 uint32_t copy_size;
1035 int rc;
1036
1037 /* FIXME: just do this if asked by user? */
1038
1039 size = copy_size = 0;
1040
1041 if (bs->idx == 0 && bs->state == 0) {
1042 /*
1043 * No swap ever happened, so need to find the largest image which
1044 * will be used to determine the amount of sectors to swap.
1045 */
1046 hdr = boot_img_hdr(&boot_data, 0);
1047 if (hdr->ih_magic == IMAGE_MAGIC) {
1048 rc = boot_read_image_size(0, hdr, &copy_size);
1049 assert(rc == 0);
1050 }
1051
1052 hdr = boot_img_hdr(&boot_data, 1);
1053 if (hdr->ih_magic == IMAGE_MAGIC) {
1054 rc = boot_read_image_size(1, hdr, &size);
1055 assert(rc == 0);
1056 }
1057
1058 if (size > copy_size) {
1059 copy_size = size;
1060 }
1061
1062 bs->swap_size = copy_size;
1063 } else {
1064 /*
1065 * If a swap was under way, the swap_size should already be present
1066 * in the trailer...
1067 */
1068 rc = boot_read_swap_size(&bs->swap_size);
1069 assert(rc == 0);
1070
1071 copy_size = bs->swap_size;
1072 }
1073
1074 size = 0;
1075 last_sector_idx = 0;
1076 while (1) {
1077 size += boot_img_sector_size(&boot_data, 0, last_sector_idx);
1078 if (size >= copy_size) {
1079 break;
1080 }
1081 last_sector_idx++;
1082 }
1083
1084 swap_idx = 0;
1085 while (last_sector_idx >= 0) {
1086 sz = boot_copy_sz(last_sector_idx, &first_sector_idx);
1087 if (swap_idx >= bs->idx) {
1088 boot_swap_sectors(first_sector_idx, sz, bs);
1089 }
1090
1091 last_sector_idx = first_sector_idx - 1;
1092 swap_idx++;
1093 }
1094
1095 return 0;
1096}
1097#endif
1098
1099/**
1100 * Marks the image in slot 0 as fully copied.
1101 */
1102#ifndef MCUBOOT_OVERWRITE_ONLY
1103static int
1104boot_set_copy_done(void)
1105{
1106 const struct flash_area *fap;
1107 int rc;
1108
1109 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
1110 if (rc != 0) {
1111 return BOOT_EFLASH;
1112 }
1113
1114 rc = boot_write_copy_done(fap);
1115 flash_area_close(fap);
1116 return rc;
1117}
1118#endif /* !MCUBOOT_OVERWRITE_ONLY */
1119
1120/**
1121 * Marks a reverted image in slot 0 as confirmed. This is necessary to ensure
1122 * the status bytes from the image revert operation don't get processed on a
1123 * subsequent boot.
1124 *
1125 * NOTE: image_ok is tested before writing because if there's a valid permanent
1126 * image installed on slot0 and the new image to be upgrade to has a bad sig,
1127 * image_ok would be overwritten.
1128 */
1129#ifndef MCUBOOT_OVERWRITE_ONLY
1130static int
1131boot_set_image_ok(void)
1132{
1133 const struct flash_area *fap;
1134 struct boot_swap_state state;
1135 int rc;
1136
1137 rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
1138 if (rc != 0) {
1139 return BOOT_EFLASH;
1140 }
1141
1142 rc = boot_read_swap_state(fap, &state);
1143 if (rc != 0) {
1144 rc = BOOT_EFLASH;
1145 goto out;
1146 }
1147
1148 if (state.image_ok == BOOT_FLAG_UNSET) {
1149 rc = boot_write_image_ok(fap);
1150 }
1151
1152out:
1153 flash_area_close(fap);
1154 return rc;
1155}
1156#endif /* !MCUBOOT_OVERWRITE_ONLY */
1157
1158/**
1159 * Performs an image swap if one is required.
1160 *
1161 * @param out_swap_type On success, the type of swap performed gets
1162 * written here.
1163 *
1164 * @return 0 on success; nonzero on failure.
1165 */
1166static int
1167boot_swap_if_needed(int *out_swap_type)
1168{
1169 struct boot_status bs;
1170 int swap_type;
1171 int rc;
1172
1173 /* Determine if we rebooted in the middle of an image swap
1174 * operation.
1175 */
1176 rc = boot_read_status(&bs);
1177 assert(rc == 0);
1178 if (rc != 0) {
1179 return rc;
1180 }
1181
1182 /* If a partial swap was detected, complete it. */
1183 if (bs.idx != 0 || bs.state != 0) {
1184 rc = boot_copy_image(&bs);
1185 assert(rc == 0);
1186
1187 /* NOTE: here we have finished a swap resume. The initial request
1188 * was either a TEST or PERM swap, which now after the completed
1189 * swap will be determined to be respectively REVERT (was TEST)
1190 * or NONE (was PERM).
1191 */
1192
1193 /* Extrapolate the type of the partial swap. We need this
1194 * information to know how to mark the swap complete in flash.
1195 */
1196 swap_type = boot_previous_swap_type();
1197 } else {
1198 swap_type = boot_validated_swap_type();
1199 switch (swap_type) {
1200 case BOOT_SWAP_TYPE_TEST:
1201 case BOOT_SWAP_TYPE_PERM:
1202 case BOOT_SWAP_TYPE_REVERT:
1203 rc = boot_copy_image(&bs);
1204 assert(rc == 0);
1205 break;
1206 }
1207 }
1208
1209 *out_swap_type = swap_type;
1210 return 0;
1211}
1212
1213/**
1214 * Prepares the booting process. This function moves images around in flash as
1215 * appropriate, and tells you what address to boot from.
1216 *
1217 * @param rsp On success, indicates how booting should occur.
1218 *
1219 * @return 0 on success; nonzero on failure.
1220 */
1221int
1222boot_go(struct boot_rsp *rsp)
1223{
1224 int swap_type;
1225 size_t slot;
1226 int rc;
1227 int fa_id;
1228 bool reload_headers = false;
1229
1230 /* The array of slot sectors are defined here (as opposed to file scope) so
1231 * that they don't get allocated for non-boot-loader apps. This is
1232 * necessary because the gcc option "-fdata-sections" doesn't seem to have
1233 * any effect in older gcc versions (e.g., 4.8.4).
1234 */
1235 static boot_sector_t slot0_sectors[BOOT_MAX_IMG_SECTORS];
1236 static boot_sector_t slot1_sectors[BOOT_MAX_IMG_SECTORS];
Tamas Ban581034a2017-12-19 19:54:37 +00001237
Tamas Banf70ef8c2017-12-19 15:35:09 +00001238 boot_data.imgs[0].sectors = slot0_sectors;
1239 boot_data.imgs[1].sectors = slot1_sectors;
1240
1241 /* Open boot_data image areas for the duration of this call. */
1242 for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
1243 fa_id = flash_area_id_from_image_slot(slot);
1244 rc = flash_area_open(fa_id, &BOOT_IMG_AREA(&boot_data, slot));
1245 assert(rc == 0);
1246 }
1247 rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH,
1248 &BOOT_SCRATCH_AREA(&boot_data));
1249 assert(rc == 0);
1250
1251 /* Determine the sector layout of the image slots and scratch area. */
1252 rc = boot_read_sectors();
1253 if (rc != 0) {
1254 goto out;
1255 }
1256
1257 /* Attempt to read an image header from each slot. */
1258 rc = boot_read_image_headers();
1259 if (rc != 0) {
1260 goto out;
1261 }
1262
1263 /* If the image slots aren't compatible, no swap is possible. Just boot
1264 * into slot 0.
1265 */
1266 if (boot_slots_compatible()) {
1267 rc = boot_swap_if_needed(&swap_type);
1268 assert(rc == 0);
1269 if (rc != 0) {
1270 goto out;
1271 }
1272
1273 /*
1274 * The following states need image_ok be explicitly set after the
1275 * swap was finished to avoid a new revert.
1276 */
Tamas Ban581034a2017-12-19 19:54:37 +00001277 if (swap_type == BOOT_SWAP_TYPE_REVERT ||
1278 swap_type == BOOT_SWAP_TYPE_FAIL) {
Tamas Banf70ef8c2017-12-19 15:35:09 +00001279#ifndef MCUBOOT_OVERWRITE_ONLY
1280 rc = boot_set_image_ok();
1281 if (rc != 0) {
1282 swap_type = BOOT_SWAP_TYPE_PANIC;
1283 }
1284#endif /* !MCUBOOT_OVERWRITE_ONLY */
1285 }
1286 } else {
1287 swap_type = BOOT_SWAP_TYPE_NONE;
1288 }
1289
1290 switch (swap_type) {
1291 case BOOT_SWAP_TYPE_NONE:
1292 slot = 0;
1293 break;
1294
1295 case BOOT_SWAP_TYPE_TEST: /* fallthrough */
1296 case BOOT_SWAP_TYPE_PERM: /* fallthrough */
1297 case BOOT_SWAP_TYPE_REVERT:
1298 slot = 1;
1299 reload_headers = true;
1300#ifndef MCUBOOT_OVERWRITE_ONLY
1301 rc = boot_set_copy_done();
1302 if (rc != 0) {
1303 swap_type = BOOT_SWAP_TYPE_PANIC;
1304 }
1305#endif /* !MCUBOOT_OVERWRITE_ONLY */
1306 break;
1307
1308 case BOOT_SWAP_TYPE_FAIL:
1309 /* The image in slot 1 was invalid and is now erased. Ensure we don't
1310 * try to boot into it again on the next reboot. Do this by pretending
1311 * we just reverted back to slot 0.
1312 */
1313 slot = 0;
1314 reload_headers = true;
1315 break;
1316
1317 default:
1318 swap_type = BOOT_SWAP_TYPE_PANIC;
1319 }
1320
1321 if (swap_type == BOOT_SWAP_TYPE_PANIC) {
1322 BOOT_LOG_ERR("panic!");
1323 assert(0);
1324
1325 /* Loop forever... */
Tamas Ban581034a2017-12-19 19:54:37 +00001326 while (1)
1327 ;
Tamas Banf70ef8c2017-12-19 15:35:09 +00001328 }
1329
1330#ifdef MCUBOOT_VALIDATE_SLOT0
1331 if (reload_headers) {
1332 rc = boot_read_image_headers();
1333 if (rc != 0) {
1334 goto out;
1335 }
1336 /* Since headers were reloaded, it can be assumed we just performed a
1337 * swap or overwrite. Now the header info that should be used to
1338 * provide the data for the bootstrap, which previously was at Slot 1,
1339 * was updated to Slot 0.
1340 */
1341 slot = 0;
1342 }
1343
1344 rc = boot_validate_slot(0);
1345 assert(rc == 0);
1346 if (rc != 0) {
1347 rc = BOOT_EBADIMAGE;
1348 goto out;
1349 }
1350#else
1351 (void)reload_headers;
1352#endif
1353
1354 /* Always boot from the primary slot. */
1355 rsp->br_flash_dev_id = boot_img_fa_device_id(&boot_data, 0);
1356 rsp->br_image_off = boot_img_slot_off(&boot_data, 0);
1357 rsp->br_hdr = boot_img_hdr(&boot_data, slot);
1358
1359 out:
1360 flash_area_close(BOOT_SCRATCH_AREA(&boot_data));
1361 for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
1362 flash_area_close(BOOT_IMG_AREA(&boot_data, BOOT_NUM_SLOTS - 1 - slot));
1363 }
1364 return rc;
1365}