Boot: add original files from MCUBoot and Zephyr project

Aligned with MCUBoot version 1.0.0
MCUBoot files:
 -- bl2/ext/mcuboot

Aligned with Zephyr version 1.10.0
Zephyr files:
 -- bl2/ext/mcuboot/include/util.h
 -- platform/ext/target/common/flash.h

Change-Id: I314c3efa2bd2c13a4a2eaefeb5da43e53e988638
Signed-off-by: Tamas Ban <tamas.ban@arm.com>
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c b/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
new file mode 100644
index 0000000..bf4e9b8
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/bootutil_misc.c
@@ -0,0 +1,559 @@
+/*
+ * 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.
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <inttypes.h>
+#include <stddef.h>
+
+#include "sysflash/sysflash.h"
+#include "hal/hal_bsp.h"
+#include "hal/hal_flash.h"
+#include "flash_map/flash_map.h"
+#include "os/os.h"
+#include "bootutil/image.h"
+#include "bootutil/bootutil.h"
+#include "bootutil_priv.h"
+
+#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
+#include "bootutil/bootutil_log.h"
+
+int boot_current_slot;
+
+const uint32_t boot_img_magic[] = {
+    0xf395c277,
+    0x7fefd260,
+    0x0f505235,
+    0x8079b62c,
+};
+
+const uint32_t BOOT_MAGIC_SZ = sizeof boot_img_magic;
+const uint32_t BOOT_MAX_ALIGN = MAX_FLASH_ALIGN;
+
+struct boot_swap_table {
+    /** * For each field, a value of 0 means "any". */
+    uint8_t magic_slot0;
+    uint8_t magic_slot1;
+    uint8_t image_ok_slot0;
+    uint8_t image_ok_slot1;
+    uint8_t copy_done_slot0;
+
+    uint8_t swap_type;
+};
+
+/**
+ * This set of tables maps image trailer contents to swap operation type.
+ * When searching for a match, these tables must be iterated sequentially.
+ *
+ * NOTE: the table order is very important. The settings in Slot 1 always
+ * are priority to Slot 0 and should be located earlier in the table.
+ *
+ * The table lists only states where there is action needs to be taken by
+ * the bootloader, as in starting/finishing a swap operation.
+ */
+static const struct boot_swap_table boot_swap_tables[] = {
+    {
+        .magic_slot0 =      0,
+        .magic_slot1 =      BOOT_MAGIC_GOOD,
+        .image_ok_slot0 =   0,
+        .image_ok_slot1 =   0xff,
+        .copy_done_slot0 =  0,
+        .swap_type =        BOOT_SWAP_TYPE_TEST,
+    },
+    {
+        .magic_slot0 =      0,
+        .magic_slot1 =      BOOT_MAGIC_GOOD,
+        .image_ok_slot0 =   0,
+        .image_ok_slot1 =   0x01,
+        .copy_done_slot0 =  0,
+        .swap_type =        BOOT_SWAP_TYPE_PERM,
+    },
+    {
+        .magic_slot0 =      BOOT_MAGIC_GOOD,
+        .magic_slot1 =      BOOT_MAGIC_UNSET,
+        .image_ok_slot0 =   0xff,
+        .image_ok_slot1 =   0,
+        .copy_done_slot0 =  0x01,
+        .swap_type =        BOOT_SWAP_TYPE_REVERT,
+    },
+};
+
+#define BOOT_SWAP_TABLES_COUNT \
+    (sizeof boot_swap_tables / sizeof boot_swap_tables[0])
+
+int
+boot_magic_code(const uint32_t *magic)
+{
+    int i;
+
+    if (memcmp(magic, boot_img_magic, BOOT_MAGIC_SZ) == 0) {
+        return BOOT_MAGIC_GOOD;
+    }
+
+    for (i = 0; i < BOOT_MAGIC_SZ / sizeof *magic; i++) {
+        if (magic[i] != 0xffffffff) {
+            return BOOT_MAGIC_BAD;
+        }
+    }
+
+    return BOOT_MAGIC_UNSET;
+}
+
+uint32_t
+boot_slots_trailer_sz(uint8_t min_write_sz)
+{
+    return /* state for all sectors */
+           BOOT_STATUS_MAX_ENTRIES * BOOT_STATUS_STATE_COUNT * min_write_sz +
+           BOOT_MAX_ALIGN * 3 /* copy_done + image_ok + swap_size */        +
+           BOOT_MAGIC_SZ;
+}
+
+static uint32_t
+boot_scratch_trailer_sz(uint8_t min_write_sz)
+{
+    return BOOT_STATUS_STATE_COUNT * min_write_sz +  /* state for one sector */
+           BOOT_MAX_ALIGN * 2                     +  /* image_ok + swap_size */
+           BOOT_MAGIC_SZ;
+}
+
+static uint32_t
+boot_magic_off(const struct flash_area *fap)
+{
+    assert(offsetof(struct image_trailer, magic) == 16);
+    return fap->fa_size - BOOT_MAGIC_SZ;
+}
+
+int
+boot_status_entries(const struct flash_area *fap)
+{
+    switch (fap->fa_id) {
+    case FLASH_AREA_IMAGE_0:
+    case FLASH_AREA_IMAGE_1:
+        return BOOT_STATUS_STATE_COUNT * BOOT_STATUS_MAX_ENTRIES;
+    case FLASH_AREA_IMAGE_SCRATCH:
+        return BOOT_STATUS_STATE_COUNT;
+    default:
+        return BOOT_EBADARGS;
+    }
+}
+
+uint32_t
+boot_status_off(const struct flash_area *fap)
+{
+    uint32_t off_from_end;
+    uint8_t elem_sz;
+
+    elem_sz = flash_area_align(fap);
+
+    if (fap->fa_id == FLASH_AREA_IMAGE_SCRATCH) {
+        off_from_end = boot_scratch_trailer_sz(elem_sz);
+    } else {
+        off_from_end = boot_slots_trailer_sz(elem_sz);
+    }
+
+    assert(off_from_end <= fap->fa_size);
+    return fap->fa_size - off_from_end;
+}
+
+static uint32_t
+boot_copy_done_off(const struct flash_area *fap)
+{
+    assert(fap->fa_id != FLASH_AREA_IMAGE_SCRATCH);
+    assert(offsetof(struct image_trailer, copy_done) == 0);
+    return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 2;
+}
+
+static uint32_t
+boot_image_ok_off(const struct flash_area *fap)
+{
+    assert(offsetof(struct image_trailer, image_ok) == 8);
+    return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN;
+}
+
+static uint32_t
+boot_swap_size_off(const struct flash_area *fap)
+{
+    /*
+     * The "swap_size" field if located just before the trailer.
+     * The scratch slot doesn't store "copy_done"...
+     */
+    if (fap->fa_id == FLASH_AREA_IMAGE_SCRATCH) {
+        return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 2;
+    }
+
+    return fap->fa_size - BOOT_MAGIC_SZ - BOOT_MAX_ALIGN * 3;
+}
+
+int
+boot_read_swap_state(const struct flash_area *fap,
+                     struct boot_swap_state *state)
+{
+    uint32_t magic[BOOT_MAGIC_SZ];
+    uint32_t off;
+    int rc;
+
+    off = boot_magic_off(fap);
+    rc = flash_area_read(fap, off, magic, BOOT_MAGIC_SZ);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+    state->magic = boot_magic_code(magic);
+
+    if (fap->fa_id != FLASH_AREA_IMAGE_SCRATCH) {
+        off = boot_copy_done_off(fap);
+        rc = flash_area_read(fap, off, &state->copy_done, sizeof state->copy_done);
+        if (rc != 0) {
+            return BOOT_EFLASH;
+        }
+    }
+
+    off = boot_image_ok_off(fap);
+    rc = flash_area_read(fap, off, &state->image_ok, sizeof state->image_ok);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+/**
+ * Reads the image trailer from the scratch area.
+ */
+int
+boot_read_swap_state_by_id(int flash_area_id, struct boot_swap_state *state)
+{
+    const struct flash_area *fap;
+    int rc;
+
+    switch (flash_area_id) {
+    case FLASH_AREA_IMAGE_SCRATCH:
+    case FLASH_AREA_IMAGE_0:
+    case FLASH_AREA_IMAGE_1:
+        rc = flash_area_open(flash_area_id, &fap);
+        if (rc != 0) {
+            return BOOT_EFLASH;
+        }
+        break;
+    default:
+        return BOOT_EBADARGS;
+    }
+
+    rc = boot_read_swap_state(fap, state);
+    flash_area_close(fap);
+    return rc;
+}
+
+int
+boot_read_swap_size(uint32_t *swap_size)
+{
+    uint32_t magic[BOOT_MAGIC_SZ];
+    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 Slot 0, 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_0, &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 (memcmp(magic, boot_img_magic, BOOT_MAGIC_SZ) != 0) {
+        /*
+         * If Slot 0 's magic is not valid, try scratch...
+         */
+
+        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(memcmp(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)
+{
+    uint32_t off;
+    int rc;
+
+    off = boot_magic_off(fap);
+
+    rc = flash_area_write(fap, off, boot_img_magic, BOOT_MAGIC_SZ);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+static int
+boot_write_flag(int flag, const struct flash_area *fap)
+{
+    uint32_t off;
+    int rc;
+    uint8_t buf[BOOT_MAX_ALIGN];
+    uint8_t align;
+
+    switch (flag) {
+    case BOOT_FLAG_COPY_DONE:
+        off = boot_copy_done_off(fap);
+        break;
+    case BOOT_FLAG_IMAGE_OK:
+        off = boot_image_ok_off(fap);
+        break;
+    default:
+        return BOOT_EBADARGS;
+    }
+
+    align = hal_flash_align(fap->fa_device_id);
+    assert(align <= BOOT_MAX_ALIGN);
+    memset(buf, 0xFF, BOOT_MAX_ALIGN);
+    buf[0] = BOOT_FLAG_SET;
+
+    rc = flash_area_write(fap, off, buf, align);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+int
+boot_write_copy_done(const struct flash_area *fap)
+{
+    return boot_write_flag(BOOT_FLAG_COPY_DONE, fap);
+}
+
+int
+boot_write_image_ok(const struct flash_area *fap)
+{
+    return boot_write_flag(BOOT_FLAG_IMAGE_OK, fap);
+}
+
+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];
+    uint8_t align;
+
+    off = boot_swap_size_off(fap);
+    align = hal_flash_align(fap->fa_device_id);
+    assert(align <= BOOT_MAX_ALIGN);
+    if (align < sizeof swap_size) {
+        align = sizeof swap_size;
+    }
+    memset(buf, 0xFF, BOOT_MAX_ALIGN);
+    memcpy(buf, (uint8_t *)&swap_size, sizeof swap_size);
+
+    rc = flash_area_write(fap, off, buf, align);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    return 0;
+}
+
+int
+boot_swap_type(void)
+{
+    const struct boot_swap_table *table;
+    struct boot_swap_state slot0;
+    struct boot_swap_state slot1;
+    int rc;
+    int i;
+
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &slot0);
+    if (rc) {
+        return BOOT_SWAP_TYPE_PANIC;
+    }
+
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &slot1);
+    if (rc) {
+        return BOOT_SWAP_TYPE_PANIC;
+    }
+
+    for (i = 0; i < BOOT_SWAP_TABLES_COUNT; i++) {
+        table = boot_swap_tables + i;
+
+        if ((!table->magic_slot0     || table->magic_slot0     == slot0.magic    ) &&
+            (!table->magic_slot1     || table->magic_slot1     == slot1.magic    ) &&
+            (!table->image_ok_slot0  || table->image_ok_slot0  == slot0.image_ok ) &&
+            (!table->image_ok_slot1  || table->image_ok_slot1  == slot1.image_ok ) &&
+            (!table->copy_done_slot0 || table->copy_done_slot0 == slot0.copy_done)) {
+            BOOT_LOG_INF("Swap type: %s",
+                         table->swap_type == BOOT_SWAP_TYPE_TEST   ? "test"   :
+                         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);
+            return table->swap_type;
+        }
+    }
+
+    BOOT_LOG_INF("Swap type: none");
+    return BOOT_SWAP_TYPE_NONE;
+}
+
+/**
+ * Marks the image in slot 1 as pending.  On the next reboot, the system will
+ * perform a one-time boot of the slot 1 image.
+ *
+ * @param permanent         Whether the image should be used permanently or
+ *                              only tested once:
+ *                                  0=run image once, then confirm or revert.
+ *                                  1=run image forever.
+ *
+ * @return                  0 on success; nonzero on failure.
+ */
+int
+boot_set_pending(int permanent)
+{
+    const struct flash_area *fap;
+    struct boot_swap_state state_slot1;
+    int rc;
+
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &state_slot1);
+    if (rc != 0) {
+        return rc;
+    }
+
+    switch (state_slot1.magic) {
+    case BOOT_MAGIC_GOOD:
+        /* Swap already scheduled. */
+        return 0;
+
+    case BOOT_MAGIC_UNSET:
+        rc = flash_area_open(FLASH_AREA_IMAGE_1, &fap);
+        if (rc != 0) {
+            rc = BOOT_EFLASH;
+        } else {
+            rc = boot_write_magic(fap);
+        }
+
+        if (rc == 0 && permanent) {
+            rc = boot_write_image_ok(fap);
+        }
+
+        flash_area_close(fap);
+        return rc;
+
+    default:
+        /* XXX: Temporary assert. */
+        assert(0);
+        return -1;
+    }
+}
+
+/**
+ * Marks the image in slot 0 as confirmed.  The system will continue booting into the image in slot 0 until told to boot from a different slot.
+ *
+ * @return                  0 on success; nonzero on failure.
+ */
+int
+boot_set_confirmed(void)
+{
+    const struct flash_area *fap;
+    struct boot_swap_state state_slot0;
+    int rc;
+
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &state_slot0);
+    if (rc != 0) {
+        return rc;
+    }
+
+    switch (state_slot0.magic) {
+    case BOOT_MAGIC_GOOD:
+        /* Confirm needed; proceed. */
+        break;
+
+    case BOOT_MAGIC_UNSET:
+        /* Already confirmed. */
+        return 0;
+
+    case BOOT_MAGIC_BAD:
+        /* Unexpected state. */
+        return BOOT_EBADVECT;
+    }
+
+    if (state_slot0.copy_done == BOOT_FLAG_UNSET) {
+        /* Swap never completed.  This is unexpected. */
+        return BOOT_EBADVECT;
+    }
+
+    if (state_slot0.image_ok != BOOT_FLAG_UNSET) {
+        /* Already confirmed. */
+        return 0;
+    }
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &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;
+}
diff --git a/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h b/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
new file mode 100644
index 0000000..c1cf779
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/bootutil_priv.h
@@ -0,0 +1,300 @@
+/*
+ * 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.
+ */
+
+#ifndef H_BOOTUTIL_PRIV_
+#define H_BOOTUTIL_PRIV_
+
+#include "sysflash/sysflash.h"
+#include "flash_map/flash_map.h"
+#include "bootutil/image.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+struct flash_area;
+
+#define BOOT_EFLASH     1
+#define BOOT_EFILE      2
+#define BOOT_EBADIMAGE  3
+#define BOOT_EBADVECT   4
+#define BOOT_EBADSTATUS 5
+#define BOOT_ENOMEM     6
+#define BOOT_EBADARGS   7
+
+#define BOOT_TMPBUF_SZ  256
+
+/*
+ * Maintain state of copy progress.
+ */
+struct boot_status {
+    uint32_t idx;         /* Which area we're operating on */
+    uint8_t state;        /* Which part of the swapping process are we at */
+    uint8_t use_scratch;  /* Are status bytes ever written to scratch? */
+    uint32_t swap_size;   /* Total size of swapped image */
+};
+
+#define BOOT_MAGIC_GOOD  1
+#define BOOT_MAGIC_BAD   2
+#define BOOT_MAGIC_UNSET 3
+
+/**
+ * End-of-image slot structure.
+ *
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~                                                               ~
+ * ~                Swap status (variable, aligned)                ~
+ * ~                                                               ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * |                          Swap size                            |
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~                  0xff padding (MAX ALIGN - 4)                 ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * |   Copy done   |          0xff padding (MAX ALIGN - 1)         ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * |   Image OK    |          0xff padding (MAX ALIGN - 1)         ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ * ~                        MAGIC (16 octets)                      ~
+ * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
+ */
+
+extern const uint32_t boot_img_magic[4];
+
+struct boot_swap_state {
+    uint8_t magic;  /* One of the BOOT_MAGIC_[...] values. */
+    uint8_t copy_done;
+    uint8_t image_ok;
+};
+
+#define BOOT_STATUS_STATE_COUNT 3
+#define BOOT_STATUS_MAX_ENTRIES 128
+
+#define BOOT_STATUS_SOURCE_NONE    0
+#define BOOT_STATUS_SOURCE_SCRATCH 1
+#define BOOT_STATUS_SOURCE_SLOT0   2
+
+#define BOOT_FLAG_IMAGE_OK         0
+#define BOOT_FLAG_COPY_DONE        1
+
+#define BOOT_FLAG_SET              0x01
+#define BOOT_FLAG_UNSET            0xff
+
+extern const uint32_t BOOT_MAGIC_SZ;
+
+/** Number of image slots in flash; currently limited to two. */
+#define BOOT_NUM_SLOTS              2
+
+/** Maximum number of image sectors supported by the bootloader. */
+#define BOOT_MAX_IMG_SECTORS        120
+
+/**
+ * Compatibility shim for flash sector type.
+ *
+ * This can be deleted when flash_area_to_sectors() is removed.
+ */
+#ifdef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
+typedef struct flash_sector boot_sector_t;
+#else
+typedef struct flash_area boot_sector_t;
+#endif
+
+/** Private state maintained during boot. */
+struct boot_loader_state {
+    struct {
+        struct image_header hdr;
+        const struct flash_area *area;
+        boot_sector_t *sectors;
+        size_t num_sectors;
+    } imgs[BOOT_NUM_SLOTS];
+
+    const struct flash_area *scratch_area;
+
+    uint8_t write_sz;
+};
+
+int bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+    uint8_t key_id);
+
+uint32_t boot_slots_trailer_sz(uint8_t min_write_sz);
+int boot_status_entries(const struct flash_area *fap);
+uint32_t boot_status_off(const struct flash_area *fap);
+int boot_read_swap_state(const struct flash_area *fap,
+                         struct boot_swap_state *state);
+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_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_size(const struct flash_area *fap, uint32_t swap_size);
+int boot_read_swap_size(uint32_t *swap_size);
+
+/*
+ * Accessors for the contents of struct boot_loader_state.
+ */
+
+/* These are macros so they can be used as lvalues. */
+#define BOOT_IMG_AREA(state, slot) ((state)->imgs[(slot)].area)
+#define BOOT_SCRATCH_AREA(state) ((state)->scratch_area)
+#define BOOT_WRITE_SZ(state) ((state)->write_sz)
+
+static inline struct image_header*
+boot_img_hdr(struct boot_loader_state *state, size_t slot)
+{
+    return &state->imgs[slot].hdr;
+}
+
+static inline uint8_t
+boot_img_fa_device_id(struct boot_loader_state *state, size_t slot)
+{
+    return state->imgs[slot].area->fa_device_id;
+}
+
+static inline uint8_t
+boot_scratch_fa_device_id(struct boot_loader_state *state)
+{
+    return state->scratch_area->fa_device_id;
+}
+
+static inline size_t
+boot_img_num_sectors(struct boot_loader_state *state, size_t slot)
+{
+    return state->imgs[slot].num_sectors;
+}
+
+/*
+ * Offset of the slot from the beginning of the flash device.
+ */
+static inline uint32_t
+boot_img_slot_off(struct boot_loader_state *state, size_t slot)
+{
+    return state->imgs[slot].area->fa_off;
+}
+
+static inline size_t boot_scratch_area_size(struct boot_loader_state *state)
+{
+    return state->scratch_area->fa_size;
+}
+
+#ifndef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
+
+static inline size_t
+boot_img_sector_size(struct boot_loader_state *state,
+                     size_t slot, size_t sector)
+{
+    return state->imgs[slot].sectors[sector].fa_size;
+}
+
+/*
+ * Offset of the sector from the beginning of the image, NOT the flash
+ * device.
+ */
+static inline uint32_t
+boot_img_sector_off(struct boot_loader_state *state, size_t slot,
+                    size_t sector)
+{
+    return state->imgs[slot].sectors[sector].fa_off -
+           state->imgs[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;
+    size_t slot;
+    int rc;
+
+    switch (flash_area) {
+    case FLASH_AREA_IMAGE_0:
+        slot = 0;
+        break;
+    case FLASH_AREA_IMAGE_1:
+        slot = 1;
+        break;
+    default:
+        return BOOT_EFLASH;
+    }
+
+    rc = flash_area_to_sectors(flash_area, &num_sectors,
+                               state->imgs[slot].sectors);
+    if (rc != 0) {
+        return rc;
+    }
+    state->imgs[slot].num_sectors = (size_t)num_sectors;
+    return 0;
+}
+
+#else  /* defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
+
+static inline size_t
+boot_img_sector_size(struct boot_loader_state *state,
+                     size_t slot, size_t sector)
+{
+    return state->imgs[slot].sectors[sector].fs_size;
+}
+
+static inline uint32_t
+boot_img_sector_off(struct boot_loader_state *state, size_t slot,
+                    size_t sector)
+{
+    return state->imgs[slot].sectors[sector].fs_off -
+           state->imgs[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;
+
+    switch (flash_area) {
+    case FLASH_AREA_IMAGE_0:
+        num_sectors = BOOT_MAX_IMG_SECTORS;
+        out_sectors = state->imgs[0].sectors;
+        out_num_sectors = &state->imgs[0].num_sectors;
+        break;
+    case FLASH_AREA_IMAGE_1:
+        num_sectors = BOOT_MAX_IMG_SECTORS;
+        out_sectors = state->imgs[1].sectors;
+        out_num_sectors = &state->imgs[1].num_sectors;
+        break;
+    default:
+        return -1;
+    }
+
+    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 __cplusplus
+}
+#endif
+
+#endif
diff --git a/bl2/ext/mcuboot/bootutil/src/caps.c b/bl2/ext/mcuboot/bootutil/src/caps.c
new file mode 100644
index 0000000..61d4f3f
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/caps.c
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2017 Linaro Limited
+ *
+ * Licensed 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.
+ */
+
+#include <bootutil/caps.h>
+
+uint32_t bootutil_get_caps(void)
+{
+        uint32_t res = 0;
+
+#if defined(MCUBOOT_SIGN_RSA)
+        res |= BOOTUTIL_CAP_RSA2048;
+#endif
+#if defined(MCUBOOT_SIGN_EC)
+        res |= BOOTUTIL_CAP_ECDSA_P224;
+#endif
+#if defined(MCUBOOT_SIGN_EC256)
+        res |= BOOTUTIL_CAP_ECDSA_P256;
+#endif
+#if defined(MCUBOOT_OVERWRITE_ONLY)
+        res |= BOOTUTIL_CAP_OVERWRITE_UPGRADE;
+#else
+        res |= BOOTUTIL_CAP_SWAP_UPGRADE;
+#endif
+
+        return res;
+}
diff --git a/bl2/ext/mcuboot/bootutil/src/image_rsa.c b/bl2/ext/mcuboot/bootutil/src/image_rsa.c
new file mode 100644
index 0000000..88ec784
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/image_rsa.c
@@ -0,0 +1,280 @@
+/*
+ * 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.
+ */
+
+#include <string.h>
+
+#ifdef MCUBOOT_MYNEWT
+#include "mcuboot_config/mcuboot_config.h"
+#endif
+
+#ifdef MCUBOOT_SIGN_RSA
+#include "bootutil/sign_key.h"
+#include "bootutil/sha256.h"
+
+#include "mbedtls/rsa.h"
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+/*
+ * Constants for this particular constrained implementation of
+ * RSA-PSS.  In particular, we support RSA 2048, with a SHA256 hash,
+ * and a 32-byte salt.  A signature with different parameters will be
+ * rejected as invalid.
+ */
+
+/* The size, in octets, of the message. */
+#define PSS_EMLEN 256
+
+/* The size of the hash function.  For SHA256, this is 32 bytes. */
+#define PSS_HLEN 32
+
+/* Size of the salt, should be fixed. */
+#define PSS_SLEN 32
+
+/* The length of the mask: emLen - hLen - 1. */
+#define PSS_MASK_LEN (256 - PSS_HLEN - 1)
+
+#define PSS_HASH_OFFSET PSS_MASK_LEN
+
+/* For the mask itself, how many bytes should be all zeros. */
+#define PSS_MASK_ZERO_COUNT (PSS_MASK_LEN - PSS_SLEN - 1)
+#define PSS_MASK_ONE_POS   PSS_MASK_ZERO_COUNT
+
+/* Where the salt starts. */
+#define PSS_MASK_SALT_POS   (PSS_MASK_ONE_POS + 1)
+
+static const uint8_t pss_zeros[8] = {0};
+
+/*
+ * Parse the public key used for signing. Simple RSA format.
+ */
+static int
+bootutil_parse_rsakey(mbedtls_rsa_context *ctx, uint8_t **p, uint8_t *end)
+{
+    int rc;
+    size_t len;
+
+    if ((rc = mbedtls_asn1_get_tag(p, end, &len,
+          MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
+        return -1;
+    }
+
+    if (*p + len != end) {
+        return -2;
+    }
+
+    if ((rc = mbedtls_asn1_get_mpi(p, end, &ctx->N)) != 0 ||
+      (rc = mbedtls_asn1_get_mpi(p, end, &ctx->E)) != 0) {
+        return -3;
+    }
+
+    if (*p != end) {
+        return -4;
+    }
+
+    if ((rc = mbedtls_rsa_check_pubkey(ctx)) != 0) {
+        return -5;
+    }
+
+    ctx->len = mbedtls_mpi_size(&ctx->N);
+
+    return 0;
+}
+
+/*
+ * Compute the RSA-PSS mask-generation function, MGF1.  Assumptions
+ * are that the mask length will be less than 256 * PSS_HLEN, and
+ * therefore we never need to increment anything other than the low
+ * byte of the counter.
+ *
+ * This is described in PKCS#1, B.2.1.
+ */
+static void
+pss_mgf1(uint8_t *mask, const uint8_t *hash)
+{
+    bootutil_sha256_context ctx;
+    uint8_t counter[4] = { 0, 0, 0, 0 };
+    uint8_t htmp[PSS_HLEN];
+    int count = PSS_MASK_LEN;
+    int bytes;
+
+    while (count > 0) {
+        bootutil_sha256_init(&ctx);
+        bootutil_sha256_update(&ctx, hash, PSS_HLEN);
+        bootutil_sha256_update(&ctx, counter, 4);
+        bootutil_sha256_finish(&ctx, htmp);
+
+        counter[3]++;
+
+        bytes = PSS_HLEN;
+        if (bytes > count)
+            bytes = count;
+
+        memcpy(mask, htmp, bytes);
+        mask += bytes;
+        count -= bytes;
+    }
+}
+
+/*
+ * Validate an RSA signature, using RSA-PSS, as described in PKCS #1
+ * v2.2, section 9.1.2, with many parameters required to have fixed
+ * values.
+ */
+static int
+bootutil_cmp_rsasig(mbedtls_rsa_context *ctx, uint8_t *hash, uint32_t hlen,
+  uint8_t *sig)
+{
+    bootutil_sha256_context shactx;
+    uint8_t em[MBEDTLS_MPI_MAX_SIZE];
+    uint8_t db_mask[PSS_MASK_LEN];
+    uint8_t h2[PSS_HLEN];
+    int i;
+
+    if (ctx->len != PSS_EMLEN || PSS_EMLEN > MBEDTLS_MPI_MAX_SIZE) {
+        return -1;
+    }
+
+    if (hlen != PSS_HLEN) {
+        return -1;
+    }
+
+    if (mbedtls_rsa_public(ctx, sig, em)) {
+        return -1;
+    }
+
+    /*
+     * PKCS #1 v2.2, 9.1.2 EMSA-PSS-Verify
+     *
+     * emBits is 2048
+     * emLen = ceil(emBits/8) = 256
+     *
+     * The salt length is not known at the beginning.
+     */
+
+    /* Step 1.  The message is constrained by the address space of a
+     * 32-bit processor, which is far less than the 2^61-1 limit of
+     * SHA-256.
+     */
+
+    /* Step 2.  mHash is passed in as 'hash', with hLen the hlen
+     * argument. */
+
+    /* Step 3.  if emLen < hLen + sLen + 2, inconsistent and stop.
+     * The salt length is not known at this point.
+     */
+
+    /* Step 4.  If the rightmost octect of EM does have the value
+     * 0xbc, output inconsistent and stop.
+     */
+    if (em[PSS_EMLEN - 1] != 0xbc) {
+        return -1;
+    }
+
+    /* Step 5.  Let maskedDB be the leftmost emLen - hLen - 1 octets
+     * of EM, and H be the next hLen octets.
+     *
+     * maskedDB is then the first 256 - 32 - 1 = 0-222
+     * H is 32 bytes 223-254
+     */
+
+    /* Step 6.  If the leftmost 8emLen - emBits bits of the leftmost
+     * octet in maskedDB are not all equal to zero, output
+     * inconsistent and stop.
+     *
+     * 8emLen - emBits is zero, so there is nothing to test here.
+     */
+
+    /* Step 7.  let dbMask = MGF(H, emLen - hLen - 1). */
+    pss_mgf1(db_mask, &em[PSS_HASH_OFFSET]);
+
+    /* Step 8.  let DB = maskedDB xor dbMask.
+     * To avoid needing an additional buffer, store the 'db' in the
+     * same buffer as db_mask.  From now, to the end of this function,
+     * db_mask refers to the unmasked 'db'. */
+    for (i = 0; i < PSS_MASK_LEN; i++) {
+        db_mask[i] ^= em[i];
+    }
+
+    /* Step 9.  Set the leftmost 8emLen - emBits bits of the leftmost
+     * octet in DB to zero.
+     * pycrypto seems to always make the emBits 2047, so we need to
+     * clear the top bit. */
+    db_mask[0] &= 0x7F;
+
+    /* Step 10.  If the emLen - hLen - sLen - 2 leftmost octets of DB
+     * are not zero or if the octet at position emLen - hLen - sLen -
+     * 1 (the leftmost position is "position 1") does not have
+     * hexadecimal value 0x01, output "inconsistent" and stop. */
+    for (i = 0; i < PSS_MASK_ZERO_COUNT; i++) {
+        if (db_mask[i] != 0) {
+            return -1;
+        }
+    }
+
+    if (db_mask[PSS_MASK_ONE_POS] != 1) {
+        return -1;
+    }
+
+    /* Step 11. Let salt be the last sLen octets of DB */
+
+    /* Step 12.  Let M' = 0x00 00 00 00 00 00 00 00 || mHash || salt; */
+
+    /* Step 13.  Let H' = Hash(M') */
+    bootutil_sha256_init(&shactx);
+    bootutil_sha256_update(&shactx, pss_zeros, 8);
+    bootutil_sha256_update(&shactx, hash, PSS_HLEN);
+    bootutil_sha256_update(&shactx, &db_mask[PSS_MASK_SALT_POS], PSS_SLEN);
+    bootutil_sha256_finish(&shactx, h2);
+
+    /* Step 14.  If H = H', output "consistent".  Otherwise, output
+     * "inconsistent". */
+    if (memcmp(h2, &em[PSS_HASH_OFFSET], PSS_HLEN) != 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+int
+bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+  uint8_t key_id)
+{
+    mbedtls_rsa_context ctx;
+    int rc;
+    uint8_t *cp;
+    uint8_t *end;
+
+    mbedtls_rsa_init(&ctx, 0, 0);
+
+    cp = (uint8_t *)bootutil_keys[key_id].key;
+    end = cp + *bootutil_keys[key_id].len;
+
+    rc = bootutil_parse_rsakey(&ctx, &cp, end);
+    if (rc || slen != ctx.len) {
+        mbedtls_rsa_free(&ctx);
+        return rc;
+    }
+    rc = bootutil_cmp_rsasig(&ctx, hash, hlen, sig);
+    mbedtls_rsa_free(&ctx);
+
+    return rc;
+}
+#endif /* MCUBOOT_SIGN_RSA */
diff --git a/bl2/ext/mcuboot/bootutil/src/image_validate.c b/bl2/ext/mcuboot/bootutil/src/image_validate.c
new file mode 100644
index 0000000..5b2b9a0
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/image_validate.c
@@ -0,0 +1,260 @@
+/*
+ * 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.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <inttypes.h>
+#include <string.h>
+
+#include "hal/hal_flash.h"
+#include "flash_map/flash_map.h"
+#include "bootutil/image.h"
+#include "bootutil/sha256.h"
+#include "bootutil/sign_key.h"
+
+#ifdef MCUBOOT_MYNEWT
+#include "mcuboot_config/mcuboot_config.h"
+#endif
+
+#ifdef MCUBOOT_SIGN_RSA
+#include "mbedtls/rsa.h"
+#endif
+#if defined(MCUBOOT_SIGN_EC) || defined(MCUBOOT_SIGN_EC256)
+#include "mbedtls/ecdsa.h"
+#endif
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+/*
+ * 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_sha256_context sha256_ctx;
+    uint32_t blk_sz;
+    uint32_t size;
+    uint32_t off;
+    int rc;
+
+    bootutil_sha256_init(&sha256_ctx);
+
+    /* in some cases (split image) the hash is seeded with data from
+     * the loader image */
+    if(seed && (seed_len > 0)) {
+        bootutil_sha256_update(&sha256_ctx, seed, seed_len);
+    }
+
+    size = hdr->ih_img_size + hdr->ih_hdr_size;
+
+    /*
+     * Hash is computed over image header and image itself. No TLV is
+     * included ATM.
+     */
+    size = hdr->ih_img_size + hdr->ih_hdr_size;
+    for (off = 0; off < size; off += blk_sz) {
+        blk_sz = size - off;
+        if (blk_sz > tmp_buf_sz) {
+            blk_sz = tmp_buf_sz;
+        }
+        rc = flash_area_read(fap, off, tmp_buf, blk_sz);
+        if (rc) {
+            return rc;
+        }
+        bootutil_sha256_update(&sha256_ctx, tmp_buf, blk_sz);
+    }
+    bootutil_sha256_finish(&sha256_ctx, hash_result);
+
+    return 0;
+}
+
+/*
+ * Currently, we only support being able to verify one type of
+ * signature, because there is a single verification function that we
+ * call.  List the type of TLV we are expecting.  If we aren't
+ * configured for any signature, don't define this macro.
+ */
+#if defined(MCUBOOT_SIGN_RSA)
+#    define EXPECTED_SIG_TLV IMAGE_TLV_RSA2048_PSS
+#    define EXPECTED_SIG_LEN(x) ((x) == 256) /* 2048 bits */
+#    if defined(MCUBOOT_SIGN_EC) || defined(MCUBOOT_SIGN_EC256)
+#        error "Multiple signature types not yet supported"
+#    endif
+#elif defined(MCUBOOT_SIGN_EC)
+#    define EXPECTED_SIG_TLV IMAGE_TLV_ECDSA224
+#    define EXPECTED_SIG_LEN(x) ((x) >= 64) /* oids + 2 * 28 bytes */
+#    if defined(MCUBOOT_SIGN_EC256)
+#        error "Multiple signature types not yet supported"
+#    endif
+#elif defined(MCUBOOT_SIGN_EC256)
+#    define EXPECTED_SIG_TLV IMAGE_TLV_ECDSA256
+#    define EXPECTED_SIG_LEN(x) ((x) >= 72) /* oids + 2 * 32 bytes */
+#endif
+
+#ifdef EXPECTED_SIG_TLV
+static int
+bootutil_find_key(uint8_t *keyhash, uint8_t keyhash_len)
+{
+    bootutil_sha256_context sha256_ctx;
+    int i;
+    const struct bootutil_key *key;
+    uint8_t hash[32];
+
+    assert(keyhash_len <= 32);
+
+    for (i = 0; i < bootutil_key_cnt; i++) {
+        key = &bootutil_keys[i];
+        bootutil_sha256_init(&sha256_ctx);
+        bootutil_sha256_update(&sha256_ctx, key->key, *key->len);
+        bootutil_sha256_finish(&sha256_ctx, hash);
+        if (!memcmp(hash, keyhash, keyhash_len)) {
+            return i;
+        }
+    }
+    return -1;
+}
+#endif
+
+/*
+ * Verify the integrity of the image.
+ * 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)
+{
+    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;
+#endif
+    struct image_tlv tlv;
+    uint8_t buf[256];
+    uint8_t hash[32];
+    int rc;
+
+    rc = bootutil_img_hash(hdr, fap, tmp_buf, tmp_buf_sz, hash,
+                           seed, seed_len);
+    if (rc) {
+        return rc;
+    }
+
+    if (out_hash) {
+        memcpy(out_hash, hash, 32);
+    }
+
+    /* The TLVs come after the image. */
+    /* After image there are TLVs. */
+    off = hdr->ih_img_size + hdr->ih_hdr_size;
+
+    rc = flash_area_read(fap, off, &info, sizeof(info));
+    if (rc) {
+        return rc;
+    }
+    if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
+        return -1;
+    }
+    end = off + info.it_tlv_tot;
+    off += sizeof(info);
+
+    /*
+     * Traverse through all of the TLVs, performing any checks we know
+     * and are able to do.
+     */
+    for (; off < end; off += sizeof(tlv) + tlv.it_len) {
+        rc = flash_area_read(fap, off, &tlv, sizeof tlv);
+        if (rc) {
+            return rc;
+        }
+
+        if (tlv.it_type == IMAGE_TLV_SHA256) {
+            /*
+             * Verify the SHA256 image hash.  This must always be
+             * present.
+             */
+            if (tlv.it_len != sizeof(hash)) {
+                return -1;
+            }
+            rc = flash_area_read(fap, off + sizeof(tlv), buf, sizeof hash);
+            if (rc) {
+                return rc;
+            }
+            if (memcmp(hash, buf, sizeof(hash))) {
+                return -1;
+            }
+
+            sha256_valid = 1;
+#ifdef EXPECTED_SIG_TLV
+        } else if (tlv.it_type == IMAGE_TLV_KEYHASH) {
+            /*
+             * Determine which key we should be checking.
+             */
+            if (tlv.it_len > 32) {
+                return -1;
+            }
+            rc = flash_area_read(fap, off + sizeof tlv, buf, tlv.it_len);
+            if (rc) {
+                return rc;
+            }
+            key_id = bootutil_find_key(buf, tlv.it_len);
+            /*
+             * The key may not be found, which is acceptable.  There
+             * can be multiple signatures, each preceded by a key.
+             */
+        } else if (tlv.it_type == EXPECTED_SIG_TLV) {
+            /* Ignore this signature if it is out of bounds. */
+            if (key_id < 0 || key_id >= bootutil_key_cnt) {
+                key_id = -1;
+                continue;
+            }
+            if (!EXPECTED_SIG_LEN(tlv.it_len) || tlv.it_len > sizeof(buf)) {
+                return -1;
+            }
+            rc = flash_area_read(fap, off + sizeof(tlv), buf, tlv.it_len);
+            if (rc) {
+                return -1;
+            }
+            rc = bootutil_verify_sig(hash, sizeof(hash), buf, tlv.it_len, key_id);
+            if (rc == 0) {
+                valid_signature = 1;
+            }
+            key_id = -1;
+#endif
+        }
+    }
+
+    if (!sha256_valid) {
+        return -1;
+    }
+
+#ifdef EXPECTED_SIG_TLV
+    if (!valid_signature) {
+        return -1;
+    }
+#endif
+
+    return 0;
+}
diff --git a/bl2/ext/mcuboot/bootutil/src/loader.c b/bl2/ext/mcuboot/bootutil/src/loader.c
new file mode 100644
index 0000000..30ac131
--- /dev/null
+++ b/bl2/ext/mcuboot/bootutil/src/loader.c
@@ -0,0 +1,1440 @@
+/*
+ * 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.
+ */
+
+/**
+ * This file provides an interface to the boot loader.  Functions defined in
+ * this file should only be called while the boot loader is running.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <stdbool.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include <hal/hal_flash.h>
+#include <os/os_malloc.h>
+#include "bootutil/bootutil.h"
+#include "bootutil/image.h"
+#include "bootutil_priv.h"
+
+#define BOOT_LOG_LEVEL BOOT_LOG_LEVEL_INFO
+#include "bootutil/bootutil_log.h"
+
+#ifdef MCUBOOT_MYNEWT
+#include "mcuboot_config/mcuboot_config.h"
+#endif
+
+static struct boot_loader_state boot_data;
+
+struct boot_status_table {
+    /**
+     * For each field, a value of 0 means "any".
+     */
+    uint8_t bst_magic_slot0;
+    uint8_t bst_magic_scratch;
+    uint8_t bst_copy_done_slot0;
+    uint8_t bst_status_source;
+};
+
+/**
+ * This set of tables maps swap state contents to boot status location.
+ * When searching for a match, these tables must be iterated in order.
+ */
+static const struct boot_status_table boot_status_tables[] = {
+    {
+        /*           | slot-0     | scratch    |
+         * ----------+------------+------------|
+         *     magic | Good       | Any        |
+         * copy-done | 0x01       | N/A        |
+         * ----------+------------+------------'
+         * source: none                        |
+         * ------------------------------------'
+         */
+        .bst_magic_slot0 =      BOOT_MAGIC_GOOD,
+        .bst_magic_scratch =    0,
+        .bst_copy_done_slot0 =  0x01,
+        .bst_status_source =    BOOT_STATUS_SOURCE_NONE,
+    },
+
+    {
+        /*           | slot-0     | scratch    |
+         * ----------+------------+------------|
+         *     magic | Good       | Any        |
+         * copy-done | 0xff       | N/A        |
+         * ----------+------------+------------'
+         * source: slot 0                      |
+         * ------------------------------------'
+         */
+        .bst_magic_slot0 =      BOOT_MAGIC_GOOD,
+        .bst_magic_scratch =    0,
+        .bst_copy_done_slot0 =  0xff,
+        .bst_status_source =    BOOT_STATUS_SOURCE_SLOT0,
+    },
+
+    {
+        /*           | slot-0     | scratch    |
+         * ----------+------------+------------|
+         *     magic | Any        | Good       |
+         * copy-done | Any        | N/A        |
+         * ----------+------------+------------'
+         * source: scratch                     |
+         * ------------------------------------'
+         */
+        .bst_magic_slot0 =      0,
+        .bst_magic_scratch =    BOOT_MAGIC_GOOD,
+        .bst_copy_done_slot0 =  0,
+        .bst_status_source =    BOOT_STATUS_SOURCE_SCRATCH,
+    },
+
+    {
+        /*           | slot-0     | scratch    |
+         * ----------+------------+------------|
+         *     magic | Unset      | Any        |
+         * copy-done | 0xff       | N/A        |
+         * ----------+------------+------------|
+         * source: varies                      |
+         * ------------------------------------+------------------------------+
+         * This represents one of two cases:                                  |
+         * o No swaps ever (no status to read, so no harm in checking).       |
+         * o Mid-revert; status in slot 0.                                    |
+         * -------------------------------------------------------------------'
+         */
+        .bst_magic_slot0 =      BOOT_MAGIC_UNSET,
+        .bst_magic_scratch =    0,
+        .bst_copy_done_slot0 =  0xff,
+        .bst_status_source =    BOOT_STATUS_SOURCE_SLOT0,
+    },
+};
+
+#define BOOT_STATUS_TABLES_COUNT \
+    (sizeof boot_status_tables / sizeof boot_status_tables[0])
+
+#define BOOT_LOG_SWAP_STATE(area, state)                            \
+    BOOT_LOG_INF("%s: magic=%s, copy_done=0x%x, image_ok=0x%x",     \
+                 (area),                                            \
+                 ((state)->magic == BOOT_MAGIC_GOOD ? "good" :      \
+                  (state)->magic == BOOT_MAGIC_UNSET ? "unset" :    \
+                  "bad"),                                           \
+                 (state)->copy_done,                                \
+                 (state)->image_ok)
+
+/**
+ * Determines where in flash the most recent boot status is stored.  The boot
+ * status is necessary for completing a swap that was interrupted by a boot
+ * loader reset.
+ *
+ * @return                      A BOOT_STATUS_SOURCE_[...] code indicating where *                                  status should be read from.
+ */
+static int
+boot_status_source(void)
+{
+    const struct boot_status_table *table;
+    struct boot_swap_state state_scratch;
+    struct boot_swap_state state_slot0;
+    int rc;
+    int i;
+    uint8_t source;
+
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_0, &state_slot0);
+    assert(rc == 0);
+
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH, &state_scratch);
+    assert(rc == 0);
+
+    BOOT_LOG_SWAP_STATE("Image 0", &state_slot0);
+    BOOT_LOG_SWAP_STATE("Scratch", &state_scratch);
+
+    for (i = 0; i < BOOT_STATUS_TABLES_COUNT; i++) {
+        table = &boot_status_tables[i];
+
+        if ((table->bst_magic_slot0     == 0    ||
+             table->bst_magic_slot0     == state_slot0.magic)   &&
+            (table->bst_magic_scratch   == 0    ||
+             table->bst_magic_scratch   == state_scratch.magic) &&
+            (table->bst_copy_done_slot0 == 0    ||
+             table->bst_copy_done_slot0 == state_slot0.copy_done)) {
+            source = table->bst_status_source;
+            BOOT_LOG_INF("Boot source: %s",
+                         source == BOOT_STATUS_SOURCE_NONE ? "none" :
+                         source == BOOT_STATUS_SOURCE_SCRATCH ? "scratch" :
+                         source == BOOT_STATUS_SOURCE_SLOT0 ? "slot 0" :
+                         "BUG; can't happen");
+            return source;
+        }
+    }
+
+    BOOT_LOG_INF("Boot source: none");
+    return BOOT_STATUS_SOURCE_NONE;
+}
+
+/**
+ * Calculates the type of swap that just completed.
+ *
+ * This is used when a swap is interrupted by an external event. After
+ * finishing the swap operation determines what the initial request was.
+ */
+static int
+boot_previous_swap_type(void)
+{
+    int post_swap_type;
+
+    post_swap_type = boot_swap_type();
+
+    switch (post_swap_type) {
+    case BOOT_SWAP_TYPE_NONE   : return BOOT_SWAP_TYPE_PERM;
+    case BOOT_SWAP_TYPE_REVERT : return BOOT_SWAP_TYPE_TEST;
+    case BOOT_SWAP_TYPE_PANIC  : return BOOT_SWAP_TYPE_PANIC;
+    }
+
+    return BOOT_SWAP_TYPE_FAIL;
+}
+
+/*
+ * Compute the total size of the given image.  Includes the size of
+ * the TLVs.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_read_image_size(int slot, struct image_header *hdr, uint32_t *size)
+{
+    const struct flash_area *fap;
+    struct image_tlv_info info;
+    int area_id;
+    int rc;
+
+    area_id = flash_area_id_from_image_slot(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));
+    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:
+    flash_area_close(fap);
+    return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+static int
+boot_read_image_header(int slot, struct image_header *out_hdr)
+{
+    const struct flash_area *fap;
+    int area_id;
+    int rc;
+
+    area_id = flash_area_id_from_image_slot(slot);
+    rc = flash_area_open(area_id, &fap);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    rc = flash_area_read(fap, 0, out_hdr, sizeof *out_hdr);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    rc = 0;
+
+done:
+    flash_area_close(fap);
+    return rc;
+}
+
+static int
+boot_read_image_headers(void)
+{
+    int rc;
+    int i;
+
+    for (i = 0; i < BOOT_NUM_SLOTS; i++) {
+        rc = boot_read_image_header(i, boot_img_hdr(&boot_data, i));
+        if (rc != 0) {
+            /* If at least the first slot's header was read successfully, then
+             * the boot loader can attempt a boot.  Failure to read any headers
+             * is a fatal error.
+             */
+            if (i > 0) {
+                return 0;
+            } else {
+                return rc;
+            }
+        }
+    }
+
+    return 0;
+}
+
+static uint8_t
+boot_write_sz(void)
+{
+    uint8_t elem_sz;
+    uint8_t align;
+
+    /* Figure out what size to write update status update as.  The size depends
+     * 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 = hal_flash_align(boot_img_fa_device_id(&boot_data, 0));
+    align = hal_flash_align(boot_scratch_fa_device_id(&boot_data));
+    if (align > elem_sz) {
+        elem_sz = align;
+    }
+
+    return elem_sz;
+}
+
+static int
+boot_slots_compatible(void)
+{
+    size_t num_sectors_0 = boot_img_num_sectors(&boot_data, 0);
+    size_t num_sectors_1 = boot_img_num_sectors(&boot_data, 1);
+    size_t size_0, size_1;
+    size_t i;
+
+    /* Ensure both image slots have identical sector layouts. */
+    if (num_sectors_0 != num_sectors_1) {
+        return 0;
+    }
+    for (i = 0; i < num_sectors_0; i++) {
+        size_0 = boot_img_sector_size(&boot_data, 0, i);
+        size_1 = boot_img_sector_size(&boot_data, 1, i);
+        if (size_0 != size_1) {
+            return 0;
+        }
+    }
+
+    return 1;
+}
+
+/**
+ * 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.
+ */
+static int
+boot_read_sectors(void)
+{
+    int rc;
+
+    rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_0);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    rc = boot_initialize_area(&boot_data, FLASH_AREA_IMAGE_1);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    BOOT_WRITE_SZ(&boot_data) = boot_write_sz();
+
+    return 0;
+}
+
+static uint32_t
+boot_status_internal_off(int idx, int state, int elem_sz)
+{
+    int idx_sz;
+
+    idx_sz = elem_sz * BOOT_STATUS_STATE_COUNT;
+
+    return idx * idx_sz + state * elem_sz;
+}
+
+/**
+ * Reads the status of a partially-completed swap, if any.  This is necessary
+ * to recover in case the boot lodaer was reset in the middle of a swap
+ * operation.
+ */
+static int
+boot_read_status_bytes(const struct flash_area *fap, struct boot_status *bs)
+{
+    uint32_t off;
+    uint8_t status;
+    int max_entries;
+    int found;
+    int rc;
+    int i;
+
+    off = boot_status_off(fap);
+    max_entries = boot_status_entries(fap);
+
+    found = 0;
+    for (i = 0; i < max_entries; i++) {
+        rc = flash_area_read(fap, off + i * BOOT_WRITE_SZ(&boot_data),
+                             &status, 1);
+        if (rc != 0) {
+            return BOOT_EFLASH;
+        }
+
+        if (status == 0xff) {
+            if (found) {
+                break;
+            }
+        } else if (!found) {
+            found = 1;
+        }
+    }
+
+    if (found) {
+        i--;
+        bs->idx = i / BOOT_STATUS_STATE_COUNT;
+        bs->state = i % BOOT_STATUS_STATE_COUNT;
+    }
+
+    return 0;
+}
+
+/**
+ * Reads the boot status from the flash.  The boot status contains
+ * the current state of an interrupted image copy operation.  If the boot
+ * status is not present, or it indicates that previous copy finished,
+ * there is no operation in progress.
+ */
+static int
+boot_read_status(struct boot_status *bs)
+{
+    const struct flash_area *fap;
+    int status_loc;
+    int area_id;
+    int rc;
+
+    memset(bs, 0, sizeof *bs);
+
+    status_loc = boot_status_source();
+    switch (status_loc) {
+    case BOOT_STATUS_SOURCE_NONE:
+        return 0;
+
+    case BOOT_STATUS_SOURCE_SCRATCH:
+        area_id = FLASH_AREA_IMAGE_SCRATCH;
+        break;
+
+    case BOOT_STATUS_SOURCE_SLOT0:
+        area_id = FLASH_AREA_IMAGE_0;
+        break;
+
+    default:
+        assert(0);
+        return BOOT_EBADARGS;
+    }
+
+    rc = flash_area_open(area_id, &fap);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    rc = boot_read_status_bytes(fap, bs);
+
+    flash_area_close(fap);
+    return rc;
+}
+
+/**
+ * Writes the supplied boot status to the flash file system.  The boot status
+ * contains the current state of an in-progress image copy operation.
+ *
+ * @param bs                    The boot status to write.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+int
+boot_write_status(struct boot_status *bs)
+{
+    const struct flash_area *fap;
+    uint32_t off;
+    int area_id;
+    int rc;
+    uint8_t buf[BOOT_MAX_ALIGN];
+    uint8_t align;
+
+    /* NOTE: The first sector copied (that is the last sector on slot) contains
+     *       the trailer. Since in the last step SLOT 0 is erased, the first
+     *       two status writes go to the scratch which will be copied to SLOT 0!
+     */
+
+    if (bs->use_scratch) {
+        /* Write to scratch. */
+        area_id = FLASH_AREA_IMAGE_SCRATCH;
+    } else {
+        /* Write to slot 0. */
+        area_id = FLASH_AREA_IMAGE_0;
+    }
+
+    rc = flash_area_open(area_id, &fap);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    off = boot_status_off(fap) +
+          boot_status_internal_off(bs->idx, bs->state,
+                                   BOOT_WRITE_SZ(&boot_data));
+
+    align = hal_flash_align(fap->fa_device_id);
+    memset(buf, 0xFF, BOOT_MAX_ALIGN);
+    buf[0] = bs->state;
+
+    rc = flash_area_write(fap, off, buf, align);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    rc = 0;
+
+done:
+    flash_area_close(fap);
+    return rc;
+}
+
+/*
+ * Validate image hash/signature in a slot.
+ */
+static int
+boot_image_check(struct image_header *hdr, const struct flash_area *fap)
+{
+    static uint8_t tmpbuf[BOOT_TMPBUF_SZ];
+
+    if (bootutil_img_validate(hdr, fap, tmpbuf, BOOT_TMPBUF_SZ,
+                              NULL, 0, NULL)) {
+        return BOOT_EBADIMAGE;
+    }
+    return 0;
+}
+
+static int
+split_image_check(struct image_header *app_hdr,
+                  const struct flash_area *app_fap,
+                  struct image_header *loader_hdr,
+                  const struct flash_area *loader_fap)
+{
+    static void *tmpbuf;
+    uint8_t loader_hash[32];
+
+    if (!tmpbuf) {
+        tmpbuf = malloc(BOOT_TMPBUF_SZ);
+        if (!tmpbuf) {
+            return BOOT_ENOMEM;
+        }
+    }
+
+    if (bootutil_img_validate(loader_hdr, loader_fap, tmpbuf, BOOT_TMPBUF_SZ,
+                              NULL, 0, loader_hash)) {
+        return BOOT_EBADIMAGE;
+    }
+
+    if (bootutil_img_validate(app_hdr, app_fap, tmpbuf, BOOT_TMPBUF_SZ,
+                              loader_hash, 32, NULL)) {
+        return BOOT_EBADIMAGE;
+    }
+
+    return 0;
+}
+
+static int
+boot_validate_slot(int slot)
+{
+    const struct flash_area *fap;
+    struct image_header *hdr;
+    int rc;
+
+    hdr = boot_img_hdr(&boot_data, slot);
+    if (hdr->ih_magic == 0xffffffff || hdr->ih_flags & IMAGE_F_NON_BOOTABLE) {
+        /* No bootable image in slot; continue booting from slot 0. */
+        return -1;
+    }
+
+    rc = flash_area_open(flash_area_id_from_image_slot(slot), &fap);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    if ((hdr->ih_magic != IMAGE_MAGIC || boot_image_check(hdr, fap) != 0)) {
+        if (slot != 0) {
+            flash_area_erase(fap, 0, fap->fa_size);
+            /* Image in slot 1 is invalid. Erase the image and
+             * continue booting from slot 0.
+             */
+        }
+        BOOT_LOG_ERR("Image in slot %d is not valid!", slot);
+        return -1;
+    }
+
+    flash_area_close(fap);
+
+    /* Image in slot 1 is valid. */
+    return 0;
+}
+
+/**
+ * Determines which swap operation to perform, if any.  If it is determined
+ * that a swap operation is required, the image in the second slot is checked
+ * for validity.  If the image in the second slot is invalid, it is erased, and
+ * a swap type of "none" is indicated.
+ *
+ * @return                      The type of swap to perform (BOOT_SWAP_TYPE...)
+ */
+static int
+boot_validated_swap_type(void)
+{
+    int swap_type;
+
+    swap_type = boot_swap_type();
+    switch (swap_type) {
+    case BOOT_SWAP_TYPE_TEST:
+    case BOOT_SWAP_TYPE_PERM:
+    case BOOT_SWAP_TYPE_REVERT:
+        /* Boot loader wants to switch to slot 1. Ensure image is valid. */
+        if (boot_validate_slot(1) != 0) {
+            swap_type = BOOT_SWAP_TYPE_FAIL;
+        }
+    }
+
+    return swap_type;
+}
+
+/**
+ * Calculates the number of sectors the scratch area can contain.  A "last"
+ * source sector is specified because images are copied backwards in flash
+ * (final index to index number 0).
+ *
+ * @param last_sector_idx       The index of the last source sector
+ *                                  (inclusive).
+ * @param out_first_sector_idx  The index of the first source sector
+ *                                  (inclusive) gets written here.
+ *
+ * @return                      The number of bytes comprised by the
+ *                                  [first-sector, last-sector] range.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static uint32_t
+boot_copy_sz(int last_sector_idx, int *out_first_sector_idx)
+{
+    size_t scratch_sz;
+    uint32_t new_sz;
+    uint32_t sz;
+    int i;
+
+    sz = 0;
+
+    scratch_sz = boot_scratch_area_size(&boot_data);
+    for (i = last_sector_idx; i >= 0; i--) {
+        new_sz = sz + boot_img_sector_size(&boot_data, 0, i);
+        if (new_sz > scratch_sz) {
+            break;
+        }
+        sz = new_sz;
+    }
+
+    /* i currently refers to a sector that doesn't fit or it is -1 because all
+     * sectors have been processed.  In both cases, exclude sector i.
+     */
+    *out_first_sector_idx = i + 1;
+    return sz;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Erases a region of flash.
+ *
+ * @param flash_area_idx        The ID of the flash area containing the region
+ *                                  to erase.
+ * @param off                   The offset within the flash area to start the
+ *                                  erase.
+ * @param sz                    The number of bytes to erase.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+static int
+boot_erase_sector(int flash_area_id, uint32_t off, uint32_t sz)
+{
+    const struct flash_area *fap;
+    int rc;
+
+    rc = flash_area_open(flash_area_id, &fap);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    rc = flash_area_erase(fap, off, sz);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    rc = 0;
+
+done:
+    flash_area_close(fap);
+    return rc;
+}
+
+/**
+ * Copies the contents of one flash region to another.  You must erase the
+ * destination region prior to calling this function.
+ *
+ * @param flash_area_id_src     The ID of the source flash area.
+ * @param flash_area_id_dst     The ID of the destination flash area.
+ * @param off_src               The offset within the source flash area to
+ *                                  copy from.
+ * @param off_dst               The offset within the destination flash area to
+ *                                  copy to.
+ * @param sz                    The number of bytes to copy.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+static int
+boot_copy_sector(int flash_area_id_src, int flash_area_id_dst,
+                 uint32_t off_src, uint32_t off_dst, uint32_t sz)
+{
+    const struct flash_area *fap_src;
+    const struct flash_area *fap_dst;
+    uint32_t bytes_copied;
+    int chunk_sz;
+    int rc;
+
+    static uint8_t buf[1024];
+
+    fap_src = NULL;
+    fap_dst = NULL;
+
+    rc = flash_area_open(flash_area_id_src, &fap_src);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    rc = flash_area_open(flash_area_id_dst, &fap_dst);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto done;
+    }
+
+    bytes_copied = 0;
+    while (bytes_copied < sz) {
+        if (sz - bytes_copied > sizeof buf) {
+            chunk_sz = sizeof buf;
+        } else {
+            chunk_sz = sz - bytes_copied;
+        }
+
+        rc = flash_area_read(fap_src, off_src + bytes_copied, buf, chunk_sz);
+        if (rc != 0) {
+            rc = BOOT_EFLASH;
+            goto done;
+        }
+
+        rc = flash_area_write(fap_dst, off_dst + bytes_copied, buf, chunk_sz);
+        if (rc != 0) {
+            rc = BOOT_EFLASH;
+            goto done;
+        }
+
+        bytes_copied += chunk_sz;
+    }
+
+    rc = 0;
+
+done:
+    if (fap_src) {
+        flash_area_close(fap_src);
+    }
+    if (fap_dst) {
+        flash_area_close(fap_dst);
+    }
+    return rc;
+}
+
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static inline int
+boot_status_init_by_id(int flash_area_id, const struct boot_status *bs)
+{
+    const struct flash_area *fap;
+    struct boot_swap_state swap_state;
+    int rc;
+
+    rc = flash_area_open(flash_area_id, &fap);
+    assert(rc == 0);
+
+    rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_1, &swap_state);
+    assert(rc == 0);
+
+    if (swap_state.image_ok == BOOT_FLAG_SET) {
+        rc = boot_write_image_ok(fap);
+        assert(rc == 0);
+    }
+
+    rc = boot_write_swap_size(fap, bs->swap_size);
+    assert(rc == 0);
+
+    rc = boot_write_magic(fap);
+    assert(rc == 0);
+
+    flash_area_close(fap);
+
+    return 0;
+}
+#endif
+
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_erase_last_sector_by_id(int flash_area_id)
+{
+    uint8_t slot;
+    uint32_t last_sector;
+    int rc;
+
+    switch (flash_area_id) {
+    case FLASH_AREA_IMAGE_0:
+        slot = 0;
+        break;
+    case FLASH_AREA_IMAGE_1:
+        slot = 1;
+        break;
+    default:
+        return BOOT_EFLASH;
+    }
+
+    last_sector = boot_img_num_sectors(&boot_data, slot) - 1;
+    rc = boot_erase_sector(flash_area_id,
+            boot_img_sector_off(&boot_data, slot, last_sector),
+            boot_img_sector_size(&boot_data, slot, last_sector));
+    assert(rc == 0);
+
+    return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Swaps the contents of two flash regions within the two image slots.
+ *
+ * @param idx                   The index of the first sector in the range of
+ *                                  sectors being swapped.
+ * @param sz                    The number of bytes to swap.
+ * @param bs                    The current boot status.  This struct gets
+ *                                  updated according to the outcome.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static void
+boot_swap_sectors(int idx, uint32_t sz, struct boot_status *bs)
+{
+    const struct flash_area *fap;
+    uint32_t copy_sz;
+    uint32_t trailer_sz;
+    uint32_t img_off;
+    uint32_t scratch_trailer_off;
+    struct boot_swap_state swap_state;
+    size_t last_sector;
+    int rc;
+
+    /* Calculate offset from start of image area. */
+    img_off = boot_img_sector_off(&boot_data, 0, idx);
+
+    copy_sz = sz;
+    trailer_sz = boot_slots_trailer_sz(BOOT_WRITE_SZ(&boot_data));
+
+    /* sz in this function is always is always sized on a multiple of the
+     * sector size. The check against the start offset of the last sector
+     * is to determine if we're swapping the last sector. The last sector
+     * needs special handling because it's where the trailer lives. If we're
+     * copying it, we need to use scratch to write the trailer temporarily.
+     *
+     * 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, 0) - 1;
+    if (img_off + sz > boot_img_sector_off(&boot_data, 0, last_sector)) {
+        copy_sz -= trailer_sz;
+    }
+
+    bs->use_scratch = (bs->idx == 0 && copy_sz != sz);
+
+    if (bs->state == 0) {
+        rc = boot_erase_sector(FLASH_AREA_IMAGE_SCRATCH, 0, sz);
+        assert(rc == 0);
+
+        rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_SCRATCH,
+                              img_off, 0, copy_sz);
+        assert(rc == 0);
+
+        if (bs->idx == 0) {
+            if (bs->use_scratch) {
+                boot_status_init_by_id(FLASH_AREA_IMAGE_SCRATCH, bs);
+            } else {
+                /* Prepare the status area... here it is known that the
+                 * last sector is not being used by the image data so it's
+                 * safe to erase.
+                 */
+                rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_0);
+                assert(rc == 0);
+
+                boot_status_init_by_id(FLASH_AREA_IMAGE_0, bs);
+            }
+        }
+
+        bs->state = 1;
+        rc = boot_write_status(bs);
+        assert(rc == 0);
+    }
+
+    if (bs->state == 1) {
+        rc = boot_erase_sector(FLASH_AREA_IMAGE_1, img_off, sz);
+        assert(rc == 0);
+
+        rc = boot_copy_sector(FLASH_AREA_IMAGE_0, FLASH_AREA_IMAGE_1,
+                              img_off, img_off, copy_sz);
+        assert(rc == 0);
+
+        if (bs->idx == 0 && !bs->use_scratch) {
+            /* If not all sectors of the slot are being swapped,
+             * guarantee here that only slot0 will have the state.
+             */
+            rc = boot_erase_last_sector_by_id(FLASH_AREA_IMAGE_1);
+            assert(rc == 0);
+        }
+
+        bs->state = 2;
+        rc = boot_write_status(bs);
+        assert(rc == 0);
+    }
+
+    if (bs->state == 2) {
+        rc = boot_erase_sector(FLASH_AREA_IMAGE_0, img_off, sz);
+        assert(rc == 0);
+
+        /* NOTE: also copy trailer from scratch (has status info) */
+        rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
+                              0, img_off, copy_sz);
+        assert(rc == 0);
+
+        if (bs->use_scratch) {
+            rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH, &fap);
+            assert(rc == 0);
+
+            scratch_trailer_off = boot_status_off(fap);
+
+            flash_area_close(fap);
+
+            rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+            assert(rc == 0);
+
+            /* copy current status that is being maintained in scratch */
+            rc = boot_copy_sector(FLASH_AREA_IMAGE_SCRATCH, FLASH_AREA_IMAGE_0,
+                        scratch_trailer_off,
+                        img_off + copy_sz,
+                        BOOT_STATUS_STATE_COUNT * BOOT_WRITE_SZ(&boot_data));
+            assert(rc == 0);
+
+            rc = boot_read_swap_state_by_id(FLASH_AREA_IMAGE_SCRATCH,
+                                            &swap_state);
+            assert(rc == 0);
+
+            if (swap_state.image_ok == BOOT_FLAG_SET) {
+                rc = boot_write_image_ok(fap);
+                assert(rc == 0);
+            }
+
+            rc = boot_write_swap_size(fap, bs->swap_size);
+            assert(rc == 0);
+
+            rc = boot_write_magic(fap);
+            assert(rc == 0);
+
+            flash_area_close(fap);
+        }
+
+        bs->idx++;
+        bs->state = 0;
+        bs->use_scratch = 0;
+        rc = boot_write_status(bs);
+        assert(rc == 0);
+    }
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Swaps the two images in flash.  If a prior copy operation was interrupted
+ * by a system reset, this function completes that operation.
+ *
+ * @param bs                    The current boot status.  This function reads
+ *                                  this struct to determine if it is resuming
+ *                                  an interrupted swap operation.  This
+ *                                  function writes the updated status to this
+ *                                  function on return.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+#ifdef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_copy_image(struct boot_status *bs)
+{
+    size_t sect_count;
+    size_t sect;
+    int rc;
+    size_t size = 0;
+    size_t this_size;
+
+    BOOT_LOG_INF("Image upgrade slot1 -> slot0");
+    BOOT_LOG_INF("Erasing slot0");
+
+    sect_count = boot_img_num_sectors(&boot_data, 0);
+    for (sect = 0; sect < sect_count; sect++) {
+        this_size = boot_img_sector_size(&boot_data, 0, sect);
+        rc = boot_erase_sector(FLASH_AREA_IMAGE_0,
+                               size,
+                               this_size);
+        assert(rc == 0);
+
+        size += this_size;
+    }
+
+    BOOT_LOG_INF("Copying slot 1 to slot 0: 0x%lx bytes", size);
+    rc = boot_copy_sector(FLASH_AREA_IMAGE_1, FLASH_AREA_IMAGE_0,
+                          0, 0, size);
+
+    /* Erase slot 1 so that we don't do the upgrade on every boot.
+     * TODO: Perhaps verify slot 0's signature again? */
+    rc = boot_erase_sector(FLASH_AREA_IMAGE_1,
+                           0, boot_img_sector_size(&boot_data, 1, 0));
+    assert(rc == 0);
+
+    return 0;
+}
+#else
+static int
+boot_copy_image(struct boot_status *bs)
+{
+    uint32_t sz;
+    int first_sector_idx;
+    int last_sector_idx;
+    int swap_idx;
+    struct image_header *hdr;
+    uint32_t size;
+    uint32_t copy_size;
+    int rc;
+
+    /* FIXME: just do this if asked by user? */
+
+    size = copy_size = 0;
+
+    if (bs->idx == 0 && bs->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, 0);
+        if (hdr->ih_magic == IMAGE_MAGIC) {
+            rc = boot_read_image_size(0, hdr, &copy_size);
+            assert(rc == 0);
+        }
+
+        hdr = boot_img_hdr(&boot_data, 1);
+        if (hdr->ih_magic == IMAGE_MAGIC) {
+            rc = boot_read_image_size(1, hdr, &size);
+            assert(rc == 0);
+        }
+
+        if (size > copy_size) {
+            copy_size = size;
+        }
+
+        bs->swap_size = copy_size;
+    } else {
+        /*
+         * If a swap was under way, the swap_size should already be present
+         * in the trailer...
+         */
+        rc = boot_read_swap_size(&bs->swap_size);
+        assert(rc == 0);
+
+        copy_size = bs->swap_size;
+    }
+
+    size = 0;
+    last_sector_idx = 0;
+    while (1) {
+        size += boot_img_sector_size(&boot_data, 0, last_sector_idx);
+        if (size >= copy_size) {
+            break;
+        }
+        last_sector_idx++;
+    }
+
+    swap_idx = 0;
+    while (last_sector_idx >= 0) {
+        sz = boot_copy_sz(last_sector_idx, &first_sector_idx);
+        if (swap_idx >= bs->idx) {
+            boot_swap_sectors(first_sector_idx, sz, bs);
+        }
+
+        last_sector_idx = first_sector_idx - 1;
+        swap_idx++;
+    }
+
+    return 0;
+}
+#endif
+
+/**
+ * Marks the image in slot 0 as fully copied.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_set_copy_done(void)
+{
+    const struct flash_area *fap;
+    int rc;
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    rc = boot_write_copy_done(fap);
+    flash_area_close(fap);
+    return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Marks a reverted image in slot 0 as confirmed.  This is necessary to ensure
+ * the status bytes from the image revert operation don't get processed on a
+ * subsequent boot.
+ *
+ * NOTE: image_ok is tested before writing because if there's a valid permanent
+ * image installed on slot0 and the new image to be upgrade to has a bad sig,
+ * image_ok would be overwritten.
+ */
+#ifndef MCUBOOT_OVERWRITE_ONLY
+static int
+boot_set_image_ok(void)
+{
+    const struct flash_area *fap;
+    struct boot_swap_state state;
+    int rc;
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+
+    rc = boot_read_swap_state(fap, &state);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+        goto out;
+    }
+
+    if (state.image_ok == BOOT_FLAG_UNSET) {
+        rc = boot_write_image_ok(fap);
+    }
+
+out:
+    flash_area_close(fap);
+    return rc;
+}
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+
+/**
+ * Performs an image swap if one is required.
+ *
+ * @param out_swap_type         On success, the type of swap performed gets
+ *                                  written here.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+static int
+boot_swap_if_needed(int *out_swap_type)
+{
+    struct boot_status bs;
+    int swap_type;
+    int rc;
+
+    /* Determine if we rebooted in the middle of an image swap
+     * operation.
+     */
+    rc = boot_read_status(&bs);
+    assert(rc == 0);
+    if (rc != 0) {
+        return rc;
+    }
+
+    /* If a partial swap was detected, complete it. */
+    if (bs.idx != 0 || bs.state != 0) {
+        rc = boot_copy_image(&bs);
+        assert(rc == 0);
+
+        /* NOTE: here we have finished a swap resume. The initial request
+         * was either a TEST or PERM swap, which now after the completed
+         * swap will be determined to be respectively REVERT (was TEST)
+         * or NONE (was PERM).
+         */
+
+        /* Extrapolate the type of the partial swap.  We need this
+         * information to know how to mark the swap complete in flash.
+         */
+        swap_type = boot_previous_swap_type();
+    } else {
+        swap_type = boot_validated_swap_type();
+        switch (swap_type) {
+        case BOOT_SWAP_TYPE_TEST:
+        case BOOT_SWAP_TYPE_PERM:
+        case BOOT_SWAP_TYPE_REVERT:
+            rc = boot_copy_image(&bs);
+            assert(rc == 0);
+            break;
+        }
+    }
+
+    *out_swap_type = swap_type;
+    return 0;
+}
+
+/**
+ * Prepares the booting process.  This function moves images around in flash as
+ * appropriate, and tells you what address to boot from.
+ *
+ * @param rsp                   On success, indicates how booting should occur.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+int
+boot_go(struct boot_rsp *rsp)
+{
+    int swap_type;
+    size_t slot;
+    int rc;
+    int fa_id;
+    bool reload_headers = false;
+
+    /* 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
+     * necessary because the gcc option "-fdata-sections" doesn't seem to have
+     * any effect in older gcc versions (e.g., 4.8.4).
+     */
+    static boot_sector_t slot0_sectors[BOOT_MAX_IMG_SECTORS];
+    static boot_sector_t slot1_sectors[BOOT_MAX_IMG_SECTORS];
+    boot_data.imgs[0].sectors = slot0_sectors;
+    boot_data.imgs[1].sectors = slot1_sectors;
+
+    /* Open boot_data 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));
+        assert(rc == 0);
+    }
+    rc = flash_area_open(FLASH_AREA_IMAGE_SCRATCH,
+                         &BOOT_SCRATCH_AREA(&boot_data));
+    assert(rc == 0);
+
+    /* Determine the sector layout of the image slots and scratch area. */
+    rc = boot_read_sectors();
+    if (rc != 0) {
+        goto out;
+    }
+
+    /* Attempt to read an image header from each slot. */
+    rc = boot_read_image_headers();
+    if (rc != 0) {
+        goto out;
+    }
+
+    /* If the image slots aren't compatible, no swap is possible.  Just boot
+     * into slot 0.
+     */
+    if (boot_slots_compatible()) {
+        rc = boot_swap_if_needed(&swap_type);
+        assert(rc == 0);
+        if (rc != 0) {
+            goto out;
+        }
+
+        /*
+         * The following states need image_ok be explicitly set after the
+         * swap was finished to avoid a new revert.
+         */
+        if (swap_type == BOOT_SWAP_TYPE_REVERT || swap_type == BOOT_SWAP_TYPE_FAIL) {
+#ifndef MCUBOOT_OVERWRITE_ONLY
+            rc = boot_set_image_ok();
+            if (rc != 0) {
+                swap_type = BOOT_SWAP_TYPE_PANIC;
+            }
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+        }
+    } else {
+        swap_type = BOOT_SWAP_TYPE_NONE;
+    }
+
+    switch (swap_type) {
+    case BOOT_SWAP_TYPE_NONE:
+        slot = 0;
+        break;
+
+    case BOOT_SWAP_TYPE_TEST:          /* fallthrough */
+    case BOOT_SWAP_TYPE_PERM:          /* fallthrough */
+    case BOOT_SWAP_TYPE_REVERT:
+        slot = 1;
+        reload_headers = true;
+#ifndef MCUBOOT_OVERWRITE_ONLY
+        rc = boot_set_copy_done();
+        if (rc != 0) {
+            swap_type = BOOT_SWAP_TYPE_PANIC;
+        }
+#endif /* !MCUBOOT_OVERWRITE_ONLY */
+        break;
+
+    case BOOT_SWAP_TYPE_FAIL:
+        /* The image in slot 1 was invalid and is now erased.  Ensure we don't
+         * try to boot into it again on the next reboot.  Do this by pretending
+         * we just reverted back to slot 0.
+         */
+        slot = 0;
+        reload_headers = true;
+        break;
+
+    default:
+        swap_type = BOOT_SWAP_TYPE_PANIC;
+    }
+
+    if (swap_type == BOOT_SWAP_TYPE_PANIC) {
+        BOOT_LOG_ERR("panic!");
+        assert(0);
+
+        /* Loop forever... */
+        while (1) {}
+    }
+
+#ifdef MCUBOOT_VALIDATE_SLOT0
+    if (reload_headers) {
+        rc = boot_read_image_headers();
+        if (rc != 0) {
+            goto out;
+        }
+        /* Since headers were reloaded, it can be assumed we just performed a
+         * swap or overwrite. Now the header info that should be used to
+         * provide the data for the bootstrap, which previously was at Slot 1,
+         * was updated to Slot 0.
+         */
+        slot = 0;
+    }
+
+    rc = boot_validate_slot(0);
+    assert(rc == 0);
+    if (rc != 0) {
+        rc = BOOT_EBADIMAGE;
+        goto out;
+    }
+#else
+    (void)reload_headers;
+#endif
+
+    /* Always boot from the primary slot. */
+    rsp->br_flash_dev_id = boot_img_fa_device_id(&boot_data, 0);
+    rsp->br_image_off = boot_img_slot_off(&boot_data, 0);
+    rsp->br_hdr = boot_img_hdr(&boot_data, slot);
+
+ out:
+    flash_area_close(BOOT_SCRATCH_AREA(&boot_data));
+    for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
+        flash_area_close(BOOT_IMG_AREA(&boot_data, BOOT_NUM_SLOTS - 1 - slot));
+    }
+    return rc;
+}
+
+int
+split_go(int loader_slot, int split_slot, void **entry)
+{
+    boot_sector_t *sectors;
+    uintptr_t entry_val;
+    int loader_flash_id;
+    int split_flash_id;
+    int rc;
+
+    sectors = malloc(BOOT_MAX_IMG_SECTORS * 2 * sizeof *sectors);
+    if (sectors == NULL) {
+        return SPLIT_GO_ERR;
+    }
+    boot_data.imgs[loader_slot].sectors = sectors + 0;
+    boot_data.imgs[split_slot].sectors = sectors + BOOT_MAX_IMG_SECTORS;
+
+    loader_flash_id = flash_area_id_from_image_slot(loader_slot);
+    rc = flash_area_open(loader_flash_id,
+                         &BOOT_IMG_AREA(&boot_data, split_slot));
+    assert(rc == 0);
+    split_flash_id = flash_area_id_from_image_slot(split_slot);
+    rc = flash_area_open(split_flash_id,
+                         &BOOT_IMG_AREA(&boot_data, split_slot));
+    assert(rc == 0);
+
+    /* Determine the sector layout of the image slots and scratch area. */
+    rc = boot_read_sectors();
+    if (rc != 0) {
+        rc = SPLIT_GO_ERR;
+        goto done;
+    }
+
+    rc = boot_read_image_headers();
+    if (rc != 0) {
+        goto done;
+    }
+
+    /* Don't check the bootable image flag because we could really call a
+     * bootable or non-bootable image.  Just validate that the image check
+     * passes which is distinct from the normal check.
+     */
+    rc = split_image_check(boot_img_hdr(&boot_data, split_slot),
+                           BOOT_IMG_AREA(&boot_data, split_slot),
+                           boot_img_hdr(&boot_data, loader_slot),
+                           BOOT_IMG_AREA(&boot_data, loader_slot));
+    if (rc != 0) {
+        rc = SPLIT_GO_NON_MATCHING;
+        goto done;
+    }
+
+    entry_val = boot_img_slot_off(&boot_data, split_slot) +
+                boot_img_hdr(&boot_data, split_slot)->ih_hdr_size;
+    *entry = (void *) entry_val;
+    rc = SPLIT_GO_OK;
+
+done:
+    flash_area_close(BOOT_IMG_AREA(&boot_data, split_slot));
+    flash_area_close(BOOT_IMG_AREA(&boot_data, loader_slot));
+    free(sectors);
+    return rc;
+}