Boot: Synchronize MCUBoot code base

Perform a partial synchronization between the MCUBoot files in TF-M
and in the original repository. The hash of the source commit in the
original repository: 4f0ea747c314547daa6b6299ccbd77ae4dee6758.

Main changes:
- Remove current_image global variable and make it part
  of the boot state struct
- Update routines to receive the boot state by parameter
- Refactor dependency check functions
- Reorganize the flash map and related files
- Fix swap status control

Change-Id: Ibe948792b306e96282fb82447bb3f05a0c6389ef
Signed-off-by: David Vincze <david.vincze@arm.com>
diff --git a/bl2/ext/mcuboot/CMakeLists.txt b/bl2/ext/mcuboot/CMakeLists.txt
index 3464c52..49f3656 100644
--- a/bl2/ext/mcuboot/CMakeLists.txt
+++ b/bl2/ext/mcuboot/CMakeLists.txt
@@ -72,18 +72,20 @@
 #Append all our source files to global lists.
 list(APPEND ALL_SRC_C
 		"${MCUBOOT_DIR}/bl2_main.c"
-		"${MCUBOOT_DIR}/flash_map.c"
+		"${MCUBOOT_DIR}/flash_map_extended.c"
+		"${MCUBOOT_DIR}/flash_map_legacy.c"
 		"${MCUBOOT_DIR}/keys.c"
 		"${MCUBOOT_DIR}/bootutil/src/loader.c"
 		"${MCUBOOT_DIR}/bootutil/src/bootutil_misc.c"
 		"${MCUBOOT_DIR}/bootutil/src/image_validate.c"
 		"${MCUBOOT_DIR}/bootutil/src/image_rsa.c"
+		"${TFM_ROOT_DIR}/bl2/src/flash_map.c"
 		"${TFM_ROOT_DIR}/bl2/src/boot_record.c"
 		"${TFM_ROOT_DIR}/bl2/src/security_cnt.c"
 	)
 
 #Define location of Mbed Crypto source, build, and installation directory.
-set(MBEDTLS_CONFIG_FILE "config-boot.h")
+set(MBEDTLS_CONFIG_FILE "config-rsa.h")
 set(MBEDTLS_CONFIG_PATH "${TFM_ROOT_DIR}/bl2/ext/mcuboot/include")
 get_filename_component(MBEDCRYPTO_SOURCE_DIR "${TFM_ROOT_DIR}/../mbed-crypto" ABSOLUTE)
 if(NOT EXISTS ${MBEDCRYPTO_SOURCE_DIR})
diff --git a/bl2/ext/mcuboot/bl2_main.c b/bl2/ext/mcuboot/bl2_main.c
index f1e289d..641fd95 100644
--- a/bl2/ext/mcuboot/bl2_main.c
+++ b/bl2/ext/mcuboot/bl2_main.c
@@ -234,7 +234,6 @@
 
     BOOT_LOG_INF("Bootloader chainload address offset: 0x%x",
                  rsp.br_image_off);
-    flash_area_warn_on_open();
     BOOT_LOG_INF("Jumping to the first image slot");
     do_boot(&rsp);
 
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h
index 33a6634..5d48124 100644
--- a/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/bootutil.h
@@ -86,6 +86,10 @@
 /* you must have pre-allocated all the entries within this structure */
 int boot_go(struct boot_rsp *rsp);
 
+struct boot_loader_state;
+int context_boot_go(struct boot_loader_state *state, struct boot_rsp *rsp);
+
+int boot_swap_type_multi(int image_index);
 int boot_swap_type(void);
 
 int boot_set_pending(int permanent);
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/image.h b/bl2/ext/mcuboot/bootutil/include/bootutil/image.h
index bb2e9b8..45b7797 100644
--- a/bl2/ext/mcuboot/bootutil/include/bootutil/image.h
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/image.h
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2018-2019 Arm Limited.
  */
 
@@ -99,10 +99,10 @@
 struct image_header {
     uint32_t ih_magic;
     uint32_t ih_load_addr;
-    uint16_t ih_hdr_size;            /* Size of image header (bytes). */
-    uint16_t ih_protect_tlv_size;    /* Size of protected TLV area (bytes). */
-    uint32_t ih_img_size;            /* Does not include header. */
-    uint32_t ih_flags;               /* IMAGE_F_[...]. */
+    uint16_t ih_hdr_size;           /* Size of image header (bytes). */
+    uint16_t ih_protect_tlv_size;   /* Size of protected TLV area (bytes). */
+    uint32_t ih_img_size;           /* Does not include header. */
+    uint32_t ih_flags;              /* IMAGE_F_[...]. */
     struct image_version ih_ver;
     uint32_t _pad1;
 };
@@ -123,7 +123,8 @@
 _Static_assert(sizeof(struct image_header) == IMAGE_HEADER_SIZE,
                "struct image_header not required size");
 
-int bootutil_img_validate(struct image_header *hdr,
+int bootutil_img_validate(int image_index,
+                          struct image_header *hdr,
                           const struct flash_area *fap,
                           uint8_t *tmp_buf, uint32_t tmp_buf_sz,
                           uint8_t *seed, int seed_len, uint8_t *out_hash);
diff --git a/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h b/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h
index 31832e2..8c3c23a 100644
--- a/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h
+++ b/bl2/ext/mcuboot/bootutil/include/bootutil/sha256.h
@@ -27,7 +27,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2019 Arm Limited.
  */
 
@@ -47,20 +47,20 @@
 static inline void bootutil_sha256_init(bootutil_sha256_context *ctx)
 {
     mbedtls_sha256_init(ctx);
-    mbedtls_sha256_starts_ret(ctx, 0);
+    (void)mbedtls_sha256_starts_ret(ctx, 0);
 }
 
 static inline void bootutil_sha256_update(bootutil_sha256_context *ctx,
                                           const void *data,
                                           uint32_t data_len)
 {
-    mbedtls_sha256_update_ret(ctx, data, data_len);
+    (void)mbedtls_sha256_update_ret(ctx, data, data_len);
 }
 
 static inline void bootutil_sha256_finish(bootutil_sha256_context *ctx,
                                           uint8_t *output)
 {
-    mbedtls_sha256_finish_ret(ctx, output);
+    (void)mbedtls_sha256_finish_ret(ctx, output);
 }
 
 #ifdef __cplusplus
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c b/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
index f83db99..8af74ca 100644
--- a/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
+++ b/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2019 Arm Limited.
  */
 
@@ -36,6 +36,7 @@
 #include "bootutil_priv.h"
 #include "bootutil/bootutil_log.h"
 
+/* Currently only used by imgmgr */
 int boot_current_slot;
 
 const uint32_t boot_img_magic[] = {
@@ -182,23 +183,16 @@
            BOOT_MAGIC_SZ;
 }
 
-static uint32_t
-boot_magic_off(const struct flash_area *fap)
-{
-    return fap->fa_size - BOOT_MAGIC_SZ;
-}
-
 int
-boot_status_entries(const struct flash_area *fap)
+boot_status_entries(int image_index, const struct flash_area *fap)
 {
     if (fap->fa_id == FLASH_AREA_IMAGE_SCRATCH) {
         return BOOT_STATUS_STATE_COUNT;
-    } else if ((fap->fa_id == FLASH_AREA_IMAGE_PRIMARY) ||
-               (fap->fa_id == FLASH_AREA_IMAGE_SECONDARY)) {
+    } else if ((fap->fa_id == FLASH_AREA_IMAGE_PRIMARY(image_index)) ||
+               (fap->fa_id == FLASH_AREA_IMAGE_SECONDARY(image_index))) {
         return BOOT_STATUS_STATE_COUNT * BOOT_STATUS_MAX_ENTRIES;
-    } else {
-        return BOOT_EBADARGS;
     }
+    return -1;
 }
 
 uint32_t
@@ -215,28 +209,34 @@
     return fap->fa_size - off_from_end;
 }
 
+static inline uint32_t
+boot_magic_off(const struct flash_area *fap)
+{
+    return fap->fa_size - BOOT_MAGIC_SZ;
+}
+
+static inline uint32_t
+boot_image_ok_off(const struct flash_area *fap)
+{
+    return boot_magic_off(fap) - BOOT_MAX_ALIGN;
+}
+
+static inline uint32_t
+boot_copy_done_off(const struct flash_area *fap)
+{
+    return boot_image_ok_off(fap) - BOOT_MAX_ALIGN;
+}
+
 uint32_t
 boot_swap_info_off(const struct flash_area *fap)
 {
-    return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 3;
+    return boot_copy_done_off(fap) - BOOT_MAX_ALIGN;
 }
 
-static uint32_t
-boot_copy_done_off(const struct flash_area *fap)
-{
-    return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 2;
-}
-
-static uint32_t
-boot_image_ok_off(const struct flash_area *fap)
-{
-    return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN;
-}
-
-static uint32_t
+static inline uint32_t
 boot_swap_size_off(const struct flash_area *fap)
 {
-    return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 4;
+    return boot_swap_info_off(fap) - BOOT_MAX_ALIGN;
 }
 
 int
@@ -310,15 +310,9 @@
     const struct flash_area *fap;
     int rc;
 
-    if (flash_area_id == FLASH_AREA_IMAGE_SCRATCH ||
-        flash_area_id == FLASH_AREA_IMAGE_PRIMARY ||
-        flash_area_id == FLASH_AREA_IMAGE_SECONDARY) {
-        rc = flash_area_open(flash_area_id, &fap);
-        if (rc != 0) {
-            return BOOT_EFLASH;
-        }
-    } else {
-        return BOOT_EBADARGS;
+    rc = flash_area_open(flash_area_id, &fap);
+    if (rc != 0) {
+        return BOOT_EFLASH;
     }
 
     rc = boot_read_swap_state(fap, state);
@@ -326,68 +320,76 @@
     return rc;
 }
 
-int
-boot_read_swap_size(uint32_t *swap_size)
+/**
+ * This functions tries to locate the status area after an aborted swap,
+ * by looking for the magic in the possible locations.
+ *
+ * If the magic is sucessfully found, a flash_area * is returned and it
+ * is the responsibility of the called to close it.
+ *
+ * @returns 0 on success, -1 on errors
+ */
+static int
+boot_find_status(int image_index, const struct flash_area **fap)
 {
     uint32_t magic[BOOT_MAGIC_ARR_SZ];
     uint32_t off;
+    uint8_t areas[2] = {
+        FLASH_AREA_IMAGE_PRIMARY(image_index),
+        FLASH_AREA_IMAGE_SCRATCH,
+    };
+    unsigned int i;
+    int rc;
+
+    /*
+     * In the middle a swap, tries to locate the area that is currently
+     * storing a valid magic, first on the primary slot, then on scratch.
+     * Both "slots" can end up being temporary storage for a swap and it
+     * is assumed that if magic is valid then other metadata is too,
+     * because magic is always written in the last step.
+     */
+
+    for (i = 0; i < sizeof(areas) / sizeof(areas[0]); i++) {
+        rc = flash_area_open(areas[i], fap);
+        if (rc != 0) {
+            return rc;
+        }
+
+        off = boot_magic_off(*fap);
+        rc = flash_area_read(*fap, off, magic, BOOT_MAGIC_SZ);
+        if (rc != 0) {
+            flash_area_close(*fap);
+            return rc;
+        }
+
+        if (memcmp(magic, boot_img_magic, BOOT_MAGIC_SZ) == 0) {
+            return 0;
+        }
+
+        flash_area_close(*fap);
+    }
+
+    /* If we got here, no magic was found */
+    return -1;
+}
+
+int
+boot_read_swap_size(int image_index, uint32_t *swap_size)
+{
+    uint32_t off;
     const struct flash_area *fap;
     int rc;
 
-    /*
-     * In the middle a swap, tries to locate the saved swap size. Looks
-     * for a valid magic, first on the primary slot, then on scratch.
-     * Both "slots" can end up being temporary storage for a swap and it
-     * is assumed that if magic is valid then swap size is too, because
-     * magic is always written in the last step.
-     */
-
-    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY, &fap);
-    if (rc != 0) {
-        return BOOT_EFLASH;
-    }
-
-    off = boot_magic_off(fap);
-    rc = flash_area_read(fap, off, magic, BOOT_MAGIC_SZ);
-    if (rc != 0) {
-        rc = BOOT_EFLASH;
-        goto out;
-    }
-
-    if (boot_secure_memequal(magic, boot_img_magic, BOOT_MAGIC_SZ) != 0) {
-        /*
-         * If the primary slot's magic is not valid, try scratch...
-         */
-
+    rc = boot_find_status(image_index, &fap);
+    if (rc == 0) {
+        off = boot_swap_size_off(fap);
+        rc = flash_area_read(fap, off, swap_size, sizeof *swap_size);
         flash_area_close(fap);
-
-        rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
-        if (rc != 0) {
-            return BOOT_EFLASH;
-        }
-
-        off = boot_magic_off(fap);
-        rc = flash_area_read(fap, off, magic, BOOT_MAGIC_SZ);
-        if (rc != 0) {
-            rc = BOOT_EFLASH;
-            goto out;
-        }
-
-        assert(boot_secure_memequal(magic, boot_img_magic, BOOT_MAGIC_SZ) == 0);
     }
 
-    off = boot_swap_size_off(fap);
-    rc = flash_area_read(fap, off, swap_size, sizeof(*swap_size));
-    if (rc != 0) {
-        rc = BOOT_EFLASH;
-    }
-
-out:
-    flash_area_close(fap);
     return rc;
 }
 
-
 int
 boot_write_magic(const struct flash_area *fap)
 {
@@ -396,8 +398,9 @@
 
     off = boot_magic_off(fap);
 
-    BOOT_LOG_DBG("writing magic; fa_id=%d off=0x%x (0x%x)",
-                 fap->fa_id, off, fap->fa_off + off);
+    BOOT_LOG_DBG("writing magic; fa_id=%d off=0x%lx (0x%lx)",
+                 fap->fa_id, (unsigned long)off,
+                 (unsigned long)(fap->fa_off + off));
     rc = flash_area_write(fap, off, boot_img_magic, BOOT_MAGIC_SZ);
     if (rc != 0) {
         return BOOT_EFLASH;
@@ -406,20 +409,30 @@
     return 0;
 }
 
+/**
+ * Write trailer data; status bytes, swap_size, etc
+ *
+ * @returns 0 on success, != 0 on error.
+ */
 static int
-boot_write_trailer_byte(const struct flash_area *fap, uint32_t off,
-                        uint8_t val)
+boot_write_trailer(const struct flash_area *fap, uint32_t off,
+        const uint8_t *inbuf, uint8_t inlen)
 {
     uint8_t buf[BOOT_MAX_ALIGN];
-    uint32_t align;
+    uint8_t align;
     uint8_t erased_val;
     int rc;
 
     align = flash_area_align(fap);
-    assert(align <= BOOT_MAX_ALIGN);
+    if (inlen > BOOT_MAX_ALIGN || align > BOOT_MAX_ALIGN) {
+        return -1;
+    }
     erased_val = flash_area_erased_val(fap);
-    memset(buf, erased_val, BOOT_MAX_ALIGN);
-    buf[0] = val;
+    if (align < inlen) {
+        align = inlen;
+    }
+    memcpy(buf, inbuf, inlen);
+    memset(&buf[inlen], erased_val, align - inlen);
 
     rc = flash_area_write(fap, off, buf, align);
     if (rc != 0) {
@@ -429,15 +442,24 @@
     return 0;
 }
 
+static int
+boot_write_trailer_flag(const struct flash_area *fap, uint32_t off,
+        uint8_t flag_val)
+{
+    const uint8_t buf[1] = { flag_val };
+    return boot_write_trailer(fap, off, buf, 1);
+}
+
 int
 boot_write_copy_done(const struct flash_area *fap)
 {
     uint32_t off;
 
     off = boot_copy_done_off(fap);
-    BOOT_LOG_DBG("writing copy_done; fa_id=%d off=0x%x (0x%x)",
-                 fap->fa_id, off, fap->fa_off + off);
-    return boot_write_trailer_byte(fap, off, BOOT_FLAG_SET);
+    BOOT_LOG_DBG("writing copy_done; fa_id=%d off=0x%lx (0x%lx)",
+                 fap->fa_id, (unsigned long)off,
+                 (unsigned long)(fap->fa_off + off));
+    return boot_write_trailer_flag(fap, off, BOOT_FLAG_SET);
 }
 
 int
@@ -446,9 +468,10 @@
     uint32_t off;
 
     off = boot_image_ok_off(fap);
-    BOOT_LOG_DBG("writing image_ok; fa_id=%d off=0x%x (0x%x)",
-                 fap->fa_id, off, fap->fa_off + off);
-    return boot_write_trailer_byte(fap, off, BOOT_FLAG_SET);
+    BOOT_LOG_DBG("writing image_ok; fa_id=%d off=0x%lx (0x%lx)",
+                 fap->fa_id, (unsigned long)off,
+                 (unsigned long)(fap->fa_off + off));
+    return boot_write_trailer_flag(fap, off, BOOT_FLAG_SET);
 }
 
 /**
@@ -465,46 +488,27 @@
 
     BOOT_SET_SWAP_INFO(swap_info, image_num, swap_type);
     off = boot_swap_info_off(fap);
-    BOOT_LOG_DBG("writing swap_info; fa_id=%d off=0x%x (0x%x), swap_type=0x%x"
+    BOOT_LOG_DBG("writing swap_info; fa_id=%d off=0x%lx (0x%lx), swap_type=0x%x"
                  " image_num=0x%x",
-                 fap->fa_id, off, fap->fa_off + off,
-                 BOOT_GET_SWAP_TYPE(swap_info),
-                 BOOT_GET_IMAGE_NUM(swap_info));
-    return boot_write_trailer_byte(fap, off, swap_info);
+                 fap->fa_id, (unsigned long)off,
+                 (unsigned long)(fap->fa_off + off), swap_type, image_num);
+    return boot_write_trailer(fap, off, (const uint8_t *) &swap_info, 1);
 }
 
 int
 boot_write_swap_size(const struct flash_area *fap, uint32_t swap_size)
 {
     uint32_t off;
-    int rc;
-    uint8_t buf[BOOT_MAX_ALIGN];
-    uint32_t align;
-    uint8_t erased_val;
 
     off = boot_swap_size_off(fap);
-    align = flash_area_align(fap);
-    assert(align <= BOOT_MAX_ALIGN);
-    if (align < sizeof(swap_size)) {
-        align = sizeof(swap_size);
-    }
-    erased_val = flash_area_erased_val(fap);
-    memset(buf, erased_val, BOOT_MAX_ALIGN);
-    memcpy(buf, (uint8_t *)&swap_size, sizeof(swap_size));
-
-    BOOT_LOG_DBG("writing swap_size; fa_id=%d off=0x%x (0x%x)",
-                 fap->fa_id, off, fap->fa_off + off);
-
-    rc = flash_area_write(fap, off, buf, align);
-    if (rc != 0) {
-        return BOOT_EFLASH;
-    }
-
-    return 0;
+    BOOT_LOG_DBG("writing swap_size; fa_id=%d off=0x%lx (0x%lx)",
+                 fap->fa_id, (unsigned long)off,
+                 (unsigned long)fap->fa_off + off);
+    return boot_write_trailer(fap, off, (const uint8_t *) &swap_size, 4);
 }
 
 int
-boot_swap_type(void)
+boot_swap_type_multi(int image_index)
 {
     const struct boot_swap_table *table;
     struct boot_swap_state primary_slot;
@@ -512,12 +516,13 @@
     int rc;
     size_t i;
 
-    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_PRIMARY, &primary_slot);
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_PRIMARY(image_index),
+                                    &primary_slot);
     if (rc) {
         return BOOT_SWAP_TYPE_PANIC;
     }
 
-    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SECONDARY,
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SECONDARY(image_index),
                                     &secondary_slot);
     if (rc) {
         return BOOT_SWAP_TYPE_PANIC;
@@ -541,9 +546,11 @@
                          table->swap_type == BOOT_SWAP_TYPE_PERM   ? "perm"   :
                          table->swap_type == BOOT_SWAP_TYPE_REVERT ? "revert" :
                          "BUG; can't happen");
-            assert(table->swap_type == BOOT_SWAP_TYPE_TEST ||
-                   table->swap_type == BOOT_SWAP_TYPE_PERM ||
-                   table->swap_type == BOOT_SWAP_TYPE_REVERT);
+            if (table->swap_type != BOOT_SWAP_TYPE_TEST &&
+                    table->swap_type != BOOT_SWAP_TYPE_PERM &&
+                    table->swap_type != BOOT_SWAP_TYPE_REVERT) {
+                return BOOT_SWAP_TYPE_PANIC;
+            }
             return table->swap_type;
         }
     }
@@ -552,6 +559,16 @@
     return BOOT_SWAP_TYPE_NONE;
 }
 
+/*
+ * This function is not used by the bootloader itself, but its required API
+ * by external tooling like mcumgr.
+ */
+int
+boot_swap_type(void)
+{
+    return boot_swap_type_multi(0);
+}
+
 /**
  * Marks the image in the secondary slot as pending.  On the next reboot,
  * the system will perform a one-time boot of the the secondary slot image.
@@ -571,7 +588,7 @@
     uint8_t swap_type;
     int rc;
 
-    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SECONDARY,
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SECONDARY(0),
                                     &state_secondary_slot);
     if (rc != 0) {
         return rc;
@@ -583,7 +600,7 @@
         return 0;
 
     case BOOT_MAGIC_UNSET:
-        rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY, &fap);
+        rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY(0), &fap);
         if (rc != 0) {
             rc = BOOT_EFLASH;
         } else {
@@ -610,7 +627,7 @@
         /* The image slot is corrupt.  There is no way to recover, so erase the
          * slot to allow future upgrades.
          */
-        rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY, &fap);
+        rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY(0), &fap);
         if (rc != 0) {
             return BOOT_EFLASH;
         }
@@ -639,7 +656,7 @@
     struct boot_swap_state state_primary_slot;
     int rc;
 
-    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_PRIMARY,
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_PRIMARY(0),
                                     &state_primary_slot);
     if (rc != 0) {
         return rc;
@@ -659,6 +676,12 @@
         return BOOT_EBADVECT;
     }
 
+    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY(0), &fap);
+    if (rc) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
     if (state_primary_slot.copy_done == BOOT_FLAG_UNSET) {
         /* Swap never completed.  This is unexpected. */
         rc = BOOT_EBADVECT;
@@ -670,59 +693,13 @@
         goto done;
     }
 
-    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY, &fap);
-    if (rc) {
-        rc = BOOT_EFLASH;
-        goto done;
-    }
-
     rc = boot_write_image_ok(fap);
-    if (rc != 0) {
-        goto done;
-    }
-
-    rc = 0;
 
 done:
     flash_area_close(fap);
     return rc;
 }
 
-#if (BOOT_IMAGE_NUMBER > 1)
-/**
- * Check if the version of the image is not older than required.
- *
- * @param req         Required minimal image version.
- * @param ver         Version of the image to be checked.
- *
- * @return            0 if the version is sufficient, nonzero otherwise.
- */
-int
-boot_is_version_sufficient(struct image_version *req,
-                           struct image_version *ver)
-{
-    if (ver->iv_major > req->iv_major) {
-        return 0;
-    }
-    if (ver->iv_major < req->iv_major) {
-        return BOOT_EBADVERSION;
-    }
-    /* The major version numbers are equal. */
-    if (ver->iv_minor > req->iv_minor) {
-        return 0;
-    }
-    if (ver->iv_minor < req->iv_minor) {
-        return BOOT_EBADVERSION;
-    }
-    /* The minor version numbers are equal. */
-    if (ver->iv_revision < req->iv_revision) {
-        return BOOT_EBADVERSION;
-    }
-
-    return 0;
-}
-#endif /* BOOT_IMAGE_NUMBER > 1 */
-
 /**
  * Checks whether on overflow can happen during a summation operation
  *
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h b/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
index 516d196..2f37047 100644
--- a/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
+++ b/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2018-2019 Arm Limited.
  */
 
@@ -52,8 +52,8 @@
 #define BOOT_EBADSTATUS  5
 #define BOOT_ENOMEM      6
 #define BOOT_EBADARGS    7
-#define BOOT_EBADMAGIC   8
-#define BOOT_EBADVERSION 9
+#define BOOT_EBADVERSION 8
+#define BOOT_EBADMAGIC   9
 
 #define BOOT_TMPBUF_SZ  256
 
@@ -111,7 +111,6 @@
  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
  */
 
-extern uint8_t current_image;
 extern const uint32_t boot_img_magic[4];
 
 struct boot_swap_state {
@@ -123,11 +122,13 @@
 };
 
 #ifdef MCUBOOT_IMAGE_NUMBER
-#define BOOT_IMAGE_NUMBER       MCUBOOT_IMAGE_NUMBER
+#define BOOT_IMAGE_NUMBER          MCUBOOT_IMAGE_NUMBER
 #else
-#define BOOT_IMAGE_NUMBER       1
+#define BOOT_IMAGE_NUMBER          1
 #endif
 
+_Static_assert(BOOT_IMAGE_NUMBER > 0, "Invalid value for BOOT_IMAGE_NUMBER");
+
 /*
  * Extract the swap type and image number from image trailers's swap_info
  * field.
@@ -204,6 +205,10 @@
 
     uint8_t swap_type[BOOT_IMAGE_NUMBER];
     uint32_t write_sz;
+
+#if (BOOT_IMAGE_NUMBER > 1)
+    uint8_t curr_img_idx;
+#endif
 };
 
 uint32_t boot_secure_memequal(const void *s1, const void *s2, size_t n);
@@ -212,7 +217,7 @@
 
 int boot_magic_compatible_check(uint8_t tbl_val, uint8_t val);
 uint32_t boot_trailer_sz(uint32_t min_write_sz);
-int boot_status_entries(const struct flash_area *fap);
+int boot_status_entries(int image_index, const struct flash_area *fap);
 uint32_t boot_status_off(const struct flash_area *fap);
 uint32_t boot_swap_info_off(const struct flash_area *fap);
 int boot_read_swap_state(const struct flash_area *fap,
@@ -220,18 +225,17 @@
 int boot_read_swap_state_by_id(int flash_area_id,
                                struct boot_swap_state *state);
 int boot_write_magic(const struct flash_area *fap);
-int boot_write_status(struct boot_status *bs);
+int boot_write_status(struct boot_loader_state *state, struct boot_status *bs);
 int boot_schedule_test_swap(void);
 int boot_write_copy_done(const struct flash_area *fap);
 int boot_write_image_ok(const struct flash_area *fap);
 int boot_write_swap_info(const struct flash_area *fap, uint8_t swap_type,
                          uint8_t image_num);
 int boot_write_swap_size(const struct flash_area *fap, uint32_t swap_size);
-int boot_read_swap_size(uint32_t *swap_size);
-#if (BOOT_IMAGE_NUMBER > 1)
-int boot_is_version_sufficient(struct image_version *req,
-                               struct image_version *ver);
-#endif
+int boot_read_swap_size(int image_index, uint32_t *swap_size);
+int boot_find_tlv_offs(const struct image_header *hdr,
+                       const struct flash_area *fap,
+                       uint32_t *off, uint32_t *end);
 bool boot_add_uint32_overflow_check(uint32_t a, uint32_t b);
 bool boot_add_uint16_overflow_check(uint16_t a, uint16_t b);
 
@@ -240,12 +244,23 @@
  */
 
 /* These are macros so they can be used as lvalues. */
-#define BOOT_IMG(state, slot) ((state)->imgs[current_image][(slot)])
+#if (BOOT_IMAGE_NUMBER > 1)
+#define BOOT_CURR_IMG(state) ((state)->curr_img_idx)
+#else
+#define BOOT_CURR_IMG(state) 0
+#endif
+#define BOOT_IMG(state, slot) ((state)->imgs[BOOT_CURR_IMG(state)][(slot)])
 #define BOOT_IMG_AREA(state, slot) (BOOT_IMG(state, slot).area)
 #define BOOT_IMG_HDR_IS_VALID(state, slot) (BOOT_IMG(state, slot).is_hdr_valid)
 #define BOOT_SCRATCH_AREA(state) ((state)->scratch.area)
 #define BOOT_WRITE_SZ(state) ((state)->write_sz)
-#define BOOT_SWAP_TYPE(state) ((state)->swap_type[current_image])
+#define BOOT_SWAP_TYPE(state) ((state)->swap_type[BOOT_CURR_IMG(state)])
+#define BOOT_TLV_OFF(hdr) ((hdr)->ih_hdr_size + (hdr)->ih_img_size)
+
+#define BOOT_IS_UPGRADE(swap_type)             \
+    (((swap_type) == BOOT_SWAP_TYPE_TEST) ||   \
+     ((swap_type) == BOOT_SWAP_TYPE_REVERT) || \
+     ((swap_type) == BOOT_SWAP_TYPE_PERM))
 
 static inline struct image_header*
 boot_img_hdr(struct boot_loader_state *state, size_t slot)
@@ -254,7 +269,7 @@
 }
 
 static inline size_t
-boot_img_num_sectors(struct boot_loader_state *state, size_t slot)
+boot_img_num_sectors(const struct boot_loader_state *state, size_t slot)
 {
     return BOOT_IMG(state, slot).num_sectors;
 }
@@ -282,7 +297,7 @@
 #ifndef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
 
 static inline size_t
-boot_img_sector_size(struct boot_loader_state *state,
+boot_img_sector_size(const struct boot_loader_state *state,
                      size_t slot, size_t sector)
 {
     return BOOT_IMG(state, slot).sectors[sector].fa_size;
@@ -293,86 +308,30 @@
  * device.
  */
 static inline uint32_t
-boot_img_sector_off(struct boot_loader_state *state, size_t slot,
+boot_img_sector_off(const struct boot_loader_state *state, size_t slot,
                     size_t sector)
 {
     return BOOT_IMG(state, slot).sectors[sector].fa_off -
            BOOT_IMG(state, slot).sectors[0].fa_off;
 }
 
-static inline int
-boot_initialize_area(struct boot_loader_state *state, int flash_area)
-{
-    int num_sectors = BOOT_MAX_IMG_SECTORS;
-    int rc;
-
-    if (flash_area == FLASH_AREA_IMAGE_PRIMARY) {
-        rc = flash_area_to_sectors(flash_area, &num_sectors,
-                                   BOOT_IMG(state, BOOT_PRIMARY_SLOT).sectors);
-        BOOT_IMG(state, BOOT_PRIMARY_SLOT).num_sectors = (size_t)num_sectors;
-    } else if (flash_area == FLASH_AREA_IMAGE_SECONDARY) {
-        rc = flash_area_to_sectors(flash_area, &num_sectors,
-                                 BOOT_IMG(state, BOOT_SECONDARY_SLOT).sectors);
-        BOOT_IMG(state, BOOT_SECONDARY_SLOT).num_sectors = (size_t)num_sectors;
-    } else if (flash_area == FLASH_AREA_IMAGE_SCRATCH) {
-        rc = flash_area_to_sectors(flash_area, &num_sectors,
-                                   state->scratch.sectors);
-        state->scratch.num_sectors = (size_t)num_sectors;
-    } else {
-        return BOOT_EFLASH;
-    }
-
-    return rc;
-}
-
 #else  /* defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
 
 static inline size_t
-boot_img_sector_size(struct boot_loader_state *state,
+boot_img_sector_size(const struct boot_loader_state *state,
                      size_t slot, size_t sector)
 {
     return BOOT_IMG(state, slot).sectors[sector].fs_size;
 }
 
 static inline uint32_t
-boot_img_sector_off(struct boot_loader_state *state, size_t slot,
+boot_img_sector_off(const struct boot_loader_state *state, size_t slot,
                     size_t sector)
 {
     return BOOT_IMG(state, slot).sectors[sector].fs_off -
            BOOT_IMG(state, slot).sectors[0].fs_off;
 }
 
-static inline int
-boot_initialize_area(struct boot_loader_state *state, int flash_area)
-{
-    uint32_t num_sectors;
-    struct flash_sector *out_sectors;
-    size_t *out_num_sectors;
-    int rc;
-
-    num_sectors = BOOT_MAX_IMG_SECTORS;
-
-    if (flash_area == FLASH_AREA_IMAGE_PRIMARY) {
-        out_sectors = BOOT_IMG(state, BOOT_PRIMARY_SLOT).sectors;
-        out_num_sectors = &BOOT_IMG(state, BOOT_PRIMARY_SLOT).num_sectors;
-    } else if (flash_area == FLASH_AREA_IMAGE_SECONDARY) {
-        out_sectors = BOOT_IMG(state, BOOT_SECONDARY_SLOT).sectors;
-        out_num_sectors = &BOOT_IMG(state, BOOT_SECONDARY_SLOT).num_sectors;
-    } else if (flash_area == FLASH_AREA_IMAGE_SCRATCH) {
-        out_sectors = state->scratch.sectors;
-        out_num_sectors = &state->scratch.num_sectors;
-    } else {
-        return BOOT_EFLASH;
-    }
-
-    rc = flash_area_get_sectors(flash_area, &num_sectors, out_sectors);
-    if (rc != 0) {
-        return rc;
-    }
-    *out_num_sectors = num_sectors;
-    return 0;
-}
-
 #endif  /* !defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
 
 #ifdef MCUBOOT_RAM_LOADING
diff --git a/bl2/ext/mcuboot/bootutil/src/image_rsa.c b/bl2/ext/mcuboot/bootutil/src/image_rsa.c
index ae71d9b..08ef6f5 100644
--- a/bl2/ext/mcuboot/bootutil/src/image_rsa.c
+++ b/bl2/ext/mcuboot/bootutil/src/image_rsa.c
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2018-2019 Arm Limited.
  */
 
diff --git a/bl2/ext/mcuboot/bootutil/src/image_validate.c b/bl2/ext/mcuboot/bootutil/src/image_validate.c
index 13892d8..59e0b69 100644
--- a/bl2/ext/mcuboot/bootutil/src/image_validate.c
+++ b/bl2/ext/mcuboot/bootutil/src/image_validate.c
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2018-2019 Arm Limited.
  */
 
@@ -35,7 +35,7 @@
 #include "bootutil/sign_key.h"
 #include "security_cnt.h"
 
-#ifdef MCUBOOT_SIGN_RSA
+#if defined(MCUBOOT_SIGN_RSA)
 #include "mbedtls/rsa.h"
 #endif
 
@@ -51,17 +51,21 @@
  * Compute SHA256 over the image.
  */
 static int
-bootutil_img_hash(struct image_header *hdr, const struct flash_area *fap,
-                  uint8_t *tmp_buf, uint32_t tmp_buf_sz,
-                  uint8_t *hash_result, uint8_t *seed, int seed_len)
+bootutil_img_hash(int image_index,
+                  struct image_header *hdr, const struct flash_area *fap,
+                  uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *hash_result,
+                  uint8_t *seed, int seed_len)
 {
     bootutil_sha256_context sha256_ctx;
     uint32_t size;
 #ifndef MCUBOOT_RAM_LOADING
     uint32_t blk_sz;
     uint32_t off;
+    int rc;
 #endif /* MCUBOOT_RAM_LOADING */
 
+    (void)image_index;
+
     bootutil_sha256_init(&sha256_ctx);
 
     /* in some cases (split image) the hash is seeded with data from
@@ -71,7 +75,7 @@
     }
 
     /* Hash is computed over image header and image itself. */
-    size = hdr->ih_img_size + hdr->ih_hdr_size;
+    size = BOOT_TLV_OFF(hdr);
 
     /* If protected TLVs are present (e.g. security counter TLV) then the
      * TLV info header and these TLVs must be included in the hash calculation.
@@ -88,8 +92,9 @@
         if (blk_sz > tmp_buf_sz) {
             blk_sz = tmp_buf_sz;
         }
-        if(flash_area_read(fap, off, tmp_buf, blk_sz)) {
-            return -1;
+        rc = flash_area_read(fap, off, tmp_buf, blk_sz);
+        if (rc) {
+            return rc;
         }
         bootutil_sha256_update(&sha256_ctx, tmp_buf, blk_sz);
     }
@@ -123,9 +128,8 @@
 #ifdef EXPECTED_SIG_TLV
 #ifdef MCUBOOT_HW_KEY
 extern unsigned int pub_key_len;
-extern uint8_t current_image;
 static int
-bootutil_find_key(uint8_t *key, uint16_t key_len)
+bootutil_find_key(uint8_t image_id, uint8_t *key, uint16_t key_len)
 {
     bootutil_sha256_context sha256_ctx;
     uint8_t hash[32];
@@ -137,7 +141,7 @@
     bootutil_sha256_update(&sha256_ctx, key, key_len);
     bootutil_sha256_finish(&sha256_ctx, hash);
 
-    plat_err = tfm_plat_get_rotpk_hash(current_image, key_hash, &key_hash_size);
+    plat_err = tfm_plat_get_rotpk_hash(image_id, key_hash, &key_hash_size);
     if (plat_err != TFM_PLAT_ERR_SUCCESS) {
         return -1;
     }
@@ -148,7 +152,7 @@
     }
     return -1;
 }
-#else
+#else /* !MCUBOOT_HW_KEY */
 static int
 bootutil_find_key(uint8_t *keyhash, uint8_t keyhash_len)
 {
@@ -157,7 +161,9 @@
     const struct bootutil_key *key;
     uint8_t hash[32];
 
-    assert(keyhash_len <= 32);
+    if (keyhash_len > 32) {
+        return -1;
+    }
 
     for (i = 0; i < bootutil_key_cnt; i++) {
         key = &bootutil_keys[i];
@@ -270,14 +276,14 @@
  * Return non-zero if image could not be validated/does not validate.
  */
 int
-bootutil_img_validate(struct image_header *hdr, const struct flash_area *fap,
-                      uint8_t *tmp_buf, uint32_t tmp_buf_sz,
-                      uint8_t *seed, int seed_len, uint8_t *out_hash)
+bootutil_img_validate(int image_index,
+                      struct image_header *hdr, const struct flash_area *fap,
+                      uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *seed,
+                      int seed_len, uint8_t *out_hash)
 {
     uint32_t off;
     uint32_t end;
     int sha256_valid = 0;
-    struct image_tlv_info info;
 #ifdef EXPECTED_SIG_TLV
     int valid_signature = 0;
     int key_id = -1;
@@ -294,8 +300,8 @@
     int32_t security_counter_valid = 0;
     int rc;
 
-    rc = bootutil_img_hash(hdr, fap, tmp_buf, tmp_buf_sz, hash,
-                           seed, seed_len);
+    rc = bootutil_img_hash(image_index, hdr, fap, tmp_buf,
+            tmp_buf_sz, hash, seed, seed_len);
     if (rc) {
         return rc;
     }
@@ -304,21 +310,10 @@
         memcpy(out_hash, hash, 32);
     }
 
-    /* The TLVs come after the image. */
-    off = hdr->ih_img_size + hdr->ih_hdr_size;
-
-    rc = LOAD_IMAGE_DATA(fap, off, &info, sizeof(info));
+    rc = boot_find_tlv_offs(hdr, fap, &off, &end);
     if (rc) {
         return rc;
     }
-    if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
-        return BOOT_EBADMAGIC;
-    }
-    if (boot_add_uint32_overflow_check(off, (info.it_tlv_tot + sizeof(info)))) {
-        return -1;
-    }
-    end = off + info.it_tlv_tot;
-    off += sizeof(info);
 
     /*
      * Traverse through all of the TLVs, performing any checks we know
@@ -365,7 +360,7 @@
              * The key may not be found, which is acceptable.  There
              * can be multiple signatures, each preceded by a key.
              */
-#else
+#else /* MCUBOOT_HW_KEY */
         } else if (tlv.it_type == IMAGE_TLV_KEY) {
             /*
              * Determine which key we should be checking.
@@ -377,7 +372,7 @@
             if (rc) {
                 return rc;
             }
-            key_id = bootutil_find_key(key_buf, tlv.it_len);
+            key_id = bootutil_find_key(image_index, key_buf, tlv.it_len);
             /*
              * The key may not be found, which is acceptable.  There
              * can be multiple signatures, each preceded by a key.
diff --git a/bl2/ext/mcuboot/bootutil/src/loader.c b/bl2/ext/mcuboot/bootutil/src/loader.c
index 3e0ba90..5204a1e 100644
--- a/bl2/ext/mcuboot/bootutil/src/loader.c
+++ b/bl2/ext/mcuboot/bootutil/src/loader.c
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2018-2019 Arm Limited.
  */
 
@@ -45,7 +45,12 @@
 #include "security_cnt.h"
 
 static struct boot_loader_state boot_data;
-uint8_t current_image = 0;
+
+#if (BOOT_IMAGE_NUMBER > 1)
+#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
+#else
+#define IMAGES_ITER(x)
+#endif
 
 #if !defined(MCUBOOT_NO_SWAP) && !defined(MCUBOOT_RAM_LOADING)
 
@@ -154,6 +159,38 @@
 #endif /* !MCUBOOT_NO_SWAP && !MCUBOOT_RAM_LOADING */
 
 /*
+ * Locate the TLVs in an image.
+ *
+ * @param hdr The image_header struct of the image being checked
+ * @param fap flash_area struct of the slot storing the image being checked
+ * @param off Address of the first TLV (after TLV info)
+ * @param end Address where TLV area ends
+ *
+ * Returns 0 on success.
+ */
+int
+boot_find_tlv_offs(const struct image_header *hdr, const struct flash_area *fap,
+        uint32_t *off, uint32_t *end)
+{
+    struct image_tlv_info info;
+    uint32_t off_;
+
+    off_ = BOOT_TLV_OFF(hdr);
+
+    if (LOAD_IMAGE_DATA(fap, off_, &info, sizeof(info))) {
+        return BOOT_EFLASH;
+    }
+
+    if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
+        return BOOT_EBADIMAGE;
+    }
+
+    *end = off_ + info.it_tlv_tot;
+    *off = off_ + sizeof(info);
+    return 0;
+}
+
+/*
  * \brief Verifies the image header: magic value, flags, integer overflow.
  *
  * \retval 0
@@ -194,13 +231,18 @@
 }
 
 static int
-boot_read_image_header(int slot, struct image_header *out_hdr)
+boot_read_image_header(struct boot_loader_state *state, int slot,
+                       struct image_header *out_hdr)
 {
     const struct flash_area *fap = NULL;
     int area_id;
     int rc;
 
-    area_id = flash_area_id_from_image_slot(slot);
+#if (BOOT_IMAGE_NUMBER == 1)
+    (void)state;
+#endif
+
+    area_id = flash_area_id_from_multi_image_slot(BOOT_CURR_IMG(state), slot);
     rc = flash_area_open(area_id, &fap);
     if (rc != 0) {
         rc = BOOT_EFLASH;
@@ -214,7 +256,7 @@
     }
 
     rc = boot_verify_image_header(out_hdr);
-    BOOT_IMG_HDR_IS_VALID(&boot_data, slot) = (rc == 0);
+    BOOT_IMG_HDR_IS_VALID(state, slot) = (rc == 0);
 
 done:
     flash_area_close(fap);
@@ -222,13 +264,13 @@
 }
 
 static int
-boot_read_image_headers(bool require_all)
+boot_read_image_headers(struct boot_loader_state *state, bool require_all)
 {
     int rc;
     int i;
 
     for (i = 0; i < BOOT_NUM_SLOTS; i++) {
-        rc = boot_read_image_header(i, boot_img_hdr(&boot_data, i));
+        rc = boot_read_image_header(state, i, boot_img_hdr(state, i));
         if (rc != 0) {
             /* If `require_all` is set, fail on any single fail, otherwise
              * if at least the first slot's header was read successfully,
@@ -248,7 +290,7 @@
 }
 
 static uint32_t
-boot_write_sz(void)
+boot_write_sz(struct boot_loader_state *state)
 {
     uint32_t elem_sz;
     uint32_t align;
@@ -257,8 +299,8 @@
      * on what the minimum write size is for scratch area, active image slot.
      * We need to use the bigger of those 2 values.
      */
-    elem_sz = flash_area_align(BOOT_IMG_AREA(&boot_data, BOOT_PRIMARY_SLOT));
-    align = flash_area_align(BOOT_SCRATCH_AREA(&boot_data));
+    elem_sz = flash_area_align(BOOT_IMG_AREA(state, BOOT_PRIMARY_SLOT));
+    align = flash_area_align(BOOT_SCRATCH_AREA(state));
     if (align > elem_sz) {
         elem_sz = align;
     }
@@ -266,33 +308,96 @@
     return elem_sz;
 }
 
+#ifndef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
+static int
+boot_initialize_area(struct boot_loader_state *state, int flash_area)
+{
+    int num_sectors = BOOT_MAX_IMG_SECTORS;
+    int rc;
+
+    if (flash_area == FLASH_AREA_IMAGE_PRIMARY(BOOT_CURR_IMG(state))) {
+        rc = flash_area_to_sectors(flash_area, &num_sectors,
+                                   BOOT_IMG(state, BOOT_PRIMARY_SLOT).sectors);
+        BOOT_IMG(state, BOOT_PRIMARY_SLOT).num_sectors = (size_t)num_sectors;
+
+    } else if (flash_area == FLASH_AREA_IMAGE_SECONDARY(BOOT_CURR_IMG(state))) {
+        rc = flash_area_to_sectors(flash_area, &num_sectors,
+                                 BOOT_IMG(state, BOOT_SECONDARY_SLOT).sectors);
+        BOOT_IMG(state, BOOT_SECONDARY_SLOT).num_sectors = (size_t)num_sectors;
+
+    } else if (flash_area == FLASH_AREA_IMAGE_SCRATCH) {
+        rc = flash_area_to_sectors(flash_area, &num_sectors,
+                                   state->scratch.sectors);
+        state->scratch.num_sectors = (size_t)num_sectors;
+    } else {
+        return BOOT_EFLASH;
+    }
+
+    return rc;
+}
+#else  /* defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
+static int
+boot_initialize_area(struct boot_loader_state *state, int flash_area)
+{
+    uint32_t num_sectors;
+    struct flash_sector *out_sectors;
+    size_t *out_num_sectors;
+    int rc;
+
+    num_sectors = BOOT_MAX_IMG_SECTORS;
+
+    if (flash_area == FLASH_AREA_IMAGE_PRIMARY(BOOT_CURR_IMG(state))) {
+        out_sectors = BOOT_IMG(state, BOOT_PRIMARY_SLOT).sectors;
+        out_num_sectors = &BOOT_IMG(state, BOOT_PRIMARY_SLOT).num_sectors;
+    } else if (flash_area == FLASH_AREA_IMAGE_SECONDARY(BOOT_CURR_IMG(state))) {
+        out_sectors = BOOT_IMG(state, BOOT_SECONDARY_SLOT).sectors;
+        out_num_sectors = &BOOT_IMG(state, BOOT_SECONDARY_SLOT).num_sectors;
+    } else if (flash_area == FLASH_AREA_IMAGE_SCRATCH) {
+        out_sectors = state->scratch.sectors;
+        out_num_sectors = &state->scratch.num_sectors;
+    } else {
+        return BOOT_EFLASH;
+    }
+
+    rc = flash_area_get_sectors(flash_area, &num_sectors, out_sectors);
+    if (rc != 0) {
+        return rc;
+    }
+    *out_num_sectors = num_sectors;
+    return 0;
+}
+#endif  /* !defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
+
 /**
  * Determines the sector layout of both image slots and the scratch area.
  * This information is necessary for calculating the number of bytes to erase
  * and copy during an image swap.  The information collected during this
- * function is used to populate the boot_data global.
+ * function is used to populate the state.
  */
 static int
-boot_read_sectors(void)
+boot_read_sectors(struct boot_loader_state *state)
 {
+    uint8_t image_index;
     int rc;
 
-    rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_PRIMARY);
+    image_index = BOOT_CURR_IMG(state);
+
+    rc = boot_initialize_area(state, FLASH_AREA_IMAGE_PRIMARY(image_index));
     if (rc != 0) {
         return BOOT_EFLASH;
     }
 
-    rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_SECONDARY);
+    rc = boot_initialize_area(state, FLASH_AREA_IMAGE_SECONDARY(image_index));
     if (rc != 0) {
         return BOOT_EFLASH;
     }
 
-    rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_SCRATCH);
+    rc = boot_initialize_area(state, FLASH_AREA_IMAGE_SCRATCH);
     if (rc != 0) {
         return BOOT_EFLASH;
     }
 
-    BOOT_WRITE_SZ(&boot_data) = boot_write_sz();
+    BOOT_WRITE_SZ(state) = boot_write_sz(state);
 
     return 0;
 }
@@ -301,17 +406,25 @@
  * Validate image hash/signature and security counter in a slot.
  */
 static int
-boot_image_check(struct image_header *hdr, const struct flash_area *fap,
-                 struct boot_status *bs)
+boot_image_check(struct boot_loader_state *state, struct image_header *hdr,
+                 const struct flash_area *fap, struct boot_status *bs)
 {
     static uint8_t tmpbuf[BOOT_TMPBUF_SZ];
+    uint8_t image_index;
+
+#if (BOOT_IMAGE_NUMBER == 1)
+    (void)state;
+#endif
 
     (void)bs;
 
-    if (bootutil_img_validate(hdr, fap, tmpbuf, BOOT_TMPBUF_SZ,
-                              NULL, 0, NULL)) {
+    image_index = BOOT_CURR_IMG(state);
+
+    if (bootutil_img_validate(image_index, hdr, fap, tmpbuf,
+                              BOOT_TMPBUF_SZ, NULL, 0, NULL)) {
         return BOOT_EBADIMAGE;
     }
+
     return 0;
 }
 
@@ -332,14 +445,16 @@
 }
 
 static int
-boot_check_header_erased(int slot)
+boot_check_header_erased(struct boot_loader_state *state, int slot)
 {
     const struct flash_area *fap;
     struct image_header *hdr;
     uint8_t erased_val;
+    int area_id;
     int rc;
 
-    rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
+    area_id = flash_area_id_from_multi_image_slot(BOOT_CURR_IMG(state), slot);
+    rc = flash_area_open(area_id, &fap);
     if (rc != 0) {
         return -1;
     }
@@ -347,7 +462,7 @@
     erased_val = flash_area_erased_val(fap);
     flash_area_close(fap);
 
-    hdr = boot_img_hdr(&boot_data, slot);
+    hdr = boot_img_hdr(state, slot);
     if (!boot_data_is_set_to(erased_val, &hdr->ih_magic,
                              sizeof(hdr->ih_magic))) {
         return -1;
@@ -356,40 +471,47 @@
     return 0;
 }
 
+/*
+ * Check that there is a valid image in a slot
+ *
+ * @returns
+ *         0 if image was succesfully validated
+ *         1 if no bootloable image was found
+ *         -1 on any errors
+ */
 static int
-boot_validate_slot(int slot, struct boot_status *bs)
+boot_validate_slot(struct boot_loader_state *state, int slot,
+                   struct boot_status *bs)
 {
     const struct flash_area *fap;
     struct image_header *hdr;
+    int area_id;
     int rc;
 
-    rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
+    area_id = flash_area_id_from_multi_image_slot(BOOT_CURR_IMG(state), slot);
+    rc = flash_area_open(area_id, &fap);
     if (rc != 0) {
-        return BOOT_EFLASH;
+        return -1;
     }
 
-    hdr = boot_img_hdr(&boot_data, slot);
-    if ((boot_check_header_erased(slot) == 0) ||
+    hdr = boot_img_hdr(state, slot);
+    if ((boot_check_header_erased(state, slot) == 0) ||
         (hdr->ih_flags & IMAGE_F_NON_BOOTABLE)) {
         /* No bootable image in slot; continue booting from the primary slot. */
-        rc = -1;
+        rc = 1;
         goto out;
     }
 
-    if ((!BOOT_IMG_HDR_IS_VALID(&boot_data, slot)) ||
-         (boot_image_check(hdr, fap, bs) != 0)) {
+    if ((!BOOT_IMG_HDR_IS_VALID(state, slot)) ||
+         (boot_image_check(state, hdr, fap, bs) != 0)) {
         if (slot != BOOT_PRIMARY_SLOT) {
-            rc = flash_area_erase(fap, 0, fap->fa_size);
-            if(rc != 0) {
-                rc = BOOT_EFLASH;
-                goto out;
-            }
+            flash_area_erase(fap, 0, fap->fa_size);
             /* Image in the secondary slot is invalid. Erase the image and
              * continue booting from the primary slot.
              */
         }
-        BOOT_LOG_ERR("Authentication failed! Image in the %s slot is not valid."
-                     , (slot == BOOT_PRIMARY_SLOT) ? "primary" : "secondary");
+        BOOT_LOG_ERR("Image in the %s slot is not valid!",
+                     (slot == BOOT_PRIMARY_SLOT) ? "primary" : "secondary");
         rc = -1;
         goto out;
     }
@@ -406,20 +528,24 @@
  * Updates the stored security counter value with the image's security counter
  * value which resides in the given slot if it's greater than the stored value.
  *
- * @param slot      Slot number of the image.
- * @param hdr       Pointer to the image header structure of the image that is
- *                  currently stored in the given slot.
+ * @param image_index   Index of the image to determine which security
+ *                      counter to update.
+ * @param slot          Slot number of the image.
+ * @param hdr           Pointer to the image header structure of the image
+ *                      that is currently stored in the given slot.
  *
- * @return          0 on success; nonzero on failure.
+ * @return              0 on success; nonzero on failure.
  */
 static int
-boot_update_security_counter(int slot, struct image_header *hdr)
+boot_update_security_counter(uint8_t image_index, int slot,
+                             struct image_header *hdr)
 {
     const struct flash_area *fap = NULL;
     uint32_t img_security_cnt;
     int rc;
 
-    rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
+    rc = flash_area_open(flash_area_id_from_multi_image_slot(image_index, slot),
+                         &fap);
     if (rc != 0) {
         rc = BOOT_EFLASH;
         goto done;
@@ -430,7 +556,7 @@
         goto done;
     }
 
-    rc = boot_nv_security_counter_update(current_image, img_security_cnt);
+    rc = boot_nv_security_counter_update(image_index, img_security_cnt);
     if (rc != 0) {
         goto done;
     }
@@ -446,31 +572,28 @@
  * the TLVs.
  */
 static int
-boot_read_image_size(int slot, struct image_header *hdr, uint32_t *size)
+boot_read_image_size(struct boot_loader_state *state, int slot, uint32_t *size)
 {
     const struct flash_area *fap = NULL;
-    struct image_tlv_info info;
+    uint32_t off;
     int area_id;
     int rc;
 
-    area_id = flash_area_id_from_image_slot(slot);
+#if (BOOT_IMAGE_NUMBER == 1)
+    (void)state;
+#endif
+
+    area_id = flash_area_id_from_multi_image_slot(BOOT_CURR_IMG(state), slot);
     rc = flash_area_open(area_id, &fap);
     if (rc != 0) {
         rc = BOOT_EFLASH;
         goto done;
     }
 
-    rc = flash_area_read(fap, hdr->ih_hdr_size + hdr->ih_img_size,
-                         &info, sizeof(info));
+    rc = boot_find_tlv_offs(boot_img_hdr(state, slot), fap, &off, size);
     if (rc != 0) {
-        rc = BOOT_EFLASH;
         goto done;
     }
-    if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
-        rc = BOOT_EBADIMAGE;
-        goto done;
-    }
-    *size = hdr->ih_hdr_size + hdr->ih_img_size + info.it_tlv_tot;
     rc = 0;
 
 done:
@@ -489,7 +612,7 @@
  *              be read from.
  */
 static int
-boot_status_source(void)
+boot_status_source(struct boot_loader_state *state)
 {
     const struct boot_status_table *table;
     struct boot_swap_state state_scratch;
@@ -497,9 +620,15 @@
     int rc;
     size_t i;
     uint8_t source;
+    uint8_t image_index;
 
-    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_PRIMARY,
-                                    &state_primary_slot);
+#if (BOOT_IMAGE_NUMBER == 1)
+    (void)state;
+#endif
+
+    image_index = BOOT_CURR_IMG(state);
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_PRIMARY(image_index),
+            &state_primary_slot);
     assert(rc == 0);
 
     rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH, &state_scratch);
@@ -526,7 +655,7 @@
              * currently examined image.
              */
             if (source == BOOT_STATUS_SOURCE_SCRATCH &&
-                state_scratch.image_num != current_image) {
+                state_scratch.image_num != BOOT_CURR_IMG(state)) {
                 source = BOOT_STATUS_SOURCE_NONE;
             }
 #endif
@@ -551,7 +680,7 @@
  * presumably!).
  */
 static int
-boot_slots_compatible(void)
+boot_slots_compatible(struct boot_loader_state *state)
 {
     size_t num_sectors_primary;
     size_t num_sectors_secondary;
@@ -561,17 +690,15 @@
     size_t i, j;
     int8_t smaller;
 
-    num_sectors_primary =
-            boot_img_num_sectors(&boot_data, BOOT_PRIMARY_SLOT);
-    num_sectors_secondary =
-            boot_img_num_sectors(&boot_data, BOOT_SECONDARY_SLOT);
+    num_sectors_primary = boot_img_num_sectors(state, BOOT_PRIMARY_SLOT);
+    num_sectors_secondary = boot_img_num_sectors(state, BOOT_SECONDARY_SLOT);
     if ((num_sectors_primary > BOOT_MAX_IMG_SECTORS) ||
         (num_sectors_secondary > BOOT_MAX_IMG_SECTORS)) {
         BOOT_LOG_WRN("Cannot upgrade: more sectors than allowed");
         return 0;
     }
 
-    scratch_sz = boot_scratch_area_size(&boot_data);
+    scratch_sz = boot_scratch_area_size(state);
 
     /*
      * The following loop scans all sectors in a linear fashion, assuring that
@@ -585,12 +712,12 @@
     smaller = 0;
     while (i < num_sectors_primary || j < num_sectors_secondary) {
         if (sz0 == sz1) {
-            sz0 += boot_img_sector_size(&boot_data, BOOT_PRIMARY_SLOT, i);
-            sz1 += boot_img_sector_size(&boot_data, BOOT_SECONDARY_SLOT, j);
+            sz0 += boot_img_sector_size(state, BOOT_PRIMARY_SLOT, i);
+            sz1 += boot_img_sector_size(state, BOOT_SECONDARY_SLOT, j);
             i++;
             j++;
         } else if (sz0 < sz1) {
-            sz0 += boot_img_sector_size(&boot_data, BOOT_PRIMARY_SLOT, i);
+            sz0 += boot_img_sector_size(state, BOOT_PRIMARY_SLOT, i);
             /* Guarantee that multiple sectors of the secondary slot
              * fit into the primary slot.
              */
@@ -602,7 +729,7 @@
             smaller = 1;
             i++;
         } else {
-            sz1 += boot_img_sector_size(&boot_data, BOOT_SECONDARY_SLOT, j);
+            sz1 += boot_img_sector_size(state, BOOT_SECONDARY_SLOT, j);
             /* Guarantee that multiple sectors of the primary slot
              * fit into the secondary slot.
              */
@@ -656,7 +783,8 @@
  * operation.
  */
 static int
-boot_read_status_bytes(const struct flash_area *fap, struct boot_status *bs)
+boot_read_status_bytes(const struct flash_area *fap,
+        struct boot_loader_state *state, struct boot_status *bs)
 {
     uint32_t off;
     uint8_t status;
@@ -668,13 +796,16 @@
     int i;
 
     off = boot_status_off(fap);
-    max_entries = boot_status_entries(fap);
+    max_entries = boot_status_entries(BOOT_CURR_IMG(state), fap);
+    if (max_entries < 0) {
+        return BOOT_EBADARGS;
+    }
 
     found = 0;
     found_idx = 0;
     invalid = 0;
     for (i = 0; i < max_entries; i++) {
-        rc = flash_area_read_is_empty(fap, off + i * BOOT_WRITE_SZ(&boot_data),
+        rc = flash_area_read_is_empty(fap, off + i * BOOT_WRITE_SZ(state),
                 &status, 1);
         if (rc < 0) {
             return BOOT_EFLASH;
@@ -710,7 +841,6 @@
         if (!found_idx) {
             found_idx = i;
         }
-        found_idx--;
         bs->idx = (found_idx / BOOT_STATUS_STATE_COUNT) + 1;
         bs->state = (found_idx % BOOT_STATUS_STATE_COUNT) + 1;
     }
@@ -725,7 +855,7 @@
  * there is no operation in progress.
  */
 static int
-boot_read_status(struct boot_status *bs)
+boot_read_status(struct boot_loader_state *state, struct boot_status *bs)
 {
     const struct flash_area *fap;
     uint32_t off;
@@ -744,7 +874,7 @@
     return 0;
 #endif
 
-    status_loc = boot_status_source();
+    status_loc = boot_status_source(state);
     switch (status_loc) {
     case BOOT_STATUS_SOURCE_NONE:
         return 0;
@@ -754,7 +884,7 @@
         break;
 
     case BOOT_STATUS_SOURCE_PRIMARY_SLOT:
-        area_id = FLASH_AREA_IMAGE_PRIMARY;
+        area_id = FLASH_AREA_IMAGE_PRIMARY(BOOT_CURR_IMG(state));
         break;
 
     default:
@@ -767,7 +897,7 @@
         return BOOT_EFLASH;
     }
 
-    rc = boot_read_status_bytes(fap, bs);
+    rc = boot_read_status_bytes(fap, state, bs);
     if (rc == 0) {
         off = boot_swap_info_off(fap);
         rc = flash_area_read_is_empty(fap, off, &swap_info, sizeof swap_info);
@@ -794,7 +924,7 @@
  * @return                      0 on success; nonzero on failure.
  */
 int
-boot_write_status(struct boot_status *bs)
+boot_write_status(struct boot_loader_state *state, struct boot_status *bs)
 {
     const struct flash_area *fap = NULL;
     uint32_t off;
@@ -815,7 +945,7 @@
         area_id = FLASH_AREA_IMAGE_SCRATCH;
     } else {
         /* Write to the primary slot. */
-        area_id = FLASH_AREA_IMAGE_PRIMARY;
+        area_id = FLASH_AREA_IMAGE_PRIMARY(BOOT_CURR_IMG(state));
     }
 
     rc = flash_area_open(area_id, &fap);
@@ -825,9 +955,7 @@
     }
 
     off = boot_status_off(fap) +
-          boot_status_internal_off(bs->idx, bs->state,
-                                   BOOT_WRITE_SZ(&boot_data));
-
+          boot_status_internal_off(bs->idx, bs->state, BOOT_WRITE_SZ(state));
     align = flash_area_align(fap);
     erased_val = flash_area_erased_val(fap);
     memset(buf, erased_val, BOOT_MAX_ALIGN);
@@ -855,19 +983,21 @@
  * @return                      The type of swap to perform (BOOT_SWAP_TYPE...)
  */
 static int
-boot_validated_swap_type(struct boot_status *bs)
+boot_validated_swap_type(struct boot_loader_state *state,
+                         struct boot_status *bs)
 {
     int swap_type;
+    int rc;
 
-    swap_type = boot_swap_type();
-    switch (swap_type) {
-    case BOOT_SWAP_TYPE_TEST:
-    case BOOT_SWAP_TYPE_PERM:
-    case BOOT_SWAP_TYPE_REVERT:
+    swap_type = boot_swap_type_multi(BOOT_CURR_IMG(state));
+    if (BOOT_IS_UPGRADE(swap_type)) {
         /* Boot loader wants to switch to the secondary slot.
          * Ensure image is valid.
          */
-        if (boot_validate_slot(BOOT_SECONDARY_SLOT, bs) != 0) {
+        rc = boot_validate_slot(state, BOOT_SECONDARY_SLOT, bs);
+        if (rc == 1) {
+            swap_type = BOOT_SWAP_TYPE_NONE;
+        } else if (rc != 0) {
             swap_type = BOOT_SWAP_TYPE_FAIL;
         }
     }
@@ -890,7 +1020,8 @@
  */
 #ifndef MCUBOOT_OVERWRITE_ONLY
 static uint32_t
-boot_copy_sz(int last_sector_idx, int *out_first_sector_idx)
+boot_copy_sz(struct boot_loader_state *state, int last_sector_idx,
+             int *out_first_sector_idx)
 {
     size_t scratch_sz;
     uint32_t new_sz;
@@ -899,9 +1030,9 @@
 
     sz = 0;
 
-    scratch_sz = boot_scratch_area_size(&boot_data);
+    scratch_sz = boot_scratch_area_size(state);
     for (i = last_sector_idx; i >= 0; i--) {
-        new_sz = sz + boot_img_sector_size(&boot_data, BOOT_PRIMARY_SLOT, i);
+        new_sz = sz + boot_img_sector_size(state, BOOT_PRIMARY_SLOT, i);
         /*
          * The secondary slot is not being checked here, because
          * `boot_slots_compatible` already provides assurance that the copy size
@@ -932,7 +1063,7 @@
  * @return                      0 on success; nonzero on failure.
  */
 static inline int
-boot_erase_sector(const struct flash_area *fap, uint32_t off, uint32_t sz)
+boot_erase_region(const struct flash_area *fap, uint32_t off, uint32_t sz)
 {
     return flash_area_erase(fap, off, sz);
 }
@@ -952,7 +1083,8 @@
  * @return                      0 on success; nonzero on failure.
  */
 static int
-boot_copy_sector(const struct flash_area *fap_src,
+boot_copy_region(struct boot_loader_state *state,
+                 const struct flash_area *fap_src,
                  const struct flash_area *fap_dst,
                  uint32_t off_src, uint32_t off_dst, uint32_t sz)
 {
@@ -962,6 +1094,8 @@
 
     static uint8_t buf[1024];
 
+    (void)state;
+
     bytes_copied = 0;
     while (bytes_copied < sz) {
         if (sz - bytes_copied > sizeof(buf)) {
@@ -988,20 +1122,28 @@
 
 #ifndef MCUBOOT_OVERWRITE_ONLY
 static inline int
-boot_status_init(const struct flash_area *fap, const struct boot_status *bs)
+boot_status_init(const struct boot_loader_state *state,
+                 const struct flash_area *fap,
+                 const struct boot_status *bs)
 {
     struct boot_swap_state swap_state;
+    uint8_t image_index;
     int rc;
 
+#if (BOOT_IMAGE_NUMBER == 1)
+    (void)state;
+#endif
+
+    image_index = BOOT_CURR_IMG(state);
+
     BOOT_LOG_DBG("initializing status; fa_id=%d", fap->fa_id);
 
-    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SECONDARY, &swap_state);
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SECONDARY(image_index),
+            &swap_state);
     assert(rc == 0);
 
     if (bs->swap_type != BOOT_SWAP_TYPE_NONE) {
-        rc = boot_write_swap_info(fap,
-                                  bs->swap_type,
-                                  current_image);
+        rc = boot_write_swap_info(fap, bs->swap_type, image_index);
         assert(rc == 0);
     }
 
@@ -1020,7 +1162,8 @@
 }
 
 static int
-boot_erase_trailer_sectors(const struct flash_area *fap)
+boot_erase_trailer_sectors(const struct boot_loader_state *state,
+                           const struct flash_area *fap)
 {
     uint8_t slot;
     uint32_t sector;
@@ -1030,12 +1173,16 @@
     uint32_t sz;
     int fa_id_primary;
     int fa_id_secondary;
+    uint8_t image_index;
     int rc;
 
     BOOT_LOG_DBG("erasing trailer; fa_id=%d", fap->fa_id);
 
-    fa_id_primary   = flash_area_id_from_image_slot(BOOT_PRIMARY_SLOT);
-    fa_id_secondary = flash_area_id_from_image_slot(BOOT_SECONDARY_SLOT);
+    image_index = BOOT_CURR_IMG(state);
+    fa_id_primary = flash_area_id_from_multi_image_slot(image_index,
+            BOOT_PRIMARY_SLOT);
+    fa_id_secondary = flash_area_id_from_multi_image_slot(image_index,
+            BOOT_SECONDARY_SLOT);
 
     if (fap->fa_id == fa_id_primary) {
         slot = BOOT_PRIMARY_SLOT;
@@ -1046,13 +1193,13 @@
     }
 
     /* delete starting from last sector and moving to beginning */
-    sector = boot_img_num_sectors(&boot_data, slot) - 1;
-    trailer_sz = boot_trailer_sz(BOOT_WRITE_SZ(&boot_data));
+    sector = boot_img_num_sectors(state, slot) - 1;
+    trailer_sz = boot_trailer_sz(BOOT_WRITE_SZ(state));
     total_sz = 0;
     do {
-        sz = boot_img_sector_size(&boot_data, slot, sector);
-        off = boot_img_sector_off(&boot_data, slot, sector);
-        rc = boot_erase_sector(fap, off, sz);
+        sz = boot_img_sector_size(state, slot, sector);
+        off = boot_img_sector_off(state, slot, sector);
+        rc = boot_erase_region(fap, off, sz);
         assert(rc == 0);
 
         sector--;
@@ -1076,7 +1223,8 @@
  */
 #ifndef MCUBOOT_OVERWRITE_ONLY
 static void
-boot_swap_sectors(int idx, uint32_t sz, struct boot_status *bs)
+boot_swap_sectors(int idx, uint32_t sz, struct boot_loader_state *state,
+        struct boot_status *bs)
 {
     const struct flash_area *fap_primary_slot;
     const struct flash_area *fap_secondary_slot;
@@ -1088,13 +1236,14 @@
     struct boot_swap_state swap_state;
     size_t last_sector;
     bool erase_scratch;
+    uint8_t image_index;
     int rc;
 
     /* Calculate offset from start of image area. */
-    img_off = boot_img_sector_off(&boot_data, BOOT_PRIMARY_SLOT, idx);
+    img_off = boot_img_sector_off(state, BOOT_PRIMARY_SLOT, idx);
 
     copy_sz = sz;
-    trailer_sz = boot_trailer_sz(BOOT_WRITE_SZ(&boot_data));
+    trailer_sz = boot_trailer_sz(BOOT_WRITE_SZ(state));
 
     /* sz in this function is always sized on a multiple of the sector size.
      * The check against the start offset of the last sector
@@ -1105,18 +1254,22 @@
      * NOTE: `use_scratch` is a temporary flag (never written to flash) which
      * controls if special handling is needed (swapping last sector).
      */
-    last_sector = boot_img_num_sectors(&boot_data, BOOT_PRIMARY_SLOT) - 1;
+    last_sector = boot_img_num_sectors(state, BOOT_PRIMARY_SLOT) - 1;
     if ((img_off + sz) >
-        boot_img_sector_off(&boot_data, BOOT_PRIMARY_SLOT, last_sector)) {
+        boot_img_sector_off(state, BOOT_PRIMARY_SLOT, last_sector)) {
         copy_sz -= trailer_sz;
     }
 
     bs->use_scratch = (bs->idx == BOOT_STATUS_IDX_0 && copy_sz != sz);
 
-    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY, &fap_primary_slot);
+    image_index = BOOT_CURR_IMG(state);
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY(image_index),
+            &fap_primary_slot);
     assert (rc == 0);
 
-    rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY, &fap_secondary_slot);
+    rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY(image_index),
+            &fap_secondary_slot);
     assert (rc == 0);
 
     rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap_scratch);
@@ -1124,7 +1277,7 @@
 
     if (bs->state == BOOT_STATUS_STATE_0) {
         BOOT_LOG_DBG("erasing scratch area");
-        rc = boot_erase_sector(fap_scratch, 0, fap_scratch->fa_size);
+        rc = boot_erase_region(fap_scratch, 0, fap_scratch->fa_size);
         assert(rc == 0);
 
         if (bs->idx == BOOT_STATUS_IDX_0) {
@@ -1132,7 +1285,7 @@
              * scratch area for status.  We need a temporary place to store the
              * `swap-type` while we erase the primary trailer.
              */
-            rc = boot_status_init(fap_scratch, bs);
+            rc = boot_status_init(state, fap_scratch, bs);
             assert(rc == 0);
 
             if (!bs->use_scratch) {
@@ -1140,32 +1293,32 @@
                  * last sector is not being used by the image data so it's safe
                  * to erase.
                  */
-                rc = boot_erase_trailer_sectors(fap_primary_slot);
+                rc = boot_erase_trailer_sectors(state, fap_primary_slot);
                 assert(rc == 0);
 
-                rc = boot_status_init(fap_primary_slot, bs);
+                rc = boot_status_init(state, fap_primary_slot, bs);
                 assert(rc == 0);
 
                 /* Erase the temporary trailer from the scratch area. */
-                rc = boot_erase_sector(fap_scratch, 0, fap_scratch->fa_size);
+                rc = boot_erase_region(fap_scratch, 0, fap_scratch->fa_size);
                 assert(rc == 0);
             }
         }
 
-        rc = boot_copy_sector(fap_secondary_slot, fap_scratch,
+        rc = boot_copy_region(state, fap_secondary_slot, fap_scratch,
                               img_off, 0, copy_sz);
         assert(rc == 0);
 
+        rc = boot_write_status(state, bs);
         bs->state = BOOT_STATUS_STATE_1;
-        rc = boot_write_status(bs);
         BOOT_STATUS_ASSERT(rc == 0);
     }
 
     if (bs->state == BOOT_STATUS_STATE_1) {
-        rc = boot_erase_sector(fap_secondary_slot, img_off, sz);
+        rc = boot_erase_region(fap_secondary_slot, img_off, sz);
         assert(rc == 0);
 
-        rc = boot_copy_sector(fap_primary_slot, fap_secondary_slot,
+        rc = boot_copy_region(state, fap_primary_slot, fap_secondary_slot,
                               img_off, img_off, copy_sz);
         assert(rc == 0);
 
@@ -1173,23 +1326,23 @@
             /* If not all sectors of the slot are being swapped,
              * guarantee here that only the primary slot will have the state.
              */
-            rc = boot_erase_trailer_sectors(fap_secondary_slot);
+            rc = boot_erase_trailer_sectors(state, fap_secondary_slot);
             assert(rc == 0);
         }
 
+        rc = boot_write_status(state, bs);
         bs->state = BOOT_STATUS_STATE_2;
-        rc = boot_write_status(bs);
         BOOT_STATUS_ASSERT(rc == 0);
     }
 
     if (bs->state == BOOT_STATUS_STATE_2) {
-        rc = boot_erase_sector(fap_primary_slot, img_off, sz);
+        rc = boot_erase_region(fap_primary_slot, img_off, sz);
         assert(rc == 0);
 
         /* NOTE: If this is the final sector, we exclude the image trailer from
          * this copy (copy_sz was truncated earlier).
          */
-        rc = boot_copy_sector(fap_scratch, fap_primary_slot,
+        rc = boot_copy_region(state, fap_scratch, fap_primary_slot,
                               0, img_off, copy_sz);
         assert(rc == 0);
 
@@ -1197,9 +1350,9 @@
             scratch_trailer_off = boot_status_off(fap_scratch);
 
             /* copy current status that is being maintained in scratch */
-            rc = boot_copy_sector(fap_scratch, fap_primary_slot,
+            rc = boot_copy_region(state, fap_scratch, fap_primary_slot,
                         scratch_trailer_off, img_off + copy_sz,
-                        BOOT_STATUS_STATE_COUNT * BOOT_WRITE_SZ(&boot_data));
+                        (BOOT_STATUS_STATE_COUNT - 1) * BOOT_WRITE_SZ(state));
             BOOT_STATUS_ASSERT(rc == 0);
 
             rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH,
@@ -1214,7 +1367,7 @@
             if (swap_state.swap_type != BOOT_SWAP_TYPE_NONE) {
                 rc = boot_write_swap_info(fap_primary_slot,
                                           swap_state.swap_type,
-                                          current_image);
+                                          image_index);
                 assert(rc == 0);
             }
 
@@ -1233,13 +1386,13 @@
         erase_scratch = bs->use_scratch;
         bs->use_scratch = 0;
 
+        rc = boot_write_status(state, bs);
         bs->idx++;
         bs->state = BOOT_STATUS_STATE_0;
-        rc = boot_write_status(bs);
         BOOT_STATUS_ASSERT(rc == 0);
 
         if (erase_scratch) {
-            rc = boot_erase_sector(fap_scratch, 0, sz);
+            rc = boot_erase_region(fap_scratch, 0, sz);
             assert(rc == 0);
         }
     }
@@ -1265,32 +1418,37 @@
  */
 #ifdef MCUBOOT_OVERWRITE_ONLY
 static int
-boot_copy_image(struct boot_status *bs)
+boot_copy_image(struct boot_loader_state *state, struct boot_status *bs)
 {
     size_t sect_count;
     size_t sect;
     int rc;
-    size_t size = 0;
+    size_t size;
     size_t this_size;
     size_t last_sector;
     const struct flash_area *fap_primary_slot;
     const struct flash_area *fap_secondary_slot;
+    uint8_t image_index;
 
     (void)bs;
 
     BOOT_LOG_INF("Image upgrade secondary slot -> primary slot");
     BOOT_LOG_INF("Erasing the primary slot");
 
-    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY, &fap_primary_slot);
+    image_index = BOOT_CURR_IMG(state);
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY(image_index),
+            &fap_primary_slot);
     assert (rc == 0);
 
-    rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY, &fap_secondary_slot);
+    rc = flash_area_open(FLASH_AREA_IMAGE_SECONDARY(image_index),
+            &fap_secondary_slot);
     assert (rc == 0);
 
-    sect_count = boot_img_num_sectors(&boot_data, BOOT_PRIMARY_SLOT);
-    for (sect = 0; sect < sect_count; sect++) {
-        this_size = boot_img_sector_size(&boot_data, BOOT_PRIMARY_SLOT, sect);
-        rc = boot_erase_sector(fap_primary_slot, size, this_size);
+    sect_count = boot_img_num_sectors(state, BOOT_PRIMARY_SLOT);
+    for (sect = 0, size = 0; sect < sect_count; sect++) {
+        this_size = boot_img_sector_size(state, BOOT_PRIMARY_SLOT, sect);
+        rc = boot_erase_region(fap_primary_slot, size, this_size);
         assert(rc == 0);
 
         size += this_size;
@@ -1298,15 +1456,16 @@
 
     BOOT_LOG_INF("Copying the secondary slot to the primary slot: 0x%zx bytes",
                  size);
-    rc = boot_copy_sector(fap_secondary_slot, fap_primary_slot, 0, 0, size);
+    rc = boot_copy_region(state, fap_secondary_slot, fap_primary_slot,
+                          0, 0, size);
 
     /* Update the stored security counter with the new image's security counter
      * value. Both slots hold the new image at this point, but the secondary
      * slot's image header must be passed because the read image headers in the
      * boot_data structure have not been updated yet.
      */
-    rc = boot_update_security_counter(BOOT_PRIMARY_SLOT,
-                                 boot_img_hdr(&boot_data, BOOT_SECONDARY_SLOT));
+    rc = boot_update_security_counter(BOOT_CURR_IMG(state), BOOT_PRIMARY_SLOT,
+                                boot_img_hdr(state, BOOT_SECONDARY_SLOT));
     if (rc != 0) {
         BOOT_LOG_ERR("Security counter update failed after image upgrade.");
         return rc;
@@ -1318,19 +1477,17 @@
      * trailer that was left might trigger a new upgrade.
      */
     BOOT_LOG_DBG("erasing secondary header");
-    rc = boot_erase_sector(fap_secondary_slot,
-                           boot_img_sector_off(&boot_data,
-                                               BOOT_SECONDARY_SLOT, 0),
-                           boot_img_sector_size(&boot_data,
-                                                BOOT_SECONDARY_SLOT, 0));
+    rc = boot_erase_region(fap_secondary_slot,
+                           boot_img_sector_off(state, BOOT_SECONDARY_SLOT, 0),
+                           boot_img_sector_size(state, BOOT_SECONDARY_SLOT, 0));
     assert(rc == 0);
-    last_sector = boot_img_num_sectors(&boot_data, BOOT_SECONDARY_SLOT) - 1;
+    last_sector = boot_img_num_sectors(state, BOOT_SECONDARY_SLOT) - 1;
     BOOT_LOG_DBG("erasing secondary trailer");
-    rc = boot_erase_sector(fap_secondary_slot,
-                           boot_img_sector_off(&boot_data, BOOT_SECONDARY_SLOT,
-                                               last_sector),
-                           boot_img_sector_size(&boot_data, BOOT_SECONDARY_SLOT,
-                                                last_sector));
+    rc = boot_erase_region(fap_secondary_slot,
+                           boot_img_sector_off(state, BOOT_SECONDARY_SLOT,
+                               last_sector),
+                           boot_img_sector_size(state, BOOT_SECONDARY_SLOT,
+                               last_sector));
     assert(rc == 0);
 
     flash_area_close(fap_primary_slot);
@@ -1354,7 +1511,7 @@
  * @return                      0 on success; nonzero on failure.
  */
 static int
-boot_swap_image(struct boot_status *bs)
+boot_swap_image(struct boot_loader_state *state, struct boot_status *bs)
 {
     uint32_t sz;
     int first_sector_idx;
@@ -1366,25 +1523,30 @@
     uint32_t copy_size;
     uint32_t primary_slot_size;
     uint32_t secondary_slot_size;
+    uint8_t image_index;
     int rc;
 
     /* FIXME: just do this if asked by user? */
 
     size = copy_size = 0;
+    image_index = BOOT_CURR_IMG(state);
 
     if (bs->idx == BOOT_STATUS_IDX_0 && bs->state == BOOT_STATUS_STATE_0) {
         /*
          * No swap ever happened, so need to find the largest image which
          * will be used to determine the amount of sectors to swap.
          */
-        hdr = boot_img_hdr(&boot_data, BOOT_PRIMARY_SLOT);
-        rc = boot_read_image_size(BOOT_PRIMARY_SLOT, hdr, &copy_size);
-        assert(rc == 0);
+        hdr = boot_img_hdr(state, BOOT_PRIMARY_SLOT);
+        if (hdr->ih_magic == IMAGE_MAGIC) {
+            rc = boot_read_image_size(state, BOOT_PRIMARY_SLOT, &copy_size);
+            assert(rc == 0);
+        }
 
-        hdr = boot_img_hdr(&boot_data, BOOT_SECONDARY_SLOT);
-        rc = boot_read_image_size(BOOT_SECONDARY_SLOT, hdr, &size);
-        assert(rc == 0);
-
+        hdr = boot_img_hdr(state, BOOT_SECONDARY_SLOT);
+        if (hdr->ih_magic == IMAGE_MAGIC) {
+            rc = boot_read_image_size(state, BOOT_SECONDARY_SLOT, &size);
+            assert(rc == 0);
+        }
 
         if (size > copy_size) {
             copy_size = size;
@@ -1396,7 +1558,7 @@
          * If a swap was under way, the swap_size should already be present
          * in the trailer...
          */
-        rc = boot_read_swap_size(&bs->swap_size);
+        rc = boot_read_swap_size(image_index, &bs->swap_size);
         assert(rc == 0);
 
         copy_size = bs->swap_size;
@@ -1416,13 +1578,13 @@
     while (1) {
         if ((primary_slot_size < copy_size) ||
             (primary_slot_size < secondary_slot_size)) {
-           primary_slot_size += boot_img_sector_size(&boot_data,
+           primary_slot_size += boot_img_sector_size(state,
                                                      BOOT_PRIMARY_SLOT,
                                                      last_sector_idx);
         }
         if ((secondary_slot_size < copy_size) ||
             (secondary_slot_size < primary_slot_size)) {
-           secondary_slot_size += boot_img_sector_size(&boot_data,
+           secondary_slot_size += boot_img_sector_size(state,
                                                        BOOT_SECONDARY_SLOT,
                                                        last_idx_secondary_slot);
         }
@@ -1437,9 +1599,9 @@
 
     swap_idx = 0;
     while (last_sector_idx >= 0) {
-        sz = boot_copy_sz(last_sector_idx, &first_sector_idx);
+        sz = boot_copy_sz(state, last_sector_idx, &first_sector_idx);
         if (swap_idx >= (bs->idx - BOOT_STATUS_IDX_0)) {
-            boot_swap_sectors(first_sector_idx, sz, bs);
+            boot_swap_sectors(first_sector_idx, sz, state, bs);
         }
 
         last_sector_idx = first_sector_idx - 1;
@@ -1462,12 +1624,13 @@
  */
 #ifndef MCUBOOT_OVERWRITE_ONLY
 static int
-boot_set_copy_done(void)
+boot_set_copy_done(uint8_t image_index)
 {
     const struct flash_area *fap;
     int rc;
 
-    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY, &fap);
+    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY(image_index),
+            &fap);
     if (rc != 0) {
         return BOOT_EFLASH;
     }
@@ -1489,13 +1652,14 @@
  */
 #ifndef MCUBOOT_OVERWRITE_ONLY
 static int
-boot_set_image_ok(void)
+boot_set_image_ok(uint8_t image_index)
 {
     const struct flash_area *fap;
     struct boot_swap_state state;
     int rc;
 
-    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY, &fap);
+    rc = flash_area_open(FLASH_AREA_IMAGE_PRIMARY(image_index),
+            &fap);
     if (rc != 0) {
         return BOOT_EFLASH;
     }
@@ -1518,6 +1682,39 @@
 
 #if (BOOT_IMAGE_NUMBER > 1)
 /**
+ * Check if the version of the image is not older than required.
+ *
+ * @param req         Required minimal image version.
+ * @param ver         Version of the image to be checked.
+ *
+ * @return            0 if the version is sufficient, nonzero otherwise.
+ */
+static int
+boot_is_version_sufficient(struct image_version *req,
+                           struct image_version *ver)
+{
+    if (ver->iv_major > req->iv_major) {
+        return 0;
+    }
+    if (ver->iv_major < req->iv_major) {
+        return BOOT_EBADVERSION;
+    }
+    /* The major version numbers are equal. */
+    if (ver->iv_minor > req->iv_minor) {
+        return 0;
+    }
+    if (ver->iv_minor < req->iv_minor) {
+        return BOOT_EBADVERSION;
+    }
+    /* The minor version numbers are equal. */
+    if (ver->iv_revision < req->iv_revision) {
+        return BOOT_EBADVERSION;
+    }
+
+    return 0;
+}
+
+/**
  * Check the image dependency whether it is satisfied and modify
  * the swap type if necessary.
  *
@@ -1526,17 +1723,20 @@
  * @return                  0 on success; nonzero on failure.
  */
 static int
-boot_verify_single_dependency(struct image_dependency *dep)
+boot_verify_slot_dependency(struct boot_loader_state *state,
+                            struct image_dependency *dep)
 {
     struct image_version *dep_version;
     size_t dep_slot;
     int rc;
+    uint8_t swap_type;
 
     /* Determine the source of the image which is the subject of
      * the dependency and get it's version. */
-    dep_slot = (boot_data.swap_type[dep->image_id] != BOOT_SWAP_TYPE_NONE) ?
+    swap_type = state->swap_type[dep->image_id];
+    dep_slot = (swap_type != BOOT_SWAP_TYPE_NONE) ?
                 BOOT_SECONDARY_SLOT : BOOT_PRIMARY_SLOT;
-    dep_version = &boot_data.imgs[dep->image_id][dep_slot].hdr.ih_ver;
+    dep_version = &state->imgs[dep->image_id][dep_slot].hdr.ih_ver;
 
     rc = boot_is_version_sufficient(&dep->image_min_version, dep_version);
     if (rc != 0) {
@@ -1546,13 +1746,13 @@
          * consequently the number of unsatisfied dependencies will be
          * decreased or remain the same.
          */
-        switch (BOOT_SWAP_TYPE(&boot_data)) {
+        switch (BOOT_SWAP_TYPE(state)) {
         case BOOT_SWAP_TYPE_TEST:
         case BOOT_SWAP_TYPE_PERM:
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_NONE;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
             break;
         case BOOT_SWAP_TYPE_NONE:
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_REVERT;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_REVERT;
             break;
         default:
             break;
@@ -1571,45 +1771,29 @@
  * @return                  0 on success; nonzero on failure.
  */
 static int
-boot_verify_all_dependency(uint32_t slot)
+boot_verify_slot_dependencies(struct boot_loader_state *state, uint32_t slot)
 {
     const struct flash_area *fap;
-    struct image_header *hdr;
-    struct image_tlv_info info;
     struct image_tlv tlv;
     struct image_dependency dep;
     uint32_t off;
     uint32_t end;
     bool dep_tlvs_found = false;
+    int area_id;
     int rc;
 
-    rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
+    area_id = flash_area_id_from_multi_image_slot(BOOT_CURR_IMG(state), slot);
+    rc = flash_area_open(area_id, &fap);
     if (rc != 0) {
         rc = BOOT_EFLASH;
         goto done;
     }
 
-    hdr = boot_img_hdr(&boot_data, slot);
-    /* The TLVs come after the image. */
-    off = hdr->ih_hdr_size + hdr->ih_img_size;
-
-    /* The TLV area always starts with an image_tlv_info structure. */
-    rc = flash_area_read(fap, off, &info, sizeof(info));
+    rc = boot_find_tlv_offs(boot_img_hdr(state, slot), fap, &off, &end);
     if (rc != 0) {
-        rc = BOOT_EFLASH;
         goto done;
     }
 
-    if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
-        rc = BOOT_EBADIMAGE;
-        goto done;
-    }
-    if (boot_add_uint32_overflow_check(off, (info.it_tlv_tot + sizeof(info)))) {
-        return -1;
-    }
-    end = off + info.it_tlv_tot;
-    off += sizeof(info);
-
     /* Traverse through all of the TLVs to find the dependency TLVs. */
     while(off < end) {
         rc = flash_area_read(fap, off, &tlv, sizeof(tlv));
@@ -1619,9 +1803,7 @@
          }
 
         if (tlv.it_type == IMAGE_TLV_DEPENDENCY) {
-            if (!dep_tlvs_found) {
-                dep_tlvs_found = true;
-            }
+            dep_tlvs_found = true;
 
             if (tlv.it_len != sizeof(dep)) {
                 rc = BOOT_EBADIMAGE;
@@ -1634,8 +1816,13 @@
                 goto done;
             }
 
+            if (dep.image_id >= BOOT_IMAGE_NUMBER) {
+                rc = BOOT_EBADARGS;
+                goto done;
+            }
+
             /* Verify dependency and modify the swap type if not satisfied. */
-            rc = boot_verify_single_dependency(&dep);
+            rc = boot_verify_slot_dependency(state, &dep);
             if (rc != 0) {
                 /* Dependency not satisfied. */
                 goto done;
@@ -1667,54 +1854,43 @@
 }
 
 /**
- * Verify whether the image dependencies in the TLV area are
- * all satisfied and modify the swap type if necessary.
- *
- * @return                  0 if all dependencies are satisfied,
- *                          nonzero otherwise.
- */
-static int
-boot_verify_single_image_dependency(void)
-{
-    size_t slot;
-
-    /* Determine the source of the dependency TLVs. Those dependencies have to
-     * be checked which belong to the image that will be located in the primary
-     * slot after the firmware update process.
-     */
-    if (BOOT_SWAP_TYPE(&boot_data) != BOOT_SWAP_TYPE_NONE &&
-        BOOT_SWAP_TYPE(&boot_data) != BOOT_SWAP_TYPE_FAIL) {
-        slot = BOOT_SECONDARY_SLOT;
-    } else {
-        slot = BOOT_PRIMARY_SLOT;
-    }
-
-    return boot_verify_all_dependency(slot);
-}
-
-/**
  * Iterate over all the images and verify whether the image dependencies in the
  * TLV area are all satisfied and update the related swap type if necessary.
  */
-static void
-boot_verify_all_image_dependency(void)
+static int
+boot_verify_dependencies(struct boot_loader_state *state)
 {
-    current_image = 0;
     int rc;
+    uint8_t slot;
 
-    while (current_image < BOOT_IMAGE_NUMBER) {
-        rc = boot_verify_single_image_dependency();
+    BOOT_CURR_IMG(state) = 0;
+    while (BOOT_CURR_IMG(state) < BOOT_IMAGE_NUMBER) {
+        if (BOOT_SWAP_TYPE(state) != BOOT_SWAP_TYPE_NONE &&
+            BOOT_SWAP_TYPE(state) != BOOT_SWAP_TYPE_FAIL) {
+            slot = BOOT_SECONDARY_SLOT;
+        } else {
+            slot = BOOT_PRIMARY_SLOT;
+        }
+
+        rc = boot_verify_slot_dependencies(state, slot);
         if (rc == 0) {
             /* All dependencies've been satisfied, continue with next image. */
-            current_image++;
+            BOOT_CURR_IMG(state)++;
         } else if (rc == BOOT_EBADVERSION) {
-            /* Dependency check needs to be restarted. */
-            current_image = 0;
+            /* Cannot upgrade due to non-met dependencies, so disable all
+             * image upgrades.
+             */
+            for (int idx = 0; idx < BOOT_IMAGE_NUMBER; idx++) {
+                BOOT_CURR_IMG(state) = idx;
+                BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
+            }
+            break;
         } else {
             /* Other error happened, images are inconsistent */
-            return;
+            return rc;
         }
     }
+    return rc;
 }
 #endif /* (BOOT_IMAGE_NUMBER > 1) */
 
@@ -1726,15 +1902,18 @@
  * @return                      0 on success; nonzero on failure.
  */
 static int
-boot_perform_update(struct boot_status *bs)
+boot_perform_update(struct boot_loader_state *state, struct boot_status *bs)
 {
     int rc;
+#ifndef MCUBOOT_OVERWRITE_ONLY
+    uint8_t swap_type;
+#endif
 
     /* At this point there are no aborted swaps. */
 #if defined(MCUBOOT_OVERWRITE_ONLY)
-    rc = boot_copy_image(bs);
+    rc = boot_copy_image(state, bs);
 #else
-    rc = boot_swap_image(bs);
+    rc = boot_swap_image(state, bs);
 #endif
     assert(rc == 0);
 
@@ -1742,15 +1921,16 @@
     /* The following state needs image_ok be explicitly set after the
      * swap was finished to avoid a new revert.
      */
-    if (BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_REVERT ||
-        BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_PERM) {
-        rc = boot_set_image_ok();
+    swap_type = BOOT_SWAP_TYPE(state);
+    if (swap_type == BOOT_SWAP_TYPE_REVERT ||
+        swap_type == BOOT_SWAP_TYPE_PERM) {
+        rc = boot_set_image_ok(BOOT_CURR_IMG(state));
         if (rc != 0) {
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_PANIC;
+            BOOT_SWAP_TYPE(state) = swap_type = BOOT_SWAP_TYPE_PANIC;
         }
     }
 
-    if (BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_PERM) {
+    if (swap_type == BOOT_SWAP_TYPE_PERM) {
         /* Update the stored security counter with the new image's security
          * counter value. The primary slot holds the new image at this
          * point, but the secondary slot's image header must be passed
@@ -1761,21 +1941,21 @@
          * revert the images on the next reboot. Therefore, the security
          * counter must be increased right after the image upgrade.
          */
-        rc = boot_update_security_counter(BOOT_PRIMARY_SLOT,
-                             boot_img_hdr(&boot_data, BOOT_SECONDARY_SLOT));
+        rc = boot_update_security_counter(
+                                    BOOT_CURR_IMG(state),
+                                    BOOT_PRIMARY_SLOT,
+                                    boot_img_hdr(state, BOOT_SECONDARY_SLOT));
         if (rc != 0) {
             BOOT_LOG_ERR("Security counter update failed after "
                          "image upgrade.");
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_PANIC;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_PANIC;
         }
     }
 
-    if (BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_TEST ||
-        BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_PERM ||
-        BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_REVERT) {
-        rc = boot_set_copy_done();
+    if (BOOT_IS_UPGRADE(swap_type)) {
+        rc = boot_set_copy_done(BOOT_CURR_IMG(state));
         if (rc != 0) {
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_PANIC;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_PANIC;
         }
     }
 #endif /* !MCUBOOT_OVERWRITE_ONLY */
@@ -1792,39 +1972,38 @@
  */
 #if !defined(MCUBOOT_OVERWRITE_ONLY)
 static int
-boot_complete_partial_swap(struct boot_status *bs)
+boot_complete_partial_swap(struct boot_loader_state *state,
+        struct boot_status *bs)
 {
     int rc;
 
     /* Determine the type of swap operation being resumed from the
      * `swap-type` trailer field.
      */
-    rc = boot_swap_image(bs);
+    rc = boot_swap_image(state, bs);
     assert(rc == 0);
 
-    BOOT_SWAP_TYPE(&boot_data) = bs->swap_type;
+    BOOT_SWAP_TYPE(state) = bs->swap_type;
 
     /* The following states need image_ok be explicitly set after the
      * swap was finished to avoid a new revert.
      */
     if (bs->swap_type == BOOT_SWAP_TYPE_REVERT ||
         bs->swap_type == BOOT_SWAP_TYPE_PERM) {
-        rc = boot_set_image_ok();
+        rc = boot_set_image_ok(BOOT_CURR_IMG(state));
         if (rc != 0) {
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_PANIC;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_PANIC;
         }
     }
 
-    if (bs->swap_type == BOOT_SWAP_TYPE_TEST ||
-        bs->swap_type == BOOT_SWAP_TYPE_PERM ||
-        bs->swap_type == BOOT_SWAP_TYPE_REVERT) {
-        rc = boot_set_copy_done();
+    if (BOOT_IS_UPGRADE(bs->swap_type)) {
+        rc = boot_set_copy_done(BOOT_CURR_IMG(state));
         if (rc != 0) {
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_PANIC;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_PANIC;
         }
     }
 
-    if (BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_PANIC) {
+    if (BOOT_SWAP_TYPE(state) == BOOT_SWAP_TYPE_PANIC) {
         BOOT_LOG_ERR("panic!");
         assert(0);
 
@@ -1844,7 +2023,8 @@
  *                              partial/aborted swap.
  */
 static void
-boot_review_image_swap_types(bool aborted_swap)
+boot_review_image_swap_types(struct boot_loader_state *state,
+                             bool aborted_swap)
 {
     /* In that case if we rebooted in the middle of an image upgrade process, we
      * must review the validity of swap types, that were previously determined
@@ -1871,22 +2051,22 @@
      *      upgrades).
      */
 
-    if (current_image == 0) {
+    if (BOOT_CURR_IMG(state) == 0) {
         /* Nothing to do */
         return;
     }
 
     if (!aborted_swap) {
-        if ((BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_NONE) ||
-            (BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_REVERT)) {
+        if ((BOOT_SWAP_TYPE(state) == BOOT_SWAP_TYPE_NONE) ||
+            (BOOT_SWAP_TYPE(state) == BOOT_SWAP_TYPE_REVERT)) {
             /* Nothing to do */
             return;
         }
     }
 
-    for (uint8_t i = 0; i < current_image; i++) {
-        if (boot_data.swap_type[i] == BOOT_SWAP_TYPE_REVERT) {
-            boot_data.swap_type[i] = BOOT_SWAP_TYPE_NONE;
+    for (uint8_t i = 0; i < BOOT_CURR_IMG(state); i++) {
+        if (state->swap_type[i] == BOOT_SWAP_TYPE_REVERT) {
+            state->swap_type[i] = BOOT_SWAP_TYPE_NONE;
         }
     }
 }
@@ -1899,46 +2079,48 @@
  * operation if one was aborted and/or determining the type of the
  * swap operation. In case of any error set the swap type to NONE.
  *
+ * @param state                 Boot loader status information.
  * @param bs                    Pointer where the read and possibly updated
  *                              boot status can be written to.
  */
 static void
-boot_prepare_image_for_update(struct boot_status *bs)
+boot_prepare_image_for_update(struct boot_loader_state *state,
+                              struct boot_status *bs)
 {
     int rc;
 
     /* Determine the sector layout of the image slots and scratch area. */
-    rc = boot_read_sectors();
+    rc = boot_read_sectors(state);
     if (rc != 0) {
         BOOT_LOG_WRN("Failed reading sectors; BOOT_MAX_IMG_SECTORS=%d"
                      " - too small?", BOOT_MAX_IMG_SECTORS);
         /* Unable to determine sector layout, continue with next image
          * if there is one.
          */
-        BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_NONE;
+        BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
         return;
     }
 
     /* Attempt to read an image header from each slot. */
-    rc = boot_read_image_headers(false);
+    rc = boot_read_image_headers(state, false);
     if (rc != 0) {
         /* Continue with next image if there is one. */
-        BOOT_LOG_WRN("Failed reading image headers; Image=%u", current_image);
-        BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_NONE;
+        BOOT_LOG_WRN("Failed reading image headers; Image=%u",
+                BOOT_CURR_IMG(state));
+        BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
         return;
     }
 
     /* If the current image's slots aren't compatible, no swap is possible.
      * Just boot into primary slot.
      */
-    if (boot_slots_compatible()) {
-
-        rc = boot_read_status(bs);
+    if (boot_slots_compatible(state)) {
+        rc = boot_read_status(state, bs);
         if (rc != 0) {
             BOOT_LOG_WRN("Failed reading boot status; Image=%u",
-                         current_image);
+                    BOOT_CURR_IMG(state));
             /* Continue with next image if there is one. */
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_NONE;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
             return;
         }
 
@@ -1948,7 +2130,7 @@
         if (bs->idx != BOOT_STATUS_IDX_0 || bs->state != BOOT_STATUS_STATE_0) {
 
 #if (BOOT_IMAGE_NUMBER > 1)
-            boot_review_image_swap_types(true);
+            boot_review_image_swap_types(state, true);
 #endif
 
 #ifdef MCUBOOT_OVERWRITE_ONLY
@@ -1960,34 +2142,35 @@
             /* Determine the type of swap operation being resumed from the
              * `swap-type` trailer field.
              */
-            rc = boot_complete_partial_swap(bs);
+            rc = boot_complete_partial_swap(state, bs);
             assert(rc == 0);
 #endif
             /* Attempt to read an image header from each slot. Ensure that
              * image headers in slots are aligned with headers in boot_data.
              */
-            rc = boot_read_image_headers(false);
+            rc = boot_read_image_headers(state, false);
             assert(rc == 0);
 
             /* Swap has finished set to NONE */
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_NONE;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
         } else {
             /* There was no partial swap, determine swap type. */
             if (bs->swap_type == BOOT_SWAP_TYPE_NONE) {
-                BOOT_SWAP_TYPE(&boot_data) = boot_validated_swap_type(bs);
-            } else if (boot_validate_slot(BOOT_SECONDARY_SLOT, bs) != 0) {
-                BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_FAIL;
+                BOOT_SWAP_TYPE(state) = boot_validated_swap_type(state, bs);
+            } else if (boot_validate_slot(state,
+                                          BOOT_SECONDARY_SLOT, bs) != 0) {
+                BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_FAIL;
             } else {
-                BOOT_SWAP_TYPE(&boot_data) = bs->swap_type;
+                BOOT_SWAP_TYPE(state) = bs->swap_type;
             }
 
 #if (BOOT_IMAGE_NUMBER > 1)
-            boot_review_image_swap_types(false);
+            boot_review_image_swap_types(state, false);
 #endif
         }
     } else {
         /* In that case if slots are not compatible. */
-        BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_NONE;
+        BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
     }
 }
 
@@ -1995,17 +2178,20 @@
  * Prepares the booting process.  This function moves images around in flash as
  * appropriate, and tells you what address to boot from.
  *
+ * @param state                 Boot loader status information.
  * @param rsp                   On success, indicates how booting should occur.
  *
  * @return                      0 on success; nonzero on failure.
  */
 int
-boot_go(struct boot_rsp *rsp)
+context_boot_go(struct boot_loader_state *state, struct boot_rsp *rsp)
 {
     size_t slot;
     struct boot_status bs;
     int rc = 0;
     int fa_id;
+    int image_index;
+    bool has_upgrade;
 
     /* The array of slot sectors are defined here (as opposed to file scope) so
      * that they don't get allocated for non-boot-loader apps.  This is
@@ -2022,43 +2208,59 @@
      * to be determined for each image and all aborted swaps have to be
      * completed.
      */
-    for (current_image = 0; current_image < BOOT_IMAGE_NUMBER; ++current_image)
-    {
-        BOOT_IMG(&boot_data, BOOT_PRIMARY_SLOT).sectors =
-                                        primary_slot_sectors[current_image];
-        BOOT_IMG(&boot_data, BOOT_SECONDARY_SLOT).sectors =
-                                        secondary_slot_sectors[current_image];
-        boot_data.scratch.sectors = scratch_sectors;
+    IMAGES_ITER(BOOT_CURR_IMG(state)) {
+
+        image_index = BOOT_CURR_IMG(state);
+
+        BOOT_IMG(state, BOOT_PRIMARY_SLOT).sectors =
+            primary_slot_sectors[image_index];
+        BOOT_IMG(state, BOOT_SECONDARY_SLOT).sectors =
+            secondary_slot_sectors[image_index];
+        state->scratch.sectors = scratch_sectors;
 
         /* Open primary and secondary image areas for the duration
          * of this call.
          */
         for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
-            fa_id = flash_area_id_from_image_slot(slot);
-            rc = flash_area_open(fa_id, &BOOT_IMG_AREA(&boot_data, slot));
+            fa_id = flash_area_id_from_multi_image_slot(image_index, slot);
+            rc = flash_area_open(fa_id, &BOOT_IMG_AREA(state, slot));
             assert(rc == 0);
         }
         rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH,
-                             &BOOT_SCRATCH_AREA(&boot_data));
+                             &BOOT_SCRATCH_AREA(state));
         assert(rc == 0);
 
         /* Determine swap type and complete swap if it has been aborted. */
-        boot_prepare_image_for_update(&bs);
+        boot_prepare_image_for_update(state, &bs);
+
+        if (BOOT_IS_UPGRADE(BOOT_SWAP_TYPE(state))) {
+            has_upgrade = true;
+        }
     }
 
 #if (BOOT_IMAGE_NUMBER > 1)
-    /* Iterate over all the images and verify whether the image dependencies
-     * are all satisfied and update swap type if necessary.
-     */
-    boot_verify_all_image_dependency();
+    if (has_upgrade) {
+        /* Iterate over all the images and verify whether the image dependencies
+         * are all satisfied and update swap type if necessary.
+         */
+        rc = boot_verify_dependencies(state);
+        if (rc == BOOT_EBADVERSION) {
+            /*
+             * It was impossible to upgrade because the expected dependency
+             * version was not available. Here we already changed the swap_type
+             * so that instead of asserting the bootloader, we continue and no
+             * upgrade is performed.
+             */
+            rc = 0;
+        }
+    }
 #endif
 
     /* Iterate over all the images. At this point there are no aborted swaps
      * and the swap types are determined for each image. By the end of the loop
      * all required update operations will have been finished.
      */
-    for (current_image = 0; current_image < BOOT_IMAGE_NUMBER; ++current_image)
-    {
+    IMAGES_ITER(BOOT_CURR_IMG(state)) {
 
 #if (BOOT_IMAGE_NUMBER > 1)
         /* Indicate that swap is not aborted */
@@ -2068,16 +2270,16 @@
 #endif /* (BOOT_IMAGE_NUMBER > 1) */
 
         /* Set the previously determined swap type */
-        bs.swap_type = BOOT_SWAP_TYPE(&boot_data);
+        bs.swap_type = BOOT_SWAP_TYPE(state);
 
-        switch (BOOT_SWAP_TYPE(&boot_data)) {
+        switch (BOOT_SWAP_TYPE(state)) {
         case BOOT_SWAP_TYPE_NONE:
             break;
 
         case BOOT_SWAP_TYPE_TEST:          /* fallthrough */
         case BOOT_SWAP_TYPE_PERM:          /* fallthrough */
         case BOOT_SWAP_TYPE_REVERT:
-            rc = boot_perform_update(&bs);
+            rc = boot_perform_update(state, &bs);
             assert(rc == 0);
             break;
 
@@ -2088,18 +2290,18 @@
              */
 #ifndef MCUBOOT_OVERWRITE_ONLY
             /* image_ok needs to be explicitly set to avoid a new revert. */
-            rc = boot_set_image_ok();
+            rc = boot_set_image_ok(BOOT_CURR_IMG(state));
             if (rc != 0) {
-                BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_PANIC;
+                BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_PANIC;
             }
 #endif /* !MCUBOOT_OVERWRITE_ONLY */
             break;
 
         default:
-            BOOT_SWAP_TYPE(&boot_data) = BOOT_SWAP_TYPE_PANIC;
+            BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_PANIC;
         }
 
-        if (BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_PANIC) {
+        if (BOOT_SWAP_TYPE(state) == BOOT_SWAP_TYPE_PANIC) {
             BOOT_LOG_ERR("panic!");
             assert(0);
 
@@ -2112,13 +2314,12 @@
      * have finished. By the end of the loop each image in the primary slot will
      * have been re-validated.
      */
-    for (current_image = 0; current_image < BOOT_IMAGE_NUMBER; ++current_image)
-    {
-        if (BOOT_SWAP_TYPE(&boot_data) != BOOT_SWAP_TYPE_NONE) {
+    IMAGES_ITER(BOOT_CURR_IMG(state)) {
+        if (BOOT_SWAP_TYPE(state) != BOOT_SWAP_TYPE_NONE) {
             /* Attempt to read an image header from each slot. Ensure that image
              * headers in slots are aligned with headers in boot_data.
              */
-            rc = boot_read_image_headers(false);
+            rc = boot_read_image_headers(state, false);
             if (rc != 0) {
                 goto out;
             }
@@ -2130,7 +2331,7 @@
         }
 
 #ifdef MCUBOOT_VALIDATE_PRIMARY_SLOT
-        rc = boot_validate_slot(BOOT_PRIMARY_SLOT, NULL);
+        rc = boot_validate_slot(state, BOOT_PRIMARY_SLOT, NULL);
         if (rc != 0) {
             rc = BOOT_EBADIMAGE;
             goto out;
@@ -2140,8 +2341,10 @@
          * onto an empty flash chip. At least do a basic sanity check that
          * the magic number on the image is OK.
          */
-        if (!BOOT_IMG_HDR_IS_VALID(&boot_data, slot)) {
-            BOOT_LOG_ERR("Invalid image header Image=%u", current_image);
+        if (!BOOT_IMG_HDR_IS_VALID(state, BOOT_PRIMARY_SLOT)) {
+            BOOT_LOG_ERR("bad image magic 0x%lx; Image=%u", (unsigned long)
+                         &boot_img_hdr(state, BOOT_PRIMARY_SLOT)->ih_magic,
+                         BOOT_CURR_IMG(state));
             rc = BOOT_EBADIMAGE;
             goto out;
         }
@@ -2157,9 +2360,11 @@
          * has been set). This way a "revert" swap can be performed if it's
          * necessary.
          */
-        if (BOOT_SWAP_TYPE(&boot_data) == BOOT_SWAP_TYPE_NONE) {
-            rc = boot_update_security_counter(BOOT_PRIMARY_SLOT,
-                                  boot_img_hdr(&boot_data, BOOT_PRIMARY_SLOT));
+        if (BOOT_SWAP_TYPE(state) == BOOT_SWAP_TYPE_NONE) {
+            rc = boot_update_security_counter(
+                                    BOOT_CURR_IMG(state),
+                                    BOOT_PRIMARY_SLOT,
+                                    boot_img_hdr(state, BOOT_PRIMARY_SLOT));
             if (rc != 0) {
                 BOOT_LOG_ERR("Security counter update failed after image "
                              "validation.");
@@ -2169,37 +2374,40 @@
 
         /* Save boot status to shared memory area */
 #if (BOOT_IMAGE_NUMBER > 1)
-        rc = boot_save_boot_status((current_image == 0) ? SW_SPE : SW_NSPE,
-                                   boot_img_hdr(&boot_data, BOOT_PRIMARY_SLOT),
-                                   BOOT_IMG_AREA(&boot_data, BOOT_PRIMARY_SLOT)
+        rc = boot_save_boot_status((BOOT_CURR_IMG(state) == 0) ?
+                                   SW_SPE : SW_NSPE,
+                                   boot_img_hdr(state, BOOT_PRIMARY_SLOT),
+                                   BOOT_IMG_AREA(state, BOOT_PRIMARY_SLOT)
                                   );
 #else
         rc = boot_save_boot_status(SW_S_NS,
-                                   boot_img_hdr(&boot_data, BOOT_PRIMARY_SLOT),
-                                   BOOT_IMG_AREA(&boot_data, BOOT_PRIMARY_SLOT)
+                                   boot_img_hdr(state, BOOT_PRIMARY_SLOT),
+                                   BOOT_IMG_AREA(state, BOOT_PRIMARY_SLOT)
                                   );
 #endif
         if (rc) {
             BOOT_LOG_ERR("Failed to add Image %u data to shared area",
-                         current_image);
+                         BOOT_CURR_IMG(state));
         }
     }
 
+#if (BOOT_IMAGE_NUMBER > 1)
     /* Always boot from the primary slot of Image 0. */
-    current_image = 0;
-    rsp->br_flash_dev_id =
-            BOOT_IMG_AREA(&boot_data, BOOT_PRIMARY_SLOT)->fa_device_id;
-    rsp->br_image_off =
-            boot_img_slot_off(&boot_data, BOOT_PRIMARY_SLOT);
-    rsp->br_hdr =
-            boot_img_hdr(&boot_data, BOOT_PRIMARY_SLOT);
+    BOOT_CURR_IMG(state) = 0;
+#endif
 
- out:
-    for (current_image = 0; current_image < BOOT_IMAGE_NUMBER; ++current_image)
-    {
-        flash_area_close(BOOT_SCRATCH_AREA(&boot_data));
+    rsp->br_flash_dev_id =
+            BOOT_IMG_AREA(state, BOOT_PRIMARY_SLOT)->fa_device_id;
+    rsp->br_image_off =
+            boot_img_slot_off(state, BOOT_PRIMARY_SLOT);
+    rsp->br_hdr =
+            boot_img_hdr(state, BOOT_PRIMARY_SLOT);
+
+out:
+    IMAGES_ITER(BOOT_CURR_IMG(state)) {
+        flash_area_close(BOOT_SCRATCH_AREA(state));
         for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
-            flash_area_close(BOOT_IMG_AREA(&boot_data,
+            flash_area_close(BOOT_IMG_AREA(state,
                                            BOOT_NUM_SLOTS - 1 - slot));
         }
     }
@@ -2279,6 +2487,7 @@
  * Sort the available images based on the version number and puts them in
  * a list.
  *
+ * @param state          Boot loader status information.
  * @param boot_sequence  A pointer to an array, whose aim is to carry
  *                       the boot order of candidate images.
  * @param slot_cnt       The number of flash areas, which can contains firmware
@@ -2287,7 +2496,8 @@
  * @return               The number of valid images.
  */
 uint32_t
-boot_get_boot_sequence(uint32_t *boot_sequence, uint32_t slot_cnt)
+boot_get_boot_sequence(struct boot_loader_state *state,
+                       uint32_t *boot_sequence, uint32_t slot_cnt)
 {
     struct boot_swap_state slot_state;
     struct image_header *hdr;
@@ -2298,7 +2508,7 @@
     int32_t fa_id;
 
     for (slot = 0; slot < slot_cnt; slot++) {
-        hdr = boot_img_hdr(&boot_data, slot);
+        hdr = boot_img_hdr(state, slot);
         fa_id = flash_area_id_from_image_slot(slot);
         rc = boot_read_swap_state_by_id(fa_id, &slot_state);
         if (rc != 0) {
@@ -2307,7 +2517,7 @@
             continue;
         }
 
-        if (BOOT_IMG_HDR_IS_VALID(&boot_data, slot)) {
+        if (BOOT_IMG_HDR_IS_VALID(state, slot)) {
             if (slot_state.magic    == BOOT_MAGIC_GOOD ||
                 slot_state.image_ok == BOOT_FLAG_SET) {
                 /* Valid cases:
@@ -2375,6 +2585,7 @@
  * address has already been inserted into the image header by this point and is
  * extracted from it within this method. The copying is done sector-by-sector.
  *
+ * @param state           Boot loader status information.
  * @param slot            The flash slot of the image to be copied to SRAM.
  *
  * @param hdr             Pointer to the image header structure of the image
@@ -2387,7 +2598,8 @@
  * @return                0 on success; nonzero on failure.
  */
 static int
-boot_copy_image_to_sram(int slot, struct image_header *hdr,
+boot_copy_image_to_sram(struct boot_loader_state *state, int slot,
+                        struct image_header *hdr,
                         uint32_t img_dst, uint32_t img_sz)
 {
     int rc;
@@ -2409,7 +2621,7 @@
     }
 
     while (bytes_copied < img_sz) {
-        sect_sz = boot_img_sector_size(&boot_data, slot, sect);
+        sect_sz = boot_img_sector_size(state, slot, sect);
         /*
          * Direct copy from where the image sector resides in flash to its new
          * location in SRAM
@@ -2456,14 +2668,15 @@
 
 /**
  * Prepares the booting process. This function choose the newer image in flash
- * as appropriate, and returns the address to boot from.
+ * as appropriate, and tells you what address to boot from.
  *
+ * @param state                 Boot loader status information.
  * @param rsp                   On success, indicates how booting should occur.
  *
  * @return                      0 on success; nonzero on failure.
  */
 int
-boot_go(struct boot_rsp *rsp)
+context_boot_go(struct boot_loader_state *state, struct boot_rsp *rsp)
 {
     size_t slot = 0;
     int32_t i;
@@ -2481,46 +2694,44 @@
     static boot_sector_t primary_slot_sectors[BOOT_MAX_IMG_SECTORS];
     static boot_sector_t secondary_slot_sectors[BOOT_MAX_IMG_SECTORS];
 
-    BOOT_IMG(&boot_data, BOOT_PRIMARY_SLOT).sectors =
-                                                &primary_slot_sectors[0];
-    BOOT_IMG(&boot_data, BOOT_SECONDARY_SLOT).sectors =
-                                                &secondary_slot_sectors[0];
+    BOOT_IMG(state, BOOT_PRIMARY_SLOT).sectors = &primary_slot_sectors[0];
+    BOOT_IMG(state, BOOT_SECONDARY_SLOT).sectors = &secondary_slot_sectors[0];
 
     /* Open boot_data image areas for the duration of this call. */
     for (i = 0; i < BOOT_NUM_SLOTS; i++) {
         fa_id = flash_area_id_from_image_slot(i);
-        rc = flash_area_open(fa_id, &BOOT_IMG_AREA(&boot_data, i));
+        rc = flash_area_open(fa_id, &BOOT_IMG_AREA(state, i));
         assert(rc == 0);
     }
 
     /* Determine the sector layout of the image slots. */
-    rc = boot_read_sectors();
+    rc = boot_read_sectors(state);
     if (rc != 0) {
-        BOOT_LOG_WRN("Failed reading sectors; BOOT_MAX_IMG_SECTORS=%d - too small?",
-                BOOT_MAX_IMG_SECTORS);
+        BOOT_LOG_WRN("Failed reading sectors; BOOT_MAX_IMG_SECTORS=%d - "
+                     "too small?", BOOT_MAX_IMG_SECTORS);
         goto out;
     }
 
     /* Attempt to read an image header from each slot. */
-    rc = boot_read_image_headers(false);
+    rc = boot_read_image_headers(state, false);
     if (rc != 0) {
         goto out;
     }
 
-    img_cnt = boot_get_boot_sequence(boot_sequence, BOOT_NUM_SLOTS);
+    img_cnt = boot_get_boot_sequence(state, boot_sequence, BOOT_NUM_SLOTS);
     if (img_cnt) {
         /* Authenticate images */
         for (i = 0; i < img_cnt; i++) {
 
             slot = boot_sequence[i];
-            selected_image_header = boot_img_hdr(&boot_data, slot);
+            selected_image_header = boot_img_hdr(state, slot);
 
 #ifdef MCUBOOT_RAM_LOADING
             if (selected_image_header->ih_flags & IMAGE_F_RAM_LOAD) {
 
                 img_dst = selected_image_header->ih_load_addr;
 
-                rc = boot_read_image_size(slot, selected_image_header, &img_sz);
+                rc = boot_read_image_size(state, slot, &img_sz);
                 if (rc != 0) {
                     rc = BOOT_EFLASH;
                     BOOT_LOG_INF("Could not load image headers from the image"
@@ -2545,7 +2756,7 @@
                 /* Copy image to the load address from where it
                  * currently resides in flash
                  */
-                rc = boot_copy_image_to_sram(slot, selected_image_header,
+                rc = boot_copy_image_to_sram(state, slot, selected_image_header,
                                              img_dst, img_sz);
                 if (rc != 0) {
                     rc = BOOT_EBADIMAGE;
@@ -2571,7 +2782,7 @@
                 continue;
             }
 #endif /* MCUBOOT_RAM_LOADING */
-            rc = boot_validate_slot(slot, NULL);
+            rc = boot_validate_slot(state, slot, NULL);
             if (rc == 0) {
                 /* If a valid image is found then there is no reason to check
                  * the rest of the images, as they were already ordered by
@@ -2598,7 +2809,8 @@
         /* Update the security counter with the newest image's security
          * counter value.
          */
-        rc = boot_update_security_counter(slot, selected_image_header);
+        rc = boot_update_security_counter(BOOT_CURR_IMG(state), slot,
+                                          selected_image_header);
         if (rc != 0) {
             BOOT_LOG_ERR("Security counter update failed after image "
                          "validation.");
@@ -2615,8 +2827,8 @@
 #endif /* MCUBOOT_RAM_LOADING */
 
         rsp->br_hdr = selected_image_header;
-        rsp->br_image_off = boot_img_slot_off(&boot_data, slot);
-        rsp->br_flash_dev_id = BOOT_IMG_AREA(&boot_data, slot)->fa_device_id;
+        rsp->br_image_off = boot_img_slot_off(state, slot);
+        rsp->br_flash_dev_id = BOOT_IMG_AREA(state, slot)->fa_device_id;
     } else {
         /* No candidate image available */
         rc = BOOT_EBADIMAGE;
@@ -2626,15 +2838,21 @@
     /* Save boot status to shared memory area */
     rc = boot_save_boot_status(SW_S_NS,
                                rsp->br_hdr,
-                               BOOT_IMG_AREA(&boot_data, slot));
+                               BOOT_IMG_AREA(state, slot));
     if (rc) {
         BOOT_LOG_ERR("Failed to add data to shared area");
     }
 
 out:
    for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
-       flash_area_close(BOOT_IMG_AREA(&boot_data, BOOT_NUM_SLOTS - 1 - slot));
+       flash_area_close(BOOT_IMG_AREA(state, BOOT_NUM_SLOTS - 1 - slot));
    }
    return rc;
 }
 #endif /* MCUBOOT_NO_SWAP || MCUBOOT_RAM_LOADING */
+
+int
+boot_go(struct boot_rsp *rsp)
+{
+    return context_boot_go(&boot_data, rsp);
+}
\ No newline at end of file
diff --git a/bl2/ext/mcuboot/flash_map.c b/bl2/ext/mcuboot/flash_map.c
deleted file mode 100644
index dbaf94a..0000000
--- a/bl2/ext/mcuboot/flash_map.c
+++ /dev/null
@@ -1,422 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/*
- * Original code taken from mcuboot project at:
- * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
- * Modifications are Copyright (c) 2018-2019 Arm Limited.
- */
-
-#include <errno.h>
-#include <stdbool.h>
-
-#include "target.h"
-#include "bl2_util.h"
-#include "Driver_Flash.h"
-
-#include <flash_map/flash_map.h>
-#include "bootutil/bootutil_log.h"
-
-/* Flash device name must be specified by target */
-extern ARM_DRIVER_FLASH FLASH_DEV_NAME;
-
-/*
- * For now, we only support one flash device.
- *
- * Pick a random device ID for it that's unlikely to collide with
- * anything "real".
- */
-#define FLASH_DEVICE_ID 100
-#define FLASH_DEVICE_BASE FLASH_BASE_ADDRESS
-
-#define FLASH_MAP_ENTRY_MAGIC 0xd00dbeef
-
-struct flash_map_entry {
-    const uint32_t magic;
-    const struct flash_area area;
-    unsigned int ref_count;
-};
-
-/*
- * The flash area describes essentially the partition table of the
- * flash.  In this case, it starts with FLASH_AREA_IMAGE_PRIMARY.
- */
-static struct flash_map_entry part_map[] = {
-    {
-        .magic = FLASH_MAP_ENTRY_MAGIC,
-        .area = {
-            .fa_id = FLASH_AREA_0_ID,
-            .fa_device_id = FLASH_DEVICE_ID,
-            .fa_off = FLASH_AREA_0_OFFSET,
-            .fa_size = FLASH_AREA_0_SIZE,
-        },
-    },
-    {
-        .magic = FLASH_MAP_ENTRY_MAGIC,
-        .area = {
-            .fa_id = FLASH_AREA_2_ID,
-            .fa_device_id = FLASH_DEVICE_ID,
-            .fa_off = FLASH_AREA_2_OFFSET,
-            .fa_size = FLASH_AREA_2_SIZE,
-        },
-    },
-#if (MCUBOOT_IMAGE_NUMBER == 2)
-    {
-        .magic = FLASH_MAP_ENTRY_MAGIC,
-        .area = {
-            .fa_id = FLASH_AREA_1_ID,
-            .fa_device_id = FLASH_DEVICE_ID,
-            .fa_off = FLASH_AREA_1_OFFSET,
-            .fa_size = FLASH_AREA_1_SIZE,
-        },
-    },
-    {
-        .magic = FLASH_MAP_ENTRY_MAGIC,
-        .area = {
-            .fa_id = FLASH_AREA_3_ID,
-            .fa_device_id = FLASH_DEVICE_ID,
-            .fa_off = FLASH_AREA_3_OFFSET,
-            .fa_size = FLASH_AREA_3_SIZE,
-        },
-    },
-#endif
-    {
-        .magic = FLASH_MAP_ENTRY_MAGIC,
-        .area = {
-            .fa_id = FLASH_AREA_SCRATCH_ID,
-            .fa_device_id = FLASH_DEVICE_ID,
-            .fa_off = FLASH_AREA_SCRATCH_OFFSET,
-            .fa_size = FLASH_AREA_SCRATCH_SIZE,
-        },
-    }
-};
-
-int flash_device_base(uint8_t fd_id, uintptr_t *ret)
-{
-    if (fd_id != FLASH_DEVICE_ID) {
-        BOOT_LOG_ERR("invalid flash ID %d; expected %d",
-                     fd_id, FLASH_DEVICE_ID);
-        return -1;
-    }
-    *ret = FLASH_DEVICE_BASE;
-    return 0;
-}
-
-/*
- * `open` a flash area.  The `area` in this case is not the individual
- * sectors, but describes the particular flash area in question.
- */
-int flash_area_open(uint8_t id, const struct flash_area **area)
-{
-    int i;
-
-    BOOT_LOG_DBG("area %d", id);
-
-    for (i = 0; i < ARRAY_SIZE(part_map); i++) {
-        if (id == part_map[i].area.fa_id) {
-            break;
-        }
-    }
-    if (i == ARRAY_SIZE(part_map)) {
-        return -1;
-    }
-
-    *area = &part_map[i].area;
-    part_map[i].ref_count++;
-    return 0;
-}
-
-/*
- * Nothing to do on close.
- */
-void flash_area_close(const struct flash_area *area)
-{
-    struct flash_map_entry *entry;
-
-    if (!area) {
-        return;
-    }
-
-    entry = CONTAINER_OF(area, struct flash_map_entry, area);
-    if (entry->magic != FLASH_MAP_ENTRY_MAGIC) {
-        BOOT_LOG_ERR("invalid area %p (id %u)", area, area->fa_id);
-        return;
-    }
-    if (entry->ref_count == 0) {
-        BOOT_LOG_ERR("area %u use count underflow", area->fa_id);
-        return;
-    }
-    entry->ref_count--;
-}
-
-void flash_area_warn_on_open(void)
-{
-    int i;
-    struct flash_map_entry *entry;
-
-    for (i = 0; i < ARRAY_SIZE(part_map); i++) {
-        entry = &part_map[i];
-        if (entry->ref_count) {
-            BOOT_LOG_WRN("area %u has %u users",
-                         entry->area.fa_id, entry->ref_count);
-        }
-    }
-}
-
-uint8_t flash_area_erased_val(const struct flash_area *area)
-{
-    (void)area;
-
-    return FLASH_DEV_NAME.GetInfo()->erased_value;
-}
-
-int flash_area_read(const struct flash_area *area, uint32_t off, void *dst,
-                    uint32_t len)
-{
-    BOOT_LOG_DBG("read area=%d, off=%#x, len=%#x", area->fa_id, off, len);
-    return FLASH_DEV_NAME.ReadData(area->fa_off + off, dst, len);
-}
-
-int flash_area_read_is_empty(const struct flash_area *area, uint32_t off,
-                             void *dst, uint32_t len)
-{
-    uint32_t i;
-    uint8_t *u8dst;
-    int rc;
-
-    BOOT_LOG_DBG("read_is_empty area=%d, off=%#x, len=%#x",
-                 area->fa_id, off, len);
-
-    rc = FLASH_DEV_NAME.ReadData(area->fa_off + off, dst, len);
-    if(rc != 0) {
-        return -1;
-    }
-
-    u8dst = (uint8_t*)dst;
-
-    for (i = 0; i < len; i++) {
-        if (u8dst[i] != flash_area_erased_val(area)) {
-            return 0;
-        }
-    }
-
-    return 1;
-}
-
-int flash_area_write(const struct flash_area *area, uint32_t off,
-                     const void *src, uint32_t len)
-{
-    BOOT_LOG_DBG("write area=%d, off=%#x, len=%#x", area->fa_id, off, len);
-    return FLASH_DEV_NAME.ProgramData(area->fa_off + off, src, len);
-}
-
-int flash_area_erase(const struct flash_area *area, uint32_t off, uint32_t len)
-{
-    ARM_FLASH_INFO *flash_info;
-    uint32_t deleted_len = 0;
-    int32_t rc = 0;
-
-    BOOT_LOG_DBG("erase area=%d, off=%#x, len=%#x", area->fa_id, off, len);
-    flash_info = FLASH_DEV_NAME.GetInfo();
-
-    if (flash_info->sector_info == NULL) {
-        /* Uniform sector layout */
-        while (deleted_len < len) {
-            rc = FLASH_DEV_NAME.EraseSector(area->fa_off + off);
-            if (rc != 0) {
-                break;
-            }
-            deleted_len += flash_info->sector_size;
-            off         += flash_info->sector_size;
-        }
-    } else {
-        /* Inhomogeneous sector layout, explicitly defined
-         * Currently not supported.
-         */
-    }
-
-    return rc;
-}
-
-uint32_t flash_area_align(const struct flash_area *area)
-{
-    ARM_FLASH_INFO *flash_info;
-
-    flash_info = FLASH_DEV_NAME.GetInfo();
-    return flash_info->program_unit;
-}
-
-/*
- * This depends on the mappings defined in sysflash.h, and assumes that the
- * primary slot, the secondary slot, and the scratch area are contiguous.
- */
-int flash_area_id_from_image_slot(int slot)
-{
-#if (MCUBOOT_IMAGE_NUMBER == 1)
-    static
-#endif
-    const int area_id_tab[] = {FLASH_AREA_IMAGE_PRIMARY,
-                               FLASH_AREA_IMAGE_SECONDARY,
-                               FLASH_AREA_IMAGE_SCRATCH};
-
-    if (slot >= 0 && slot < ARRAY_SIZE(area_id_tab)) {
-        return area_id_tab[slot];
-    }
-
-    return -EINVAL; /* flash_area_open will fail on that */
-}
-
-int flash_area_id_to_image_slot(int area_id)
-{
-    if (area_id == FLASH_AREA_IMAGE_PRIMARY) {
-        return 0;
-    }
-    if (area_id == FLASH_AREA_IMAGE_SECONDARY) {
-        return 1;
-    }
-
-    BOOT_LOG_ERR("invalid flash area ID");
-    return -1;
-}
-
-static int validate_idx(int idx, uint32_t *off, uint32_t *len)
-{
-    /*
-     * This simple layout has uniform slots, so just fill in the
-     * right one.
-     */
-
-    switch (idx) {
-    case FLASH_AREA_0_ID:
-        *off = FLASH_AREA_0_OFFSET;
-        *len = FLASH_AREA_0_SIZE;
-        break;
-    case FLASH_AREA_2_ID:
-        *off = FLASH_AREA_2_OFFSET;
-        *len = FLASH_AREA_2_SIZE;
-        break;
-#if (MCUBOOT_IMAGE_NUMBER == 2)
-    case FLASH_AREA_1_ID:
-        *off = FLASH_AREA_1_OFFSET;
-        *len = FLASH_AREA_1_SIZE;
-        break;
-    case FLASH_AREA_3_ID:
-        *off = FLASH_AREA_3_OFFSET;
-        *len = FLASH_AREA_3_SIZE;
-        break;
-#endif
-    case FLASH_AREA_SCRATCH_ID:
-        *off = FLASH_AREA_SCRATCH_OFFSET;
-        *len = FLASH_AREA_SCRATCH_SIZE;
-        break;
-    default:
-        BOOT_LOG_ERR("unknown flash area %d", idx);
-        return -1;
-    }
-
-    BOOT_LOG_DBG("area %d: offset=0x%x, length=0x%x, sector size=0x%x",
-                 idx, *off, *len, FLASH_AREA_IMAGE_SECTOR_SIZE);
-    return 0;
-}
-
-int flash_area_to_sectors(int idx, int *cnt, struct flash_area *ret)
-{
-    uint32_t off;
-    uint32_t len;
-    uint32_t max_cnt = *cnt;
-    uint32_t rem_len;
-
-    if (validate_idx(idx, &off, &len)) {
-        return -1;
-    }
-
-    if (*cnt < 1) {
-        return -1;
-    }
-
-    rem_len = len;
-    *cnt = 0;
-    while (rem_len > 0 && *cnt < max_cnt) {
-        if (rem_len < FLASH_AREA_IMAGE_SECTOR_SIZE) {
-            BOOT_LOG_ERR("area %d size 0x%x not divisible by sector size 0x%x",
-                     idx, len, FLASH_AREA_IMAGE_SECTOR_SIZE);
-            return -1;
-        }
-
-        ret[*cnt].fa_id = idx;
-        ret[*cnt].fa_device_id = 0;
-        ret[*cnt].pad16 = 0;
-        ret[*cnt].fa_off = off + (FLASH_AREA_IMAGE_SECTOR_SIZE * (*cnt));
-        ret[*cnt].fa_size = FLASH_AREA_IMAGE_SECTOR_SIZE;
-        *cnt = *cnt + 1;
-        rem_len -= FLASH_AREA_IMAGE_SECTOR_SIZE;
-    }
-
-    if (*cnt > max_cnt) {
-        BOOT_LOG_ERR("flash area %d sector count overflow", idx);
-        return -1;
-    }
-
-    return 0;
-}
-
-/*
- * Lookup the sector map for a given flash area.  This should fill in
- * `ret` with all of the sectors in the area.  `*cnt` will be set to
- * the storage at `ret` and should be set to the final number of
- * sectors in this area.
- */
-int flash_area_get_sectors(int idx, uint32_t *cnt, struct flash_sector *ret)
-{
-    uint32_t off;
-    uint32_t len;
-    uint32_t max_cnt = *cnt;
-    uint32_t rem_len;
-
-    if (validate_idx(idx, &off, &len)) {
-        return -1;
-    }
-
-    if (*cnt < 1) {
-        return -1;
-    }
-
-    rem_len = len;
-    *cnt = 0;
-    while (rem_len > 0 && *cnt < max_cnt) {
-        if (rem_len < FLASH_AREA_IMAGE_SECTOR_SIZE) {
-            BOOT_LOG_ERR("area %d size 0x%x not divisible by sector size 0x%x",
-                         idx, len, FLASH_AREA_IMAGE_SECTOR_SIZE);
-            return -1;
-        }
-
-        ret[*cnt].fs_off = FLASH_AREA_IMAGE_SECTOR_SIZE * (*cnt);
-        ret[*cnt].fs_size = FLASH_AREA_IMAGE_SECTOR_SIZE;
-        *cnt = *cnt + 1;
-        rem_len -= FLASH_AREA_IMAGE_SECTOR_SIZE;
-    }
-
-    if (*cnt > max_cnt) {
-        BOOT_LOG_ERR("flash area %d sector count overflow", idx);
-        return -1;
-    }
-
-    return 0;
-}
diff --git a/bl2/ext/mcuboot/flash_map_extended.c b/bl2/ext/mcuboot/flash_map_extended.c
new file mode 100644
index 0000000..d00686e
--- /dev/null
+++ b/bl2/ext/mcuboot/flash_map_extended.c
@@ -0,0 +1,105 @@
+/*
+ * Copyright (c) 2018 Nordic Semiconductor ASA
+ * Copyright (c) 2015 Runtime Inc
+ * Copyright (c) 2019 Arm Limited.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+/*
+ * Original code taken from mcuboot project at:
+ * https://github.com/JuulLabs-OSS/mcuboot
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
+ */
+
+#include <errno.h>
+#include "target.h"
+#include "Driver_Flash.h"
+#include "flash_map/flash_map.h"
+#include "bootutil/bootutil_log.h"
+
+/* Flash device name must be specified by target */
+extern ARM_DRIVER_FLASH FLASH_DEV_NAME;
+
+int flash_device_base(uint8_t fd_id, uintptr_t *ret)
+{
+    if (fd_id != FLASH_DEVICE_ID) {
+        BOOT_LOG_ERR("invalid flash ID %d; expected %d",
+                     fd_id, FLASH_DEVICE_ID);
+        return -EINVAL;
+    }
+    *ret = FLASH_DEVICE_BASE;
+    return 0;
+}
+
+/*
+ * This depends on the mappings defined in flash_map.h.
+ * MCUBoot uses continuous numbering for the primary slot, the secondary slot,
+ * and the scratch while TF-M might number it differently.
+ */
+int flash_area_id_from_multi_image_slot(int image_index, int slot)
+{
+    switch (slot) {
+    case 0: return FLASH_AREA_IMAGE_PRIMARY(image_index);
+    case 1: return FLASH_AREA_IMAGE_SECONDARY(image_index);
+    case 2: return FLASH_AREA_IMAGE_SCRATCH;
+    }
+
+    return -EINVAL; /* flash_area_open will fail on that */
+}
+
+int flash_area_id_from_image_slot(int slot)
+{
+    return flash_area_id_from_multi_image_slot(0, slot);
+}
+
+int flash_area_id_to_multi_image_slot(int image_index, int area_id)
+{
+    if (area_id == FLASH_AREA_IMAGE_PRIMARY(image_index)) {
+        return 0;
+    }
+    if (area_id == FLASH_AREA_IMAGE_SECONDARY(image_index)) {
+        return 1;
+    }
+
+    BOOT_LOG_ERR("invalid flash area ID");
+    return -1;
+}
+
+int flash_area_id_to_image_slot(int area_id)
+{
+    return flash_area_id_to_multi_image_slot(0, area_id);
+}
+
+uint8_t flash_area_erased_val(const struct flash_area *fap)
+{
+    (void)fap;
+
+    return FLASH_DEV_NAME.GetInfo()->erased_value;
+}
+
+int flash_area_read_is_empty(const struct flash_area *fa, uint32_t off,
+        void *dst, uint32_t len)
+{
+    uint32_t i;
+    uint8_t *u8dst;
+    int rc;
+
+    BOOT_LOG_DBG("read_is_empty area=%d, off=%#x, len=%#x",
+                 fa->fa_id, off, len);
+
+    rc = FLASH_DEV_NAME.ReadData(fa->fa_off + off, dst, len);
+    if (rc) {
+        return -1;
+    }
+
+    u8dst = (uint8_t*)dst;
+
+    for (i = 0; i < len; i++) {
+        if (u8dst[i] != flash_area_erased_val(fa)) {
+            return 0;
+        }
+    }
+
+    return 1;
+}
diff --git a/bl2/ext/mcuboot/flash_map_legacy.c b/bl2/ext/mcuboot/flash_map_legacy.c
new file mode 100644
index 0000000..34b6b54
--- /dev/null
+++ b/bl2/ext/mcuboot/flash_map_legacy.c
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Original code taken from mcuboot project at:
+ * https://github.com/JuulLabs-OSS/mcuboot
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
+ * Modifications are Copyright (c) 2019 Arm Limited.
+ */
+
+#include "bootutil/bootutil_log.h"
+#include "flash_map/flash_map.h"
+#include <inttypes.h>
+#include <target.h>
+
+/*
+ * Lookup the sector map for a given flash area.  This should fill in
+ * `ret` with all of the sectors in the area.  `*cnt` will be set to
+ * the storage at `ret` and should be set to the final number of
+ * sectors in this area.
+ */
+int flash_area_get_sectors(int idx, uint32_t *cnt, struct flash_sector *ret)
+{
+    const struct flash_area *fa;
+    uint32_t max_cnt = *cnt;
+    uint32_t rem_len;
+    int rc = -1;
+
+    if (flash_area_open(idx, &fa)) {
+        goto out;
+    }
+
+    BOOT_LOG_DBG("area %d: offset=0x%x, length=0x%x", idx, fa->fa_off,
+                 fa->fa_size);
+
+    if (*cnt < 1) {
+        goto fa_close_out;
+    }
+
+    rem_len = fa->fa_size;
+    *cnt = 0;
+    while (rem_len > 0 && *cnt < max_cnt) {
+        if (rem_len < FLASH_AREA_IMAGE_SECTOR_SIZE) {
+            BOOT_LOG_ERR("area %d size 0x%x not divisible by sector size 0x%x",
+                         idx, fa->fa_size, FLASH_AREA_IMAGE_SECTOR_SIZE);
+            goto fa_close_out;
+        }
+
+        ret[*cnt].fs_off = FLASH_AREA_IMAGE_SECTOR_SIZE * (*cnt);
+        ret[*cnt].fs_size = FLASH_AREA_IMAGE_SECTOR_SIZE;
+        *cnt = *cnt + 1;
+        rem_len -= FLASH_AREA_IMAGE_SECTOR_SIZE;
+    }
+
+    if (*cnt > max_cnt) {
+        BOOT_LOG_ERR("flash area %d sector count overflow", idx);
+        goto fa_close_out;
+    }
+
+    rc = 0;
+
+fa_close_out:
+    flash_area_close(fa);
+out:
+    return rc;
+}
diff --git a/bl2/ext/mcuboot/include/config-boot.h b/bl2/ext/mcuboot/include/config-rsa.h
similarity index 85%
rename from bl2/ext/mcuboot/include/config-boot.h
rename to bl2/ext/mcuboot/include/config-rsa.h
index 352c117..33a356b 100644
--- a/bl2/ext/mcuboot/include/config-boot.h
+++ b/bl2/ext/mcuboot/include/config-rsa.h
@@ -1,9 +1,8 @@
 /*
  *  Minimal configuration for using TLS in the bootloader
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ *  Copyright (C) 2006-2019, Arm Limited. All rights reserved.
  *  Copyright (C) 2016, Linaro Ltd
- *  Copyright (c) 2019, Arm Limited.
  *
  *  SPDX-License-Identifier: Apache-2.0
  *
@@ -23,13 +22,19 @@
  */
 
 /*
+ * Original code taken from mcuboot project at:
+ * https://github.com/JuulLabs-OSS/mcuboot
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
+ */
+
+/*
  * Minimal configuration for using TLS in the bootloader
  *
  * - RSA signature verification
  */
 
-#ifndef MBEDTLS_CONFIG_BOOT_H
-#define MBEDTLS_CONFIG_BOOT_H
+#ifndef MCUBOOT_MBEDTLS_CONFIG_RSA
+#define MCUBOOT_MBEDTLS_CONFIG_RSA
 
 /* System support */
 #define MBEDTLS_PLATFORM_C
@@ -80,4 +85,4 @@
 
 #include "mbedtls/check_config.h"
 
-#endif /* MBEDTLS_CONFIG_BOOT_H */
+#endif /* MCUBOOT_MBEDTLS_CONFIG_RSA */
diff --git a/bl2/ext/mcuboot/include/flash_map/flash_map.h b/bl2/ext/mcuboot/include/flash_map/flash_map.h
index 8c73d8f..df8c6dd 100644
--- a/bl2/ext/mcuboot/include/flash_map/flash_map.h
+++ b/bl2/ext/mcuboot/include/flash_map/flash_map.h
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2018-2019 Arm Limited.
  */
 
@@ -50,27 +50,41 @@
  */
 #include <inttypes.h>
 
-extern uint8_t current_image;
-
 #if (MCUBOOT_IMAGE_NUMBER == 1)
-#define FLASH_AREA_IMAGE_PRIMARY     FLASH_AREA_0_ID
-#define FLASH_AREA_IMAGE_SECONDARY   FLASH_AREA_2_ID
+/*
+ * NOTE: the definition below returns the same values for true/false on
+ * purpose, to avoid having to mark x as non-used by all callers when
+ * running in single image mode.
+ */
+#define FLASH_AREA_IMAGE_PRIMARY(x)     (((x) == 0) ? FLASH_AREA_0_ID : \
+                                                      FLASH_AREA_0_ID)
+#define FLASH_AREA_IMAGE_SECONDARY(x)   (((x) == 0) ? FLASH_AREA_2_ID : \
+                                                      FLASH_AREA_2_ID)
 #elif (MCUBOOT_IMAGE_NUMBER == 2)
 /* MCUBoot currently supports only up to 2 updatable firmware images.
  * If the number of the current image is greater than MCUBOOT_IMAGE_NUMBER - 1
  * then a dummy value will be assigned to the flash area macros.
  */
-#define FLASH_AREA_IMAGE_PRIMARY     ((current_image == 0) ? FLASH_AREA_0_ID : \
-                                      (current_image == 1) ? FLASH_AREA_1_ID : \
-                                                             255 )
-#define FLASH_AREA_IMAGE_SECONDARY   ((current_image == 0) ? FLASH_AREA_2_ID : \
-                                      (current_image == 1) ? FLASH_AREA_3_ID : \
-                                                             255 )
+#define FLASH_AREA_IMAGE_PRIMARY(x)     (((x) == 0) ? FLASH_AREA_0_ID : \
+                                         ((x) == 1) ? FLASH_AREA_1_ID : \
+                                                      255 )
+#define FLASH_AREA_IMAGE_SECONDARY(x)   (((x) == 0) ? FLASH_AREA_2_ID : \
+                                         ((x) == 1) ? FLASH_AREA_3_ID : \
+                                                      255 )
 #else
 #error "Image slot and flash area mapping is not defined"
 #endif
 
-#define FLASH_AREA_IMAGE_SCRATCH     FLASH_AREA_SCRATCH_ID
+#define FLASH_AREA_IMAGE_SCRATCH        FLASH_AREA_SCRATCH_ID
+
+/*
+ * For now, we only support one flash device.
+ *
+ * Pick a random device ID for it that's unlikely to collide with
+ * anything "real".
+ */
+#define FLASH_DEVICE_ID                 100
+#define FLASH_DEVICE_BASE               FLASH_BASE_ADDRESS
 
 /**
  * @brief Structure describing an area on a flash device.
@@ -146,27 +160,29 @@
 int flash_area_read(const struct flash_area *area, uint32_t off, void *dst,
                     uint32_t len);
 
-/*
- * Returns 1 if read data is erased, 0 if non-erased, and -1 on failure.
- */
-int flash_area_read_is_empty(const struct flash_area *area, uint32_t off,
-                             void *dst, uint32_t len);
-
 int flash_area_write(const struct flash_area *area, uint32_t off,
                      const void *src, uint32_t len);
 
 int flash_area_erase(const struct flash_area *area, uint32_t off, uint32_t len);
 
 /*
+ * Alignment restriction for flash writes.
+ */
+uint32_t flash_area_align(const struct flash_area *area);
+
+/*
  * Returns the value expected to be read when accessing any erased
  * flash byte.
  */
 uint8_t flash_area_erased_val(const struct flash_area *area);
 
 /*
- * Alignment restriction for flash writes.
+ * Reads len bytes from off, and checks if the read data is erased.
+ *
+ * Returns 1 if erased, 0 if non-erased, and -1 on failure.
  */
-uint32_t flash_area_align(const struct flash_area *area);
+int flash_area_read_is_empty(const struct flash_area *area, uint32_t off,
+                             void *dst, uint32_t len);
 
 /*
  * Given flash area ID, return info about sectors within the area.
@@ -182,8 +198,9 @@
 int flash_area_to_sectors(int idx, int *cnt, struct flash_area *ret);
 
 int flash_area_id_from_image_slot(int slot);
+int flash_area_id_from_multi_image_slot(int image_index, int slot);
 int flash_area_id_to_image_slot(int area_id);
-void flash_area_warn_on_open(void);
+int flash_area_id_to_multi_image_slot(int image_index, int area_id);
 
 #ifdef __cplusplus
 }
diff --git a/bl2/ext/mcuboot/include/target.h b/bl2/ext/mcuboot/include/target.h
index 256f725..69f691a 100644
--- a/bl2/ext/mcuboot/include/target.h
+++ b/bl2/ext/mcuboot/include/target.h
@@ -5,6 +5,12 @@
  *  SPDX-License-Identifier: Apache-2.0
  */
 
+/*
+ * Original code taken from mcuboot project at:
+ * https://github.com/JuulLabs-OSS/mcuboot
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
+ */
+
 #ifndef H_TARGETS_TARGET_
 #define H_TARGETS_TARGET_
 
diff --git a/bl2/ext/mcuboot/keys.c b/bl2/ext/mcuboot/keys.c
index 8f245a4..f8e500a 100644
--- a/bl2/ext/mcuboot/keys.c
+++ b/bl2/ext/mcuboot/keys.c
@@ -20,7 +20,7 @@
 /*
  * Original code taken from mcuboot project at:
  * https://github.com/JuulLabs-OSS/mcuboot
- * Git SHA of the original version: 3c469bc698a9767859ed73cd0201c44161204d5c
+ * Git SHA of the original version: 4f0ea747c314547daa6b6299ccbd77ae4dee6758
  * Modifications are Copyright (c) 2019 Arm Limited.
  */