1 /*
2  * SPDX-License-Identifier: Apache-2.0
3  *
4  * Copyright (c) 2019 JUUL Labs
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * 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, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 
19 #include <stddef.h>
20 #include <stdbool.h>
21 #include <inttypes.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include "bootutil/bootutil.h"
25 #include "bootutil_priv.h"
26 #include "swap_priv.h"
27 #include "bootutil/bootutil_log.h"
28 
29 #include "mcuboot_config/mcuboot_config.h"
30 
31 BOOT_LOG_MODULE_DECLARE(mcuboot);
32 
33 #ifdef MCUBOOT_SWAP_USING_MOVE
34 
35 #if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT)
36 /*
37  * FIXME: this might have to be updated for threaded sim
38  */
39 int boot_status_fails = 0;
40 #define BOOT_STATUS_ASSERT(x)                \
41     do {                                     \
42         if (!(x)) {                          \
43             boot_status_fails++;             \
44         }                                    \
45     } while (0)
46 #else
47 #define BOOT_STATUS_ASSERT(x) ASSERT(x)
48 #endif
49 
50 uint32_t
find_last_idx(struct boot_loader_state * state,uint32_t swap_size)51 find_last_idx(struct boot_loader_state *state, uint32_t swap_size)
52 {
53     uint32_t sector_sz;
54     uint32_t sz;
55     uint32_t last_idx;
56 
57     sector_sz = boot_img_sector_size(state, BOOT_PRIMARY_SLOT, 0);
58     sz = 0;
59     last_idx = 0;
60     while (1) {
61         sz += sector_sz;
62         last_idx++;
63         if (sz >= swap_size) {
64             break;
65         }
66     }
67 
68     return last_idx;
69 }
70 
71 int
boot_read_image_header(struct boot_loader_state * state,int slot,struct image_header * out_hdr,struct boot_status * bs)72 boot_read_image_header(struct boot_loader_state *state, int slot,
73                        struct image_header *out_hdr, struct boot_status *bs)
74 {
75     const struct flash_area *fap;
76     uint32_t off;
77     uint32_t sz;
78     uint32_t last_idx;
79     uint32_t swap_size;
80     int area_id;
81     int rc;
82 
83 #if (BOOT_IMAGE_NUMBER == 1)
84     (void)state;
85 #endif
86 
87     off = 0;
88     if (bs && !boot_status_is_reset(bs)) {
89         boot_find_status(BOOT_CURR_IMG(state), &fap);
90         if (fap == NULL || boot_read_swap_size(fap, &swap_size)) {
91             rc = BOOT_EFLASH;
92             goto done;
93         }
94         flash_area_close(fap);
95 
96         last_idx = find_last_idx(state, swap_size);
97         sz = boot_img_sector_size(state, BOOT_PRIMARY_SLOT, 0);
98 
99         /*
100          * Find the correct offset or slot where the image header is expected to
101          * be found for the steps where it is moved or swapped.
102          */
103         if (bs->op == BOOT_STATUS_OP_MOVE && slot == 0 && bs->idx > last_idx) {
104             off = sz;
105         } else if (bs->op == BOOT_STATUS_OP_SWAP) {
106             if (bs->idx > 1 && bs->idx <= last_idx) {
107                 slot = (slot == 0) ? 1 : 0;
108             } else if (bs->idx == 1) {
109                 if (slot == 0) {
110                     off = sz;
111                 } else if (slot == 1 && bs->state == 2) {
112                     slot = 0;
113                 }
114             }
115         }
116     }
117 
118     area_id = flash_area_id_from_multi_image_slot(BOOT_CURR_IMG(state), slot);
119     rc = flash_area_open(area_id, &fap);
120     if (rc != 0) {
121         rc = BOOT_EFLASH;
122         goto done;
123     }
124 
125     rc = flash_area_read(fap, off, out_hdr, sizeof *out_hdr);
126     if (rc != 0) {
127         rc = BOOT_EFLASH;
128         goto done;
129     }
130 
131     /* We only know where the headers are located when bs is valid */
132     if (bs != NULL && out_hdr->ih_magic != IMAGE_MAGIC) {
133         rc = -1;
134         goto done;
135     }
136 
137     rc = 0;
138 
139 done:
140     flash_area_close(fap);
141     return rc;
142 }
143 
144 int
swap_read_status_bytes(const struct flash_area * fap,struct boot_loader_state * state,struct boot_status * bs)145 swap_read_status_bytes(const struct flash_area *fap,
146         struct boot_loader_state *state, struct boot_status *bs)
147 {
148     uint32_t off;
149     uint8_t status;
150     int max_entries;
151     int found_idx;
152     uint8_t write_sz;
153     int move_entries;
154     int rc;
155     int last_rc;
156     int erased_sections;
157     int i;
158 
159     max_entries = boot_status_entries(BOOT_CURR_IMG(state), fap);
160     if (max_entries < 0) {
161         return BOOT_EBADARGS;
162     }
163 
164     erased_sections = 0;
165     found_idx = -1;
166     /* skip erased sectors at the end */
167     last_rc = 1;
168     write_sz = BOOT_WRITE_SZ(state);
169     off = boot_status_off(fap);
170     for (i = max_entries; i > 0; i--) {
171         rc = flash_area_read(fap, off + (i - 1) * write_sz, &status, 1);
172         if (rc < 0) {
173             return BOOT_EFLASH;
174         }
175 
176         if (bootutil_buffer_is_erased(fap, &status, 1)) {
177             if (rc != last_rc) {
178                 erased_sections++;
179             }
180         } else {
181             if (found_idx == -1) {
182                 found_idx = i;
183             }
184         }
185         last_rc = rc;
186     }
187 
188     if (erased_sections > 1) {
189         /* This means there was an error writing status on the last
190          * swap. Tell user and move on to validation!
191          */
192 #if !defined(__BOOTSIM__)
193         BOOT_LOG_ERR("Detected inconsistent status!");
194 #endif
195 
196 #if !defined(MCUBOOT_VALIDATE_PRIMARY_SLOT)
197         /* With validation of the primary slot disabled, there is no way
198          * to be sure the swapped primary slot is OK, so abort!
199          */
200         assert(0);
201 #endif
202     }
203 
204     move_entries = BOOT_MAX_IMG_SECTORS * BOOT_STATUS_MOVE_STATE_COUNT;
205     if (found_idx == -1) {
206         /* no swap status found; nothing to do */
207     } else if (found_idx < move_entries) {
208         bs->op = BOOT_STATUS_OP_MOVE;
209         bs->idx = (found_idx  / BOOT_STATUS_MOVE_STATE_COUNT) + BOOT_STATUS_IDX_0;
210         bs->state = (found_idx % BOOT_STATUS_MOVE_STATE_COUNT) + BOOT_STATUS_STATE_0;;
211     } else {
212         bs->op = BOOT_STATUS_OP_SWAP;
213         bs->idx = ((found_idx - move_entries) / BOOT_STATUS_SWAP_STATE_COUNT) + BOOT_STATUS_IDX_0;
214         bs->state = ((found_idx - move_entries) % BOOT_STATUS_SWAP_STATE_COUNT) + BOOT_STATUS_STATE_0;
215     }
216 
217     return 0;
218 }
219 
220 uint32_t
boot_status_internal_off(const struct boot_status * bs,int elem_sz)221 boot_status_internal_off(const struct boot_status *bs, int elem_sz)
222 {
223     uint32_t off;
224     int idx_sz;
225 
226     idx_sz = elem_sz * ((bs->op == BOOT_STATUS_OP_MOVE) ?
227             BOOT_STATUS_MOVE_STATE_COUNT : BOOT_STATUS_SWAP_STATE_COUNT);
228 
229     off = ((bs->op == BOOT_STATUS_OP_MOVE) ?
230                0 : (BOOT_MAX_IMG_SECTORS * BOOT_STATUS_MOVE_STATE_COUNT * elem_sz)) +
231            (bs->idx - BOOT_STATUS_IDX_0) * idx_sz +
232            (bs->state - BOOT_STATUS_STATE_0) * elem_sz;
233 
234     return off;
235 }
236 
app_max_sectors(struct boot_loader_state * state)237 static int app_max_sectors(struct boot_loader_state *state)
238 {
239     uint32_t sz = 0;
240     uint32_t sector_sz;
241     uint32_t trailer_sz;
242     uint32_t first_trailer_idx;
243 
244     sector_sz = boot_img_sector_size(state, BOOT_PRIMARY_SLOT, 0);
245     trailer_sz = boot_trailer_sz(BOOT_WRITE_SZ(state));
246     first_trailer_idx = boot_img_num_sectors(state, BOOT_PRIMARY_SLOT) - 1;
247 
248     while (1) {
249         sz += sector_sz;
250         if  (sz >= trailer_sz) {
251             break;
252         }
253         first_trailer_idx--;
254     }
255 
256     return first_trailer_idx;
257 }
258 
259 int
boot_slots_compatible(struct boot_loader_state * state)260 boot_slots_compatible(struct boot_loader_state *state)
261 {
262     size_t num_sectors_pri;
263     size_t num_sectors_sec;
264     size_t sector_sz_pri = 0;
265     size_t sector_sz_sec = 0;
266     size_t i;
267     size_t num_usable_sectors_pri;
268 
269     num_sectors_pri = boot_img_num_sectors(state, BOOT_PRIMARY_SLOT);
270     num_sectors_sec = boot_img_num_sectors(state, BOOT_SECONDARY_SLOT);
271     num_usable_sectors_pri = app_max_sectors(state);
272 
273     if ((num_sectors_pri != num_sectors_sec) &&
274             (num_sectors_pri != (num_sectors_sec + 1)) &&
275             (num_usable_sectors_pri != (num_sectors_sec + 1))) {
276         BOOT_LOG_WRN("Cannot upgrade: not a compatible amount of sectors");
277         BOOT_LOG_DBG("slot0 sectors: %d, slot1 sectors: %d, usable slot0 sectors: %d",
278                      (int)num_sectors_pri, (int)num_sectors_sec,
279                      (int)(num_usable_sectors_pri - 1));
280         return 0;
281     } else if (num_sectors_pri > BOOT_MAX_IMG_SECTORS) {
282         BOOT_LOG_WRN("Cannot upgrade: more sectors than allowed");
283         return 0;
284     }
285 
286     if (num_usable_sectors_pri != (num_sectors_sec + 1)) {
287         BOOT_LOG_DBG("Non-optimal sector distribution, slot0 has %d usable sectors (%d assigned) "
288                      "but slot1 has %d assigned", (int)(num_usable_sectors_pri - 1),
289                      (int)num_sectors_pri, (int)num_sectors_sec);
290     }
291 
292     for (i = 0; i < num_sectors_sec; i++) {
293         sector_sz_pri = boot_img_sector_size(state, BOOT_PRIMARY_SLOT, i);
294         sector_sz_sec = boot_img_sector_size(state, BOOT_SECONDARY_SLOT, i);
295         if (sector_sz_pri != sector_sz_sec) {
296             BOOT_LOG_WRN("Cannot upgrade: not same sector layout");
297             return 0;
298         }
299     }
300 
301 #ifdef MCUBOOT_SLOT0_EXPECTED_ERASE_SIZE
302     if (sector_sz_pri != MCUBOOT_SLOT0_EXPECTED_ERASE_SIZE) {
303         BOOT_LOG_DBG("Discrepancy, slot0 expected erase size: %d, actual: %d",
304                      MCUBOOT_SLOT0_EXPECTED_ERASE_SIZE, sector_sz_pri);
305     }
306 #endif
307 #ifdef MCUBOOT_SLOT1_EXPECTED_ERASE_SIZE
308     if (sector_sz_sec != MCUBOOT_SLOT1_EXPECTED_ERASE_SIZE) {
309         BOOT_LOG_DBG("Discrepancy, slot1 expected erase size: %d, actual: %d",
310                      MCUBOOT_SLOT1_EXPECTED_ERASE_SIZE, sector_sz_sec);
311     }
312 #endif
313 
314 #if defined(MCUBOOT_SLOT0_EXPECTED_WRITE_SIZE) || defined(MCUBOOT_SLOT1_EXPECTED_WRITE_SIZE)
315     if (!swap_write_block_size_check(state)) {
316         BOOT_LOG_WRN("Cannot upgrade: slot write sizes are not compatible");
317         return 0;
318     }
319 #endif
320 
321     if (num_sectors_pri > num_sectors_sec) {
322         if (sector_sz_pri != boot_img_sector_size(state, BOOT_PRIMARY_SLOT, i)) {
323             BOOT_LOG_WRN("Cannot upgrade: not same sector layout");
324             return 0;
325         }
326     }
327 
328     return 1;
329 }
330 
331 #define BOOT_LOG_SWAP_STATE(area, state)                            \
332     BOOT_LOG_INF("%s: magic=%s, swap_type=0x%x, copy_done=0x%x, "   \
333                  "image_ok=0x%x",                                   \
334                  (area),                                            \
335                  ((state)->magic == BOOT_MAGIC_GOOD ? "good" :      \
336                   (state)->magic == BOOT_MAGIC_UNSET ? "unset" :    \
337                   "bad"),                                           \
338                  (state)->swap_type,                                \
339                  (state)->copy_done,                                \
340                  (state)->image_ok)
341 
342 int
swap_status_source(struct boot_loader_state * state)343 swap_status_source(struct boot_loader_state *state)
344 {
345     struct boot_swap_state state_primary_slot;
346     struct boot_swap_state state_secondary_slot;
347     int rc;
348     uint8_t source;
349     uint8_t image_index;
350 
351 #if (BOOT_IMAGE_NUMBER == 1)
352     (void)state;
353 #endif
354 
355     image_index = BOOT_CURR_IMG(state);
356 
357     rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_PRIMARY(image_index),
358             &state_primary_slot);
359     assert(rc == 0);
360 
361     BOOT_LOG_SWAP_STATE("Primary image", &state_primary_slot);
362 
363     rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SECONDARY(image_index),
364             &state_secondary_slot);
365     assert(rc == 0);
366 
367     BOOT_LOG_SWAP_STATE("Secondary image", &state_secondary_slot);
368 
369     if (state_primary_slot.magic == BOOT_MAGIC_GOOD &&
370             state_primary_slot.copy_done == BOOT_FLAG_UNSET &&
371             state_secondary_slot.magic != BOOT_MAGIC_GOOD) {
372 
373         source = BOOT_STATUS_SOURCE_PRIMARY_SLOT;
374 
375         BOOT_LOG_INF("Boot source: primary slot");
376         return source;
377     }
378 
379     BOOT_LOG_INF("Boot source: none");
380     return BOOT_STATUS_SOURCE_NONE;
381 }
382 
383 /*
384  * "Moves" the sector located at idx - 1 to idx.
385  */
386 static void
boot_move_sector_up(int idx,uint32_t sz,struct boot_loader_state * state,struct boot_status * bs,const struct flash_area * fap_pri,const struct flash_area * fap_sec)387 boot_move_sector_up(int idx, uint32_t sz, struct boot_loader_state *state,
388         struct boot_status *bs, const struct flash_area *fap_pri,
389         const struct flash_area *fap_sec)
390 {
391     uint32_t new_off;
392     uint32_t old_off;
393     int rc;
394 
395     /*
396      * FIXME: assuming sectors of size == sz, a single off variable
397      * would be enough
398      */
399 
400     /* Calculate offset from start of image area. */
401     new_off = boot_img_sector_off(state, BOOT_PRIMARY_SLOT, idx);
402     old_off = boot_img_sector_off(state, BOOT_PRIMARY_SLOT, idx - 1);
403 
404     if (bs->idx == BOOT_STATUS_IDX_0) {
405         if (bs->source != BOOT_STATUS_SOURCE_PRIMARY_SLOT) {
406             rc = swap_erase_trailer_sectors(state, fap_pri);
407             assert(rc == 0);
408 
409             rc = swap_status_init(state, fap_pri, bs);
410             assert(rc == 0);
411         }
412 
413         rc = swap_erase_trailer_sectors(state, fap_sec);
414         assert(rc == 0);
415     }
416 
417     rc = boot_erase_region(fap_pri, new_off, sz);
418     assert(rc == 0);
419 
420     rc = boot_copy_region(state, fap_pri, fap_pri, old_off, new_off, sz);
421     assert(rc == 0);
422 
423     rc = boot_write_status(state, bs);
424 
425     bs->idx++;
426     BOOT_STATUS_ASSERT(rc == 0);
427 }
428 
429 static void
boot_swap_sectors(int idx,uint32_t sz,struct boot_loader_state * state,struct boot_status * bs,const struct flash_area * fap_pri,const struct flash_area * fap_sec)430 boot_swap_sectors(int idx, uint32_t sz, struct boot_loader_state *state,
431         struct boot_status *bs, const struct flash_area *fap_pri,
432         const struct flash_area *fap_sec)
433 {
434     uint32_t pri_off;
435     uint32_t pri_up_off;
436     uint32_t sec_off;
437     int rc;
438 
439     pri_up_off = boot_img_sector_off(state, BOOT_PRIMARY_SLOT, idx);
440     pri_off = boot_img_sector_off(state, BOOT_PRIMARY_SLOT, idx - 1);
441     sec_off = boot_img_sector_off(state, BOOT_SECONDARY_SLOT, idx - 1);
442 
443     if (bs->state == BOOT_STATUS_STATE_0) {
444         rc = boot_erase_region(fap_pri, pri_off, sz);
445         assert(rc == 0);
446 
447         rc = boot_copy_region(state, fap_sec, fap_pri, sec_off, pri_off, sz);
448         assert(rc == 0);
449 
450         rc = boot_write_status(state, bs);
451         bs->state = BOOT_STATUS_STATE_1;
452         BOOT_STATUS_ASSERT(rc == 0);
453     }
454 
455     if (bs->state == BOOT_STATUS_STATE_1) {
456         rc = boot_erase_region(fap_sec, sec_off, sz);
457         assert(rc == 0);
458 
459         rc = boot_copy_region(state, fap_pri, fap_sec, pri_up_off, sec_off, sz);
460         assert(rc == 0);
461 
462         rc = boot_write_status(state, bs);
463         bs->idx++;
464         bs->state = BOOT_STATUS_STATE_0;
465         BOOT_STATUS_ASSERT(rc == 0);
466     }
467 }
468 
469 /*
470  * When starting a revert the swap status exists in the primary slot, and
471  * the status in the secondary slot is erased. To start the swap, the status
472  * area in the primary slot must be re-initialized; if during the small
473  * window of time between re-initializing it and writing the first metadata
474  * a reset happens, the swap process is broken and cannot be resumed.
475  *
476  * This function handles the issue by making the revert look like a permanent
477  * upgrade (by initializing the secondary slot).
478  */
479 void
fixup_revert(const struct boot_loader_state * state,struct boot_status * bs,const struct flash_area * fap_sec)480 fixup_revert(const struct boot_loader_state *state, struct boot_status *bs,
481         const struct flash_area *fap_sec)
482 {
483     struct boot_swap_state swap_state;
484     int rc;
485 
486 #if (BOOT_IMAGE_NUMBER == 1)
487     (void)state;
488 #endif
489 
490     /* No fixup required */
491     if (bs->swap_type != BOOT_SWAP_TYPE_REVERT ||
492         bs->op != BOOT_STATUS_OP_MOVE ||
493         bs->idx != BOOT_STATUS_IDX_0) {
494         return;
495     }
496 
497     rc = boot_read_swap_state(fap_sec, &swap_state);
498     assert(rc == 0);
499 
500     BOOT_LOG_SWAP_STATE("Secondary image", &swap_state);
501 
502     if (swap_state.magic == BOOT_MAGIC_UNSET) {
503         rc = swap_erase_trailer_sectors(state, fap_sec);
504         assert(rc == 0);
505 
506         rc = boot_write_image_ok(fap_sec);
507         assert(rc == 0);
508 
509         rc = boot_write_swap_size(fap_sec, bs->swap_size);
510         assert(rc == 0);
511 
512         rc = boot_write_magic(fap_sec);
513         assert(rc == 0);
514     }
515 }
516 
517 void
swap_run(struct boot_loader_state * state,struct boot_status * bs,uint32_t copy_size)518 swap_run(struct boot_loader_state *state, struct boot_status *bs,
519          uint32_t copy_size)
520 {
521     uint32_t sz;
522     uint32_t sector_sz;
523     uint32_t idx;
524     uint32_t trailer_sz;
525     uint32_t first_trailer_idx;
526     uint32_t last_idx;
527     uint8_t image_index;
528     const struct flash_area *fap_pri;
529     const struct flash_area *fap_sec;
530     int rc;
531 
532     BOOT_LOG_INF("Starting swap using move algorithm.");
533 
534     last_idx = find_last_idx(state, copy_size);
535     sector_sz = boot_img_sector_size(state, BOOT_PRIMARY_SLOT, 0);
536 
537     /*
538      * When starting a new swap upgrade, check that there is enough space.
539      */
540     if (boot_status_is_reset(bs)) {
541         sz = 0;
542         trailer_sz = boot_trailer_sz(BOOT_WRITE_SZ(state));
543         first_trailer_idx = boot_img_num_sectors(state, BOOT_PRIMARY_SLOT) - 1;
544 
545         while (1) {
546             sz += sector_sz;
547             if  (sz >= trailer_sz) {
548                 break;
549             }
550             first_trailer_idx--;
551         }
552 
553         if (last_idx >= first_trailer_idx) {
554             BOOT_LOG_WRN("Not enough free space to run swap upgrade");
555             BOOT_LOG_WRN("required %d bytes but only %d are available",
556                          (last_idx + 1) * sector_sz,
557                          first_trailer_idx * sector_sz);
558             bs->swap_type = BOOT_SWAP_TYPE_NONE;
559             return;
560         }
561     }
562 
563     image_index = BOOT_CURR_IMG(state);
564 
565     rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY(image_index), &fap_pri);
566     assert (rc == 0);
567 
568     rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY(image_index), &fap_sec);
569     assert (rc == 0);
570 
571     fixup_revert(state, bs, fap_sec);
572 
573     if (bs->op == BOOT_STATUS_OP_MOVE) {
574         idx = last_idx;
575         while (idx > 0) {
576             if (idx <= (last_idx - bs->idx + 1)) {
577                 boot_move_sector_up(idx, sector_sz, state, bs, fap_pri, fap_sec);
578             }
579             idx--;
580         }
581         bs->idx = BOOT_STATUS_IDX_0;
582     }
583 
584     bs->op = BOOT_STATUS_OP_SWAP;
585 
586     idx = 1;
587     while (idx <= last_idx) {
588         if (idx >= bs->idx) {
589             boot_swap_sectors(idx, sector_sz, state, bs, fap_pri, fap_sec);
590         }
591         idx++;
592     }
593 
594     flash_area_close(fap_pri);
595     flash_area_close(fap_sec);
596 }
597 
app_max_size(struct boot_loader_state * state)598 int app_max_size(struct boot_loader_state *state)
599 {
600     uint32_t sector_sz_primary;
601     uint32_t sector_sz_secondary;
602     uint32_t sz_primary;
603     uint32_t sz_secondary;
604 
605     sector_sz_primary = boot_img_sector_size(state, BOOT_PRIMARY_SLOT, 0);
606     sector_sz_secondary = boot_img_sector_size(state, BOOT_SECONDARY_SLOT, 0);
607 
608     /* Account for image flags and move sector */
609     sz_primary = app_max_sectors(state) * sector_sz_primary - sector_sz_primary;
610     sz_secondary = boot_img_num_sectors(state, BOOT_SECONDARY_SLOT) * sector_sz_secondary;
611 
612     return (sz_primary <= sz_secondary ? sz_primary : sz_secondary);
613 }
614 
615 #endif
616