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