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