From 014f42df092f9e026a32db86d49fbd1cb75f94aa Mon Sep 17 00:00:00 2001
From: Kumar Gala <kumar.gala@linaro.org>
Date: Wed, 8 Apr 2020 12:02:03 -0500
Subject: [PATCH 01/72] zephyr: Replace DT_FLASH_DEV_NAME with
 DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL

As upstream zephyr is phasing out DT_FLASH defines for non-partition
usage replace DT_FLASH_DEV_NAME with
DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
---
 boot/zephyr/flash_map_extended.c | 2 +-
 boot/zephyr/include/target.h     | 2 +-
 boot/zephyr/main.c               | 7 ++++---
 3 files changed, 6 insertions(+), 5 deletions(-)

diff --git a/boot/zephyr/flash_map_extended.c b/boot/zephyr/flash_map_extended.c
index b2de88494..4723af187 100644
--- a/boot/zephyr/flash_map_extended.c
+++ b/boot/zephyr/flash_map_extended.c
@@ -17,7 +17,7 @@
 
 MCUBOOT_LOG_MODULE_DECLARE(mcuboot);
 
-#if (!defined(CONFIG_XTENSA) && defined(DT_FLASH_DEV_NAME))
+#if (!defined(CONFIG_XTENSA) && defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL))
 #define FLASH_DEVICE_ID SOC_FLASH_0_ID
 #define FLASH_DEVICE_BASE CONFIG_FLASH_BASE_ADDRESS
 #elif (defined(CONFIG_XTENSA) && defined(DT_JEDEC_SPI_NOR_0_LABEL))
diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index 57a412b66..794f40f2d 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -28,7 +28,7 @@
 /*
  * Sanity check the target support.
  */
-#if (!defined(CONFIG_XTENSA) && !defined(DT_FLASH_DEV_NAME)) || \
+#if (!defined(CONFIG_XTENSA) && !defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) || \
     (defined(CONFIG_XTENSA) && !defined(DT_JEDEC_SPI_NOR_0_LABEL)) || \
     !defined(FLASH_ALIGN) ||                  \
     !defined(DT_FLASH_AREA_IMAGE_0_OFFSET) || \
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index 978d517e4..ce628519a 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -277,9 +277,10 @@ void main(void)
 
     ZEPHYR_BOOT_LOG_START();
 
-#if (!defined(CONFIG_XTENSA) && defined(DT_FLASH_DEV_NAME))
-    if (!flash_device_get_binding(DT_FLASH_DEV_NAME)) {
-        BOOT_LOG_ERR("Flash device %s not found", DT_FLASH_DEV_NAME);
+#if (!defined(CONFIG_XTENSA) && defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL))
+    if (!flash_device_get_binding(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) {
+        BOOT_LOG_ERR("Flash device %s not found",
+		     DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL);
         while (1)
             ;
     }

From 8cd5dc5f9fc9582e9e4e52996e23ed5078dabf82 Mon Sep 17 00:00:00 2001
From: Kumar Gala <kumar.gala@linaro.org>
Date: Wed, 8 Apr 2020 12:06:21 -0500
Subject: [PATCH 02/72] zephyr: convert DT_JEDEC_SPI_NOR_0_LABEL to new dt
 macros

As the DT define DT_JEDEC_SPI_NOR_0_LABEL is intended to be deprecated
move to the new macro style to determine for DT_JEDEC_SPI_NOR_0_LABEL

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
---
 boot/zephyr/include/target.h | 6 +++++-
 boot/zephyr/main.c           | 6 +++---
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index 794f40f2d..d6f5b74fc 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -25,11 +25,15 @@
 
 #endif /* !defined(MCUBOOT_TARGET_CONFIG) */
 
+#if DT_NODE_HAS_PROP(DT_INST(0, jedec_spi_nor), label)
+#define JEDEC_SPI_NOR_0_LABEL DT_LABEL(DT_INST(0, jedec_spi_nor))
+#endif
+
 /*
  * Sanity check the target support.
  */
 #if (!defined(CONFIG_XTENSA) && !defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) || \
-    (defined(CONFIG_XTENSA) && !defined(DT_JEDEC_SPI_NOR_0_LABEL)) || \
+    (defined(CONFIG_XTENSA) && !defined(JEDEC_SPI_NOR_0_LABEL)) || \
     !defined(FLASH_ALIGN) ||                  \
     !defined(DT_FLASH_AREA_IMAGE_0_OFFSET) || \
     !defined(DT_FLASH_AREA_IMAGE_0_SIZE) || \
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index ce628519a..c3e4cfef2 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -284,9 +284,9 @@ void main(void)
         while (1)
             ;
     }
-#elif (defined(CONFIG_XTENSA) && defined(DT_JEDEC_SPI_NOR_0_LABEL))
-    if (!flash_device_get_binding(DT_JEDEC_SPI_NOR_0_LABEL)) {
-        BOOT_LOG_ERR("Flash device %s not found", DT_JEDEC_SPI_NOR_0_LABEL);
+#elif (defined(CONFIG_XTENSA) && defined(JEDEC_SPI_NOR_0_LABEL))
+    if (!flash_device_get_binding(JEDEC_SPI_NOR_0_LABEL)) {
+        BOOT_LOG_ERR("Flash device %s not found", JEDEC_SPI_NOR_0_LABEL);
         while (1)
             ;
     }

From 39d1aef28cacde4de2ca3f65fa31ba18925e46ea Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Thu, 7 May 2020 12:38:39 +0200
Subject: [PATCH 03/72] Revert "zephyr: convert DT_JEDEC_SPI_NOR_0_LABEL to new
 dt macros"

This reverts commit 8cd5dc5f9fc9582e9e4e52996e23ed5078dabf82.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/include/target.h | 6 +-----
 boot/zephyr/main.c           | 6 +++---
 2 files changed, 4 insertions(+), 8 deletions(-)

diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index d6f5b74fc..794f40f2d 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -25,15 +25,11 @@
 
 #endif /* !defined(MCUBOOT_TARGET_CONFIG) */
 
-#if DT_NODE_HAS_PROP(DT_INST(0, jedec_spi_nor), label)
-#define JEDEC_SPI_NOR_0_LABEL DT_LABEL(DT_INST(0, jedec_spi_nor))
-#endif
-
 /*
  * Sanity check the target support.
  */
 #if (!defined(CONFIG_XTENSA) && !defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) || \
-    (defined(CONFIG_XTENSA) && !defined(JEDEC_SPI_NOR_0_LABEL)) || \
+    (defined(CONFIG_XTENSA) && !defined(DT_JEDEC_SPI_NOR_0_LABEL)) || \
     !defined(FLASH_ALIGN) ||                  \
     !defined(DT_FLASH_AREA_IMAGE_0_OFFSET) || \
     !defined(DT_FLASH_AREA_IMAGE_0_SIZE) || \
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index c3e4cfef2..ce628519a 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -284,9 +284,9 @@ void main(void)
         while (1)
             ;
     }
-#elif (defined(CONFIG_XTENSA) && defined(JEDEC_SPI_NOR_0_LABEL))
-    if (!flash_device_get_binding(JEDEC_SPI_NOR_0_LABEL)) {
-        BOOT_LOG_ERR("Flash device %s not found", JEDEC_SPI_NOR_0_LABEL);
+#elif (defined(CONFIG_XTENSA) && defined(DT_JEDEC_SPI_NOR_0_LABEL))
+    if (!flash_device_get_binding(DT_JEDEC_SPI_NOR_0_LABEL)) {
+        BOOT_LOG_ERR("Flash device %s not found", DT_JEDEC_SPI_NOR_0_LABEL);
         while (1)
             ;
     }

From 48b8ef0a9231cd2d16ed4dcb479472c4d33ac708 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Thu, 7 May 2020 12:38:48 +0200
Subject: [PATCH 04/72] Revert "Revert "zephyr: convert
 DT_JEDEC_SPI_NOR_0_LABEL to new dt macros""

This reverts commit 39d1aef28cacde4de2ca3f65fa31ba18925e46ea.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/include/target.h | 6 +++++-
 boot/zephyr/main.c           | 6 +++---
 2 files changed, 8 insertions(+), 4 deletions(-)

diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index 794f40f2d..d6f5b74fc 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -25,11 +25,15 @@
 
 #endif /* !defined(MCUBOOT_TARGET_CONFIG) */
 
+#if DT_NODE_HAS_PROP(DT_INST(0, jedec_spi_nor), label)
+#define JEDEC_SPI_NOR_0_LABEL DT_LABEL(DT_INST(0, jedec_spi_nor))
+#endif
+
 /*
  * Sanity check the target support.
  */
 #if (!defined(CONFIG_XTENSA) && !defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) || \
-    (defined(CONFIG_XTENSA) && !defined(DT_JEDEC_SPI_NOR_0_LABEL)) || \
+    (defined(CONFIG_XTENSA) && !defined(JEDEC_SPI_NOR_0_LABEL)) || \
     !defined(FLASH_ALIGN) ||                  \
     !defined(DT_FLASH_AREA_IMAGE_0_OFFSET) || \
     !defined(DT_FLASH_AREA_IMAGE_0_SIZE) || \
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index ce628519a..c3e4cfef2 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -284,9 +284,9 @@ void main(void)
         while (1)
             ;
     }
-#elif (defined(CONFIG_XTENSA) && defined(DT_JEDEC_SPI_NOR_0_LABEL))
-    if (!flash_device_get_binding(DT_JEDEC_SPI_NOR_0_LABEL)) {
-        BOOT_LOG_ERR("Flash device %s not found", DT_JEDEC_SPI_NOR_0_LABEL);
+#elif (defined(CONFIG_XTENSA) && defined(JEDEC_SPI_NOR_0_LABEL))
+    if (!flash_device_get_binding(JEDEC_SPI_NOR_0_LABEL)) {
+        BOOT_LOG_ERR("Flash device %s not found", JEDEC_SPI_NOR_0_LABEL);
         while (1)
             ;
     }

From b7254d11cd305e321e48368a09795dd01c3856af Mon Sep 17 00:00:00 2001
From: Kumar Gala <kumar.gala@linaro.org>
Date: Thu, 7 May 2020 19:31:57 -0500
Subject: [PATCH 05/72] zephyr: Change DT_FLASH_AREA_ macros to FLASH_AREA_

As we replace the legacy DT_FLASH_ support use the new FLASH_AREA_
macros.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
---
 boot/zephyr/include/sysflash/sysflash.h | 18 +++++++++---------
 boot/zephyr/include/target.h            | 10 ++++------
 2 files changed, 13 insertions(+), 15 deletions(-)

diff --git a/boot/zephyr/include/sysflash/sysflash.h b/boot/zephyr/include/sysflash/sysflash.h
index e745ffa19..66dce1d24 100644
--- a/boot/zephyr/include/sysflash/sysflash.h
+++ b/boot/zephyr/include/sysflash/sysflash.h
@@ -13,32 +13,32 @@
  * running in single image mode.
  */
 #define FLASH_AREA_IMAGE_PRIMARY(x)    (((x) == 0) ?                \
-                                         DT_FLASH_AREA_IMAGE_0_ID : \
-                                         DT_FLASH_AREA_IMAGE_0_ID)
+                                         FLASH_AREA_ID(image_0) : \
+                                         FLASH_AREA_ID(image_0))
 #define FLASH_AREA_IMAGE_SECONDARY(x)  (((x) == 0) ?                \
-                                         DT_FLASH_AREA_IMAGE_1_ID : \
-                                         DT_FLASH_AREA_IMAGE_1_ID)
+                                         FLASH_AREA_ID(image_1) : \
+                                         FLASH_AREA_ID(image_1))
 #elif (MCUBOOT_IMAGE_NUMBER == 2)
 /* MCUBoot currently supports only up to 2 updateable 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(x)    (((x) == 0) ?                \
-                                         DT_FLASH_AREA_IMAGE_0_ID : \
+                                         FLASH_AREA_ID(image_0) : \
                                         ((x) == 1) ?                \
-                                         DT_FLASH_AREA_IMAGE_2_ID : \
+                                         FLASH_AREA_ID(image_2) : \
                                          255)
 #define FLASH_AREA_IMAGE_SECONDARY(x)  (((x) == 0) ?                \
-                                         DT_FLASH_AREA_IMAGE_1_ID : \
+                                         FLASH_AREA_ID(image_1) : \
                                         ((x) == 1) ?                \
-                                         DT_FLASH_AREA_IMAGE_3_ID : \
+                                         FLASH_AREA_ID(image_3) : \
                                          255)
 #else
 #error "Image slot and flash area mapping is not defined"
 #endif
 
 #if !defined(CONFIG_BOOT_SWAP_USING_MOVE)
-#define FLASH_AREA_IMAGE_SCRATCH    DT_FLASH_AREA_IMAGE_SCRATCH_ID
+#define FLASH_AREA_IMAGE_SCRATCH    FLASH_AREA_ID(image_scratch)
 #endif
 
 #endif /* __SYSFLASH_H__ */
diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index d6f5b74fc..3cff9f36c 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -20,6 +20,7 @@
  * everything we need.
  */
 #include <soc.h>
+#include <storage/flash_map.h>
 
 #define FLASH_ALIGN FLASH_WRITE_BLOCK_SIZE
 
@@ -35,12 +36,9 @@
 #if (!defined(CONFIG_XTENSA) && !defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) || \
     (defined(CONFIG_XTENSA) && !defined(JEDEC_SPI_NOR_0_LABEL)) || \
     !defined(FLASH_ALIGN) ||                  \
-    !defined(DT_FLASH_AREA_IMAGE_0_OFFSET) || \
-    !defined(DT_FLASH_AREA_IMAGE_0_SIZE) || \
-    !defined(DT_FLASH_AREA_IMAGE_1_OFFSET) || \
-    !defined(DT_FLASH_AREA_IMAGE_1_SIZE) || \
-    (!defined(CONFIG_BOOT_SWAP_USING_MOVE) && !defined(DT_FLASH_AREA_IMAGE_SCRATCH_OFFSET)) || \
-    (!defined(CONFIG_BOOT_SWAP_USING_MOVE) && !defined(DT_FLASH_AREA_IMAGE_SCRATCH_SIZE))
+    !(FLASH_AREA_LABEL_EXISTS(image_0)) || \
+    !(FLASH_AREA_LABEL_EXISTS(image_1)) || \
+    (!defined(CONFIG_BOOT_SWAP_USING_MOVE) && !(FLASH_AREA_LABEL_EXISTS(image_scratch)))
 #error "Target support is incomplete; cannot build mcuboot."
 #endif
 

From 322b11ae3489e04b86ec2188a7de29ca6593178d Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Mon, 11 May 2020 14:20:29 +0200
Subject: [PATCH 06/72] zephyr: Change DT_FLASH_AREA_ macros to FLASH_AREA for
 multimage

Use the new FLASH_AREA_ macros.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/include/target.h | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)

diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index 3cff9f36c..2e0f5fdaf 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -42,10 +42,8 @@
 #error "Target support is incomplete; cannot build mcuboot."
 #endif
 
-#if ((MCUBOOT_IMAGE_NUMBER == 2) && (!defined(FLASH_AREA_IMAGE_2_OFFSET) || \
-                                     !defined(FLASH_AREA_IMAGE_2_SIZE)   || \
-                                     !defined(FLASH_AREA_IMAGE_3_OFFSET) || \
-                                     !defined(FLASH_AREA_IMAGE_3_SIZE)))
+#if (MCUBOOT_IMAGE_NUMBER == 2) && (!(FLASH_AREA_LABEL_EXISTS(image_2)) || \
+                                     !(FLASH_AREA_LABEL_EXISTS(image_3)))
 #error "Target support is incomplete; cannot build mcuboot."
 #endif
 

From 1f181dda41e618e6269024ea6f097c52a68b9d3f Mon Sep 17 00:00:00 2001
From: Kumar Gala <kumar.gala@linaro.org>
Date: Mon, 11 May 2020 15:08:19 -0500
Subject: [PATCH 07/72] sim: Fixup devicetree.h for changes to mcuboot

Fixup how we fake out devicetree.h, which is now really the flash map
API for what mcuboot is using.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
---
 sim/mcuboot-sys/csupport/devicetree.h | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/sim/mcuboot-sys/csupport/devicetree.h b/sim/mcuboot-sys/csupport/devicetree.h
index f268640ae..434e4eebf 100644
--- a/sim/mcuboot-sys/csupport/devicetree.h
+++ b/sim/mcuboot-sys/csupport/devicetree.h
@@ -4,15 +4,17 @@
  * SPDX-License-Identifier: Apache-2.0
  */
 
-/* This file mocks zephyr's autogenerated DT output header file */
+/* This file mocks zephyr's flash map / DT macro */
 
 #ifndef __DEVICETREE_H__
 #define __DEVICETREE_H__
 
-#define DT_FLASH_AREA_IMAGE_0_ID 1
-#define DT_FLASH_AREA_IMAGE_1_ID 2
-#define DT_FLASH_AREA_IMAGE_SCRATCH_ID 3
-#define DT_FLASH_AREA_IMAGE_2_ID 4
-#define DT_FLASH_AREA_IMAGE_3_ID 5
+#define FLASH_AREA_ID(x) FLASH_AREA_ID_##x
+
+#define FLASH_AREA_ID_image_0 1
+#define FLASH_AREA_ID_image_1 2
+#define FLASH_AREA_ID_image_scratch 3
+#define FLASH_AREA_ID_image_2 4
+#define FLASH_AREA_ID_image_3 5
 
 #endif /*__DEVICETREE_H__*/

From e88113bbebe34ff2ccc6627ffae885cfeed6fdfd Mon Sep 17 00:00:00 2001
From: Kumar Gala <kumar.gala@linaro.org>
Date: Mon, 11 May 2020 15:33:03 -0500
Subject: [PATCH 08/72] scripts/assemble: Rework to use EDT library to get
 devicetree data

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
---
 scripts/assemble.py | 55 +++++++++++++++++++++++++++++----------------
 1 file changed, 36 insertions(+), 19 deletions(-)

diff --git a/scripts/assemble.py b/scripts/assemble.py
index d8c824b00..e895ee773 100755
--- a/scripts/assemble.py
+++ b/scripts/assemble.py
@@ -23,6 +23,14 @@
 import io
 import re
 import os.path
+import sys
+
+ZEPHYR_BASE = os.getenv("ZEPHYR_BASE")
+if not ZEPHYR_BASE:
+    sys.exit("$ZEPHYR_BASE environment variable undefined")
+
+sys.path.insert(0, os.path.join(ZEPHYR_BASE, "scripts", "dts"))
+import edtlib
 
 def same_keys(a, b):
     """Determine if the dicts a and b have the same keys in them"""
@@ -38,8 +46,8 @@ def same_keys(a, b):
 size_re   = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_SIZE(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
 
 class Assembly():
-    def __init__(self, output, bootdir):
-        self.find_slots(bootdir)
+    def __init__(self, output, bootdir, edt):
+        self.find_slots(edt)
         try:
             os.unlink(output)
         except OSError as e:
@@ -47,29 +55,29 @@ def __init__(self, output, bootdir):
                 raise
         self.output = output
 
-    def find_slots(self, bootdir):
+    def find_slots(self, edt):
         offsets = {}
         sizes = {}
-        with open(os.path.join(bootdir, 'zephyr', 'include', 'generated', 'devicetree_legacy_unfixed.h'), 'r') as fd:
-            for line in fd:
-                m = offset_re.match(line)
-                if m is not None:
-                    offsets[m.group(1)] = int(m.group(3), 0)
-                m = size_re.match(line)
-                if m is not None:
-                    sizes[m.group(1)] = int(m.group(3), 0)
+
+        part_nodes = edt.compat2nodes["fixed-partitions"]
+        for node in part_nodes:
+            for child in node.children.values():
+                if "label" in child.props:
+                    label = child.props["label"].val
+                    offsets[label] = child.regs[0].addr
+                    sizes[label] = child.regs[0].size
 
         if not same_keys(offsets, sizes):
             raise Exception("Inconsistent data in devicetree.h")
 
-        # We care about the MCUBOOT, IMAGE_0, and IMAGE_1 partitions.
-        if 'MCUBOOT' not in offsets:
+        # We care about the mcuboot, image-0, and image-1 partitions.
+        if 'mcuboot' not in offsets:
             raise Exception("Board partition table does not have mcuboot partition")
 
-        if 'IMAGE_0' not in offsets:
+        if 'image-0' not in offsets:
             raise Exception("Board partition table does not have image-0 partition")
 
-        if 'IMAGE_1' not in offsets:
+        if 'image-1' not in offsets:
             raise Exception("Board partition table does not have image-1 partition")
 
         self.offsets = offsets
@@ -103,12 +111,21 @@ def main():
             help='Filename to write full image to')
 
     args = parser.parse_args()
-    output = Assembly(args.output, args.bootdir)
 
-    output.add_image(os.path.join(args.bootdir, 'zephyr', 'zephyr.bin'), 'MCUBOOT')
-    output.add_image(args.primary, "IMAGE_0")
+    # Extract board name from path
+    board = os.path.split(os.path.split(args.bootdir)[0])[1]
+
+    dts_path = os.path.join(args.bootdir, "zephyr", board + ".dts.pre.tmp")
+
+    edt = edtlib.EDT(dts_path, [os.path.join(ZEPHYR_BASE, "dts", "bindings")],
+            warn_reg_unit_address_mismatch=False)
+
+    output = Assembly(args.output, args.bootdir, edt)
+
+    output.add_image(os.path.join(args.bootdir, 'zephyr', 'zephyr.bin'), 'mcuboot')
+    output.add_image(args.primary, "image-0")
     if args.secondary is not None:
-        output.add_image(args.secondary, "IMAGE_1")
+        output.add_image(args.secondary, "image-1")
 
 if __name__ == '__main__':
     main()

From f6252674aaef5988222925f1dfc05e68df2da2c6 Mon Sep 17 00:00:00 2001
From: Joakim Andersson <joakim.andersson@nordicsemi.no>
Date: Tue, 19 May 2020 17:12:52 +0200
Subject: [PATCH 09/72] kconfig: Update to CONFIG_FLOAT to CONFIG_FPU rename in
 zephyr

Update CONFIG_FLOAT to CONFIG_FPU which has been renamed in zephyr.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
---
 boot/zephyr/boards/nrf52_minimal_footprint.conf | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/boot/zephyr/boards/nrf52_minimal_footprint.conf b/boot/zephyr/boards/nrf52_minimal_footprint.conf
index 8c24f54cc..afe8c9baf 100644
--- a/boot/zephyr/boards/nrf52_minimal_footprint.conf
+++ b/boot/zephyr/boards/nrf52_minimal_footprint.conf
@@ -53,7 +53,7 @@ CONFIG_IRQ_OFFLOAD=n
 # Memory protection
 CONFIG_MEMORY_PROTECTION=n
 CONFIG_THREAD_CUSTOM_DATA=n
-CONFIG_FLOAT=n
+CONFIG_FPU=n
 
 # Boot
 CONFIG_BOOT_BANNER=n

From 4bb0f9547f80e1d14cb6591db12030e2dbf891f4 Mon Sep 17 00:00:00 2001
From: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Date: Thu, 28 May 2020 12:34:15 +0200
Subject: [PATCH 10/72] cmake: use find_package to locate Zephyr

Using find_package to locate Zephyr.

Old behavior was to use $ENV{ZEPHYR_BASE} for inclusion of boiler plate
code.

Whenever an automatic run of CMake happend by the build system / IDE
then it was required that ZEPHYR_BASE was defined.
Using ZEPHYR_BASE only to locate the Zephyr package allows CMake to
cache the base variable and thus allowing subsequent invocation even
if ZEPHYR_BASE is not set in the environment.

It also removes the risk of strange build results if a user switchs
between different Zephyr based project folders and forgetting to reset
ZEPHYR_BASE before running ninja / make.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
---
 boot/zephyr/CMakeLists.txt | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot/zephyr/CMakeLists.txt b/boot/zephyr/CMakeLists.txt
index c382c528b..b860e97b7 100644
--- a/boot/zephyr/CMakeLists.txt
+++ b/boot/zephyr/CMakeLists.txt
@@ -39,9 +39,9 @@ macro(app_set_runner_args)
   endif()
 endmacro()
 
-# Standard Zephyr application boilerplate:
+# find_package(Zephyr) in order to load application boilerplate:
 # http://docs.zephyrproject.org/application/application.html
-include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE)
+find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
 project(NONE)
 
 # Path to "boot" subdirectory of repository root.

From ba7748d0923077488fd8d7864db8d0af0a4b4657 Mon Sep 17 00:00:00 2001
From: Kumar Gala <kumar.gala@linaro.org>
Date: Wed, 27 May 2020 12:25:41 -0500
Subject: [PATCH 11/72] Convert from Zephyr to C99 types

Convert to use C99 types as we intend to deprecate the zephyr
specific integer types.

Signed-off-by: Kumar Gala <kumar.gala@linaro.org>
---
 boot/boot_serial/src/boot_serial.c | 2 +-
 boot/zephyr/arm_cleanup.c          | 4 ++--
 boot/zephyr/main.c                 | 4 ++--
 boot/zephyr/serial_adapter.c       | 6 +++---
 4 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/boot/boot_serial/src/boot_serial.c b/boot/boot_serial/src/boot_serial.c
index 44a28fcba..f00c8e885 100644
--- a/boot/boot_serial/src/boot_serial.c
+++ b/boot/boot_serial/src/boot_serial.c
@@ -485,7 +485,7 @@ boot_serial_output(void)
     bs_hdr->nh_group = htons(bs_hdr->nh_group);
 
 #ifdef __ZEPHYR__
-    crc =  crc16((u8_t *)bs_hdr, sizeof(*bs_hdr), CRC_CITT_POLYMINAL,
+    crc =  crc16((uint8_t *)bs_hdr, sizeof(*bs_hdr), CRC_CITT_POLYMINAL,
                  CRC16_INITIAL_CRC, false);
     crc =  crc16(data, len, CRC_CITT_POLYMINAL, crc, true);
 #else
diff --git a/boot/zephyr/arm_cleanup.c b/boot/zephyr/arm_cleanup.c
index 647b8b429..a36592685 100644
--- a/boot/zephyr/arm_cleanup.c
+++ b/boot/zephyr/arm_cleanup.c
@@ -12,11 +12,11 @@ void cleanup_arm_nvic(void) {
 	__disable_irq();
 
 	/* Disable NVIC interrupts */
-	for (u8_t i = 0; i < ARRAY_SIZE(NVIC->ICER); i++) {
+	for (uint8_t i = 0; i < ARRAY_SIZE(NVIC->ICER); i++) {
 		NVIC->ICER[i] = 0xFFFFFFFF;
 	}
 	/* Clear pending NVIC interrupts */
-	for (u8_t i = 0; i < ARRAY_SIZE(NVIC->ICPR); i++) {
+	for (uint8_t i = 0; i < ARRAY_SIZE(NVIC->ICPR); i++) {
 		NVIC->ICPR[i] = 0xFFFFFFFF;
 	}
 }
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index c3e4cfef2..1bea3bbda 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -79,7 +79,7 @@ K_SEM_DEFINE(boot_log_sem, 1, 1);
 static inline bool boot_skip_serial_recovery()
 {
 #if NRF_POWER_HAS_RESETREAS
-    u32_t rr = nrf_power_resetreas_get(NRF_POWER);
+    uint32_t rr = nrf_power_resetreas_get(NRF_POWER);
 
     return !(rr == 0 || (rr & NRF_POWER_RESETREAS_RESETPIN_MASK));
 #else
@@ -295,7 +295,7 @@ void main(void)
 #ifdef CONFIG_MCUBOOT_SERIAL
 
     struct device *detect_port;
-    u32_t detect_value = !CONFIG_BOOT_SERIAL_DETECT_PIN_VAL;
+    uint32_t detect_value = !CONFIG_BOOT_SERIAL_DETECT_PIN_VAL;
 
     detect_port = device_get_binding(CONFIG_BOOT_SERIAL_DETECT_PORT);
     __ASSERT(detect_port, "Error: Bad port for boot serial detection.\n");
diff --git a/boot/zephyr/serial_adapter.c b/boot/zephyr/serial_adapter.c
index 63dca025a..896ed5231 100644
--- a/boot/zephyr/serial_adapter.c
+++ b/boot/zephyr/serial_adapter.c
@@ -47,7 +47,7 @@ static struct line_input line_bufs[2];
 static sys_slist_t avail_queue;
 static sys_slist_t lines_queue;
 
-static u16_t cur;
+static uint16_t cur;
 
 static int boot_uart_fifo_getline(char **line);
 static int boot_uart_fifo_init(void);
@@ -118,7 +118,7 @@ static void
 boot_uart_fifo_callback(struct device *dev)
 {
 	static struct line_input *cmd;
-	u8_t byte;
+	uint8_t byte;
 	int rx;
 
 	uart_irq_update(uart_dev);
@@ -203,7 +203,7 @@ boot_uart_fifo_init(void)
 		}
 	}
 #endif
-	u8_t c;
+	uint8_t c;
 
 	if (!uart_dev) {
 		return (-1);

From 60cc568615e9f34f90677c12bc4264a5dd802303 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Mon, 8 Jun 2020 11:36:13 +0200
Subject: [PATCH 12/72] Revert "zephyr: Change DT_FLASH_AREA_ macros to
 FLASH_AREA_"

This reverts commit b7254d11cd305e321e48368a09795dd01c3856af.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/include/sysflash/sysflash.h | 18 +++++++++---------
 boot/zephyr/include/target.h            | 10 ++++++----
 2 files changed, 15 insertions(+), 13 deletions(-)

diff --git a/boot/zephyr/include/sysflash/sysflash.h b/boot/zephyr/include/sysflash/sysflash.h
index 66dce1d24..e745ffa19 100644
--- a/boot/zephyr/include/sysflash/sysflash.h
+++ b/boot/zephyr/include/sysflash/sysflash.h
@@ -13,32 +13,32 @@
  * running in single image mode.
  */
 #define FLASH_AREA_IMAGE_PRIMARY(x)    (((x) == 0) ?                \
-                                         FLASH_AREA_ID(image_0) : \
-                                         FLASH_AREA_ID(image_0))
+                                         DT_FLASH_AREA_IMAGE_0_ID : \
+                                         DT_FLASH_AREA_IMAGE_0_ID)
 #define FLASH_AREA_IMAGE_SECONDARY(x)  (((x) == 0) ?                \
-                                         FLASH_AREA_ID(image_1) : \
-                                         FLASH_AREA_ID(image_1))
+                                         DT_FLASH_AREA_IMAGE_1_ID : \
+                                         DT_FLASH_AREA_IMAGE_1_ID)
 #elif (MCUBOOT_IMAGE_NUMBER == 2)
 /* MCUBoot currently supports only up to 2 updateable 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(x)    (((x) == 0) ?                \
-                                         FLASH_AREA_ID(image_0) : \
+                                         DT_FLASH_AREA_IMAGE_0_ID : \
                                         ((x) == 1) ?                \
-                                         FLASH_AREA_ID(image_2) : \
+                                         DT_FLASH_AREA_IMAGE_2_ID : \
                                          255)
 #define FLASH_AREA_IMAGE_SECONDARY(x)  (((x) == 0) ?                \
-                                         FLASH_AREA_ID(image_1) : \
+                                         DT_FLASH_AREA_IMAGE_1_ID : \
                                         ((x) == 1) ?                \
-                                         FLASH_AREA_ID(image_3) : \
+                                         DT_FLASH_AREA_IMAGE_3_ID : \
                                          255)
 #else
 #error "Image slot and flash area mapping is not defined"
 #endif
 
 #if !defined(CONFIG_BOOT_SWAP_USING_MOVE)
-#define FLASH_AREA_IMAGE_SCRATCH    FLASH_AREA_ID(image_scratch)
+#define FLASH_AREA_IMAGE_SCRATCH    DT_FLASH_AREA_IMAGE_SCRATCH_ID
 #endif
 
 #endif /* __SYSFLASH_H__ */
diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index 2e0f5fdaf..861d25431 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -20,7 +20,6 @@
  * everything we need.
  */
 #include <soc.h>
-#include <storage/flash_map.h>
 
 #define FLASH_ALIGN FLASH_WRITE_BLOCK_SIZE
 
@@ -36,9 +35,12 @@
 #if (!defined(CONFIG_XTENSA) && !defined(DT_CHOSEN_ZEPHYR_FLASH_CONTROLLER_LABEL)) || \
     (defined(CONFIG_XTENSA) && !defined(JEDEC_SPI_NOR_0_LABEL)) || \
     !defined(FLASH_ALIGN) ||                  \
-    !(FLASH_AREA_LABEL_EXISTS(image_0)) || \
-    !(FLASH_AREA_LABEL_EXISTS(image_1)) || \
-    (!defined(CONFIG_BOOT_SWAP_USING_MOVE) && !(FLASH_AREA_LABEL_EXISTS(image_scratch)))
+    !defined(DT_FLASH_AREA_IMAGE_0_OFFSET) || \
+    !defined(DT_FLASH_AREA_IMAGE_0_SIZE) || \
+    !defined(DT_FLASH_AREA_IMAGE_1_OFFSET) || \
+    !defined(DT_FLASH_AREA_IMAGE_1_SIZE) || \
+    (!defined(CONFIG_BOOT_SWAP_USING_MOVE) && !defined(DT_FLASH_AREA_IMAGE_SCRATCH_OFFSET)) || \
+    (!defined(CONFIG_BOOT_SWAP_USING_MOVE) && !defined(DT_FLASH_AREA_IMAGE_SCRATCH_SIZE))
 #error "Target support is incomplete; cannot build mcuboot."
 #endif
 

From 9920005e1bedf20d0e2b24d39a44de193fc36691 Mon Sep 17 00:00:00 2001
From: Carles Cufi <carles.cufi@nordicsemi.no>
Date: Mon, 20 Jul 2020 17:43:17 +0200
Subject: [PATCH 13/72] zephyr: serial: Align with new callback signature

Align the code to the new UART callback signature, see:

https://github.com/zephyrproject-rtos/zephyr/pull/26426

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
---
 boot/zephyr/serial_adapter.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/boot/zephyr/serial_adapter.c b/boot/zephyr/serial_adapter.c
index 896ed5231..8787780e3 100644
--- a/boot/zephyr/serial_adapter.c
+++ b/boot/zephyr/serial_adapter.c
@@ -115,7 +115,7 @@ boot_console_init(void)
 }
 
 static void
-boot_uart_fifo_callback(struct device *dev)
+boot_uart_fifo_callback(struct device *dev, void *user_data)
 {
 	static struct line_input *cmd;
 	uint8_t byte;

From 3ab5ab307cbfd1f7d3028dc7461b35c156d3e5ab Mon Sep 17 00:00:00 2001
From: Anas Nashif <anas.nashif@intel.com>
Date: Wed, 26 Aug 2020 18:07:05 -0400
Subject: [PATCH 14/72] sample: inclusive language: whitelist -> allow

Change whitelist->allow to be compatible with sanitycheck in zephyr.

Signed-off-by: Anas Nashif <anas.nashif@intel.com>
---
 boot/zephyr/sample.yaml | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/boot/zephyr/sample.yaml b/boot/zephyr/sample.yaml
index faef68e59..6c41d2820 100644
--- a/boot/zephyr/sample.yaml
+++ b/boot/zephyr/sample.yaml
@@ -5,16 +5,16 @@ sample:
 tests:
   sample.bootloader.mcuboot:
     tags: bootloader_mcuboot
-    platform_whitelist: nrf52840dk_nrf52840 frdm_k64f
+    platform_allow: nrf52840dk_nrf52840 frdm_k64f
   sample.bootloader.mcuboot.serial_recovery:
     extra_args: OVERLAY_CONFIG=serial_recovery.conf
-    platform_whitelist:  nrf52840dk_nrf52840
+    platform_allow:  nrf52840dk_nrf52840
     tags: bootloader_mcuboot
   sample.bootloader.mcuboot.usb_cdc_acm_recovery:
     tags: bootloader_mcuboot
-    platform_whitelist:  nrf52840dongle_nrf52840
+    platform_allow:  nrf52840dongle_nrf52840
   sample.bootloader.mcuboot.usb_cdc_acm_recovery_log:
     extra_args: OVERLAY_CONFIG=./usb_cdc_acm_log_recovery.conf
       DTC_OVERLAY_FILE=./boards/nrf52840_big.overlay
-    platform_whitelist:  nrf52840dk_nrf52840
+    platform_allow:  nrf52840dk_nrf52840
     tags: bootloader_mcuboot

From f78d1d0fc7105111f04e9e0c83e0b9e9f04d07fe Mon Sep 17 00:00:00 2001
From: Fabio Utzig <fabio.utzig@nordicsemi.no>
Date: Mon, 17 Aug 2020 12:05:52 -0300
Subject: [PATCH 15/72] imgtool: fix package's author email

Fix author email after move to new mailing list.

Signed-off-by: Fabio Utzig <fabio.utzig@nordicsemi.no>
---
 scripts/setup.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/scripts/setup.py b/scripts/setup.py
index 058d0cb4e..bf35d9ffe 100644
--- a/scripts/setup.py
+++ b/scripts/setup.py
@@ -5,7 +5,7 @@
     name="imgtool",
     version=imgtool_version,
     author="The MCUboot committers",
-    author_email="dev-mcuboot@lists.runtime.co",
+    author_email="mcuboot@groups.io",
     description=("MCUboot's image signing and key management"),
     license="Apache Software License",
     url="http://github.com/JuulLabs-OSS/mcuboot",

From 480421999ec2d8d2a20091e4f3a0393db04de5c4 Mon Sep 17 00:00:00 2001
From: Fabio Utzig <fabio.utzig@nordicsemi.no>
Date: Wed, 2 Sep 2020 11:39:43 -0300
Subject: [PATCH 16/72] zephyr: struct device const-ification

Follows up the change added to Zephyr with:

https://github.com/zephyrproject-rtos/zephyr/pull/24873

Signed-off-by: Fabio Utzig <fabio.utzig@nordicsemi.no>
---
 boot/zephyr/flash_map_extended.c                          | 4 ++--
 boot/zephyr/include/flash_map_backend/flash_map_backend.h | 2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/boot/zephyr/flash_map_extended.c b/boot/zephyr/flash_map_extended.c
index c77f96cf1..ffa45006a 100644
--- a/boot/zephyr/flash_map_extended.c
+++ b/boot/zephyr/flash_map_extended.c
@@ -27,9 +27,9 @@ MCUBOOT_LOG_MODULE_DECLARE(mcuboot);
 #error "FLASH_DEVICE_ID could not be determined"
 #endif
 
-static struct device *flash_dev;
+static const struct device *flash_dev;
 
-struct device *flash_device_get_binding(char *dev_name)
+const struct device *flash_device_get_binding(char *dev_name)
 {
     if (!flash_dev) {
         flash_dev = device_get_binding(dev_name);
diff --git a/boot/zephyr/include/flash_map_backend/flash_map_backend.h b/boot/zephyr/include/flash_map_backend/flash_map_backend.h
index 20dd37914..8b5fd0ca6 100644
--- a/boot/zephyr/include/flash_map_backend/flash_map_backend.h
+++ b/boot/zephyr/include/flash_map_backend/flash_map_backend.h
@@ -38,7 +38,7 @@ extern "C" {
  *
  * Returns the flash device on success, or NULL on failure.
  */
-struct device *flash_device_get_binding(char *dev_name);
+const struct device *flash_device_get_binding(char *dev_name);
 
 /*
  * Retrieve a memory-mapped flash device's base address.

From a5d79cf8ccb2c71e68ef32a71d6a2716e831d12e Mon Sep 17 00:00:00 2001
From: Marek Pieta <Marek.Pieta@nordicsemi.no>
Date: Wed, 12 Aug 2020 04:29:12 -0700
Subject: [PATCH 17/72] boot: zephyr: Fix build issue for multiple conf files

Change fixes build issue that occurs if CONF_FILE contains multiple
file paths instead of single file path.

Signed-off-by: Marek Pieta <Marek.Pieta@nordicsemi.no>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/CMakeLists.txt | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/boot/zephyr/CMakeLists.txt b/boot/zephyr/CMakeLists.txt
index abe931e5e..b660bc74c 100644
--- a/boot/zephyr/CMakeLists.txt
+++ b/boot/zephyr/CMakeLists.txt
@@ -231,17 +231,30 @@ if(CONFIG_MCUBOOT_SERIAL)
     )
 endif()
 
-# CONF_FILE points to the KConfig configuration file of the bootloader
-get_filename_component(CONF_DIR ${CONF_FILE} DIRECTORY)
+# CONF_FILE points to the KConfig configuration files of the bootloader.
+foreach (filepath ${CONF_FILE})
+  file(READ ${filepath} temp_text)
+  string(FIND "${temp_text}" ${CONFIG_BOOT_SIGNATURE_KEY_FILE} match)
+  if (${match} GREATER_EQUAL 0)
+    if (NOT DEFINED CONF_DIR)
+      get_filename_component(CONF_DIR ${filepath} DIRECTORY)
+    else()
+      message(FATAL_ERROR "Signature key file defined in multiple conf files")
+    endif()
+  endif()
+endforeach()
 
 if(NOT CONFIG_BOOT_SIGNATURE_KEY_FILE STREQUAL "")
   if(IS_ABSOLUTE ${CONFIG_BOOT_SIGNATURE_KEY_FILE})
     set(KEY_FILE ${CONFIG_BOOT_SIGNATURE_KEY_FILE})
-  elseif(EXISTS ${CONF_DIR}/${CONFIG_BOOT_SIGNATURE_KEY_FILE})
+  elseif((DEFINED CONF_DIR) AND
+	 (EXISTS ${CONF_DIR}/${CONFIG_BOOT_SIGNATURE_KEY_FILE}))
     set(KEY_FILE ${CONF_DIR}/${CONFIG_BOOT_SIGNATURE_KEY_FILE})
   else()
     set(KEY_FILE ${MCUBOOT_DIR}/${CONFIG_BOOT_SIGNATURE_KEY_FILE})
   endif()
+  message("MCUBoot bootloader key file: ${KEY_FILE}")
+
   set(GENERATED_PUBKEY ${ZEPHYR_BINARY_DIR}/autogen-pubkey.c)
   add_custom_command(
     OUTPUT ${GENERATED_PUBKEY}

From e8bfc030a541ac0385d2708927a64fb5a9db4648 Mon Sep 17 00:00:00 2001
From: Dominik Ermel <dominik.ermel@nordicsemi.no>
Date: Fri, 11 Sep 2020 11:31:38 +0000
Subject: [PATCH 18/72] zephyr: Fix serial recovery compilation warnings

Missing const on pointers to device structures caused compilation
warnings when compiling bootloader with serial recovery enabled.

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
---
 boot/zephyr/main.c           | 2 +-
 boot/zephyr/serial_adapter.c | 4 ++--
 2 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index 4050f4c49..48ce6eb75 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -317,7 +317,7 @@ void main(void)
 
 #ifdef CONFIG_MCUBOOT_SERIAL
 
-    struct device *detect_port;
+    struct device const *detect_port;
     uint32_t detect_value = !CONFIG_BOOT_SERIAL_DETECT_PIN_VAL;
 
     detect_port = device_get_binding(CONFIG_BOOT_SERIAL_DETECT_PORT);
diff --git a/boot/zephyr/serial_adapter.c b/boot/zephyr/serial_adapter.c
index 8787780e3..829752289 100644
--- a/boot/zephyr/serial_adapter.c
+++ b/boot/zephyr/serial_adapter.c
@@ -41,7 +41,7 @@ struct line_input {
 	char line[CONFIG_BOOT_MAX_LINE_INPUT_LEN];
 };
 
-static struct device *uart_dev;
+static struct device const *uart_dev;
 static struct line_input line_bufs[2];
 
 static sys_slist_t avail_queue;
@@ -115,7 +115,7 @@ boot_console_init(void)
 }
 
 static void
-boot_uart_fifo_callback(struct device *dev, void *user_data)
+boot_uart_fifo_callback(const struct device *dev, void *user_data)
 {
 	static struct line_input *cmd;
 	uint8_t byte;

From 62b78ff2a2148490f91ee9a4b4d7a7ab8bbc4fd4 Mon Sep 17 00:00:00 2001
From: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
Date: Tue, 27 Jul 2021 23:17:05 +0200
Subject: [PATCH 19/72] boot: zephyr: add integration platforms to the allow
 list

The platforms that are listed as integration platforms in
the Zephyr boot sample need to be included in the platform
allow list, otherwise zephyr CI will throw an error. This
commit removes the common list of integration platforms and
adds integration platform entries in each test variant, in
accordance with the allow-list in each of the variants.

Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
---
 boot/zephyr/sample.yaml | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)

diff --git a/boot/zephyr/sample.yaml b/boot/zephyr/sample.yaml
index d9fb54a1b..35b4f1ef8 100644
--- a/boot/zephyr/sample.yaml
+++ b/boot/zephyr/sample.yaml
@@ -1,34 +1,42 @@
 sample:
   description: mcuboot test build sample
   name: mcuboot
-common:
-  integration_platforms:
-    - nrf52840dk_nrf52840
-    - nrf52840dongle_nrf52840
 
 tests:
   sample.bootloader.mcuboot:
     tags: bootloader_mcuboot
     platform_allow: nrf52840dk_nrf52840 frdm_k64f
+    integration_platforms:
+      - nrf52840dk_nrf52840
   sample.bootloader.mcuboot.serial_recovery:
     extra_args: OVERLAY_CONFIG=serial_recovery.conf
     platform_allow:  nrf52840dk_nrf52840
+    integration_platforms:
+      - nrf52840dk_nrf52840
     tags: bootloader_mcuboot
   sample.bootloader.mcuboot.usb_cdc_acm_recovery:
     tags: bootloader_mcuboot
     platform_allow:  nrf52840dongle_nrf52840
+    integration_platforms:
+      - nrf52840dongle_nrf52840
   sample.bootloader.mcuboot.usb_cdc_acm_recovery_log:
     extra_args: OVERLAY_CONFIG=./usb_cdc_acm_log_recovery.conf
       DTC_OVERLAY_FILE=./boards/nrf52840_big.overlay
     platform_allow:  nrf52840dk_nrf52840
+    integration_platforms:
+      - nrf52840dk_nrf52840
     tags: bootloader_mcuboot
   sample.bootloader.mcuboot.single_slot:
     extra_args: OVERLAY_CONFIG=./single_slot.conf
       DTC_OVERLAY_FILE=./boards/nrf52840_single_slot.overlay
     platform_allow:  nrf52840dk_nrf52840
+    integration_platforms:
+      - nrf52840dk_nrf52840
     tags: bootloader_mcuboot
   sample.bootloader.mcuboot.qspi_nor_slot:
     extra_args: DTC_OVERLAY_FILE=./boards/nrf52840dk_qspi_nor_secondary.overlay
       OVERLAY_CONFIG="./boards/nrf52840dk_qspi_nor.conf;./boards/nrf52840dk_qspi_secondary_boot.conf"
     platform_allow: nrf52840dk_nrf52840
+    integration_platforms:
+      - nrf52840dk_nrf52840
     tags: bootloader_mcuboot

From 35576c623f3b64b2c496889f1959f6beb64e64bc Mon Sep 17 00:00:00 2001
From: Johann Fischer <johann.fischer@nordicsemi.no>
Date: Mon, 2 Aug 2021 13:20:09 +0200
Subject: [PATCH 20/72] zephyr: remove Kconfig option CONFIG_USB

USB device support configuration is revised,
CONFIG_USB option is deprecated.
Only USB_DEVICE_STACK option should be used to
enable USB device support.

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
---
 boot/zephyr/Kconfig                             | 5 ++---
 boot/zephyr/boards/nrf52840dongle_nrf52840.conf | 1 -
 2 files changed, 2 insertions(+), 4 deletions(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index dde97dd8e..bacb127df 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -364,7 +364,7 @@ config BOOT_USB_DFU_NO
 
 config BOOT_USB_DFU_WAIT
 	bool "Wait for a prescribed duration to see if USB DFU is invoked"
-	select USB
+	select USB_DEVICE_STACK
 	select USB_DFU_CLASS
 	select IMG_MANAGER
 	help
@@ -374,7 +374,7 @@ config BOOT_USB_DFU_WAIT
 
 config BOOT_USB_DFU_GPIO
 	bool "Use GPIO to detect whether to trigger DFU mode"
-	select USB
+	select USB_DEVICE_STACK
 	select USB_DFU_CLASS
 	select IMG_MANAGER
 	help
@@ -487,7 +487,6 @@ config BOOT_SERIAL_UART
 
 config BOOT_SERIAL_CDC_ACM
 	bool "CDC ACM"
-	select USB
 	select USB_DEVICE_STACK
 	select USB_CDC_ACM
 
diff --git a/boot/zephyr/boards/nrf52840dongle_nrf52840.conf b/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
index ba333d9c1..25dd6529b 100644
--- a/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
+++ b/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
@@ -24,7 +24,6 @@ CONFIG_BOOT_SERIAL_DETECT_PIN=6
 CONFIG_MULTITHREADING=y
 
 # USB
-CONFIG_USB=y
 CONFIG_USB_DEVICE_STACK=y
 CONFIG_USB_DEVICE_PRODUCT="MCUBOOT"
 CONFIG_USB_CDC_ACM=y

From 3c5eb02451081db4b5876760600f638985ce46b0 Mon Sep 17 00:00:00 2001
From: Johann Fischer <johann.fischer@nordicsemi.no>
Date: Fri, 30 Jul 2021 16:01:03 +0200
Subject: [PATCH 21/72] zephyr: get CDC ACM UART device from devicetree

Adapt to Zephyr OS changes to get CDC ACM UART device.
Remove RECOVERY_UART_DEV_NAME Kconfig option and
use DEVICE_DT_GET() in serial_adapter.c

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
---
 boot/zephyr/Kconfig                           | 13 -----------
 .../boards/nrf52840dongle_nrf52840.conf       |  1 -
 boot/zephyr/dts.overlay                       |  7 ++++++
 boot/zephyr/serial_adapter.c                  | 23 ++++++++++---------
 4 files changed, 19 insertions(+), 25 deletions(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index bacb127df..80cfc31ac 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -488,7 +488,6 @@ config BOOT_SERIAL_UART
 config BOOT_SERIAL_CDC_ACM
 	bool "CDC ACM"
 	select USB_DEVICE_STACK
-	select USB_CDC_ACM
 
 endchoice
 
@@ -539,18 +538,6 @@ config BOOT_SERIAL_DETECT_DELAY
 	  Useful for powering on when using the same button as
 	  the one used to place the device in bootloader mode.
 
-# Workaround for not being able to have commas in macro arguments
-DT_CHOSEN_Z_CONSOLE := zephyr,console
-
-config RECOVERY_UART_DEV_NAME
-	string "UART Device Name for Recovery UART"
-	default "$(dt_chosen_label,$(DT_CHOSEN_Z_CONSOLE))" if HAS_DTS
-	default "UART_0"
-	depends on BOOT_SERIAL_UART
-	help
-	  This option specifies the name of UART device to be used for
-	  serial recovery.
-
 endif # MCUBOOT_SERIAL
 
 config BOOT_INTR_VEC_RELOC
diff --git a/boot/zephyr/boards/nrf52840dongle_nrf52840.conf b/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
index 25dd6529b..f4fbb39de 100644
--- a/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
+++ b/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
@@ -26,6 +26,5 @@ CONFIG_MULTITHREADING=y
 # USB
 CONFIG_USB_DEVICE_STACK=y
 CONFIG_USB_DEVICE_PRODUCT="MCUBOOT"
-CONFIG_USB_CDC_ACM=y
 CONFIG_USB_COMPOSITE_DEVICE=n
 CONFIG_USB_MASS_STORAGE=n
diff --git a/boot/zephyr/dts.overlay b/boot/zephyr/dts.overlay
index 74d3dfbfd..706d95421 100644
--- a/boot/zephyr/dts.overlay
+++ b/boot/zephyr/dts.overlay
@@ -3,3 +3,10 @@
 		zephyr,code-partition = &boot_partition;
 	};
 };
+
+&zephyr_udc0 {
+	cdc_acm_uart0 {
+		compatible = "zephyr,cdc-acm-uart";
+		label = "CDC_ACM_0";
+	};
+};
diff --git a/boot/zephyr/serial_adapter.c b/boot/zephyr/serial_adapter.c
index 7923914fa..effde31b3 100644
--- a/boot/zephyr/serial_adapter.c
+++ b/boot/zephyr/serial_adapter.c
@@ -192,27 +192,28 @@ static int
 boot_uart_fifo_init(void)
 {
 #ifdef CONFIG_BOOT_SERIAL_UART
-	uart_dev = device_get_binding(CONFIG_RECOVERY_UART_DEV_NAME);
+	uart_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));
 #elif CONFIG_BOOT_SERIAL_CDC_ACM
-	uart_dev = device_get_binding(CONFIG_USB_CDC_ACM_DEVICE_NAME "_0");
-	if (uart_dev) {
-		int rc;
-		rc = usb_enable(NULL);
-		if (rc) {
-			return (-1);
-		}
-	}
+	uart_dev = DEVICE_DT_GET_ONE(zephyr_cdc_acm_uart);
 #endif
-	uint8_t c;
 
-	if (!uart_dev) {
+	if (!device_is_ready(uart_dev)) {
 		return (-1);
 	}
 
+#if CONFIG_BOOT_SERIAL_CDC_ACM
+	int rc = usb_enable(NULL);
+	if (rc) {
+		return (-1);
+	}
+#endif
+
 	uart_irq_callback_set(uart_dev, boot_uart_fifo_callback);
 
 	/* Drain the fifo */
 	if (uart_irq_rx_ready(uart_dev)) {
+		uint8_t c;
+
 		while (uart_fifo_read(uart_dev, &c, 1)) {
 			;
 		}

From ca01db4216c63678768ea78fe04f27cd80b83246 Mon Sep 17 00:00:00 2001
From: Johann Fischer <johann.fischer@nordicsemi.no>
Date: Fri, 20 Aug 2021 18:15:25 +0200
Subject: [PATCH 22/72] zephyr: CDC ACM UART node to specific overlays

Move CDC ACM UART node from common DTC overlay to
specific overlays, nrf52840_big.overlays and
usb_cdc_acm.overlays.

Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
---
 boot/zephyr/boards/nrf52840_big.overlay | 7 +++++++
 boot/zephyr/dts.overlay                 | 7 -------
 boot/zephyr/sample.yaml                 | 1 +
 boot/zephyr/usb_cdc_acm.overlay         | 6 ++++++
 4 files changed, 14 insertions(+), 7 deletions(-)
 create mode 100644 boot/zephyr/usb_cdc_acm.overlay

diff --git a/boot/zephyr/boards/nrf52840_big.overlay b/boot/zephyr/boards/nrf52840_big.overlay
index 094a7a45a..778a1edce 100644
--- a/boot/zephyr/boards/nrf52840_big.overlay
+++ b/boot/zephyr/boards/nrf52840_big.overlay
@@ -28,3 +28,10 @@
 			};
 	};
 };
+
+&zephyr_udc0 {
+	cdc_acm_uart0 {
+		compatible = "zephyr,cdc-acm-uart";
+		label = "CDC_ACM_0";
+	};
+};
diff --git a/boot/zephyr/dts.overlay b/boot/zephyr/dts.overlay
index 706d95421..74d3dfbfd 100644
--- a/boot/zephyr/dts.overlay
+++ b/boot/zephyr/dts.overlay
@@ -3,10 +3,3 @@
 		zephyr,code-partition = &boot_partition;
 	};
 };
-
-&zephyr_udc0 {
-	cdc_acm_uart0 {
-		compatible = "zephyr,cdc-acm-uart";
-		label = "CDC_ACM_0";
-	};
-};
diff --git a/boot/zephyr/sample.yaml b/boot/zephyr/sample.yaml
index 35b4f1ef8..326e82c06 100644
--- a/boot/zephyr/sample.yaml
+++ b/boot/zephyr/sample.yaml
@@ -17,6 +17,7 @@ tests:
   sample.bootloader.mcuboot.usb_cdc_acm_recovery:
     tags: bootloader_mcuboot
     platform_allow:  nrf52840dongle_nrf52840
+    extra_args: DTC_OVERLAY_FILE=./usb_cdc_acm.overlay
     integration_platforms:
       - nrf52840dongle_nrf52840
   sample.bootloader.mcuboot.usb_cdc_acm_recovery_log:
diff --git a/boot/zephyr/usb_cdc_acm.overlay b/boot/zephyr/usb_cdc_acm.overlay
new file mode 100644
index 000000000..09eb8cffe
--- /dev/null
+++ b/boot/zephyr/usb_cdc_acm.overlay
@@ -0,0 +1,6 @@
+&zephyr_udc0 {
+	cdc_acm_uart0 {
+		compatible = "zephyr,cdc-acm-uart";
+		label = "CDC_ACM_0";
+	};
+};

From a1d5aea6e318665453f38440c214ae3af300f34a Mon Sep 17 00:00:00 2001
From: Marek Pieta <Marek.Pieta@nordicsemi.no>
Date: Thu, 15 Jul 2021 14:53:10 +0200
Subject: [PATCH 23/72] boot: bootutil: Fix memory alignment of RAM buffer

Change fixes memory alignment of the RAM buffer that is used to
temporarily store data during swap. Some FLASH drivers require
word-aligned input data buffer. Using unaligned buffer results
in FLASH write error.

Signed-off-by: Marek Pieta <Marek.Pieta@nordicsemi.no>
(cherry picked from commit e51ec0707b668d42c6581ba4687d4f9659f7556a)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/bootutil/src/loader.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
index b0d33295d..398ab2cf4 100644
--- a/boot/bootutil/src/loader.c
+++ b/boot/bootutil/src/loader.c
@@ -907,7 +907,7 @@ boot_copy_region(struct boot_loader_state *state,
     uint8_t image_index;
 #endif
 
-    TARGET_STATIC uint8_t buf[1024];
+    TARGET_STATIC uint8_t buf[1024] __attribute__((aligned(4)));
 
 #if !defined(MCUBOOT_ENC_IMAGES)
     (void)state;

From 26bbc18743cb442d311e98fa0afa79d16f7c8b34 Mon Sep 17 00:00:00 2001
From: Salome Thirot <salome.thirot@arm.com>
Date: Fri, 23 Jul 2021 11:24:36 +0100
Subject: [PATCH 24/72] boot: Fix IS_ENCRYPTED macro definition

The previous definition did not work as setting any type of flag would
make IS_ENCRYPTED true.

Signed-off-by: Salome Thirot <salome.thirot@arm.com>
(cherry picked from commit 2386267279d2f693b64e9f71ff90da439a65b0fb)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/bootutil/include/bootutil/image.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot/bootutil/include/bootutil/image.h b/boot/bootutil/include/bootutil/image.h
index fc94915dc..35146e296 100644
--- a/boot/bootutil/include/bootutil/image.h
+++ b/boot/bootutil/include/bootutil/image.h
@@ -149,8 +149,8 @@ struct image_tlv {
     uint16_t it_len;    /* Data length (not including TLV header). */
 };
 
-#define IS_ENCRYPTED(hdr) (((hdr)->ih_flags && IMAGE_F_ENCRYPTED_AES128) \
-                        || ((hdr)->ih_flags && IMAGE_F_ENCRYPTED_AES256))
+#define IS_ENCRYPTED(hdr) (((hdr)->ih_flags & IMAGE_F_ENCRYPTED_AES128) \
+                        || ((hdr)->ih_flags & IMAGE_F_ENCRYPTED_AES256))
 #define MUST_DECRYPT(fap, idx, hdr) \
     ((fap)->fa_id == FLASH_AREA_IMAGE_SECONDARY(idx) && IS_ENCRYPTED(hdr))
 

From 23c9c4304c127c92cb046f911cc0fc86a1863166 Mon Sep 17 00:00:00 2001
From: Carl-Johan Landin <carl-johan.landin@endian.se>
Date: Wed, 30 Jun 2021 11:31:34 +0200
Subject: [PATCH 25/72] zephyr: update devicetree py package lib files include
 path in assembly

This PR updates the path to the devicetree python package lib files according to the Zephyr PR
zephyrproject-rtos#33746 which moved the devicetree lib files.

Old path: ZEPHYR_BASE/scripts/dts/
New path: ZEPHYR_BASE/scripts/dts/python-devicetree/src/devicetree/

Signed-off-by: Carl-Johan Landin <carl-johan.landin@endian.se>
(cherry picked from commit f44fd6199c356f808adc0f8f665b6436713da640)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 scripts/assemble.py | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/scripts/assemble.py b/scripts/assemble.py
index 5ef403fa6..0f39fcc24 100755
--- a/scripts/assemble.py
+++ b/scripts/assemble.py
@@ -127,14 +127,14 @@ def main():
             print('Need to either have ZEPHYR_BASE in environment or pass in -z')
             sys.exit(1)
 
-    sys.path.insert(0, os.path.join(zephyr_base, "scripts", "dts"))
-    import edtlib
+    sys.path.insert(0, os.path.join(zephyr_base, "scripts", "dts", "python-devicetree", "src"))
+    import devicetree.edtlib
 
     board = find_board_name(args.bootdir)
 
     dts_path = os.path.join(args.bootdir, "zephyr", board + ".dts.pre.tmp")
 
-    edt = edtlib.EDT(dts_path, [os.path.join(zephyr_base, "dts", "bindings")],
+    edt = devicetree.edtlib.EDT(dts_path, [os.path.join(zephyr_base, "dts", "bindings")],
             warn_reg_unit_address_mismatch=False)
 
     output = Assembly(args.output, args.bootdir, edt)

From 2282da33530545bf62f168d92000bae670b12309 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Wed, 28 Jul 2021 17:19:02 +0200
Subject: [PATCH 26/72] cbor_encoder: fix str encoding macros

Fix structure member assignment in tstrx_put() tstrx_put_term()
macro.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
(cherry picked from commit fc1ad8d080e6b6252dc5337273c6195500d7caf0)
---
 boot/boot_serial/src/cbor_encode.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot/boot_serial/src/cbor_encode.h b/boot/boot_serial/src/cbor_encode.h
index ca0a8f845..654fc55fe 100644
--- a/boot/boot_serial/src/cbor_encode.h
+++ b/boot/boot_serial/src/cbor_encode.h
@@ -55,10 +55,10 @@ bool bstrx_encode(cbor_state_t *state, const cbor_string_type_t *result);
 bool tstrx_encode(cbor_state_t *state, const cbor_string_type_t *result);
 
 #define tstrx_put(state, string) \
-	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, len = (sizeof(string) - 1)})
+	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, .len = (sizeof(string) - 1)})
 
 #define tstrx_put_term(state, string) \
-	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, len = strlen((const char *)string)})
+	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, .len = strlen((const char *)string)})
 
 /** Encode a LIST header.
  *

From 8812dc89d23c6a93fe3fe356277b155c5e804ddd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mart=C3=AD=20Bol=C3=ADvar?= <marti.bolivar@nordicsemi.no>
Date: Wed, 28 Jul 2021 12:16:06 -0700
Subject: [PATCH 27/72] zephyr: Kconfig: fix board references
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Upstream Zephyr has renamed the 'nonsecure' variants for boards that
support TF-M. The rename consistently uses '_ns' or '_NS' (with
underscore) as the postfix which distinguishes these variants from
their 'secure' versions.

This affects Kconfig symbols used by MCUboot, so fix them to keep
working with the latest zephyr main branch.

Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
(cherry picked from commit 994816d04a055b39de2d174930271023965e8138)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/Kconfig | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index 80cfc31ac..de6e2e77b 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -403,8 +403,8 @@ config BOOT_USB_DFU_DETECT_PIN
 	default 6 if BOARD_NRF9160DK_NRF9160
 	default 11 if BOARD_NRF52840DK_NRF52840
 	default 13 if BOARD_NRF52DK_NRF52832
-	default 23 if BOARD_NRF5340_DK_NRF5340_CPUAPP || BOARD_NRF5340_DK_NRF5340_CPUAPPNS
-	default 43 if BOARD_BL5340_DVK_CPUAPP || BOARD_BL5340_DVK_CPUAPPNS
+	default 23 if BOARD_NRF5340_DK_NRF5340_CPUAPP || BOARD_NRF5340_DK_NRF5340_CPUAPP_NS
+	default 43 if BOARD_BL5340_DVK_CPUAPP || BOARD_BL5340_DVK_CPUAPP_NS
 	help
 	  Pin on the DFU detect port that triggers DFU mode.
 
@@ -517,8 +517,8 @@ config BOOT_SERIAL_DETECT_PIN
 	default 6 if BOARD_NRF9160DK_NRF9160
 	default 11 if BOARD_NRF52840DK_NRF52840
 	default 13 if BOARD_NRF52DK_NRF52832 || BOARD_NRF52833DK_NRF52833
-	default 23 if BOARD_NRF5340PDK_NRF5340_CPUAPP || BOARD_NRF5340PDK_NRF5340_CPUAPPNS || \
-		BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF5340DK_NRF5340_CPUAPPNS
+	default 23 if BOARD_NRF5340PDK_NRF5340_CPUAPP || BOARD_NRF5340PDK_NRF5340_CPUAPP_NS || \
+		BOARD_NRF5340DK_NRF5340_CPUAPP || BOARD_NRF5340DK_NRF5340_CPUAPP_NS
 	help
 	  Pin on the serial detect port that triggers serial recovery mode.
 

From 9ab84e50a798633a7ed2fa4f1d5781516e10234a Mon Sep 17 00:00:00 2001
From: Piotr Mienkowski <piotr.mienkowski@gmail.com>
Date: Sun, 25 Jul 2021 01:45:41 +0200
Subject: [PATCH 28/72] zephyr: do not set defaults for LOG_IMMEDIATE Kconfig

LOG_IMMEDIATE Kconfig option has been repurposed and is now a Zephyr's
internal, non-visible symbol that should not be used by the end user.

The logging mode used by MCUBoot is defined in prj.conf

Signed-off-by: Piotr Mienkowski <piotr.mienkowski@gmail.com>
(cherry picked from commit 01c84425b6523f8455c7201a779c43f48a227e4a)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/Kconfig | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index de6e2e77b..643edd6eb 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -624,10 +624,6 @@ config MULTITHREADING
 	default n if SOC_FAMILY_NRF
 	default y
 
-config LOG_IMMEDIATE
-	default n if MULTITHREADING
-	default y
-
 config LOG_PROCESS_THREAD
 	default n # mcuboot has its own log processing thread
 

From f62460044edf4f1fe93d28fa036591769b8bb25c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=98yvind=20R=C3=B8nningstad?=
 <oyvind.ronningstad@nordicsemi.no>
Date: Mon, 2 Aug 2021 16:13:44 +0200
Subject: [PATCH 29/72] boot_serial: Update cddl-gen version
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

To bring in bugfixes.
Regenerate code.

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
(cherry picked from commit 1e63e8f1d986a8d176b53958b45da3b18990812f)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/boot_serial/src/cbor_common.c            |  2 +-
 boot/boot_serial/src/cbor_common.h            |  2 +-
 boot/boot_serial/src/cbor_decode.c            | 21 ++++++++++++++-----
 boot/boot_serial/src/cbor_decode.h            |  5 +++--
 boot/boot_serial/src/cbor_encode.c            |  5 ++++-
 boot/boot_serial/src/cbor_encode.h            |  6 +++---
 .../src/regenerate_serial_recovery_cbor.sh    |  2 +-
 boot/boot_serial/src/serial_recovery_cbor.c   | 14 ++++++-------
 boot/boot_serial/src/serial_recovery_cbor.h   |  4 ++--
 .../src/types_serial_recovery_cbor.h          |  4 ++--
 ext/cddl-gen                                  |  2 +-
 11 files changed, 41 insertions(+), 26 deletions(-)

diff --git a/boot/boot_serial/src/cbor_common.c b/boot/boot_serial/src/cbor_common.c
index 79469d5d3..8a4cd9c70 100644
--- a/boot/boot_serial/src/cbor_common.c
+++ b/boot/boot_serial/src/cbor_common.c
@@ -1,6 +1,6 @@
 /*
  * This file has been copied from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
diff --git a/boot/boot_serial/src/cbor_common.h b/boot/boot_serial/src/cbor_common.h
index ce73dd696..e6529083e 100644
--- a/boot/boot_serial/src/cbor_common.h
+++ b/boot/boot_serial/src/cbor_common.h
@@ -1,6 +1,6 @@
 /*
  * This file has been copied from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
diff --git a/boot/boot_serial/src/cbor_decode.c b/boot/boot_serial/src/cbor_decode.c
index 74c4cd7e2..970772943 100644
--- a/boot/boot_serial/src/cbor_decode.c
+++ b/boot/boot_serial/src/cbor_decode.c
@@ -1,6 +1,6 @@
 /*
  * This file has been copied from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
@@ -126,6 +126,7 @@ static bool value_extract(cbor_state_t *state,
 
 static bool int32_decode(cbor_state_t *state, int32_t *result)
 {
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 	uint32_t uint_result;
 	int32_t int_result;
@@ -155,6 +156,7 @@ static bool int32_decode(cbor_state_t *state, int32_t *result)
 
 bool intx32_decode(cbor_state_t *state, int32_t *result)
 {
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 
 	if (major_type != CBOR_MAJOR_TYPE_PINT
@@ -197,6 +199,7 @@ static bool uint32_decode(cbor_state_t *state, uint32_t *result)
 
 bool uintx32_decode(cbor_state_t *state, uint32_t *result)
 {
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 
 	if (major_type != CBOR_MAJOR_TYPE_PINT) {
@@ -233,6 +236,7 @@ bool uintx32_expect_union(cbor_state_t *state, uint32_t result)
 static bool strx_start_decode(cbor_state_t *state,
 		cbor_string_type_t *result, cbor_major_type_t exp_major_type)
 {
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 
 	if (major_type != exp_major_type) {
@@ -243,10 +247,10 @@ static bool strx_start_decode(cbor_state_t *state,
 		FAIL();
 	}
 
-	if ((state->payload + result->len) > state->payload_end) {
+	if (result->len > (state->payload_end - state->payload)) {
 		cbor_print("error: 0x%x > 0x%x\r\n",
-		(uint32_t)(state->payload + result->len),
-		(uint32_t)state->payload_end);
+		(uint32_t)result->len,
+		(uint32_t)(state->payload_end - state->payload));
 		FAIL_RESTORE();
 	}
 
@@ -264,6 +268,7 @@ bool bstrx_cbor_start_decode(cbor_state_t *state, cbor_string_type_t *result)
 		FAIL_RESTORE();
 	}
 
+	/* Overflow is checked in strx_start_decode() */
 	state->payload_end = result->value + result->len;
 	return true;
 }
@@ -290,6 +295,7 @@ bool strx_decode(cbor_state_t *state, cbor_string_type_t *result,
 		FAIL();
 	}
 
+	/* Overflow is checked in strx_start_decode() */
 	(state->payload) += result->len;
 	return true;
 }
@@ -338,8 +344,9 @@ bool tstrx_expect(cbor_state_t *state, cbor_string_type_t *result)
 static bool list_map_start_decode(cbor_state_t *state,
 		cbor_major_type_t exp_major_type)
 {
-	uint32_t new_elem_count;
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
+	uint32_t new_elem_count;
 
 	if (major_type != exp_major_type) {
 		FAIL();
@@ -400,6 +407,7 @@ bool map_end_decode(cbor_state_t *state)
 
 static bool primx_decode(cbor_state_t *state, uint32_t *result)
 {
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 
 	if (major_type != CBOR_MAJOR_TYPE_PRIM) {
@@ -468,6 +476,7 @@ bool boolx_expect(cbor_state_t *state, bool result)
 
 bool double_decode(cbor_state_t *state, double *result)
 {
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 
 	if (major_type != CBOR_MAJOR_TYPE_PRIM) {
@@ -501,6 +510,7 @@ bool any_decode(cbor_state_t *state, void *result)
 	cbor_assert(result == NULL,
 			"'any' type cannot be returned, only skipped.\n");
 
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 	uint32_t value;
 	uint32_t num_decode;
@@ -545,6 +555,7 @@ bool any_decode(cbor_state_t *state, void *result)
 
 bool tag_decode(cbor_state_t *state, uint32_t *result)
 {
+	FAIL_IF(state->payload >= state->payload_end);
 	uint8_t major_type = MAJOR_TYPE(*state->payload);
 
 	if (major_type != CBOR_MAJOR_TYPE_TAG) {
diff --git a/boot/boot_serial/src/cbor_decode.h b/boot/boot_serial/src/cbor_decode.h
index b0cfaa104..5bdc80016 100644
--- a/boot/boot_serial/src/cbor_decode.h
+++ b/boot/boot_serial/src/cbor_decode.h
@@ -1,6 +1,6 @@
 /*
  * This file has been copied from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
@@ -19,7 +19,8 @@
 /** The cbor_decode library provides functions for decoding CBOR data elements.
  *
  * This library is primarily meant to be called from code generated by
- * $CDDL_GEN_BASE/scripts/cddl_gen.py
+ * $CDDL_GEN_BASE/cddl_gen/cddl_gen.py script, or its equivalent cddl_gen
+ * command line executable.
  *
  * Some details to notice about this library:
  *  - Integers are all 32 bits (uint32_t). This means that CBOR's 64 bit values
diff --git a/boot/boot_serial/src/cbor_encode.c b/boot/boot_serial/src/cbor_encode.c
index c2e919167..4d187949c 100644
--- a/boot/boot_serial/src/cbor_encode.c
+++ b/boot/boot_serial/src/cbor_encode.c
@@ -1,6 +1,6 @@
 /*
  * This file has been copied from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
@@ -239,6 +239,9 @@ static bool strx_encode(cbor_state_t *state,
 	if (!strx_start_encode(state, input, major_type)) {
 		FAIL();
 	}
+	if (input->len > (state->payload_end - state->payload)) {
+		FAIL();
+	}
 	if (state->payload_mut != input->value) {
 		memmove(state->payload_mut, input->value, input->len);
 	}
diff --git a/boot/boot_serial/src/cbor_encode.h b/boot/boot_serial/src/cbor_encode.h
index 654fc55fe..57b450925 100644
--- a/boot/boot_serial/src/cbor_encode.h
+++ b/boot/boot_serial/src/cbor_encode.h
@@ -1,6 +1,6 @@
 /*
  * This file has been copied from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
@@ -55,10 +55,10 @@ bool bstrx_encode(cbor_state_t *state, const cbor_string_type_t *result);
 bool tstrx_encode(cbor_state_t *state, const cbor_string_type_t *result);
 
 #define tstrx_put(state, string) \
-	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, .len = (sizeof(string) - 1)})
+	tstrx_encode(state, &(cbor_string_type_t){.value = string, len = (sizeof(string) - 1)})
 
 #define tstrx_put_term(state, string) \
-	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, .len = strlen((const char *)string)})
+	tstrx_encode(state, &(cbor_string_type_t){.value = string, len = strlen(string)})
 
 /** Encode a LIST header.
  *
diff --git a/boot/boot_serial/src/regenerate_serial_recovery_cbor.sh b/boot/boot_serial/src/regenerate_serial_recovery_cbor.sh
index b371e0aaa..08d122005 100755
--- a/boot/boot_serial/src/regenerate_serial_recovery_cbor.sh
+++ b/boot/boot_serial/src/regenerate_serial_recovery_cbor.sh
@@ -30,7 +30,7 @@ copy_with_copy_notice ../../../ext/cddl-gen/include/cbor_encode.h cbor_encode.h
 copy_with_copy_notice ../../../ext/cddl-gen/include/cbor_common.h cbor_common.h
 
 echo "Generating serial_recovery_cbor.c|h"
-python3 ../../../ext/cddl-gen/scripts/cddl_gen.py -c serial_recovery.cddl code -d -t Upload --oc serial_recovery_cbor.c --oh serial_recovery_cbor.h --time-header
+python3 ../../../ext/cddl-gen/cddl_gen/cddl_gen.py -c serial_recovery.cddl code -d -t Upload --oc serial_recovery_cbor.c --oh serial_recovery_cbor.h --time-header
 
 add_copyright() {
 echo "$(printf '/*
diff --git a/boot/boot_serial/src/serial_recovery_cbor.c b/boot/boot_serial/src/serial_recovery_cbor.c
index 4277a7d32..3b4374cd0 100644
--- a/boot/boot_serial/src/serial_recovery_cbor.c
+++ b/boot/boot_serial/src/serial_recovery_cbor.c
@@ -1,6 +1,6 @@
 /*
  * This file has been generated from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
@@ -11,7 +11,7 @@
 
 /*
  * Generated with cddl_gen.py (https://github.com/NordicSemiconductor/cddl-gen)
- * at: 2021-05-10 09:40:43
+ * at: 2021-08-02 17:09:42
  * Generated with a default_max_qty of 3
  */
 
@@ -34,19 +34,19 @@ static bool decode_Member(
 	cbor_string_type_t tmp_str;
 	bool int_res;
 
-	bool tmp_result = (((union_start_code(state) && (int_res = (((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"image",
+	bool tmp_result = (((union_start_code(state) && (int_res = (((((tstrx_expect(state, ((tmp_str.value = "image",
     tmp_str.len = sizeof("image") - 1, &tmp_str)))))
 	&& (intx32_decode(state, (&(*result)._Member_image)))) && (((*result)._Member_choice = _Member_image) || 1))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"data",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "data",
     tmp_str.len = sizeof("data") - 1, &tmp_str)))))
 	&& (bstrx_decode(state, (&(*result)._Member_data)))) && (((*result)._Member_choice = _Member_data) || 1)))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"len",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "len",
     tmp_str.len = sizeof("len") - 1, &tmp_str)))))
 	&& (intx32_decode(state, (&(*result)._Member_len)))) && (((*result)._Member_choice = _Member_len) || 1)))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"off",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "off",
     tmp_str.len = sizeof("off") - 1, &tmp_str)))))
 	&& (intx32_decode(state, (&(*result)._Member_off)))) && (((*result)._Member_choice = _Member_off) || 1)))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"sha",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "sha",
     tmp_str.len = sizeof("sha") - 1, &tmp_str)))))
 	&& (bstrx_decode(state, (&(*result)._Member_sha)))) && (((*result)._Member_choice = _Member_sha) || 1)))), union_end_code(state), int_res))));
 
diff --git a/boot/boot_serial/src/serial_recovery_cbor.h b/boot/boot_serial/src/serial_recovery_cbor.h
index bccc443e8..f167d9b5f 100644
--- a/boot/boot_serial/src/serial_recovery_cbor.h
+++ b/boot/boot_serial/src/serial_recovery_cbor.h
@@ -1,6 +1,6 @@
 /*
  * This file has been generated from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
@@ -11,7 +11,7 @@
 
 /*
  * Generated with cddl_gen.py (https://github.com/NordicSemiconductor/cddl-gen)
- * at: 2021-05-10 09:40:43
+ * at: 2021-08-02 17:09:42
  * Generated with a default_max_qty of 3
  */
 
diff --git a/boot/boot_serial/src/types_serial_recovery_cbor.h b/boot/boot_serial/src/types_serial_recovery_cbor.h
index 01505eba3..885601789 100644
--- a/boot/boot_serial/src/types_serial_recovery_cbor.h
+++ b/boot/boot_serial/src/types_serial_recovery_cbor.h
@@ -1,11 +1,11 @@
 /*
  * This file has been generated from the cddl-gen submodule.
- * Commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+ * Commit 9f77837f9950da1633d22abf6181a830521a6688
  */
 
 /*
  * Generated with cddl_gen.py (https://github.com/NordicSemiconductor/cddl-gen)
- * at: 2021-05-10 09:40:43
+ * at: 2021-08-02 17:09:42
  * Generated with a default_max_qty of 3
  */
 
diff --git a/ext/cddl-gen b/ext/cddl-gen
index 8f9358a0b..9f77837f9 160000
--- a/ext/cddl-gen
+++ b/ext/cddl-gen
@@ -1 +1 @@
-Subproject commit 8f9358a0b4b0e9b0cd579f0988056ef0b60760e4
+Subproject commit 9f77837f9950da1633d22abf6181a830521a6688

From ff5549156fbb35d4cd10ac199a2be45a6955cc18 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=C3=98yvind=20R=C3=B8nningstad?=
 <oyvind.ronningstad@nordicsemi.no>
Date: Mon, 2 Aug 2021 16:13:44 +0200
Subject: [PATCH 30/72] boot_serial: Reintroduce change from fc1ad8d
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Also, keep casts to make build pass.

Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
(cherry picked from commit 6693067b3ae9c53d8e159b885744058447ff6c3f)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/boot_serial/src/cbor_encode.h          |  4 ++--
 boot/boot_serial/src/serial_recovery_cbor.c | 10 +++++-----
 2 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/boot/boot_serial/src/cbor_encode.h b/boot/boot_serial/src/cbor_encode.h
index 57b450925..4c53d4599 100644
--- a/boot/boot_serial/src/cbor_encode.h
+++ b/boot/boot_serial/src/cbor_encode.h
@@ -55,10 +55,10 @@ bool bstrx_encode(cbor_state_t *state, const cbor_string_type_t *result);
 bool tstrx_encode(cbor_state_t *state, const cbor_string_type_t *result);
 
 #define tstrx_put(state, string) \
-	tstrx_encode(state, &(cbor_string_type_t){.value = string, len = (sizeof(string) - 1)})
+	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, .len = (sizeof(string) - 1)})
 
 #define tstrx_put_term(state, string) \
-	tstrx_encode(state, &(cbor_string_type_t){.value = string, len = strlen(string)})
+	tstrx_encode(state, &(cbor_string_type_t){.value = (const uint8_t *)string, .len = strlen((const char *)string)})
 
 /** Encode a LIST header.
  *
diff --git a/boot/boot_serial/src/serial_recovery_cbor.c b/boot/boot_serial/src/serial_recovery_cbor.c
index 3b4374cd0..2561b7067 100644
--- a/boot/boot_serial/src/serial_recovery_cbor.c
+++ b/boot/boot_serial/src/serial_recovery_cbor.c
@@ -34,19 +34,19 @@ static bool decode_Member(
 	cbor_string_type_t tmp_str;
 	bool int_res;
 
-	bool tmp_result = (((union_start_code(state) && (int_res = (((((tstrx_expect(state, ((tmp_str.value = "image",
+	bool tmp_result = (((union_start_code(state) && (int_res = (((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"image",
     tmp_str.len = sizeof("image") - 1, &tmp_str)))))
 	&& (intx32_decode(state, (&(*result)._Member_image)))) && (((*result)._Member_choice = _Member_image) || 1))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "data",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"data",
     tmp_str.len = sizeof("data") - 1, &tmp_str)))))
 	&& (bstrx_decode(state, (&(*result)._Member_data)))) && (((*result)._Member_choice = _Member_data) || 1)))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "len",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"len",
     tmp_str.len = sizeof("len") - 1, &tmp_str)))))
 	&& (intx32_decode(state, (&(*result)._Member_len)))) && (((*result)._Member_choice = _Member_len) || 1)))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "off",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"off",
     tmp_str.len = sizeof("off") - 1, &tmp_str)))))
 	&& (intx32_decode(state, (&(*result)._Member_off)))) && (((*result)._Member_choice = _Member_off) || 1)))
-	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = "sha",
+	|| (union_elem_code(state) && ((((tstrx_expect(state, ((tmp_str.value = (const uint8_t *)"sha",
     tmp_str.len = sizeof("sha") - 1, &tmp_str)))))
 	&& (bstrx_decode(state, (&(*result)._Member_sha)))) && (((*result)._Member_choice = _Member_sha) || 1)))), union_end_code(state), int_res))));
 

From 1e033433a5e47c3310a9b55edd93abbb0726fc99 Mon Sep 17 00:00:00 2001
From: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
Date: Fri, 6 Aug 2021 10:32:49 +0200
Subject: [PATCH 31/72] boot: zephyr: Do not use `irq_lock()` if using arm
 cleanup

`irq_lock()` sets `BASEPRI_MAX` aka. the `BASEPRI` mask to whatever
zephyr has configured it to be by the value of `_EXC_IRQ_DEFAULT_PRIO`.

However by calling arm_cleanup() we also do the call to
`__disable_irq()` setting the PRIMASK to 1. Meaning the only exceptions
we can recive is fault exceptions. Masking out more exceptions does not
really make sense.

Sometimes applications booted by MCUBoot will not expect the `BASEPRI`
to be set to something else than 0(No effect). Meaning if they depend on
using some exception which now is masked out by `BASEPRI` they will
fail.

Signed-off-by: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
(cherry picked from commit e933e586ec179789d98d10821226533586577460)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/main.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index a4f87e970..1ac4342bb 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -183,7 +183,6 @@ static void do_boot(struct boot_rsp *rsp)
                                      rsp->br_image_off +
                                      rsp->br_hdr->ih_hdr_size);
 
-    irq_lock();
 #ifdef CONFIG_SYS_CLOCK_EXISTS
     sys_clock_disable();
 #endif
@@ -202,6 +201,8 @@ static void do_boot(struct boot_rsp *rsp)
 
 #if CONFIG_CPU_HAS_ARM_MPU || CONFIG_CPU_HAS_NXP_MPU
     z_arm_clear_arm_mpu_config();
+#else
+    irq_lock();
 #endif
 
 #if defined(CONFIG_BUILTIN_STACK_GUARD) && \

From 8b668c1527cb68f8a26807021b70a22e3cf2a5b4 Mon Sep 17 00:00:00 2001
From: Marek Pieta <Marek.Pieta@nordicsemi.no>
Date: Wed, 18 Aug 2021 13:52:52 +0200
Subject: [PATCH 32/72] boot_serial: cbor_encode: Fix encoding data length

Change fixes encoding data length and adds support for big endian
byte ordering. According to specification, data length can be
encoded either on 1, 2, 4 or 8 bytes.

Signed-off-by: Marek Pieta <Marek.Pieta@nordicsemi.no>
(cherry picked from commit 4960d12cc1b5c3440848fb20bbc3f8863ba13e2a)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/boot_serial/src/cbor_encode.c | 27 +++++++++++++++++++++++++--
 1 file changed, 25 insertions(+), 2 deletions(-)

diff --git a/boot/boot_serial/src/cbor_encode.c b/boot/boot_serial/src/cbor_encode.c
index 4d187949c..d12dc9456 100644
--- a/boot/boot_serial/src/cbor_encode.c
+++ b/boot/boot_serial/src/cbor_encode.c
@@ -86,12 +86,35 @@ static bool value_encode_len(cbor_state_t *state, cbor_major_type_t major_type,
 static uint32_t get_result_len(const void *const input, uint32_t max_result_len)
 {
 	uint8_t *u8_result  = (uint8_t *)input;
+	size_t i;
 
-	for (; max_result_len > 0; max_result_len--) {
-		if (u8_result[max_result_len - 1] != 0) {
+	for (i = 0; i < max_result_len; i++) {
+#ifdef CONFIG_BIG_ENDIAN
+		size_t idx = i;
+#else
+		size_t idx = max_result_len - 1 - i;
+#endif
+		if (u8_result[idx] != 0) {
+			break;
+		}
+	}
+	max_result_len -= i;
+
+	/* According to specification result length can be encoded on 1, 2, 4
+	 * or 8 bytes.
+	 */
+	cbor_assert(max_result_len <= 8, "Up to 8 bytes can be used to encode length.\n");
+	size_t encode_byte_cnt = 1;
+
+	for (size_t i = 0; i <= 3; i++) {
+		if (max_result_len <= encode_byte_cnt) {
+			max_result_len = encode_byte_cnt;
 			break;
 		}
+
+		encode_byte_cnt *= 2;
 	}
+
 	if ((max_result_len == 1) && (u8_result[0] <= VALUE_IN_HEADER)) {
 		max_result_len = 0;
 	}

From d465ab5f482f3a0a46dd6db26cd7effb4bfb982f Mon Sep 17 00:00:00 2001
From: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
Date: Fri, 20 Aug 2021 16:33:55 +0200
Subject: [PATCH 33/72] boot: zephyr: Fix misaligned #else for `irq_lock`

So in PR #1089 I misaligned the `#else` used for the `irq_lock` as it
should be aligned with `CONFIG_MCUBOOT_CLEANUP_ARM_CORE`. So that
`irq_lock`is called when we don't call `__disable_irq` from arm core
clean up code.

Signed-off-by: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
(cherry picked from commit 9647c46544877b47d9fdfe10eaafed962538c890)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/main.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index 1ac4342bb..49c582f11 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -201,8 +201,6 @@ static void do_boot(struct boot_rsp *rsp)
 
 #if CONFIG_CPU_HAS_ARM_MPU || CONFIG_CPU_HAS_NXP_MPU
     z_arm_clear_arm_mpu_config();
-#else
-    irq_lock();
 #endif
 
 #if defined(CONFIG_BUILTIN_STACK_GUARD) && \
@@ -214,6 +212,8 @@ static void do_boot(struct boot_rsp *rsp)
     __set_MSPLIM(0);
 #endif
 
+#else
+    irq_lock();
 #endif /* CONFIG_MCUBOOT_CLEANUP_ARM_CORE */
 
 #ifdef CONFIG_BOOT_INTR_VEC_RELOC

From b549f678aa2392bad7c558619f9a9809af8f65b5 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Fri, 23 Jul 2021 15:22:27 +0200
Subject: [PATCH 34/72] zephyr/Kconfig: fix deadlock on cryptolib selectors

If user generate project and the will try to switch signature type
then it is very likely that MBETLS will be enabled simultaneously when
tinycrypt has to be force-selected, which causes kconfig warning on
impossible configuration. Such configuration won't be possible to be
fixed using menuconfig etc.

This patch moves dependency check on !MBEDTLS from kconfig to preprocessor
which makes manual fixing using menuconfig possible.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
(cherry picked from commit 5cf941013f1745bfa45a3cdbd591c3de3c3e7342)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/Kconfig                                 | 2 --
 boot/zephyr/include/mcuboot_config/mcuboot_config.h | 8 ++++++++
 2 files changed, 8 insertions(+), 2 deletions(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index 643edd6eb..fb0631c3d 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -30,7 +30,6 @@ config BOOT_USE_TINYCRYPT
 	# When building for ECDSA, we use our own copy of mbedTLS, so the
 	# Zephyr one must not be enabled or the MBEDTLS_CONFIG_FILE macros
 	# will collide.
-	depends on ! MBEDTLS
 	help
 	  Use TinyCrypt for crypto primitives.
 
@@ -41,7 +40,6 @@ config BOOT_USE_CC310
 	# When building for ECDSA, we use our own copy of mbedTLS, so the
 	# Zephyr one must not be enabled or the MBEDTLS_CONFIG_FILE macros
 	# will collide.
-	depends on ! MBEDTLS
 	help
 	  Use cc310 for crypto primitives.
 
diff --git a/boot/zephyr/include/mcuboot_config/mcuboot_config.h b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
index 13a28e68c..843667bfb 100644
--- a/boot/zephyr/include/mcuboot_config/mcuboot_config.h
+++ b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
@@ -34,6 +34,14 @@
 #define MCUBOOT_SIGN_ED25519
 #endif
 
+#if defined(CONFIG_BOOT_USE_TINYCRYPT)
+#  if defined(CONFIG_MBEDTLS) || defined(CONFIG_BOOT_USE_CC310)
+#     error "One crypto library implementation allowed at a time."
+#  endif
+#elif defined(CONFIG_MBEDTLS) && defined(CONFIG_BOOT_USE_CC310)
+#     error "One crypto library implementation allowed at a time."
+#endif
+
 #ifdef CONFIG_BOOT_USE_MBEDTLS
 #define MCUBOOT_USE_MBED_TLS
 #elif defined(CONFIG_BOOT_USE_TINYCRYPT)

From 9233aeff6bc0d631916af3d116ca508153962c30 Mon Sep 17 00:00:00 2001
From: David Brown <david.brown@linaro.org>
Date: Fri, 27 Aug 2021 13:15:16 -0600
Subject: [PATCH 35/72] Preps for 1.8.0-rc2

Update version fields for 1.8.0-rc2 release.

Signed-off-by: David Brown <david.brown@linaro.org>
---
 README.md                   | 2 +-
 docs/release-notes.md       | 4 ++++
 repository.yml              | 2 +-
 scripts/imgtool/__init__.py | 2 +-
 4 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/README.md b/README.md
index 60d6594ff..44df72943 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@
 [travis]: https://travis-ci.org/mcu-tools/mcuboot
 [license]: https://github.com/mcu-tools/mcuboot/blob/main/LICENSE
 
-This is mcuboot version 1.8.0-rc1
+This is mcuboot version 1.8.0-rc2
 
 MCUboot is a secure bootloader for 32-bit MCUs. The goal of MCUboot is to
 define a common infrastructure for the bootloader, system flash layout on
diff --git a/docs/release-notes.md b/docs/release-notes.md
index 60171f023..0b3e01cef 100644
--- a/docs/release-notes.md
+++ b/docs/release-notes.md
@@ -26,6 +26,10 @@ for the NuttX RTOS, and the Espressif ESP32 SDK.
 - Allow to boot primary image if secondary one is unreachable.
 - Add AES256 image encryption support.
 - Add Multiimage boot for direct-xip and ram-load mode.
+- Cargo files moved to top level, now `cargo test` can be run from the
+  top level directory.
+- Fault injection tests use updated TF-M.
+- Thingy:53 now supports multi-image DFU.
 
 ### Security fixes
 
diff --git a/repository.yml b/repository.yml
index 2e365ad33..daf3d8715 100644
--- a/repository.yml
+++ b/repository.yml
@@ -33,7 +33,7 @@ repo.versions:
     "1.7.0": "v1.7.0"
     "1.7.1": "v1.7.1"
     "1.7.2": "v1.7.2"
-    "1.8.0": "v1.8.0-rc1"
+    "1.8.0": "v1.8.0-rc2"
 
     "0-dev": "0.0.0"        # main
     "0-latest": "1.7.2"     # latest stable release
diff --git a/scripts/imgtool/__init__.py b/scripts/imgtool/__init__.py
index 42e7cc5db..f34144a01 100644
--- a/scripts/imgtool/__init__.py
+++ b/scripts/imgtool/__init__.py
@@ -14,4 +14,4 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
-imgtool_version = "1.8.0rc1"
+imgtool_version = "1.8.0rc2"

From 3f06d75e6ba6113c4ce3c6d3051304394db96754 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Mon, 10 Jan 2022 10:49:09 +0100
Subject: [PATCH 36/72] zephyr/boot_serial_extension: us BOOT_LOG instead of
 LOG_

Use MCUboot logging macros instead of zephyr-rtos native.
This fixes build failure on MCUBOOT_LOG_MODULE_DECLARE() when
LOG is disabled.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
(cherry picked from commit d16598f561c07a486b3c5c40a6c0fd904d80be80)
---
 boot/zephyr/boot_serial_extensions.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/boot/zephyr/boot_serial_extensions.c b/boot/zephyr/boot_serial_extensions.c
index 49bb4eacc..763dedbfc 100644
--- a/boot/zephyr/boot_serial_extensions.c
+++ b/boot/zephyr/boot_serial_extensions.c
@@ -19,7 +19,7 @@
 #include "bootutil/bootutil_public.h"
 #include "bootutil/boot_hooks.h"
 
-MCUBOOT_LOG_MODULE_DECLARE(mcuboot);
+BOOT_LOG_MODULE_DECLARE(mcuboot);
 
 #ifdef CONFIG_BOOT_MGMT_CUSTOM_STORAGE_ERASE
 static int bs_custom_storage_erase(cbor_state_t *cs)
@@ -31,11 +31,11 @@ static int bs_custom_storage_erase(cbor_state_t *cs)
     rc = flash_area_open(FLASH_AREA_ID(storage), &fa);
 
     if (rc < 0) {
-        LOG_ERR("failed to open flash area");
+        BOOT_LOG_ERR("failed to open flash area");
     } else {
         rc = flash_area_erase(fa, 0, FLASH_AREA_SIZE(storage));
         if (rc < 0) {
-            LOG_ERR("failed to erase flash area");
+            BOOT_LOG_ERR("failed to erase flash area");
         }
         flash_area_close(fa);
     }

From 1c32a04417b387e57b58510c41a2cc7ad5eff824 Mon Sep 17 00:00:00 2001
From: Carles Cufi <carles.cufi@nordicsemi.no>
Date: Thu, 10 Feb 2022 11:41:57 +0100
Subject: [PATCH 37/72] boot: serial: Adapt to Zephyr's new CRC APIs

As part of https://github.com/zephyrproject-rtos/zephyr/pull/42457,
Zephyr recently changed its CRC APIs. The commit below
adapted the use of mcumgr in-tree, but MCUboot was missing the change:
https://github.com/zephyrproject-rtos/zephyr/commit/07c78e515c827c8346a758a5ce04cd56a46ae124

Note that although on other platforms the function called is
crc_ccitt(), the CRC16 actually used by MCUboot/mcumgr is:
https://reveng.sourceforge.io/crc-catalogue/16.htm#crc.cat.crc-16-xmodem

Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
(cherry picked from commit b9192a4c80ec96044442bedbe122e2afd624c4a0)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/boot_serial/src/boot_serial.c | 7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)

diff --git a/boot/boot_serial/src/boot_serial.c b/boot/boot_serial/src/boot_serial.c
index 89dbc3017..bfe4ec8fe 100644
--- a/boot/boot_serial/src/boot_serial.c
+++ b/boot/boot_serial/src/boot_serial.c
@@ -555,9 +555,8 @@ boot_serial_output(void)
     bs_hdr->nh_group = htons(bs_hdr->nh_group);
 
 #ifdef __ZEPHYR__
-    crc =  crc16((uint8_t *)bs_hdr, sizeof(*bs_hdr), CRC_CITT_POLYMINAL,
-                 CRC16_INITIAL_CRC, false);
-    crc =  crc16(data, len, CRC_CITT_POLYMINAL, crc, true);
+    crc =  crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
+    crc =  crc16_itu_t(crc, data, len);
 #else
     crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
     crc = crc16_ccitt(crc, data, len);
@@ -631,7 +630,7 @@ boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
 
     out += sizeof(uint16_t);
 #ifdef __ZEPHYR__
-    crc = crc16(out, len, CRC_CITT_POLYMINAL, CRC16_INITIAL_CRC, true);
+    crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
 #else
     crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
 #endif

From 2df4d57e050861e08adb04ef691ecd16e40c5c1e Mon Sep 17 00:00:00 2001
From: Marek Pieta <Marek.Pieta@nordicsemi.no>
Date: Mon, 28 Mar 2022 11:29:12 +0200
Subject: [PATCH 38/72] boot: zephyr: Disable CONFIG_USB_DEVICE_REMOTE_WAKEUP

Change disables CONFIG_USB_DEVICE_REMOTE_WAKEUP, because it is not
supported by the MCUboot bootloader source code.

Signed-off-by: Marek Pieta <Marek.Pieta@nordicsemi.no>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/boards/nrf52840dongle_nrf52840.conf | 1 +
 boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf | 1 +
 2 files changed, 2 insertions(+)

diff --git a/boot/zephyr/boards/nrf52840dongle_nrf52840.conf b/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
index f4fbb39de..a6965bb83 100644
--- a/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
+++ b/boot/zephyr/boards/nrf52840dongle_nrf52840.conf
@@ -25,6 +25,7 @@ CONFIG_MULTITHREADING=y
 
 # USB
 CONFIG_USB_DEVICE_STACK=y
+CONFIG_USB_DEVICE_REMOTE_WAKEUP=n
 CONFIG_USB_DEVICE_PRODUCT="MCUBOOT"
 CONFIG_USB_COMPOSITE_DEVICE=n
 CONFIG_USB_MASS_STORAGE=n
diff --git a/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf b/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf
index 8e29a8bf5..7910bc66f 100644
--- a/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf
+++ b/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf
@@ -36,6 +36,7 @@ CONFIG_NORDIC_QSPI_NOR_STACK_WRITE_BUFFER_SIZE=16
 CONFIG_MULTITHREADING=y
 
 # USB
+CONFIG_USB_DEVICE_REMOTE_WAKEUP=n
 CONFIG_USB_DEVICE_MANUFACTURER="Nordic Semiconductor ASA"
 CONFIG_USB_DEVICE_PRODUCT="Bootloader Thingy:53"
 CONFIG_USB_DEVICE_VID=0x1915

From 30889ae50a3d25449a587a9e4a62b5f6d4d5e8eb Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Fri, 1 Apr 2022 16:51:27 +0200
Subject: [PATCH 39/72] zephyr/Kconfig: fix CONFIG_MCUBOOT_INDICATION_LED usage

This option was reserved for serial recovery mode, while
it should be available for USB DFU as well.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/Kconfig | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index 347823411..da008ba5f 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -482,6 +482,14 @@ config MCUBOOT_LOG_THREAD_STACK_SIZE
 	help
 	  Set the internal stack size for MCUBoot log processing thread.
 
+config MCUBOOT_INDICATION_LED
+	bool "Turns on LED indication when device is in DFU"
+	default n
+	help
+	  Device device activates the LED while in bootloader mode.
+	  bootloader-led0 alias must be set in the device's .dts
+	  definitions for this to work.
+
 menuconfig MCUBOOT_SERIAL
 	bool "MCUboot serial recovery"
 	default n
@@ -527,14 +535,6 @@ config MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD
 	  Note that 0 is default upload target when no explicit
 	  selection is done.
 
-config MCUBOOT_INDICATION_LED
-	bool "Turns on LED indication when device is in DFU"
-	default n
-	help
-	  Device device activates the LED while in bootloader mode.
-	  bootloader-led0 alias must be set in the device's .dts
-	  definitions for this to work.
-
 config BOOT_MAX_LINE_INPUT_LEN
 	int "Maximum command line length"
 	default 512

From ccd490caef91167556e67725dec6799d4d1b37a0 Mon Sep 17 00:00:00 2001
From: Jamie McCrae <jamie.mccrae@lairdconnect.com>
Date: Tue, 3 May 2022 08:28:06 +0100
Subject: [PATCH 40/72] bootutil: zephyr: Fix not including tinycrypt path when
 needed

This fixes a build issue when building mcuboot for zephyr with image
encryption support enabled using tinycrypt.

Signed-off-by: Jamie McCrae <jamie.mccrae@lairdconnect.com>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/bootutil/zephyr/CMakeLists.txt | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/boot/bootutil/zephyr/CMakeLists.txt b/boot/bootutil/zephyr/CMakeLists.txt
index ea1fc2b19..d66751b40 100644
--- a/boot/bootutil/zephyr/CMakeLists.txt
+++ b/boot/bootutil/zephyr/CMakeLists.txt
@@ -42,4 +42,10 @@ endif()
 
 zephyr_library_link_libraries(MCUBOOT_BOOTUTIL)
 target_link_libraries(MCUBOOT_BOOTUTIL INTERFACE zephyr_interface)
+
+if(CONFIG_BOOT_USE_TINYCRYPT)
+target_include_directories(MCUBOOT_BOOTUTIL INTERFACE
+  ../../../ext/tinycrypt/lib/include
+)
+endif()
 endif()

From 75958ecff21fca4790da8709b428dd1af5e786e7 Mon Sep 17 00:00:00 2001
From: Ryan McClelland <ryanmcclelland@fb.com>
Date: Fri, 20 May 2022 23:53:35 -0700
Subject: [PATCH 41/72] boot: zephyr: add Kconfig for arm cortex-m that
 implements a cache

The Cache is an optional configuration of both the ARM Cortex-M7 and
Cortex-M55. Previously, it was just checking that it was just an M7
rather than knowing that the CPU actually was built with the cache.

Signed-off-by: Ryan McClelland <ryanmcclelland@fb.com>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index 09a6f40dc..70a4a6f6c 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -196,7 +196,7 @@ static void do_boot(struct boot_rsp *rsp)
 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
     cleanup_arm_nvic(); /* cleanup NVIC registers */
 
-#ifdef CONFIG_CPU_CORTEX_M7
+#ifdef CONFIG_CPU_CORTEX_M_HAS_CACHE
     /* Disable instruction cache and data cache before chain-load the application */
     SCB_DisableDCache();
     SCB_DisableICache();

From 13296b0a4f7dadc41f6d21216d776827e1d10af5 Mon Sep 17 00:00:00 2001
From: Jamie McCrae <jamie.mccrae@lairdconnect.com>
Date: Tue, 3 May 2022 08:22:08 +0100
Subject: [PATCH 42/72] bootutil: zephyr: Fix not linking with mbedtls when
 needed

This fixes a build issue when building mcuboot for zephyr with RSA
image encryption support enabled using mbedtls.

Signed-off-by: Jamie McCrae <jamie.mccrae@lairdconnect.com>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/bootutil/zephyr/CMakeLists.txt | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/boot/bootutil/zephyr/CMakeLists.txt b/boot/bootutil/zephyr/CMakeLists.txt
index d66751b40..efdbf6013 100644
--- a/boot/bootutil/zephyr/CMakeLists.txt
+++ b/boot/bootutil/zephyr/CMakeLists.txt
@@ -48,4 +48,8 @@ target_include_directories(MCUBOOT_BOOTUTIL INTERFACE
   ../../../ext/tinycrypt/lib/include
 )
 endif()
+
+if(CONFIG_BOOT_USE_MBEDTLS)
+  zephyr_link_libraries(mbedTLS)
+endif()
 endif()

From df6249a6c87b79118bf25c7c8bdc98f248f52d5a Mon Sep 17 00:00:00 2001
From: Almir Okato <almir.okato@espressif.com>
Date: Fri, 6 May 2022 14:59:43 -0300
Subject: [PATCH 43/72] espressif:esp32: Move app entry point call back to
 iram_loader_seg region

Entry point call was moved back from main to esp_loader, so it is
called from iram_loader_seg memory region

Signed-off-by: Almir Okato <almir.okato@espressif.com>
(cherry picked from commit c4b305863a5d508c3223361d4a20c089a803879f)
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/espressif/include/esp_loader.h        |  5 +++++
 boot/espressif/main.c                      | 12 ++----------
 boot/espressif/port/esp32/ld/bootloader.ld |  1 +
 boot/espressif/port/esp_loader.c           | 21 +++++++++++++++++++++
 4 files changed, 29 insertions(+), 10 deletions(-)

diff --git a/boot/espressif/include/esp_loader.h b/boot/espressif/include/esp_loader.h
index dc5537397..480022c29 100644
--- a/boot/espressif/include/esp_loader.h
+++ b/boot/espressif/include/esp_loader.h
@@ -6,4 +6,9 @@
 
 #pragma once
 
+void start_cpu0_image(int image_index, int slot, unsigned int hdr_offset);
+#ifdef CONFIG_ESP_MULTI_PROCESSOR_BOOT
+void start_cpu1_image(int image_index, int slot, unsigned int hdr_offset);
+#endif
+
 void esp_app_image_load(int image_index, int slot, unsigned int hdr_offset, unsigned int *entry_addr);
diff --git a/boot/espressif/main.c b/boot/espressif/main.c
index 6fe93a243..028d50619 100644
--- a/boot/espressif/main.c
+++ b/boot/espressif/main.c
@@ -22,9 +22,6 @@
 #ifdef CONFIG_SECURE_FLASH_ENC_ENABLED
 #include "esp_flash_encrypt.h"
 #endif
-#ifdef CONFIG_ESP_MULTI_PROCESSOR_BOOT
-#include "app_cpu_start.h"
-#endif
 
 #include "esp_loader.h"
 #include "os/os_malloc.h"
@@ -41,13 +38,10 @@ extern esp_err_t check_and_generate_secure_boot_keys(void);
 
 void do_boot(struct boot_rsp *rsp)
 {
-    unsigned int entry_addr;
     BOOT_LOG_INF("br_image_off = 0x%x", rsp->br_image_off);
     BOOT_LOG_INF("ih_hdr_size = 0x%x", rsp->br_hdr->ih_hdr_size);
     int slot = (rsp->br_image_off == CONFIG_ESP_IMAGE0_PRIMARY_START_ADDRESS) ? PRIMARY_SLOT : SECONDARY_SLOT;
-    esp_app_image_load(IMAGE_INDEX_0, slot, rsp->br_hdr->ih_hdr_size, &entry_addr);
-    ((void (*)(void))entry_addr)(); /* Call to application entry address should not return */
-    FIH_PANIC; /* It should not get here */
+    start_cpu0_image(IMAGE_INDEX_0, slot, rsp->br_hdr->ih_hdr_size);
 }
 
 #ifdef CONFIG_ESP_MULTI_PROCESSOR_BOOT
@@ -79,15 +73,13 @@ int read_image_header(uint32_t img_index, uint32_t slot, struct image_header *im
 
 void do_boot_appcpu(uint32_t img_index, uint32_t slot)
 {
-    unsigned int entry_addr;
     struct image_header img_header;
 
     if (read_image_header(img_index, slot, &img_header) != 0) {
         FIH_PANIC;
     }
 
-    esp_app_image_load(img_index, slot, img_header.ih_hdr_size, &entry_addr);
-    appcpu_start(entry_addr);
+    start_cpu1_image(img_index, slot, img_header.ih_hdr_size);
 }
 #endif
 
diff --git a/boot/espressif/port/esp32/ld/bootloader.ld b/boot/espressif/port/esp32/ld/bootloader.ld
index 9933bd381..c2102294f 100644
--- a/boot/espressif/port/esp32/ld/bootloader.ld
+++ b/boot/espressif/port/esp32/ld/bootloader.ld
@@ -55,6 +55,7 @@ SECTIONS
     *libhal.a:esp_efuse_api.*(.literal .text .literal.* .text.*)
     *libhal.a:esp_efuse_utility.*(.literal .text .literal.* .text.*)
     *libhal.a:esp_efuse_api_key_esp32.*(.literal .text .literal.* .text.*)
+    *libhal.a:app_cpu_start.*(.literal .text .literal.* .text.*)
     *esp_mcuboot.*(.literal .text .literal.* .text.*)
     *esp_loader.*(.literal .text .literal.* .text.*)
     *(.fini.literal)
diff --git a/boot/espressif/port/esp_loader.c b/boot/espressif/port/esp_loader.c
index a0806d30e..4978df656 100644
--- a/boot/espressif/port/esp_loader.c
+++ b/boot/espressif/port/esp_loader.c
@@ -27,6 +27,10 @@
 #include "esp_loader.h"
 #include "flash_map_backend/flash_map_backend.h"
 
+#ifdef CONFIG_ESP_MULTI_PROCESSOR_BOOT
+#include "app_cpu_start.h"
+#endif
+
 static int load_segment(const struct flash_area *fap, uint32_t data_addr, uint32_t data_len, uint32_t load_addr)
 {
     const uint32_t *data = (const uint32_t *)bootloader_mmap((fap->fa_off + data_addr), data_len);
@@ -90,3 +94,20 @@ void esp_app_image_load(int image_index, int slot, unsigned int hdr_offset, unsi
     assert(entry_addr != NULL);
     *entry_addr = load_header.entry_addr;
 }
+
+void start_cpu0_image(int image_index, int slot, unsigned int hdr_offset)
+{
+    unsigned int entry_addr;
+    esp_app_image_load(image_index, slot, hdr_offset, &entry_addr);
+    ((void (*)(void))entry_addr)(); /* Call to application entry address should not return */
+    FIH_PANIC; /* It should not get here */
+}
+
+#ifdef CONFIG_ESP_MULTI_PROCESSOR_BOOT
+void start_cpu1_image(int image_index, int slot, unsigned int hdr_offset)
+{
+    unsigned int entry_addr;
+    esp_app_image_load(image_index, slot, hdr_offset, &entry_addr);
+    appcpu_start(entry_addr);
+}
+#endif

From 67cb0242af4df8a7ad2cb3738fd7c267acc5192d Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Wed, 22 Jun 2022 16:54:06 +0200
Subject: [PATCH 44/72] Revert "zephyr/Kconfig: fix
 CONFIG_MCUBOOT_INDICATION_LED usage"

This reverts commit 30889ae50a3d25449a587a9e4a62b5f6d4d5e8eb.

This prepares clean synchronization by merging mcu-tools/mcuboot

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/Kconfig | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index da008ba5f..347823411 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -482,14 +482,6 @@ config MCUBOOT_LOG_THREAD_STACK_SIZE
 	help
 	  Set the internal stack size for MCUBoot log processing thread.
 
-config MCUBOOT_INDICATION_LED
-	bool "Turns on LED indication when device is in DFU"
-	default n
-	help
-	  Device device activates the LED while in bootloader mode.
-	  bootloader-led0 alias must be set in the device's .dts
-	  definitions for this to work.
-
 menuconfig MCUBOOT_SERIAL
 	bool "MCUboot serial recovery"
 	default n
@@ -535,6 +527,14 @@ config MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD
 	  Note that 0 is default upload target when no explicit
 	  selection is done.
 
+config MCUBOOT_INDICATION_LED
+	bool "Turns on LED indication when device is in DFU"
+	default n
+	help
+	  Device device activates the LED while in bootloader mode.
+	  bootloader-led0 alias must be set in the device's .dts
+	  definitions for this to work.
+
 config BOOT_MAX_LINE_INPUT_LEN
 	int "Maximum command line length"
 	default 512

From 2fcae1c1a05fe3a0892ba3c649f93cf3e1077949 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Fri, 16 Sep 2022 14:38:02 +0200
Subject: [PATCH 45/72] zephyr/sample.yaml Limit allowed build platforms

Building sample.bootloader.mcuboot for many platforms
is not possible (for instance a qemu). The limit is need
as otherwise zephyr-rtos/zephyr CI is failing on any push to
main branch or nightly CI run.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/sample.yaml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/boot/zephyr/sample.yaml b/boot/zephyr/sample.yaml
index d8abab581..44ea89a2d 100644
--- a/boot/zephyr/sample.yaml
+++ b/boot/zephyr/sample.yaml
@@ -5,6 +5,7 @@ sample:
 tests:
   sample.bootloader.mcuboot:
     tags: bootloader_mcuboot
+    platform_allow:  nrf52840dk_nrf52840 frdm_k64f disco_l475_iot1
     integration_platforms:
       - nrf52840dk_nrf52840
       - frdm_k64f

From 13f63976bca672ee018f9d55f1e31f02f4135b64 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Wed, 28 Sep 2022 15:58:19 +0200
Subject: [PATCH 46/72] zephyr/Kconfig: fixed BOOT_WATCHDOG_FEED default value

This property should be enabled by default only when watchdog
driver is available.
This fixed build with pristine configuration on targets
with CONFIG_WATCHDOG=n.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
---
 boot/zephyr/Kconfig | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index 3604964b1..efd4f5507 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -557,7 +557,9 @@ endchoice
 
 config BOOT_WATCHDOG_FEED
 	bool "Feed the watchdog while doing swap"
-	default y
+	default y if WATCHDOG
+	default y if SOC_FAMILY_NRF
+	# for nRF nrfx based implementation is available
 	imply NRFX_WDT if SOC_FAMILY_NRF
 	imply NRFX_WDT0 if SOC_FAMILY_NRF
 	imply NRFX_WDT1 if SOC_FAMILY_NRF

From 89673f882a45f52ba1136e201cd4ae1229ba8a43 Mon Sep 17 00:00:00 2001
From: Thomas Stilwell <Thomas.Stilwell@nordicsemi.no>
Date: Fri, 23 Nov 2018 15:37:52 +0100
Subject: [PATCH 47/72] [nrf noup] ci: add downstream-only NCS customizations
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Add Jenkinsfile, .gitlint, and backport workflow files.

Signed-off-by: Thomas Stilwell <Thomas.Stilwell@nordicsemi.no>
Signed-off-by: Ulrich Myhre <ulrich.solli.myhre@nordicsemi.no>
Signed-off-by: Chris Bittner <chris.bittner@nordicsemi.no>
Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit d0bc9b51d2a36cbc6de5338b78ba183b4386fdd6)
---
 .github/workflows/backport.yml | 19 ++++++++++++
 .gitlint                       | 57 ++++++++++++++++++++++++++++++++++
 Jenkinsfile                    |  6 ++++
 3 files changed, 82 insertions(+)
 create mode 100644 .github/workflows/backport.yml
 create mode 100644 .gitlint
 create mode 100644 Jenkinsfile

diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml
new file mode 100644
index 000000000..a6f3a2d5d
--- /dev/null
+++ b/.github/workflows/backport.yml
@@ -0,0 +1,19 @@
+name: Backport
+on:
+  pull_request:
+    types:
+      - closed
+      - labeled
+
+jobs:
+  backport:
+    runs-on: ubuntu-18.04
+    name: Backport
+    steps:
+      - name: Backport Bot
+        uses: Gaurav0/backport@v1.0.24
+        with:
+          bot_username: NordicBuilder
+          bot_token: 151a9b45052f9ee8be5a59963d31ad7b92c3ecb5
+          bot_token_key: 67bb1f1f998d546859786a4088917c65415c0ebd
+          github_token: ${{ secrets.GITHUB_TOKEN }}
\ No newline at end of file
diff --git a/.gitlint b/.gitlint
new file mode 100644
index 000000000..512813bbb
--- /dev/null
+++ b/.gitlint
@@ -0,0 +1,57 @@
+# All these sections are optional, edit this file as you like.
+[general]
+ignore=title-trailing-punctuation, T3, title-max-length, T1, body-hard-tab, B3, B1
+# verbosity should be a value between 1 and 3, the commandline -v flags take precedence over this
+verbosity = 3
+# By default gitlint will ignore merge commits. Set to 'false' to disable.
+ignore-merge-commits=true
+# Enable debug mode (prints more output). Disabled by default
+debug = false
+
+# Set the extra-path where gitlint will search for user defined rules
+# See http://jorisroovers.github.io/gitlint/user_defined_rules for details
+extra-path=../../zephyr/scripts/gitlint
+
+[title-max-length-no-revert]
+line-length=72
+
+[body-min-line-count]
+min-line-count=1
+
+[body-max-line-count]
+max-line-count=200
+
+[title-starts-with-subsystem]
+regex = ^(?!subsys:)(([^:]+):)(\s([^:]+):)*\s(.+)$
+
+[title-must-not-contain-word]
+# Comma-separated list of words that should not occur in the title. Matching is case
+# insensitive. It's fine if the keyword occurs as part of a larger word (so "WIPING"
+# will not cause a violation, but "WIP: my title" will.
+words=wip
+
+[title-match-regex]
+# python like regex (https://docs.python.org/2/library/re.html) that the
+# commit-msg title must be matched to.
+# Note that the regex can contradict with other rules if not used correctly
+# (e.g. title-must-not-contain-word).
+#regex=^US[0-9]*
+
+[max-line-length-with-exceptions]
+# B1 = body-max-line-length
+line-length=72
+
+[body-min-length]
+min-length=3
+
+[body-is-missing]
+# Whether to ignore this rule on merge commits (which typically only have a title)
+# default = True
+ignore-merge-commits=false
+
+[body-changed-file-mention]
+# List of files that need to be explicitly mentioned in the body when they are changed
+# This is useful for when developers often erroneously edit certain files or git submodules.
+# By specifying this rule, developers can only change the file when they explicitly reference
+# it in the commit message.
+#files=gitlint/rules.py,README.md
diff --git a/Jenkinsfile b/Jenkinsfile
new file mode 100644
index 000000000..8220afe03
--- /dev/null
+++ b/Jenkinsfile
@@ -0,0 +1,6 @@
+@Library("CI_LIB") _
+
+def pipeline = new ncs.sdk_mcuboot.Main()
+
+pipeline.run(JOB_NAME)
+

From f7de93fe96daf9776a7331d2157d33f54e9f526f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20B=C3=B8e?= <sebastian.boe@nordicsemi.no>
Date: Wed, 12 Dec 2018 08:59:47 +0100
Subject: [PATCH 48/72] [nrf noup] treewide: add NCS partition manager support
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Partition Manager is an nRF Connect SDK component which uses yaml
files to resolve flash partition placement with a holistic view of the
device.

This component's MCUboot portions began life as upstream mcuboot
PR#430. This added support for being built as a sub image from the
downstream Nordic patch set for a zephyr multi image build
system (mcuboot 430 was combined with effor submitted to upstream
zephyr as PR#13672, which was ultimately reworked after being rejected
for mainline at the ELCE 2019 conference in Lyon).

It has since evolved over time. This is the version that will go into
NCS v1.3. It features:

- page size aligned partitions for all partitions used by mcuboot.
- image swaps without scratch partitions

Add support for configurations where there exists two primary slots
but only one secondary slot, which is shared. These two primary slots
are the regular application and B1. B1 can be either S0 or S1
depending on the state of the device.

Decide where an upgrade should be stored by looking at the vector
table.

Provide update candidates for both s0 and s1. These candidates must be
signed with mcuboot after being signed by b0.

Additional notes:

- we make update.hex without trailer data

  This is needed for serial recovery to work using hex files.
  Prior to this the update.hex got TLV data at the end of the
  partition, which caused many blank pages to be included,
  which made it hard to use in a serial recovery scheme.

  Instead, make update.hex without TLV data at the end,
  and provide a new file test_update.hex which contains
  the TLV data, and can be directly flashed to test the
  upgrade procedure.

- we use a function for signing the application as future-proofing
  for when other components must be signed as well

- this includes an update to single image applications that enables
  support for partition manager; when single image DFU is used, a
  scratch partition is not needed.

- In NCS, image 1 primary slot is the upgrade bank for mcuboot (IE S0 or
  S1 depending on the active slot). It is not required that this slot
  contains any valid data.

- The nRF boards all have a single flash page size, and partition
  manager deals with the size of the update partitions and so on, so we
  must skip a boot_slots_compatible() check to avoid getting an error.

- There is no need to verify the target when using partition manager.

- We lock mcuboot using fprotect before jumping, to enable the secure
  boot property of the system.

- Call fw_info_ext_api_provide() before booting if EXT_API_PROVIDE
  EXT_API is enabled. This is relevant only when the immutable
  bootloader has booted mcuboot.

Signed-off-by: Håkon Øye Amundsen <haakon.amundsen@nordicsemi.no>
Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
Signed-off-by: Sigvart Hovland <sigvart.m@gmail.com>
Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Andrzej Głąbek <andrzej.glabek@nordicsemi.no>
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
Signed-off-by: Emil Obalski <emil.obalski@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Pawel Dunaj <pawel.dunaj@nordicsemi.no>
Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
Signed-off-by: Vidar Berg <vidar.berg@nordicsemi.no>
Signed-off-by: Draus, Sebastian <sebastian.draus@nordicsemi.no>
Signed-off-by: Trond Einar Snekvik <Trond.Einar.Snekvik@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 1f84c4507bc6a04c53df26a776705fc6223e551a)
---
 boot/bootutil/src/loader.c              | 85 +++++++++++++++++++++++--
 boot/bootutil/src/swap_move.c           | 13 ++++
 boot/bootutil/src/swap_scratch.c        | 13 ++++
 boot/zephyr/CMakeLists.txt              |  7 ++
 boot/zephyr/Kconfig                     |  2 +
 boot/zephyr/include/sysflash/sysflash.h | 47 ++++++++++++++
 boot/zephyr/include/target.h            |  4 ++
 boot/zephyr/main.c                      | 43 +++++++++++++
 boot/zephyr/pm.yml                      | 74 +++++++++++++++++++++
 boot/zephyr/prj.conf                    |  1 +
 zephyr/module.yml                       |  3 +-
 11 files changed, 286 insertions(+), 6 deletions(-)
 create mode 100644 boot/zephyr/pm.yml

diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
index e59fad78d..b60a3a141 100644
--- a/boot/bootutil/src/loader.c
+++ b/boot/bootutil/src/loader.c
@@ -108,6 +108,15 @@ boot_read_image_headers(struct boot_loader_state *state, bool require_all,
              *
              * Failure to read any headers is a fatal error.
              */
+#ifdef PM_S1_ADDRESS
+            /* Patch needed for NCS. The primary slot of the second image
+             * (image 1) will not contain a valid image header until an upgrade
+             * of mcuboot has happened (filling S1 with the new version).
+             */
+            if (BOOT_CURR_IMG(state) == 1 && i == 0) {
+                continue;
+            }
+#endif /* PM_S1_ADDRESS */
             if (i > 0 && !require_all) {
                 return 0;
             } else {
@@ -799,7 +808,24 @@ boot_validate_slot(struct boot_loader_state *state, int slot,
             goto out;
         }
 
-        if (reset_value < pri_fa->fa_off || reset_value> (pri_fa->fa_off + pri_fa->fa_size)) {
+        uint32_t min_addr, max_addr;
+
+#ifdef PM_CPUNET_APP_ADDRESS
+        /* The primary slot for the network core is emulated in RAM.
+         * Its flash_area hasn't got relevant boundaries.
+         * Therfore need to override its boundaries for the check.
+         */
+        if (BOOT_CURR_IMG(state) == 1) {
+            min_addr = PM_CPUNET_APP_ADDRESS;
+            max_addr = PM_CPUNET_APP_ADDRESS + PM_CPUNET_APP_SIZE;
+        } else
+#endif
+        {
+            min_addr = pri_fa->fa_off;
+            max_addr = pri_fa->fa_off + pri_fa->fa_size;
+        }
+
+        if (reset_value < min_addr || reset_value> (max_addr)) {
             BOOT_LOG_ERR("Reset address of image in secondary slot is not in the primary slot");
             BOOT_LOG_ERR("Erasing image from secondary slot");
 
@@ -882,6 +908,42 @@ boot_validated_swap_type(struct boot_loader_state *state,
 {
     int swap_type;
     fih_int fih_rc = FIH_FAILURE;
+#ifdef PM_S1_ADDRESS
+    /* Patch needed for NCS. Since image 0 (the app) and image 1 (the other
+     * B1 slot S0 or S1) share the same secondary slot, we need to check
+     * whether the update candidate in the secondary slot is intended for
+     * image 0 or image 1 primary by looking at the address of the reset
+     * vector. Note that there are good reasons for not using img_num from
+     * the swap info.
+     */
+    const struct flash_area *secondary_fa =
+	    BOOT_IMG_AREA(state, BOOT_SECONDARY_SLOT);
+    struct image_header *hdr =
+	    (struct image_header *)secondary_fa->fa_off;
+
+    if (hdr->ih_magic == IMAGE_MAGIC) {
+	    const struct flash_area *primary_fa;
+	    uint32_t vtable_addr = (uint32_t)hdr + hdr->ih_hdr_size;
+	    uint32_t *vtable = (uint32_t *)(vtable_addr);
+	    uint32_t reset_addr = vtable[1];
+	    int rc = flash_area_open(
+			    flash_area_id_from_multi_image_slot(
+				    BOOT_CURR_IMG(state),
+				    BOOT_PRIMARY_SLOT),
+			    &primary_fa);
+
+	    if (rc != 0) {
+		    return BOOT_SWAP_TYPE_FAIL;
+	    }
+	    /* Get start and end of primary slot for current image */
+	    if (reset_addr < primary_fa->fa_off ||
+	        reset_addr > (primary_fa->fa_off + primary_fa->fa_size)) {
+		    /* The image in the secondary slot is not intended for this image
+		    */
+		    return BOOT_SWAP_TYPE_NONE;
+	    }
+    }
+#endif
 
     swap_type = boot_swap_type_multi(BOOT_CURR_IMG(state));
     if (BOOT_IS_UPGRADE(swap_type)) {
@@ -2159,10 +2221,23 @@ context_boot_go(struct boot_loader_state *state, struct boot_rsp *rsp)
         }
 
 #ifdef MCUBOOT_VALIDATE_PRIMARY_SLOT
-        FIH_CALL(boot_validate_slot, fih_rc, state, BOOT_PRIMARY_SLOT, NULL);
-        if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
-            goto out;
-        }
+#ifdef PM_S1_ADDRESS
+	/* Patch needed for NCS. If secure boot is enabled, then mcuboot
+	 * will be stored in either partition S0 or S1. Image 1 primary
+	 * will point to the 'other' Sx partition. Hence, image 1 primary
+	 * does not contain a valid image until mcuboot has been upgraded.
+	 * Note that B0 will perform validation of the active mcuboot image,
+	 * so there is no security lost by skipping this check for image 1
+	 * primary.
+	 */
+	if (BOOT_CURR_IMG(state) == 0)
+#endif
+	{
+            FIH_CALL(boot_validate_slot, fih_rc, state, BOOT_PRIMARY_SLOT, NULL);
+            if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
+                goto out;
+            }
+	}
 #else
         /* Even if we're not re-validating the primary slot, we could be booting
          * onto an empty flash chip. At least do a basic sanity check that
diff --git a/boot/bootutil/src/swap_move.c b/boot/bootutil/src/swap_move.c
index 6f3398270..60cb16772 100644
--- a/boot/bootutil/src/swap_move.c
+++ b/boot/bootutil/src/swap_move.c
@@ -211,6 +211,18 @@ boot_status_internal_off(const struct boot_status *bs, int elem_sz)
 int
 boot_slots_compatible(struct boot_loader_state *state)
 {
+#ifdef PM_S1_ADDRESS
+    /* Patch needed for NCS. In this case, image 1 primary points to the other
+     * B1 slot (ie S0 or S1), and image 0 primary points to the app.
+     * With this configuration, image 0 and image 1 share the secondary slot.
+     * Hence, the primary slot of image 1 will be *smaller* than image 1's
+     * secondary slot. This is not allowed in upstream mcuboot, so we need
+     * this patch to allow it. Also, all of these checks are redundant when
+     * partition manager is in use, and since we have the same sector size
+     * in all of our flash.
+     */
+        return 1;
+#else
     size_t num_sectors_pri;
     size_t num_sectors_sec;
     size_t sector_sz_pri = 0;
@@ -247,6 +259,7 @@ boot_slots_compatible(struct boot_loader_state *state)
     }
 
     return 1;
+#endif /* PM_S1_ADDRESS */
 }
 
 #define BOOT_LOG_SWAP_STATE(area, state)                            \
diff --git a/boot/bootutil/src/swap_scratch.c b/boot/bootutil/src/swap_scratch.c
index f3275c747..d31083115 100644
--- a/boot/bootutil/src/swap_scratch.c
+++ b/boot/bootutil/src/swap_scratch.c
@@ -170,6 +170,18 @@ boot_status_internal_off(const struct boot_status *bs, int elem_sz)
 int
 boot_slots_compatible(struct boot_loader_state *state)
 {
+#ifdef PM_S1_ADDRESS
+    /* Patch needed for NCS. In this case, image 1 primary points to the other
+     * B1 slot (ie S0 or S1), and image 0 primary points to the app.
+     * With this configuration, image 0 and image 1 share the secondary slot.
+     * Hence, the primary slot of image 1 will be *smaller* than image 1's
+     * secondary slot. This is not allowed in upstream mcuboot, so we need
+     * this patch to allow it. Also, all of these checks are redundant when
+     * partition manager is in use, and since we have the same sector size
+     * in all of our flash.
+     */
+        return 1;
+#else
     size_t num_sectors_primary;
     size_t num_sectors_secondary;
     size_t sz0, sz1;
@@ -255,6 +267,7 @@ boot_slots_compatible(struct boot_loader_state *state)
     }
 
     return 1;
+#endif /* PM_S1_ADDRESS */
 }
 
 #define BOOT_LOG_SWAP_STATE(area, state)                            \
diff --git a/boot/zephyr/CMakeLists.txt b/boot/zephyr/CMakeLists.txt
index 6070cd582..8561343b2 100644
--- a/boot/zephyr/CMakeLists.txt
+++ b/boot/zephyr/CMakeLists.txt
@@ -292,6 +292,13 @@ if(NOT CONFIG_BOOT_SIGNATURE_KEY_FILE STREQUAL "")
   endif()
   message("MCUBoot bootloader key file: ${KEY_FILE}")
 
+  set_property(
+	GLOBAL
+	PROPERTY
+	KEY_FILE
+	${KEY_FILE}
+	)
+
   set(GENERATED_PUBKEY ${ZEPHYR_BINARY_DIR}/autogen-pubkey.c)
   add_custom_command(
     OUTPUT ${GENERATED_PUBKEY}
diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index 74925856d..facd52996 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -8,6 +8,8 @@ mainmenu "MCUboot configuration"
 
 comment "MCUboot-specific configuration options"
 
+source "$(ZEPHYR_NRF_MODULE_DIR)/modules/mcuboot/boot/zephyr/Kconfig"
+
 # Hidden option to mark a project as MCUboot
 config MCUBOOT
 	default y
diff --git a/boot/zephyr/include/sysflash/sysflash.h b/boot/zephyr/include/sysflash/sysflash.h
index 574927873..2495a9810 100644
--- a/boot/zephyr/include/sysflash/sysflash.h
+++ b/boot/zephyr/include/sysflash/sysflash.h
@@ -3,6 +3,51 @@
 #ifndef __SYSFLASH_H__
 #define __SYSFLASH_H__
 
+#if USE_PARTITION_MANAGER
+#include <pm_config.h>
+#include <mcuboot_config/mcuboot_config.h>
+
+#ifndef CONFIG_SINGLE_APPLICATION_SLOT
+
+#if (MCUBOOT_IMAGE_NUMBER == 1)
+
+#define FLASH_AREA_IMAGE_PRIMARY(x)    PM_MCUBOOT_PRIMARY_ID
+#define FLASH_AREA_IMAGE_SECONDARY(x)  PM_MCUBOOT_SECONDARY_ID
+
+#elif (MCUBOOT_IMAGE_NUMBER == 2)
+
+extern uint32_t _image_1_primary_slot_id[];
+
+#define FLASH_AREA_IMAGE_PRIMARY(x)            \
+        ((x == 0) ?                            \
+           PM_MCUBOOT_PRIMARY_ID :             \
+         (x == 1) ?                            \
+          (uint32_t)_image_1_primary_slot_id : \
+           255 )
+
+#define FLASH_AREA_IMAGE_SECONDARY(x) \
+        ((x == 0) ?                   \
+            PM_MCUBOOT_SECONDARY_ID:  \
+        (x == 1) ?                    \
+           PM_MCUBOOT_SECONDARY_ID:   \
+           255 )
+#endif
+#define FLASH_AREA_IMAGE_SCRATCH    PM_MCUBOOT_SCRATCH_ID
+
+#else /* CONFIG_SINGLE_APPLICATION_SLOT */
+
+#define FLASH_AREA_IMAGE_PRIMARY(x)	PM_MCUBOOT_PRIMARY_ID
+#define FLASH_AREA_IMAGE_SECONDARY(x)	PM_MCUBOOT_PRIMARY_ID
+/* NOTE: Scratch parition is not used by single image DFU but some of
+ * functions in common files reference it, so the definitions has been
+ * provided to allow compilation of common units.
+ */
+#define FLASH_AREA_IMAGE_SCRATCH       0
+
+#endif /* CONFIG_SINGLE_APPLICATION_SLOT */
+
+#else
+
 #include <zephyr/devicetree.h>
 #include <mcuboot_config/mcuboot_config.h>
 
@@ -55,4 +100,6 @@
 
 #endif /* CONFIG_SINGLE_APPLICATION_SLOT */
 
+#endif /* USE_PARTITION_MANAGER */
+
 #endif /* __SYSFLASH_H__ */
diff --git a/boot/zephyr/include/target.h b/boot/zephyr/include/target.h
index d4a00c93a..be1653db4 100644
--- a/boot/zephyr/include/target.h
+++ b/boot/zephyr/include/target.h
@@ -8,6 +8,8 @@
 #ifndef H_TARGETS_TARGET_
 #define H_TARGETS_TARGET_
 
+#ifndef USE_PARTITION_MANAGER
+
 #if defined(MCUBOOT_TARGET_CONFIG)
 /*
  * Target-specific definitions are permitted in legacy cases that
@@ -44,4 +46,6 @@
 #error "Target support is incomplete; cannot build mcuboot."
 #endif
 
+#endif /* ifndef USE_PARTITION_MANAGER */
+
 #endif /* H_TARGETS_TARGET_ */
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index 148f06e14..c1473f741 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -42,6 +42,10 @@
 #include "bootutil/mcuboot_status.h"
 #include "flash_map_backend/flash_map_backend.h"
 
+#ifdef CONFIG_FW_INFO
+#include <fw_info.h>
+#endif
+
 #ifdef CONFIG_MCUBOOT_SERIAL
 #include "boot_serial/boot_serial.h"
 #include "serial_adapter/serial_adapter.h"
@@ -102,6 +106,11 @@ K_SEM_DEFINE(boot_log_sem, 1, 1);
         * !defined(ZEPHYR_LOG_MODE_MINIMAL)
 	*/
 
+#if USE_PARTITION_MANAGER && CONFIG_FPROTECT
+#include <fprotect.h>
+#include <pm_config.h>
+#endif
+
 #ifdef CONFIG_SOC_FAMILY_NRF
 #include <helpers/nrfx_reset_reason.h>
 
@@ -196,6 +205,19 @@ static void do_boot(struct boot_rsp *rsp)
     /* Disable the USB to prevent it from firing interrupts */
     usb_disable();
 #endif
+
+#if defined(CONFIG_FW_INFO) && !defined(CONFIG_EXT_API_PROVIDE_EXT_API_UNUSED)
+    bool provided = fw_info_ext_api_provide(fw_info_find((uint32_t)vt), true);
+
+#ifdef PM_S0_ADDRESS
+    /* Only fail if the immutable bootloader is present. */
+    if (!provided) {
+        BOOT_LOG_ERR("Failed to provide EXT_APIs\n");
+        return;
+    }
+#endif
+#endif
+
 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
     cleanup_arm_nvic(); /* cleanup NVIC registers */
 
@@ -616,7 +638,28 @@ void main(void)
 
     mcuboot_status_change(MCUBOOT_STATUS_BOOTABLE_IMAGE_FOUND);
 
+#if USE_PARTITION_MANAGER && CONFIG_FPROTECT
+
+#ifdef PM_S1_ADDRESS
+/* MCUBoot is stored in either S0 or S1, protect both */
+#define PROTECT_SIZE (PM_MCUBOOT_PRIMARY_ADDRESS - PM_S0_ADDRESS)
+#define PROTECT_ADDR PM_S0_ADDRESS
+#else
+/* There is only one instance of MCUBoot */
+#define PROTECT_SIZE (PM_MCUBOOT_PRIMARY_ADDRESS - PM_MCUBOOT_ADDRESS)
+#define PROTECT_ADDR PM_MCUBOOT_ADDRESS
+#endif
+
+    rc = fprotect_area(PROTECT_ADDR, PROTECT_SIZE);
+
+    if (rc != 0) {
+        BOOT_LOG_ERR("Protect mcuboot flash failed, cancel startup.");
+        while (1)
+            ;
+    }
+
     ZEPHYR_BOOT_LOG_STOP();
+
     do_boot(&rsp);
 
     mcuboot_status_change(MCUBOOT_STATUS_BOOT_FAILED);
diff --git a/boot/zephyr/pm.yml b/boot/zephyr/pm.yml
new file mode 100644
index 000000000..dd08096e6
--- /dev/null
+++ b/boot/zephyr/pm.yml
@@ -0,0 +1,74 @@
+#include <autoconf.h>
+
+mcuboot:
+  size: CONFIG_PM_PARTITION_SIZE_MCUBOOT
+  placement:
+    before: [mcuboot_primary]
+
+mcuboot_primary_app:
+  # All images to be placed in MCUboot's slot 0 should be placed in this
+  # partition
+  span: [app]
+
+mcuboot_primary:
+  span: [mcuboot_pad, mcuboot_primary_app]
+
+# Partition for secondary slot is not created if building in single application
+# slot configuration.
+#if !defined(CONFIG_SINGLE_APPLICATION_SLOT) && !defined(CONFIG_BOOT_DIRECT_XIP)
+mcuboot_secondary:
+  share_size: [mcuboot_primary]
+#if defined(CONFIG_PM_EXTERNAL_FLASH_MCUBOOT_SECONDARY)
+  region: external_flash
+  placement:
+    align: {start: 4}
+#else
+  placement:
+    align: {start: CONFIG_FPROTECT_BLOCK_SIZE}
+    align_next: CONFIG_FPROTECT_BLOCK_SIZE # Ensure that the next partition does not interfere with this image
+    after: mcuboot_primary
+#endif /* CONFIG_PM_EXTERNAL_FLASH_MCUBOOT_SECONDARY */
+
+#endif /* !defined(CONFIG_SINGLE_APPLICATION_SLOT) && !defined(CONFIG_BOOT_DIRECT_XIP) */
+
+#if CONFIG_BOOT_DIRECT_XIP
+
+# Direct XIP is enabled, reserve area for metadata (padding) and name the
+# partition so that its clear that it is not the secondary slot, but the direct
+# XIP alternative.
+
+mcuboot_secondary_pad:
+  share_size: mcuboot_pad
+  placement:
+    after: mcuboot_primary
+    align: {start: CONFIG_FPROTECT_BLOCK_SIZE}
+
+mcuboot_secondary_app:
+  share_size: mcuboot_primary_app
+  placement:
+    after: mcuboot_secondary_pad
+
+mcuboot_secondary:
+  span: [mcuboot_secondary_pad, mcuboot_secondary_app]
+
+#endif /* CONFIG_BOOT_DIRECT_XIP */
+
+#if CONFIG_BOOT_SWAP_USING_SCRATCH
+mcuboot_scratch:
+  size: CONFIG_PM_PARTITION_SIZE_MCUBOOT_SCRATCH
+  placement:
+    after: app
+    align: {start: CONFIG_FPROTECT_BLOCK_SIZE}
+#endif /* CONFIG_BOOT_SWAP_USING_SCRATCH */
+
+# Padding placed before image to boot. This reserves space for the MCUboot image header
+# and it ensures that the boot image gets linked with the correct address offset in flash.
+mcuboot_pad:
+    # MCUboot pad must be placed before the 'spm' partition if that is present.
+    # If 'spm' partition is not present, it must be placed before the 'app'.
+  size: CONFIG_PM_PARTITION_SIZE_MCUBOOT_PAD
+  placement:
+    before: [mcuboot_primary_app]
+#ifdef CONFIG_FPROTECT
+    align: {start: CONFIG_FPROTECT_BLOCK_SIZE}
+#endif
diff --git a/boot/zephyr/prj.conf b/boot/zephyr/prj.conf
index e4c012943..ec6ac9fa0 100644
--- a/boot/zephyr/prj.conf
+++ b/boot/zephyr/prj.conf
@@ -22,6 +22,7 @@ CONFIG_BOOT_BOOTSTRAP=n
 # CONFIG_TINYCRYPT_SHA256 is not set
 
 CONFIG_FLASH=y
+CONFIG_FPROTECT=y
 
 ### Various Zephyr boards enable features that we don't want.
 # CONFIG_BT is not set
diff --git a/zephyr/module.yml b/zephyr/module.yml
index c4293e387..797b0fa10 100644
--- a/zephyr/module.yml
+++ b/zephyr/module.yml
@@ -1,4 +1,5 @@
 samples:
   - boot/zephyr
 build:
-  cmake: ./boot/bootutil/zephyr
+  cmake-ext: True
+  kconfig-ext: True

From d2c6668ad066a89541a2b4618e969de232e369c5 Mon Sep 17 00:00:00 2001
From: Sigvart Hovland <sigvart.m@gmail.com>
Date: Tue, 26 Mar 2019 15:42:38 +0100
Subject: [PATCH 49/72] [nrf noup] zephyr: Remove duplication from  cmake
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Removes the `add_subdirectory`
of nrfxlib it will still check that the nrfxlib is located outside
the mcuboot directory.

Signed-off-by: Sigvart Hovland <sigvart.m@gmail.com>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
Signed-off-by: Emil Obalski <emil.obalski@nordicsemi.no>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Signed-off-by: Håkon Øye Amundsen <haakon.amundsen@nordicsemi.no>
Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit ae87eb51c2de168c9dec81d9fe048a6c9e8f67f1)
---
 boot/zephyr/CMakeLists.txt | 2 --
 1 file changed, 2 deletions(-)

diff --git a/boot/zephyr/CMakeLists.txt b/boot/zephyr/CMakeLists.txt
index 8561343b2..8d717c69e 100644
--- a/boot/zephyr/CMakeLists.txt
+++ b/boot/zephyr/CMakeLists.txt
@@ -74,8 +74,6 @@ if(NOT EXISTS ${NRFXLIB_DIR})
     To use the tinycrypt set `CONFIG_BOOT_ECDSA_TINYCRYPT` to y.
     ------------------------------------------------------------------------")
 endif()
-# Don't include this if we are using west
- add_subdirectory(${NRFXLIB_DIR} ${PROJECT_BINARY_DIR}/nrfxlib)
 endif()
 
 zephyr_library_include_directories(

From 192dfe6050ec51a2b0b1b9df8ec1a8ef65fdcdef Mon Sep 17 00:00:00 2001
From: Sigvart Hovland <sigvart.m@gmail.com>
Date: Thu, 14 Feb 2019 13:20:34 +0100
Subject: [PATCH 50/72] [nrf noup] boot: bootutil: Add shared crypto for ECDSA
 and SHA
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

* Add functions for ecdsa_verify_secp256r1 and sha256 to use the shared
crypto API
* Add Kconfig and CMake variables for selecting shared crypto when using
ecdsa
* Add custom section to project for placing the API section in the
correct location in flash
* Add kconfig fragment for using external crypto

Signed-off-by: Sigvart Hovland <sigvart.m@gmail.com>
Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
Signed-off-by: Emil Obalski <emil.obalski@nordicsemi.no>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Signed-off-by: Håkon Øye Amundsen <haakon.amundsen@nordicsemi.no>
Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
Signed-off-by: Trond Einar Snekvik <Trond.Einar.Snekvik@nordicsemi.no>
Signed-off-by: Georgios Vasilakis <georgios.vasilakis@nordicsemi.no>
Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 2576bf350ef096d7aec15cb2e06d813e34a8fbec)
---
 .../include/bootutil/crypto/ecdsa_p256.h      | 43 +++++++++++++++++++
 .../bootutil/include/bootutil/crypto/sha256.h | 32 ++++++++++++++
 boot/bootutil/src/image_ec256.c               |  5 ++-
 boot/zephyr/CMakeLists.txt                    |  2 +
 boot/zephyr/external_crypto.conf              | 20 +++++++++
 .../include/mcuboot_config/mcuboot_config.h   |  5 +--
 6 files changed, 103 insertions(+), 4 deletions(-)
 create mode 100644 boot/zephyr/external_crypto.conf

diff --git a/boot/bootutil/include/bootutil/crypto/ecdsa_p256.h b/boot/bootutil/include/bootutil/crypto/ecdsa_p256.h
index 6b5b31567..eedb81a44 100644
--- a/boot/bootutil/include/bootutil/crypto/ecdsa_p256.h
+++ b/boot/bootutil/include/bootutil/crypto/ecdsa_p256.h
@@ -14,6 +14,7 @@
 
 #if (defined(MCUBOOT_USE_TINYCRYPT) + \
      defined(MCUBOOT_USE_CC310) + \
+     defined(MCUBOOT_USE_NRF_EXTERNAL_CRYPTO) + \
      defined(MCUBOOT_USE_MBED_TLS)) != 1
     #error "One crypto backend must be defined: either CC310, TINYCRYPT, or MBED_TLS"
 #endif
@@ -35,6 +36,11 @@
     #define BOOTUTIL_CRYPTO_ECDSA_P256_HASH_SIZE (4 * 8)
 #endif
 
+#if defined(MCUBOOT_USE_NRF_EXTERNAL_CRYPTO)
+    #include <bl_crypto.h>
+    #define BOOTUTIL_CRYPTO_ECDSA_P256_HASH_SIZE (4 * 8)
+#endif /* MCUBOOT_USE_NRF_EXTERNAL_CRYPTO */
+
 #ifdef __cplusplus
 extern "C" {
 #endif
@@ -158,6 +164,43 @@ static inline int bootutil_ecdsa_p256_verify(bootutil_ecdsa_p256_context *ctx,
 }
 #endif /* MCUBOOT_USE_MBED_TLS */
 
+#if defined(MCUBOOT_USE_NRF_EXTERNAL_CRYPTO)
+typedef uintptr_t bootutil_ecdsa_p256_context;
+
+static inline void bootutil_ecdsa_p256_init(bootutil_ecdsa_p256_context *ctx)
+{
+    (void)ctx;
+}
+
+static inline void bootutil_ecdsa_p256_drop(bootutil_ecdsa_p256_context *ctx)
+{
+    (void)ctx;
+}
+
+static inline int bootutil_ecdsa_p256_verify(bootutil_ecdsa_p256_context *ctx,
+                                             uint8_t *pk, size_t pk_len,
+                                             uint8_t *hash,
+                                             uint8_t *sig, size_t sig_len)
+{
+    (void)ctx;
+    (void)pk_len;
+    (void)sig_len;
+
+	/* As described on the compact representation in IETF protocols,
+	 * the first byte of the key defines if the ECC points are
+	 * compressed (0x2 or 0x3) or uncompressed (0x4).
+	 * We only support uncompressed keys.
+	 */
+	if (pk[0] != 0x04)
+		return -1;
+
+	pk++;
+
+    return bl_secp256r1_validate(hash, BOOTUTIL_CRYPTO_ECDSA_P256_HASH_SIZE,
+                                 pk, sig);
+}
+#endif /* MCUBOOT_USE_NRF_EXTERNAL_CRYPTO */
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/boot/bootutil/include/bootutil/crypto/sha256.h b/boot/bootutil/include/bootutil/crypto/sha256.h
index b45cd6316..c5534e61d 100644
--- a/boot/bootutil/include/bootutil/crypto/sha256.h
+++ b/boot/bootutil/include/bootutil/crypto/sha256.h
@@ -22,6 +22,7 @@
 
 #if (defined(MCUBOOT_USE_MBED_TLS) + \
      defined(MCUBOOT_USE_TINYCRYPT) + \
+     defined(MCUBOOT_USE_NRF_EXTERNAL_CRYPTO) + \
      defined(MCUBOOT_USE_CC310)) != 1
     #error "One crypto backend must be defined: either CC310, MBED_TLS or TINYCRYPT"
 #endif
@@ -139,6 +140,37 @@ static inline int bootutil_sha256_finish(bootutil_sha256_context *ctx,
 }
 #endif /* MCUBOOT_USE_CC310 */
 
+#if defined(MCUBOOT_USE_NRF_EXTERNAL_CRYPTO)
+
+#include <bl_crypto.h>
+
+typedef bl_sha256_ctx_t bootutil_sha256_context;
+
+static inline void bootutil_sha256_init(bootutil_sha256_context *ctx)
+{
+    bl_sha256_init(ctx);
+}
+
+static inline void bootutil_sha256_drop(bootutil_sha256_context *ctx)
+{
+    (void)ctx;
+}
+
+static inline int bootutil_sha256_update(bootutil_sha256_context *ctx,
+                                          const void *data,
+                                          uint32_t data_len)
+{
+    return bl_sha256_update(ctx, data, data_len);
+}
+
+static inline int bootutil_sha256_finish(bootutil_sha256_context *ctx,
+                                          uint8_t *output)
+{
+    bl_sha256_finalize(ctx, output);
+    return 0;
+}
+#endif /* MCUBOOT_USE_NRF_EXTERNAL_CRYPTO */
+
 #ifdef __cplusplus
 }
 #endif
diff --git a/boot/bootutil/src/image_ec256.c b/boot/bootutil/src/image_ec256.c
index 196d59319..542159ef6 100644
--- a/boot/bootutil/src/image_ec256.c
+++ b/boot/bootutil/src/image_ec256.c
@@ -34,8 +34,11 @@
 #if defined(MCUBOOT_USE_CC310) || defined(MCUBOOT_USE_MBED_TLS)
 #define NUM_ECC_BYTES (256 / 8)
 #endif
+#ifdef MCUBOOT_USE_NRF_EXTERNAL_CRYPTO
+#define NUM_ECC_BYTES (256 / 8)
+#endif
 #if defined(MCUBOOT_USE_TINYCRYPT) || defined(MCUBOOT_USE_CC310) || \
-    defined(MCUBOOT_USE_MBED_TLS)
+    defined(MCUBOOT_USE_MBED_TLS) || defined (MCUBOOT_USE_NRF_EXTERNAL_CRYPTO)
 #include "bootutil/sign_key.h"
 
 #include "mbedtls/oid.h"
diff --git a/boot/zephyr/CMakeLists.txt b/boot/zephyr/CMakeLists.txt
index 8d717c69e..6b5ccbe35 100644
--- a/boot/zephyr/CMakeLists.txt
+++ b/boot/zephyr/CMakeLists.txt
@@ -168,6 +168,8 @@ if(CONFIG_BOOT_SIGNATURE_TYPE_ECDSA_P256 OR CONFIG_BOOT_ENCRYPT_EC256 OR CONFIG_
     zephyr_library_sources(${NRF_DIR}/cc310_glue.c)
     zephyr_library_include_directories(${NRF_DIR})
     zephyr_link_libraries(nrfxlib_crypto)
+  elseif(CONFIG_BOOT_USE_NRF_EXTERNAL_CRYPTO)
+    zephyr_include_directories(${BL_CRYPTO_DIR}/../include)
   endif()
 
   # Since here we are not using Zephyr's mbedTLS but rather our own, we need
diff --git a/boot/zephyr/external_crypto.conf b/boot/zephyr/external_crypto.conf
new file mode 100644
index 000000000..3ed56cc16
--- /dev/null
+++ b/boot/zephyr/external_crypto.conf
@@ -0,0 +1,20 @@
+#
+# Copyright (c) 2021 Nordic Semiconductor ASA
+#
+# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+#
+
+# These configurations should be used when using nrf/samples/bootloader
+# as the immutable bootloader (B0), and MCUBoot as the second stage updateable
+# bootloader.
+
+# Set ECDSA as signing mechanism
+CONFIG_BOOT_SIGNATURE_TYPE_ECDSA_P256=y
+
+# Use crypto backend from B0
+CONFIG_BOOT_NRF_EXTERNAL_CRYPTO=y
+CONFIG_SECURE_BOOT_CRYPTO=y
+CONFIG_SB_CRYPTO_CLIENT_ECDSA_SECP256R1=y
+CONFIG_SB_CRYPTO_CLIENT_SHA256=y
+CONFIG_BL_SHA256_EXT_API_REQUIRED=y
+CONFIG_BL_SECP256R1_EXT_API_REQUIRED=y
diff --git a/boot/zephyr/include/mcuboot_config/mcuboot_config.h b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
index 4dc105fe9..db5d656dc 100644
--- a/boot/zephyr/include/mcuboot_config/mcuboot_config.h
+++ b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
@@ -39,9 +39,8 @@
 #define MCUBOOT_USE_TINYCRYPT
 #elif defined(CONFIG_BOOT_USE_CC310)
 #define MCUBOOT_USE_CC310
-#ifdef CONFIG_BOOT_USE_NRF_CC310_BL
-#define MCUBOOT_USE_NRF_CC310_BL
-#endif
+#elif defined(CONFIG_BOOT_USE_NRF_EXTERNAL_CRYPTO)
+#define MCUBOOT_USE_NRF_EXTERNAL_CRYPTO
 #endif
 
 /* Zephyr, regardless of C library used, provides snprintf */

From 7abea26499a67222c63329bd6ee3cffe02400321 Mon Sep 17 00:00:00 2001
From: Kamil Piszczek <Kamil.Piszczek@nordicsemi.no>
Date: Mon, 14 Nov 2022 14:58:53 +0100
Subject: [PATCH 51/72] [nrf fromtree] boot: zephyr: remove
 thingy53_nrf5340_cpuapp.conf board configuration

Removed the board configuration for Thingy:53 Application Core as it
contains references to the Kconfig modules that are not available in
the upstream Zephyr. The current configuration is set up to work
in the nRF Connect SDK environment and should be moved there.

Signed-off-by: Kamil Piszczek <Kamil.Piszczek@nordicsemi.no>
(cherry picked from commit b9e47b76ed43209f88c02b945b0ffa9b022e993c)
---
 .../boards/thingy53_nrf5340_cpuapp.conf       | 72 -------------------
 1 file changed, 72 deletions(-)
 delete mode 100644 boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf

diff --git a/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf b/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf
deleted file mode 100644
index cde9d45b0..000000000
--- a/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf
+++ /dev/null
@@ -1,72 +0,0 @@
-CONFIG_SIZE_OPTIMIZATIONS=y
-
-CONFIG_SYSTEM_CLOCK_NO_WAIT=y
-CONFIG_PM=n
-
-CONFIG_MAIN_STACK_SIZE=10240
-CONFIG_MBEDTLS_CFG_FILE="mcuboot-mbedtls-cfg.h"
-
-CONFIG_BOOT_MAX_IMG_SECTORS=2048
-CONFIG_BOOT_SIGNATURE_TYPE_RSA=y
-
-# Flash
-CONFIG_FLASH=y
-CONFIG_BOOT_ERASE_PROGRESSIVELY=y
-CONFIG_SOC_FLASH_NRF_EMULATE_ONE_BYTE_WRITE_ACCESS=y
-CONFIG_FPROTECT=y
-
-# Serial
-CONFIG_SERIAL=y
-CONFIG_UART_LINE_CTRL=y
-
-# MCUBoot serial
-CONFIG_GPIO=y
-CONFIG_MCUBOOT_SERIAL=y
-CONFIG_MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD=y
-CONFIG_BOOT_SERIAL_CDC_ACM=y
-
-# Required by QSPI
-CONFIG_NORDIC_QSPI_NOR=y
-CONFIG_NORDIC_QSPI_NOR_FLASH_LAYOUT_PAGE_SIZE=4096
-CONFIG_NORDIC_QSPI_NOR_STACK_WRITE_BUFFER_SIZE=16
-
-# Required by USB and QSPI
-CONFIG_MULTITHREADING=y
-
-# USB
-CONFIG_USB_DEVICE_REMOTE_WAKEUP=n
-CONFIG_USB_DEVICE_MANUFACTURER="Nordic Semiconductor ASA"
-CONFIG_USB_DEVICE_PRODUCT="Bootloader Thingy:53"
-CONFIG_USB_DEVICE_VID=0x1915
-CONFIG_USB_DEVICE_PID=0x5300
-CONFIG_USB_CDC_ACM=y
-
-# Decrease memory footprint
-CONFIG_CBPRINTF_NANO=y
-CONFIG_TIMESLICING=n
-CONFIG_BOOT_BANNER=n
-CONFIG_CONSOLE=n
-CONFIG_CONSOLE_HANDLER=n
-CONFIG_UART_CONSOLE=n
-CONFIG_USE_SEGGER_RTT=n
-CONFIG_LOG=n
-CONFIG_ERRNO=n
-CONFIG_PRINTK=n
-CONFIG_RESET_ON_FATAL_ERROR=n
-CONFIG_SPI=n
-CONFIG_I2C=n
-CONFIG_UART_NRFX=n
-
-# The following configurations are required to support simultaneous multi image update
-CONFIG_PCD_APP=y
-CONFIG_UPDATEABLE_IMAGE_NUMBER=2
-CONFIG_BOOT_UPGRADE_ONLY=y
-# The network core cannot access external flash directly. The flash simulator must be used to
-# provide a memory region that is used to forward the new firmware to the network core.
-CONFIG_FLASH_SIMULATOR=y
-CONFIG_FLASH_SIMULATOR_DOUBLE_WRITES=y
-CONFIG_FLASH_SIMULATOR_STATS=n
-
-# Enable custom command to erase settings partition.
-CONFIG_ENABLE_MGMT_PERUSER=y
-CONFIG_BOOT_MGMT_CUSTOM_STORAGE_ERASE=y

From 625c84e33ce748a155adc689e54d81cfab2a44ac Mon Sep 17 00:00:00 2001
From: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
Date: Thu, 27 Aug 2020 14:29:31 +0200
Subject: [PATCH 52/72] [nrf noup] boot: nrf53-specific customizations
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

- Add network core bootloader implementation

  Enables network core updates of nrf53 using MCUBoot by identifying
  images through their start addresses. Also implements the control and
  transfer using the PCD module.

- Add support for multi image DFU using partition manager.

- Add check for netcore addr if NSIB is enabled so netcore updates works

- boot: zephyr: move thingy53_nrf5340_cpuapp.conf downstream

  Moved the board configuration for Thingy:53 Application Core to the
  nRF Connect SDK MCUboot downstream repository. The configuration file
  contains references to the Kconfig modules that are only available in
  the nRF Connect SDK. The current configuration is set up to work in the
  nRF Connect SDK environment and cannot be used upstream.

- pm: enable ram flash partition using common flag

  This patch makes mcuboot_primary_1 ram-flash partition
  selectable using CONFIG_NRF53_MCUBOOT_PRIMARY_1_RAM_FLASH
  property. This is needed since CONFIG_NRF53_MULTI_IMAGE_UPDATE
  become not only configuration which requires that partition.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Signed-off-by: Emil Obalski <emil.obalski@nordicsemi.no>
Signed-off-by: Håkon Øye Amundsen <haakon.amundsen@nordicsemi.no>
Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
Signed-off-by: Kamil Piszczek <Kamil.Piszczek@nordicsemi.no>
Signed-off-by: Ole Sæther <ole.saether@nordicsemi.no>
Signed-off-by: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
Signed-off-by: Simon Iversen <simon.iversen@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Trond Einar Snekvik <Trond.Einar.Snekvik@nordicsemi.no>
(cherry picked from commit 7c3d7ed725919b5c0cce8688d565dec59957cb9b)
(cherry picked from commit 3895554024edc1b518657fcfdc802a8fdf71bd65)
(cherry picked from commit 2da20eb0f92974ce1dbcc700a25c43dcddc72b29)
(cherry picked from commit 1d535d0ccbf4d213752a58b235e8e46c6a39a6a1)
---
 boot/bootutil/src/loader.c                    | 96 ++++++++++++++-----
 .../boards/thingy53_nrf5340_cpuapp.conf       | 72 ++++++++++++++
 boot/zephyr/include/sysflash/sysflash.h       | 23 +++++
 boot/zephyr/main.c                            |  9 ++
 boot/zephyr/pm.yml                            | 13 +++
 5 files changed, 187 insertions(+), 26 deletions(-)
 create mode 100644 boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf

diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
index b60a3a141..4a4593d76 100644
--- a/boot/bootutil/src/loader.c
+++ b/boot/bootutil/src/loader.c
@@ -48,6 +48,10 @@
 #include "bootutil/boot_hooks.h"
 #include "bootutil/mcuboot_status.h"
 
+#if defined(CONFIG_SOC_NRF5340_CPUAPP) && defined(PM_CPUNET_B0N_ADDRESS)
+#include <dfu/pcd.h> 
+#endif
+
 #ifdef MCUBOOT_ENC_IMAGES
 #include "bootutil/enc_key.h"
 #endif
@@ -908,7 +912,15 @@ boot_validated_swap_type(struct boot_loader_state *state,
 {
     int swap_type;
     fih_int fih_rc = FIH_FAILURE;
-#ifdef PM_S1_ADDRESS
+    bool upgrade_valid = false;
+
+#if defined(PM_S1_ADDRESS) || defined(CONFIG_SOC_NRF5340_CPUAPP)
+    const struct flash_area *secondary_fa =
+        BOOT_IMG_AREA(state, BOOT_SECONDARY_SLOT);
+    struct image_header *hdr = (struct image_header *)secondary_fa->fa_off;
+    uint32_t vtable_addr = 0;
+    uint32_t *vtable = 0;
+    uint32_t reset_addr = 0;
     /* Patch needed for NCS. Since image 0 (the app) and image 1 (the other
      * B1 slot S0 or S1) share the same secondary slot, we need to check
      * whether the update candidate in the secondary slot is intended for
@@ -916,34 +928,36 @@ boot_validated_swap_type(struct boot_loader_state *state,
      * vector. Note that there are good reasons for not using img_num from
      * the swap info.
      */
-    const struct flash_area *secondary_fa =
-	    BOOT_IMG_AREA(state, BOOT_SECONDARY_SLOT);
-    struct image_header *hdr =
-	    (struct image_header *)secondary_fa->fa_off;
 
     if (hdr->ih_magic == IMAGE_MAGIC) {
-	    const struct flash_area *primary_fa;
-	    uint32_t vtable_addr = (uint32_t)hdr + hdr->ih_hdr_size;
-	    uint32_t *vtable = (uint32_t *)(vtable_addr);
-	    uint32_t reset_addr = vtable[1];
-	    int rc = flash_area_open(
-			    flash_area_id_from_multi_image_slot(
-				    BOOT_CURR_IMG(state),
-				    BOOT_PRIMARY_SLOT),
-			    &primary_fa);
-
-	    if (rc != 0) {
-		    return BOOT_SWAP_TYPE_FAIL;
-	    }
-	    /* Get start and end of primary slot for current image */
-	    if (reset_addr < primary_fa->fa_off ||
-	        reset_addr > (primary_fa->fa_off + primary_fa->fa_size)) {
-		    /* The image in the secondary slot is not intended for this image
-		    */
-		    return BOOT_SWAP_TYPE_NONE;
-	    }
-    }
+        vtable_addr = (uint32_t)hdr + hdr->ih_hdr_size;
+        vtable = (uint32_t *)(vtable_addr);
+        reset_addr = vtable[1];
+#ifdef PM_S1_ADDRESS
+#ifdef PM_CPUNET_B0N_ADDRESS
+        if(reset_addr < PM_CPUNET_B0N_ADDRESS)
 #endif
+        {
+            const struct flash_area *primary_fa;
+            int rc = flash_area_open(flash_area_id_from_multi_image_slot(
+                        BOOT_CURR_IMG(state),
+                        BOOT_PRIMARY_SLOT),
+                    &primary_fa);
+
+            if (rc != 0) {
+                return BOOT_SWAP_TYPE_FAIL;
+            }
+            /* Get start and end of primary slot for current image */
+            if (reset_addr < primary_fa->fa_off ||
+                    reset_addr > (primary_fa->fa_off + primary_fa->fa_size)) {
+                /* The image in the secondary slot is not intended for this image
+                */
+                return BOOT_SWAP_TYPE_NONE;
+            }
+        }
+#endif /* PM_S1_ADDRESS */
+    }
+#endif /* PM_S1_ADDRESS || CONFIG_SOC_NRF5340_CPUAPP */
 
     swap_type = boot_swap_type_multi(BOOT_CURR_IMG(state));
     if (BOOT_IS_UPGRADE(swap_type)) {
@@ -957,7 +971,37 @@ boot_validated_swap_type(struct boot_loader_state *state,
             } else {
                 swap_type = BOOT_SWAP_TYPE_FAIL;
             }
+        } else {
+            upgrade_valid = true;
+        }
+
+#if defined(CONFIG_SOC_NRF5340_CPUAPP) && defined(PM_CPUNET_B0N_ADDRESS)
+        /* If the update is valid, and it targets the network core: perform the
+         * update and indicate to the caller of this function that no update is
+         * available
+         */
+        if (upgrade_valid && reset_addr > PM_CPUNET_B0N_ADDRESS) {
+            uint32_t fw_size = hdr->ih_img_size;
+
+            BOOT_LOG_INF("Starting network core update");
+            int rc = pcd_network_core_update(vtable, fw_size);
+
+            if (rc != 0) {
+                swap_type = BOOT_SWAP_TYPE_FAIL;
+            } else {
+                BOOT_LOG_INF("Done updating network core");
+#if defined(MCUBOOT_SWAP_USING_SCRATCH) || defined(MCUBOOT_SWAP_USING_MOVE)
+                /* swap_erase_trailer_sectors is undefined if upgrade only
+                 * method is used. There is no need to erase sectors, because
+                 * the image cannot be reverted.
+                 */
+                rc = swap_erase_trailer_sectors(state,
+                        secondary_fa);
+#endif
+                swap_type = BOOT_SWAP_TYPE_NONE;
+            }
         }
+#endif /* CONFIG_SOC_NRF5340_CPUAPP */
     }
 
     return swap_type;
diff --git a/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf b/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf
new file mode 100644
index 000000000..cde9d45b0
--- /dev/null
+++ b/boot/zephyr/boards/thingy53_nrf5340_cpuapp.conf
@@ -0,0 +1,72 @@
+CONFIG_SIZE_OPTIMIZATIONS=y
+
+CONFIG_SYSTEM_CLOCK_NO_WAIT=y
+CONFIG_PM=n
+
+CONFIG_MAIN_STACK_SIZE=10240
+CONFIG_MBEDTLS_CFG_FILE="mcuboot-mbedtls-cfg.h"
+
+CONFIG_BOOT_MAX_IMG_SECTORS=2048
+CONFIG_BOOT_SIGNATURE_TYPE_RSA=y
+
+# Flash
+CONFIG_FLASH=y
+CONFIG_BOOT_ERASE_PROGRESSIVELY=y
+CONFIG_SOC_FLASH_NRF_EMULATE_ONE_BYTE_WRITE_ACCESS=y
+CONFIG_FPROTECT=y
+
+# Serial
+CONFIG_SERIAL=y
+CONFIG_UART_LINE_CTRL=y
+
+# MCUBoot serial
+CONFIG_GPIO=y
+CONFIG_MCUBOOT_SERIAL=y
+CONFIG_MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD=y
+CONFIG_BOOT_SERIAL_CDC_ACM=y
+
+# Required by QSPI
+CONFIG_NORDIC_QSPI_NOR=y
+CONFIG_NORDIC_QSPI_NOR_FLASH_LAYOUT_PAGE_SIZE=4096
+CONFIG_NORDIC_QSPI_NOR_STACK_WRITE_BUFFER_SIZE=16
+
+# Required by USB and QSPI
+CONFIG_MULTITHREADING=y
+
+# USB
+CONFIG_USB_DEVICE_REMOTE_WAKEUP=n
+CONFIG_USB_DEVICE_MANUFACTURER="Nordic Semiconductor ASA"
+CONFIG_USB_DEVICE_PRODUCT="Bootloader Thingy:53"
+CONFIG_USB_DEVICE_VID=0x1915
+CONFIG_USB_DEVICE_PID=0x5300
+CONFIG_USB_CDC_ACM=y
+
+# Decrease memory footprint
+CONFIG_CBPRINTF_NANO=y
+CONFIG_TIMESLICING=n
+CONFIG_BOOT_BANNER=n
+CONFIG_CONSOLE=n
+CONFIG_CONSOLE_HANDLER=n
+CONFIG_UART_CONSOLE=n
+CONFIG_USE_SEGGER_RTT=n
+CONFIG_LOG=n
+CONFIG_ERRNO=n
+CONFIG_PRINTK=n
+CONFIG_RESET_ON_FATAL_ERROR=n
+CONFIG_SPI=n
+CONFIG_I2C=n
+CONFIG_UART_NRFX=n
+
+# The following configurations are required to support simultaneous multi image update
+CONFIG_PCD_APP=y
+CONFIG_UPDATEABLE_IMAGE_NUMBER=2
+CONFIG_BOOT_UPGRADE_ONLY=y
+# The network core cannot access external flash directly. The flash simulator must be used to
+# provide a memory region that is used to forward the new firmware to the network core.
+CONFIG_FLASH_SIMULATOR=y
+CONFIG_FLASH_SIMULATOR_DOUBLE_WRITES=y
+CONFIG_FLASH_SIMULATOR_STATS=n
+
+# Enable custom command to erase settings partition.
+CONFIG_ENABLE_MGMT_PERUSER=y
+CONFIG_BOOT_MGMT_CUSTOM_STORAGE_ERASE=y
diff --git a/boot/zephyr/include/sysflash/sysflash.h b/boot/zephyr/include/sysflash/sysflash.h
index 2495a9810..d5c8e2f26 100644
--- a/boot/zephyr/include/sysflash/sysflash.h
+++ b/boot/zephyr/include/sysflash/sysflash.h
@@ -16,6 +16,11 @@
 
 #elif (MCUBOOT_IMAGE_NUMBER == 2)
 
+/* If B0 is present then two bootloaders are present, and we must use
+ * a single secondary slot for both primary slots.
+ */
+#ifdef PM_B0_ADDRESS
+
 extern uint32_t _image_1_primary_slot_id[];
 
 #define FLASH_AREA_IMAGE_PRIMARY(x)            \
@@ -31,6 +36,24 @@ extern uint32_t _image_1_primary_slot_id[];
         (x == 1) ?                    \
            PM_MCUBOOT_SECONDARY_ID:   \
            255 )
+#else
+
+#define FLASH_AREA_IMAGE_PRIMARY(x)          \
+        ((x == 0) ?                          \
+           PM_MCUBOOT_PRIMARY_ID :           \
+         (x == 1) ?                          \
+           PM_MCUBOOT_PRIMARY_1_ID :         \
+           255 )
+
+#define FLASH_AREA_IMAGE_SECONDARY(x) \
+        ((x == 0) ?                   \
+           PM_MCUBOOT_SECONDARY_ID:   \
+        (x == 1) ?                    \
+           PM_MCUBOOT_SECONDARY_1_ID: \
+           255 )
+
+#endif /* PM_B0_ADDRESS */
+
 #endif
 #define FLASH_AREA_IMAGE_SCRATCH    PM_MCUBOOT_SCRATCH_ID
 
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index c1473f741..751a50a37 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -64,6 +64,10 @@ const struct boot_uart_funcs boot_funcs = {
 #include <arm_cleanup.h>
 #endif
 
+#if defined(CONFIG_SOC_NRF5340_CPUAPP) && defined(PM_CPUNET_B0N_ADDRESS)
+#include <dfu/pcd.h>
+#endif
+
 /* CONFIG_LOG_MINIMAL is the legacy Kconfig property,
  * replaced by CONFIG_LOG_MODE_MINIMAL.
  */
@@ -658,6 +662,11 @@ void main(void)
             ;
     }
 
+#endif /* USE_PARTITION_MANAGER && CONFIG_FPROTECT */
+#if defined(CONFIG_SOC_NRF5340_CPUAPP) && defined(PM_CPUNET_B0N_ADDRESS)
+    pcd_lock_ram();
+#endif
+
     ZEPHYR_BOOT_LOG_STOP();
 
     do_boot(&rsp);
diff --git a/boot/zephyr/pm.yml b/boot/zephyr/pm.yml
index dd08096e6..80ca3d946 100644
--- a/boot/zephyr/pm.yml
+++ b/boot/zephyr/pm.yml
@@ -72,3 +72,16 @@ mcuboot_pad:
 #ifdef CONFIG_FPROTECT
     align: {start: CONFIG_FPROTECT_BLOCK_SIZE}
 #endif
+
+#if (CONFIG_NRF53_MCUBOOT_PRIMARY_1_RAM_FLASH)
+mcuboot_primary_1:
+  region: ram_flash
+  size: CONFIG_NRF53_RAM_FLASH_SIZE
+#endif /* CONFIG_NRF53_MULTI_IMAGE_UPDATE */
+
+#if (CONFIG_NRF53_MULTI_IMAGE_UPDATE)
+mcuboot_secondary_1:
+  region: external_flash
+  size: CONFIG_NRF53_RAM_FLASH_SIZE
+
+#endif /* CONFIG_NRF53_MULTI_IMAGE_UPDATE */

From 0701661c8f52c0644a405fc36c0fe96455b7c876 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mart=C3=AD=20Bol=C3=ADvar?= <marti.bolivar@nordicsemi.no>
Date: Fri, 3 Sep 2021 14:38:54 -0700
Subject: [PATCH 53/72] [nrf noup] boot: add 'minimal' configuration files
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Add prj_minimal.conf, a Kconfig fragment to be used for minimally
sized image production. The minimal fragment has been simplified for
only external crypto.

Move partition sizing into Kconfig to be consistent with the method
used by b0.

Using this fragment with prj_minimal.conf makes MCUboot < 16kB for
all nRF devices (9160 still needs 32kB partition).

Ref: NCSDK-6704
Signed-off-by: Stephen Stauts <stephen.stauts@nordicsemi.no>
Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 6186a438257ae8097e3a1b742aa7fcf52fc5e653)
---
 .../nrf5340dk_nrf5340_cpuapp_minimal.conf     | 13 ++++++
 boot/zephyr/prj_minimal.conf                  | 45 +++++++++++++++++++
 2 files changed, 58 insertions(+)
 create mode 100644 boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf
 create mode 100644 boot/zephyr/prj_minimal.conf

diff --git a/boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf b/boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf
new file mode 100644
index 000000000..11dd2ab68
--- /dev/null
+++ b/boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf
@@ -0,0 +1,13 @@
+#
+# Copyright (c) 2021 Nordic Semiconductor ASA
+#
+# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+#
+
+# CC3xx is currently not used for nrf53
+CONFIG_HW_CC3XX=n
+CONFIG_NRF_CC3XX_PLATFORM=n
+
+# Required for kernel operation
+CONFIG_CLOCK_CONTROL=y
+CONFIG_SYS_CLOCK_EXISTS=y
diff --git a/boot/zephyr/prj_minimal.conf b/boot/zephyr/prj_minimal.conf
new file mode 100644
index 000000000..c1a3a065d
--- /dev/null
+++ b/boot/zephyr/prj_minimal.conf
@@ -0,0 +1,45 @@
+#
+# Copyright (c) 2021 Nordic Semiconductor ASA
+#
+# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+#
+
+CONFIG_MAIN_STACK_SIZE=10240
+CONFIG_MBEDTLS_CFG_FILE="mcuboot-mbedtls-cfg.h"
+
+CONFIG_FLASH=y
+CONFIG_FPROTECT=y
+CONFIG_PM=n
+
+CONFIG_BOOT_ENCRYPT_EC256=n
+CONFIG_BOOT_ENCRYPT_RSA=n
+CONFIG_BOOT_ENCRYPT_X25519=n
+CONFIG_BOOT_SWAP_SAVE_ENCTLV=n
+
+CONFIG_BOOT_BOOTSTRAP=n
+CONFIG_BOOT_UPGRADE_ONLY=n
+
+### Minimal Configurations ###
+CONFIG_BOOT_USE_MIN_PARTITION_SIZE=y
+CONFIG_ASSERT=n
+CONFIG_BOOT_BANNER=n
+CONFIG_CLOCK_CONTROL=n
+CONFIG_CONSOLE=n
+CONFIG_CONSOLE_HANDLER=n
+CONFIG_GPIO=n
+CONFIG_KERNEL_MEM_POOL=n
+CONFIG_LOG=n
+CONFIG_MINIMAL_LIBC_CALLOC=n
+CONFIG_MINIMAL_LIBC_MALLOC=n
+CONFIG_MINIMAL_LIBC_REALLOCARRAY=n
+CONFIG_NCS_SAMPLES_DEFAULTS=n
+CONFIG_NO_RUNTIME_CHECKS=y
+CONFIG_NRF_RTC_TIMER=n
+CONFIG_PRINTK=n
+CONFIG_REBOOT=n
+CONFIG_RESET_ON_FATAL_ERROR=n
+CONFIG_SECURE_BOOT_DEBUG=n
+CONFIG_SERIAL=n
+CONFIG_SIZE_OPTIMIZATIONS=y
+CONFIG_SYS_CLOCK_EXISTS=n
+CONFIG_UART_CONSOLE=n

From d1f2ef8d7bd84d4524d20807ff2dcd6b76a54aff Mon Sep 17 00:00:00 2001
From: Bernt Johan Damslora <bernt.johan.damslora@nordicsemi.no>
Date: Fri, 20 Sep 2019 18:25:41 +0200
Subject: [PATCH 54/72] [nrf noup] boot: zephyr: add support for Thingy:91

Adds project configurations for the two systems on the Thingy:91
(PCA-20035) board.

The bootloader that is factory-programmed on thing91 does not support
ECDSA signature type. Hence this commit also sets the signature type
to RSA for applications built for Thingy:91.

Signed-off-by: Bernt Johan Damslora <bernt.johan.damslora@nordicsemi.no>
Signed-off-by: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
Signed-off-by: Jon Helge Nistad <jon.helge.nistad@nordicsemi.no>
Signed-off-by: Balaji Srinivasan <balaji.srinivasan@nordicsemi.no>
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 145fa69ecc23ed84ff9c4b53fe1e84c3780c9a48)
---
 boot/zephyr/boards/thingy91_nrf52840.conf | 37 +++++++++++++++++++++++
 boot/zephyr/boards/thingy91_nrf9160.conf  | 16 ++++++++++
 2 files changed, 53 insertions(+)
 create mode 100644 boot/zephyr/boards/thingy91_nrf52840.conf
 create mode 100644 boot/zephyr/boards/thingy91_nrf9160.conf

diff --git a/boot/zephyr/boards/thingy91_nrf52840.conf b/boot/zephyr/boards/thingy91_nrf52840.conf
new file mode 100644
index 000000000..5a415cc62
--- /dev/null
+++ b/boot/zephyr/boards/thingy91_nrf52840.conf
@@ -0,0 +1,37 @@
+# Disable Zephyr console
+CONFIG_LOG=n
+CONFIG_CONSOLE=n
+CONFIG_CONSOLE_HANDLER=n
+CONFIG_UART_CONSOLE=n
+
+# The build won't fit on the partition allocated for it without size
+# optimizations.
+CONFIG_SIZE_OPTIMIZATIONS=y
+CONFIG_PM_PARTITION_SIZE_MCUBOOT=0x12000
+
+# Serial
+CONFIG_SERIAL=y
+CONFIG_UART_NRFX=y
+CONFIG_UART_INTERRUPT_DRIVEN=y
+CONFIG_UART_LINE_CTRL=y
+
+# MCUboot serial recovery
+CONFIG_GPIO=y
+CONFIG_MCUBOOT_SERIAL=y
+CONFIG_BOOT_SERIAL_CDC_ACM=y
+CONFIG_BOOT_SERIAL_DETECT_PORT="GPIO_1"
+CONFIG_BOOT_SERIAL_DETECT_PIN=13
+CONFIG_BOOT_SERIAL_DETECT_PIN_VAL=0
+
+# Required by USB
+CONFIG_MULTITHREADING=y
+
+# USB
+CONFIG_USB_DEVICE_STACK=y
+CONFIG_USB_DEVICE_PRODUCT="MCUBOOT"
+CONFIG_USB_CDC_ACM=y
+CONFIG_USB_COMPOSITE_DEVICE=y
+CONFIG_USB_MASS_STORAGE=n
+CONFIG_USB_DEVICE_MANUFACTURER="Nordic Semiconductor"
+CONFIG_USB_DEVICE_VID=0x1915
+CONFIG_USB_DEVICE_PID=0x520F
diff --git a/boot/zephyr/boards/thingy91_nrf9160.conf b/boot/zephyr/boards/thingy91_nrf9160.conf
new file mode 100644
index 000000000..6e671a286
--- /dev/null
+++ b/boot/zephyr/boards/thingy91_nrf9160.conf
@@ -0,0 +1,16 @@
+# Disable Zephyr console
+CONFIG_CONSOLE=n
+CONFIG_CONSOLE_HANDLER=n
+CONFIG_UART_CONSOLE=n
+
+# Disable Flash protection
+CONFIG_FPROTECT=n
+
+# MCUBoot settings
+CONFIG_BOOT_MAX_IMG_SECTORS=256
+
+# MCUboot serial recovery
+CONFIG_MCUBOOT_SERIAL=y
+CONFIG_BOOT_SERIAL_DETECT_PORT="GPIO_0"
+CONFIG_BOOT_SERIAL_DETECT_PIN=26
+CONFIG_BOOT_SERIAL_DETECT_PIN_VAL=0

From 9dac8ad815b22eda104f7771d8b82c88f6cfef48 Mon Sep 17 00:00:00 2001
From: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Date: Thu, 27 Feb 2020 12:48:56 +0100
Subject: [PATCH 55/72] [nrf noup] do_boot: clean peripherals state before boot
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Do some cleanup of nRF peripherals. This is necessary since Zephyr
doesn't have any driver deinitialization functionality, and we'd like
to leave peripherals in a more predictable state before booting the
Zephyr image. This should be re-worked when the zephyr driver model
allows us to deinitialize devices cleanly before jumping to the
chain-loaded image.

Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
Signed-off-by: Robert Lubos <robert.lubos@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Øyvind Rønningstad <oyvind.ronningstad@nordicsemi.no>
Signed-off-by: Martí Bolívar <marti.bolivar@nordicsemi.no>
Signed-off-by: Håkon Øye Amundsen <haakon.amundsen@nordicsemi.no>
Signed-off-by: Ioannis Glaropoulos <Ioannis.Glaropoulos@nordicsemi.no>
Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
Signed-off-by: Trond Einar Snekvik <Trond.Einar.Snekvik@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 4869eb3bf7e3a0d30035e5d0649ed28b5023d613)
---
 boot/zephyr/CMakeLists.txt        |  6 +++
 boot/zephyr/include/nrf_cleanup.h | 19 +++++++
 boot/zephyr/main.c                |  8 ++-
 boot/zephyr/nrf_cleanup.c         | 83 +++++++++++++++++++++++++++++++
 4 files changed, 115 insertions(+), 1 deletion(-)
 create mode 100644 boot/zephyr/include/nrf_cleanup.h
 create mode 100644 boot/zephyr/nrf_cleanup.c

diff --git a/boot/zephyr/CMakeLists.txt b/boot/zephyr/CMakeLists.txt
index 6b5ccbe35..48935db90 100644
--- a/boot/zephyr/CMakeLists.txt
+++ b/boot/zephyr/CMakeLists.txt
@@ -359,3 +359,9 @@ zephyr_library_sources(
   ${BOOT_DIR}/zephyr/arm_cleanup.c
 )
 endif()
+
+if(CONFIG_MCUBOOT_NRF_CLEANUP_PERIPHERAL)
+zephyr_library_sources(
+  ${BOOT_DIR}/zephyr/nrf_cleanup.c
+)
+endif()
diff --git a/boot/zephyr/include/nrf_cleanup.h b/boot/zephyr/include/nrf_cleanup.h
new file mode 100644
index 000000000..2b175634e
--- /dev/null
+++ b/boot/zephyr/include/nrf_cleanup.h
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2020 Nordic Semiconductor ASA
+ *
+ * SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+ */
+
+#ifndef H_NRF_CLEANUP_
+#define H_NRF_CLEANUP_
+
+/**
+ * Perform cleanup on some peripheral resources used by MCUBoot prior chainload
+ * the application.
+ *
+ * This function disables all RTC instances and UARTE instances.
+ * It Disables their interrupts signals as well.
+ */
+void nrf_cleanup_peripheral(void);
+
+#endif
diff --git a/boot/zephyr/main.c b/boot/zephyr/main.c
index 751a50a37..faba8b948 100644
--- a/boot/zephyr/main.c
+++ b/boot/zephyr/main.c
@@ -115,6 +115,10 @@ K_SEM_DEFINE(boot_log_sem, 1, 1);
 #include <pm_config.h>
 #endif
 
+#if CONFIG_MCUBOOT_NRF_CLEANUP_PERIPHERAL
+#include <nrf_cleanup.h>
+#endif
+
 #ifdef CONFIG_SOC_FAMILY_NRF
 #include <helpers/nrfx_reset_reason.h>
 
@@ -221,7 +225,9 @@ static void do_boot(struct boot_rsp *rsp)
     }
 #endif
 #endif
-
+#if CONFIG_MCUBOOT_NRF_CLEANUP_PERIPHERAL
+    nrf_cleanup_peripheral();
+#endif
 #if CONFIG_MCUBOOT_CLEANUP_ARM_CORE
     cleanup_arm_nvic(); /* cleanup NVIC registers */
 
diff --git a/boot/zephyr/nrf_cleanup.c b/boot/zephyr/nrf_cleanup.c
new file mode 100644
index 000000000..a8fff30a8
--- /dev/null
+++ b/boot/zephyr/nrf_cleanup.c
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2020 Nordic Semiconductor ASA
+ *
+ * SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+ */
+
+#include <hal/nrf_clock.h>
+#if defined(NRF_UARTE0) || defined(NRF_UARTE1)
+    #include <hal/nrf_uarte.h>
+#endif
+#if defined(NRF_RTC0) || defined(NRF_RTC1) || defined(NRF_RTC2)
+    #include <hal/nrf_rtc.h>
+#endif
+#if defined(NRF_PPI)
+    #include <hal/nrf_ppi.h>
+#endif
+#if defined(NRF_DPPIC)
+    #include <hal/nrf_dppi.h>
+#endif
+
+#include <string.h>
+
+#define NRF_UARTE_SUBSCRIBE_CONF_OFFS offsetof(NRF_UARTE_Type, SUBSCRIBE_STARTRX)
+#define NRF_UARTE_SUBSCRIBE_CONF_SIZE (offsetof(NRF_UARTE_Type, EVENTS_CTS) -\
+                                       NRF_UARTE_SUBSCRIBE_CONF_OFFS)
+
+#define NRF_UARTE_PUBLISH_CONF_OFFS offsetof(NRF_UARTE_Type, PUBLISH_CTS)
+#define NRF_UARTE_PUBLISH_CONF_SIZE (offsetof(NRF_UARTE_Type, SHORTS) -\
+                                     NRF_UARTE_PUBLISH_CONF_OFFS)
+
+#if defined(NRF_RTC0) || defined(NRF_RTC1) || defined(NRF_RTC2)
+static inline void nrf_cleanup_rtc(NRF_RTC_Type * rtc_reg)
+{
+    nrf_rtc_task_trigger(rtc_reg, NRF_RTC_TASK_STOP);
+    nrf_rtc_event_disable(rtc_reg, 0xFFFFFFFF);
+    nrf_rtc_int_disable(rtc_reg, 0xFFFFFFFF);
+}
+#endif
+
+static void nrf_cleanup_clock(void)
+{
+    nrf_clock_int_disable(NRF_CLOCK, 0xFFFFFFFF);
+}
+
+void nrf_cleanup_peripheral(void)
+{
+#if defined(NRF_RTC0)
+    nrf_cleanup_rtc(NRF_RTC0);
+#endif
+#if defined(NRF_RTC1)
+    nrf_cleanup_rtc(NRF_RTC1);
+#endif
+#if defined(NRF_RTC2)
+    nrf_cleanup_rtc(NRF_RTC2);
+#endif
+#if defined(NRF_UARTE0)
+    nrf_uarte_disable(NRF_UARTE0);
+    nrf_uarte_int_disable(NRF_UARTE0, 0xFFFFFFFF);
+#if defined(NRF_DPPIC)
+    /* Clear all SUBSCRIBE configurations. */
+    memset((uint8_t *)NRF_UARTE0 + NRF_UARTE_SUBSCRIBE_CONF_OFFS, 0, NRF_UARTE_SUBSCRIBE_CONF_SIZE);
+    /* Clear all PUBLISH configurations. */
+    memset((uint8_t *)NRF_UARTE0 + NRF_UARTE_PUBLISH_CONF_OFFS, 0, NRF_UARTE_PUBLISH_CONF_SIZE);
+#endif
+#endif
+#if defined(NRF_UARTE1)
+    nrf_uarte_disable(NRF_UARTE1);
+    nrf_uarte_int_disable(NRF_UARTE1, 0xFFFFFFFF);
+#if defined(NRF_DPPIC)
+    /* Clear all SUBSCRIBE configurations. */
+    memset((uint8_t *)NRF_UARTE1 + NRF_UARTE_SUBSCRIBE_CONF_OFFS, 0, NRF_UARTE_SUBSCRIBE_CONF_SIZE);
+    /* Clear all PUBLISH configurations. */
+    memset((uint8_t *)NRF_UARTE1 + NRF_UARTE_PUBLISH_CONF_OFFS, 0, NRF_UARTE_PUBLISH_CONF_SIZE);
+#endif
+#endif
+#if defined(NRF_PPI)
+    nrf_ppi_channels_disable_all(NRF_PPI);
+#endif
+#if defined(NRF_DPPIC)
+    nrf_dppi_channels_disable_all(NRF_DPPIC);
+#endif
+    nrf_cleanup_clock();
+}

From 8f299e8f1bf2511558fe0f33969abc2a449824ad Mon Sep 17 00:00:00 2001
From: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
Date: Tue, 30 Mar 2021 22:45:17 +0200
Subject: [PATCH 56/72] [nrf noup] bootutil: loader: work-around for
 multi-image builds

Seems multi-image dependencies are not supported for multi-image in
NCS yet. This is a workaround which reverts some lines to restore
previous MCUboot behavior, so that Immutable bootloader + MCUBoot type
builds will work.

Ref. NCSDK-8681

Signed-off-by: Sigvart Hovland <sigvart.hovland@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 72ce504ebe3da055e7b99536d50838496bab50a2)
---
 boot/bootutil/src/loader.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
index 4a4593d76..7d41d3818 100644
--- a/boot/bootutil/src/loader.c
+++ b/boot/bootutil/src/loader.c
@@ -1594,7 +1594,7 @@ boot_verify_dependencies(struct boot_loader_state *state)
         if (rc == 0) {
             /* All dependencies've been satisfied, continue with next image. */
             BOOT_CURR_IMG(state)++;
-        } else {
+	} else if (rc == BOOT_EBADIMAGE) {
             /* Cannot upgrade due to non-met dependencies, so disable all
              * image upgrades.
              */
@@ -1603,7 +1603,10 @@ boot_verify_dependencies(struct boot_loader_state *state)
                 BOOT_SWAP_TYPE(state) = BOOT_SWAP_TYPE_NONE;
             }
             break;
-        }
+	} else {
+	    /* Other error happened, images are inconsistent */
+		return rc;
+	}
     }
     return rc;
 }

From 3ab5fbb92f6bcfc8808a0cc160ec30f9b48af3a7 Mon Sep 17 00:00:00 2001
From: Georgios Vasilakis <georgios.vasilakis@nordicsemi.no>
Date: Mon, 8 Nov 2021 22:58:59 +0100
Subject: [PATCH 57/72] [nrf noup] zephyr: Set at least provide EXT_API

-This sets the provide EXT_API to be at least
 optional when the external_crypto is being used.

Ref: NCSDK-12021

Signed-off-by: Georgios Vasilakis <georgios.vasilakis@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit ec8b60d67fa4006ffdc377d1e0e011427a31d095)
---
 boot/zephyr/external_crypto.conf | 1 +
 1 file changed, 1 insertion(+)

diff --git a/boot/zephyr/external_crypto.conf b/boot/zephyr/external_crypto.conf
index 3ed56cc16..934a19720 100644
--- a/boot/zephyr/external_crypto.conf
+++ b/boot/zephyr/external_crypto.conf
@@ -18,3 +18,4 @@ CONFIG_SB_CRYPTO_CLIENT_ECDSA_SECP256R1=y
 CONFIG_SB_CRYPTO_CLIENT_SHA256=y
 CONFIG_BL_SHA256_EXT_API_REQUIRED=y
 CONFIG_BL_SECP256R1_EXT_API_REQUIRED=y
+CONFIG_EXT_API_PROVIDE_EXT_API_ATLEAST_OPTIONAL=y

From c56439c9793a5b700b534bf1f81b85d50efb83a6 Mon Sep 17 00:00:00 2001
From: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Date: Fri, 27 Nov 2020 15:30:50 +0100
Subject: [PATCH 58/72] [nrf noup] boot: zephyr: remove CONFIG_DEBUG=y in
 prj.conf
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This commit removes the `CONFIG_DEBUG=y` setting from Zephyr prj.conf
to save on flash size.

Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Johann Fischer <johann.fischer@nordicsemi.no>
Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 2dc0e40450470686af0d7d27b3caad0fbe4bdcb4)
---
 boot/zephyr/prj.conf | 1 -
 1 file changed, 1 deletion(-)

diff --git a/boot/zephyr/prj.conf b/boot/zephyr/prj.conf
index ec6ac9fa0..e14395b80 100644
--- a/boot/zephyr/prj.conf
+++ b/boot/zephyr/prj.conf
@@ -1,4 +1,3 @@
-CONFIG_DEBUG=y
 CONFIG_PM=n
 
 CONFIG_MAIN_STACK_SIZE=10240

From 542f51fc3361b554109f95350d0cffeef6913ca9 Mon Sep 17 00:00:00 2001
From: Georgios Vasilakis <georgios.vasilakis@nordicsemi.no>
Date: Fri, 4 Feb 2022 00:16:33 +0100
Subject: [PATCH 59/72] [nrf noup] boot: zephyr: Enable zeroize ALT func

-This enables the MBEDTLS_PLATFORM_ZEROIZE_ALT
 definition on Mbed TLS build of the MCUBOOT when
 the platform library is enabled. If not defined
 the Mbed TLS will compile the zeroize function
 and it will cause multiple definition errors.
 This is a noup because the configuration
 does not exist outside the sdk-nrf.

Ref: NCSDK-13503

Signed-off-by: Georgios Vasilakis <georgios.vasilakis@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit 6dfa1a125623cbcd80264762e77251bf8a7c1fdc)
---
 boot/zephyr/include/mcuboot-mbedtls-cfg.h | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/boot/zephyr/include/mcuboot-mbedtls-cfg.h b/boot/zephyr/include/mcuboot-mbedtls-cfg.h
index 02bf0b082..b89c95492 100644
--- a/boot/zephyr/include/mcuboot-mbedtls-cfg.h
+++ b/boot/zephyr/include/mcuboot-mbedtls-cfg.h
@@ -21,6 +21,16 @@
  * the simulator build.rs accordingly.
  */
 
+/*
+ * When the CC3XX_PLATFORM library is enabled we need to
+ * inform the Mbed TLS library to not compile the
+ * platform_zeroize function, otherwise we will get
+ * a multiple definitions error.
+ */
+#if defined(CONFIG_NRF_CC3XX_PLATFORM)
+#define MBEDTLS_PLATFORM_ZEROIZE_ALT
+#endif
+
 #if defined(CONFIG_BOOT_SIGNATURE_TYPE_RSA) || defined(CONFIG_BOOT_ENCRYPT_RSA)
 #include "config-rsa.h"
 #elif defined(CONFIG_BOOT_SIGNATURE_TYPE_ECDSA_P256) || \

From dbcdfae9ae7f8c32bfe59529a2473e611e4aa294 Mon Sep 17 00:00:00 2001
From: Damian Krolik <damian.krolik@nordicsemi.no>
Date: Mon, 21 Mar 2022 13:44:27 +0100
Subject: [PATCH 60/72] [nrf noup] Restore default RTC user channel count

The default value of CONFIG_NRF_RTC_TIMER_USER_CHAN_COUNT
for nRF52 SOCs has been changed from 0 to 3, but it makes
MCUBoot get stuck on erasing flash pages when swapping two
images. Restore the previous value until the RTC issue is
resolved (see NCSDK-14427)

Signed-off-by: Damian Krolik <damian.krolik@nordicsemi.no>
Signed-off-by: Torsten Rasmussen <Torsten.Rasmussen@nordicsemi.no>
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
(cherry picked from commit f8d7b0b0c91f8201efa60337133357baec746fed)
---
 boot/zephyr/prj.conf | 1 +
 1 file changed, 1 insertion(+)

diff --git a/boot/zephyr/prj.conf b/boot/zephyr/prj.conf
index e14395b80..9b8696e3f 100644
--- a/boot/zephyr/prj.conf
+++ b/boot/zephyr/prj.conf
@@ -34,3 +34,4 @@ CONFIG_LOG_MODE_MINIMAL=y # former CONFIG_MODE_MINIMAL
 CONFIG_LOG_DEFAULT_LEVEL=0
 ### Decrease footprint by ~4 KB in comparison to CBPRINTF_COMPLETE=y
 CONFIG_CBPRINTF_NANO=y
+CONFIG_NRF_RTC_TIMER_USER_CHAN_COUNT=0

From bf04817597a2c967ed0e686748234bea07fe9644 Mon Sep 17 00:00:00 2001
From: Marek Pieta <Marek.Pieta@nordicsemi.no>
Date: Tue, 13 Sep 2022 12:12:08 +0200
Subject: [PATCH 61/72] [nrf noup] boot: zephyr: Align serial recovery config
 on Thingy:91

Change removes the legacy configuration. The legacy configuration
became problematic, because GPIO DTS nodes no longer support labels
that were used to identify nodes in MCUboot. Therefore we need to
use GPIO DTS node name with the legacy approach.

The GPIO should be configured by board's DTS, which is simpler.

Jira: NCSDK-16550

Signed-off-by: Marek Pieta <Marek.Pieta@nordicsemi.no>
(cherry picked from commit bf00840a090f396ec1554968e19fa0e02c077d38)
---
 boot/zephyr/boards/thingy91_nrf52840.conf | 3 ---
 boot/zephyr/boards/thingy91_nrf9160.conf  | 3 ---
 2 files changed, 6 deletions(-)

diff --git a/boot/zephyr/boards/thingy91_nrf52840.conf b/boot/zephyr/boards/thingy91_nrf52840.conf
index 5a415cc62..c0d183401 100644
--- a/boot/zephyr/boards/thingy91_nrf52840.conf
+++ b/boot/zephyr/boards/thingy91_nrf52840.conf
@@ -19,9 +19,6 @@ CONFIG_UART_LINE_CTRL=y
 CONFIG_GPIO=y
 CONFIG_MCUBOOT_SERIAL=y
 CONFIG_BOOT_SERIAL_CDC_ACM=y
-CONFIG_BOOT_SERIAL_DETECT_PORT="GPIO_1"
-CONFIG_BOOT_SERIAL_DETECT_PIN=13
-CONFIG_BOOT_SERIAL_DETECT_PIN_VAL=0
 
 # Required by USB
 CONFIG_MULTITHREADING=y
diff --git a/boot/zephyr/boards/thingy91_nrf9160.conf b/boot/zephyr/boards/thingy91_nrf9160.conf
index 6e671a286..1bf2e424d 100644
--- a/boot/zephyr/boards/thingy91_nrf9160.conf
+++ b/boot/zephyr/boards/thingy91_nrf9160.conf
@@ -11,6 +11,3 @@ CONFIG_BOOT_MAX_IMG_SECTORS=256
 
 # MCUboot serial recovery
 CONFIG_MCUBOOT_SERIAL=y
-CONFIG_BOOT_SERIAL_DETECT_PORT="GPIO_0"
-CONFIG_BOOT_SERIAL_DETECT_PIN=26
-CONFIG_BOOT_SERIAL_DETECT_PIN_VAL=0

From 96fe9dd6c7ab672953d537175c6414e70965c7ab Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Andrzej=20G=C5=82=C4=85bek?= <andrzej.glabek@nordicsemi.no>
Date: Fri, 30 Sep 2022 18:05:18 +0200
Subject: [PATCH 62/72] [nrf fromtree] ext/nrf/cc310_glue.h: Update Zephyr
 include path
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Add `zephyr/` prefix to `<devicetree.h>`.

Signed-off-by: Andrzej Głąbek <andrzej.glabek@nordicsemi.no>
(cherry picked from commit 14e45ce9478b8b95a3d41aac6ba92a12569784c4)
---
 ext/nrf/cc310_glue.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/ext/nrf/cc310_glue.h b/ext/nrf/cc310_glue.h
index 0979cb7d9..aac41ae63 100644
--- a/ext/nrf/cc310_glue.h
+++ b/ext/nrf/cc310_glue.h
@@ -10,7 +10,7 @@
 #include <nrf_cc310_bl_init.h>
 #include <nrf_cc310_bl_hash_sha256.h>
 #include <nrf_cc310_bl_ecdsa_verify_secp256r1.h>
-#include <devicetree.h>
+#include <zephyr/devicetree.h>
 #include <string.h>
 
 /*

From 11c5149a7dd6c9f7581e971656bae461c135e31a Mon Sep 17 00:00:00 2001
From: Jamie McCrae <jamie.mccrae@nordicsemi.no>
Date: Wed, 30 Nov 2022 15:44:44 +0000
Subject: [PATCH 63/72] [nrf fromlist] boot_serial: Add unaligned stack buffer
 writing

Fixes a bug when writing to devices which have memory alignment
requirements with data being using directly from a zcbor-response
whereby the alignment of the buffer data does not meet the
requirements of the flash driver.

Upstream PR: https://github.com/mcu-tools/mcuboot/pull/1533

Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
---
 boot/boot_serial/src/boot_serial.c            | 31 +++++++++++++++++++
 boot/zephyr/Kconfig.serial_recovery           |  8 +++++
 .../include/mcuboot_config/mcuboot_config.h   |  4 +++
 3 files changed, 43 insertions(+)

diff --git a/boot/boot_serial/src/boot_serial.c b/boot/boot_serial/src/boot_serial.c
index 9a82804ea..3a322cf91 100644
--- a/boot/boot_serial/src/boot_serial.c
+++ b/boot/boot_serial/src/boot_serial.c
@@ -508,7 +508,38 @@ bs_upload(char *buf, int len)
 
     BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
     /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
+#if defined(MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE) && MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE > 0
+    if (flash_area_align(fap) > 1 &&
+        (((size_t)img_chunk) & (flash_area_align(fap) - 1)) != 0) {
+        /* Buffer address incompatible with write address, use buffer to write */
+        uint8_t write_size = MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE;
+        uint8_t wbs_aligned[MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE];
+
+        while (img_chunk_len >= flash_area_align(fap)) {
+            if (write_size > img_chunk_len) {
+                write_size = img_chunk_len;
+            }
+
+            memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
+            memcpy(wbs_aligned, img_chunk, write_size);
+
+            rc = flash_area_write(fap, curr_off, wbs_aligned, write_size);
+
+            if (rc != 0) {
+                break;
+            }
+
+            curr_off += write_size;
+            img_chunk += write_size;
+            img_chunk_len -= write_size;
+        }
+    } else {
+        rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
+    }
+#else
     rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
+#endif
+
     if (rc == 0 && rem_bytes) {
         /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
          * part, in the img_chunk_len - rem_bytes count bytes, has already been
diff --git a/boot/zephyr/Kconfig.serial_recovery b/boot/zephyr/Kconfig.serial_recovery
index eabebfaa2..c9781f81a 100644
--- a/boot/zephyr/Kconfig.serial_recovery
+++ b/boot/zephyr/Kconfig.serial_recovery
@@ -50,6 +50,14 @@ config MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD
 	  Note that 0 is default upload target when no explicit
 	  selection is done.
 
+config BOOT_SERIAL_UNALIGNED_BUFFER_SIZE
+	int "Stack buffer for unaligned memory writes"
+	default 64
+	help
+	  Specifies the stack usage for a buffer which is used for unaligned
+	  memory access when data is written to a device with memory alignment
+	  requirements. Set to 0 to disable.
+
 config BOOT_MAX_LINE_INPUT_LEN
 	int "Maximum command line length"
 	default 512
diff --git a/boot/zephyr/include/mcuboot_config/mcuboot_config.h b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
index db5d656dc..57e4aae82 100644
--- a/boot/zephyr/include/mcuboot_config/mcuboot_config.h
+++ b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
@@ -240,6 +240,10 @@
 #define MCUBOOT_MAX_IMG_SECTORS       128
 #endif
 
+#ifdef CONFIG_BOOT_SERIAL_UNALIGNED_BUFFER_SIZE
+#define MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE CONFIG_BOOT_SERIAL_UNALIGNED_BUFFER_SIZE
+#endif
+
 /* Support 32-byte aligned flash sizes */
 #if DT_HAS_CHOSEN(zephyr_flash)
     #if DT_PROP_OR(DT_CHOSEN(zephyr_flash), write_block_size, 0) > 8

From db3da7f4f3eefffb00d1900c231b84386eb5440e Mon Sep 17 00:00:00 2001
From: Jamie McCrae <jamie.mccrae@nordicsemi.no>
Date: Thu, 1 Dec 2022 14:24:37 +0000
Subject: [PATCH 64/72] [nrf fromlist] boot_serial: Allow using a buffer larger
 than 512 bytes

There are 3 levels of buffers and only the first one seems to be
configurable, this fixes that issue.

Upstream PR: https://github.com/mcu-tools/mcuboot/pull/1536

Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
---
 boot/boot_serial/src/boot_serial.c                  |  9 ++++++---
 boot/zephyr/Kconfig.serial_recovery                 | 10 ++++++++--
 boot/zephyr/include/mcuboot_config/mcuboot_config.h |  4 ++++
 3 files changed, 18 insertions(+), 5 deletions(-)

diff --git a/boot/boot_serial/src/boot_serial.c b/boot/boot_serial/src/boot_serial.c
index 3a322cf91..e8662d81e 100644
--- a/boot/boot_serial/src/boot_serial.c
+++ b/boot/boot_serial/src/boot_serial.c
@@ -78,7 +78,10 @@
 
 BOOT_LOG_MODULE_DECLARE(mcuboot);
 
-#define BOOT_SERIAL_INPUT_MAX   512
+#ifndef MCUBOOT_SERIAL_MAX_RECEIVE_SIZE
+#define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE 512
+#endif
+
 #define BOOT_SERIAL_OUT_MAX     (128 * BOOT_IMAGE_NUMBER)
 
 #ifdef __ZEPHYR__
@@ -107,8 +110,8 @@ BOOT_LOG_MODULE_DECLARE(mcuboot);
 #define IMAGES_ITER(x)
 #endif
 
-static char in_buf[BOOT_SERIAL_INPUT_MAX + 1];
-static char dec_buf[BOOT_SERIAL_INPUT_MAX + 1];
+static char in_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
+static char dec_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
 const struct boot_uart_funcs *boot_uf;
 static struct nmgr_hdr *bs_hdr;
 static bool bs_entry;
diff --git a/boot/zephyr/Kconfig.serial_recovery b/boot/zephyr/Kconfig.serial_recovery
index c9781f81a..7eb243c1e 100644
--- a/boot/zephyr/Kconfig.serial_recovery
+++ b/boot/zephyr/Kconfig.serial_recovery
@@ -59,10 +59,16 @@ config BOOT_SERIAL_UNALIGNED_BUFFER_SIZE
 	  requirements. Set to 0 to disable.
 
 config BOOT_MAX_LINE_INPUT_LEN
-	int "Maximum command line length"
+	int "Maximum input line length"
 	default 512
 	help
-	  Maximum length of commands transported over the serial port.
+	  Maximum length of input serial port buffer.
+
+config BOOT_SERIAL_MAX_RECEIVE_SIZE
+	int "Maximum command line length"
+	default 1024
+	help
+	  Maximum length of received commands via the serial port.
 
 config BOOT_SERIAL_DETECT_PORT
 	string "GPIO device to trigger serial recovery mode (DEPRECATED)"
diff --git a/boot/zephyr/include/mcuboot_config/mcuboot_config.h b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
index 57e4aae82..6b08bd271 100644
--- a/boot/zephyr/include/mcuboot_config/mcuboot_config.h
+++ b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
@@ -244,6 +244,10 @@
 #define MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE CONFIG_BOOT_SERIAL_UNALIGNED_BUFFER_SIZE
 #endif
 
+#ifdef CONFIG_BOOT_SERIAL_MAX_RECEIVE_SIZE
+#define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE CONFIG_BOOT_SERIAL_MAX_RECEIVE_SIZE
+#endif
+
 /* Support 32-byte aligned flash sizes */
 #if DT_HAS_CHOSEN(zephyr_flash)
     #if DT_PROP_OR(DT_CHOSEN(zephyr_flash), write_block_size, 0) > 8

From 78fd7ff9f31d88b9119734965e2afdda0cb9689a Mon Sep 17 00:00:00 2001
From: Jamie McCrae <jamie.mccrae@nordicsemi.no>
Date: Fri, 2 Dec 2022 09:24:10 +0000
Subject: [PATCH 65/72] [nrf fromlist] boot_serial: Fix rc not being returned
 as a signed value

Fixes an issue whereby rc is a signed variable but is returned as
an unsigned variable in the zcbor functions.

Upstream PR: https://github.com/mcu-tools/mcuboot/pull/1538

Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
---
 boot/boot_serial/src/boot_serial.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot/boot_serial/src/boot_serial.c b/boot/boot_serial/src/boot_serial.c
index e8662d81e..3759c8839 100644
--- a/boot/boot_serial/src/boot_serial.c
+++ b/boot/boot_serial/src/boot_serial.c
@@ -586,7 +586,7 @@ bs_upload(char *buf, int len)
     BOOT_LOG_INF("RX: 0x%x", rc);
     zcbor_map_start_encode(cbor_state, 10);
     zcbor_tstr_put_lit_cast(cbor_state, "rc");
-    zcbor_uint32_put(cbor_state, rc);
+    zcbor_int32_put(cbor_state, rc);
     if (rc == 0) {
         zcbor_tstr_put_lit_cast(cbor_state, "off");
         zcbor_uint32_put(cbor_state, curr_off);
@@ -612,7 +612,7 @@ bs_rc_rsp(int rc_code)
 {
     zcbor_map_start_encode(cbor_state, 10);
     zcbor_tstr_put_lit_cast(cbor_state, "rc");
-    zcbor_uint32_put(cbor_state, rc_code);
+    zcbor_int32_put(cbor_state, rc_code);
     zcbor_map_end_encode(cbor_state, 10);
     boot_serial_output();
 }

From 20f8d86f787331daa6812a32f12077189cebd31f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20B=C3=B8e?= <sebastian.boe@nordicsemi.no>
Date: Thu, 8 Dec 2022 16:43:56 +0100
Subject: [PATCH 66/72] [nrf noup] treewide: add NCS partition manager support
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

fixup! [nrf noup] treewide: add NCS partition manager support

The comment correctly states that we should skip the check for image
1, but the code skips validation for all images except image 0.

Today it is only supported for two images, 0 and 1, but in the future
it is expected that there might be an image 2, so we refactor this
code to make it future-proof.

Also, the comment was confusing and misleading so it has been
re-written.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
---
 boot/bootutil/src/loader.c | 13 +++++--------
 1 file changed, 5 insertions(+), 8 deletions(-)

diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
index 7d41d3818..a1fe9a5da 100644
--- a/boot/bootutil/src/loader.c
+++ b/boot/bootutil/src/loader.c
@@ -2269,15 +2269,12 @@ context_boot_go(struct boot_loader_state *state, struct boot_rsp *rsp)
 
 #ifdef MCUBOOT_VALIDATE_PRIMARY_SLOT
 #ifdef PM_S1_ADDRESS
-	/* Patch needed for NCS. If secure boot is enabled, then mcuboot
-	 * will be stored in either partition S0 or S1. Image 1 primary
-	 * will point to the 'other' Sx partition. Hence, image 1 primary
-	 * does not contain a valid image until mcuboot has been upgraded.
-	 * Note that B0 will perform validation of the active mcuboot image,
-	 * so there is no security lost by skipping this check for image 1
-	 * primary.
+	/* Patch needed for NCS. Image 1 primary is the currently
+	 * executing MCUBoot image, and is therefore already trusted and
+	 * does not need validation.
 	 */
-	if (BOOT_CURR_IMG(state) == 0)
+    bool image_needs_validation = BOOT_CURR_IMG(state) != 1;
+	if (image_needs_validation)
 #endif
 	{
             FIH_CALL(boot_validate_slot, fih_rc, state, BOOT_PRIMARY_SLOT, NULL);

From 7a3357e0dbc0e1ebde44690e98a4b6df317d3d84 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20B=C3=B8e?= <sebastian.boe@nordicsemi.no>
Date: Tue, 13 Dec 2022 11:29:38 +0100
Subject: [PATCH 67/72] [nrf noup] treewide: add NCS partition manager support
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

fixup! [nrf noup] treewide: add NCS partition manager support

It is more precise to note that it's NSIB that does the
validation. Also, this makes the comment more applicable to the fact
that we won't be updating the HW counters for this image.

Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
---
 boot/bootutil/src/loader.c | 18 +++++++++---------
 1 file changed, 9 insertions(+), 9 deletions(-)

diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
index a1fe9a5da..9b12bc01e 100644
--- a/boot/bootutil/src/loader.c
+++ b/boot/bootutil/src/loader.c
@@ -2269,19 +2269,19 @@ context_boot_go(struct boot_loader_state *state, struct boot_rsp *rsp)
 
 #ifdef MCUBOOT_VALIDATE_PRIMARY_SLOT
 #ifdef PM_S1_ADDRESS
-	/* Patch needed for NCS. Image 1 primary is the currently
-	 * executing MCUBoot image, and is therefore already trusted and
-	 * does not need validation.
-	 */
-    bool image_needs_validation = BOOT_CURR_IMG(state) != 1;
-	if (image_needs_validation)
-#endif
-	{
+        /* Patch needed for NCS. Image 1 primary is the currently
+         * executing MCUBoot image, and is therefore already validated by NSIB and
+         * does not need to also be validated by MCUBoot.
+         */
+        bool image_validated_by_nsib = BOOT_CURR_IMG(state) == 1;
+        if (!image_validated_by_nsib)
+#endif
+        {
             FIH_CALL(boot_validate_slot, fih_rc, state, BOOT_PRIMARY_SLOT, NULL);
             if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
                 goto out;
             }
-	}
+        }
 #else
         /* Even if we're not re-validating the primary slot, we could be booting
          * onto an empty flash chip. At least do a basic sanity check that

From 34b3ac78780f861fb6a6eeffa42e6c7242c4eec9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20B=C3=B8e?= <sebastian.boe@nordicsemi.no>
Date: Tue, 13 Dec 2022 11:30:50 +0100
Subject: [PATCH 68/72] [nrf noup] boot: zephyr: Skip updating sec counters for
 MCUBOOT
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Don't update security counters for the MCUBoot image as it is NSIB
that maintains a counter for this image.

Ref: NCSDK-9045

Signed-off-by: Georgios Vasilakis <georgios.vasilakis@nordicsemi.no>
Signed-off-by: Sebastian Bøe <sebastian.boe@nordicsemi.no>
---
 boot/bootutil/src/loader.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
index 9b12bc01e..3fa690a21 100644
--- a/boot/bootutil/src/loader.c
+++ b/boot/bootutil/src/loader.c
@@ -2296,10 +2296,15 @@ context_boot_go(struct boot_loader_state *state, struct boot_rsp *rsp)
         }
 #endif /* MCUBOOT_VALIDATE_PRIMARY_SLOT */
 
+#ifdef PM_S1_ADDRESS
+        if (!image_validated_by_nsib)
+#endif
+        {
         rc = boot_update_hw_rollback_protection(state);
         if (rc != 0) {
             goto out;
         }
+        }
 
         rc = boot_add_shared_data(state, BOOT_PRIMARY_SLOT);
         if (rc != 0) {

From 191a94694903761e17de9f70d5a2494a99f29915 Mon Sep 17 00:00:00 2001
From: Dominik Kilian <Dominik.Kilian@nordicsemi.no>
Date: Thu, 15 Dec 2022 15:23:29 +0100
Subject: [PATCH 69/72] [nrf noup] treewide: Fix old Nordic license ID

NCS has switch to the new license ID some time ago
from LicenseRef-BSD-5-Clause-Nordic to new (more
accurate) LicenseRef-Nordic-5-Clause. All source files
must be adjusted to the new name.

Ref: NCSIDB-717
Signed-off-by: Dominik Kilian <Dominik.Kilian@nordicsemi.no>
---
 boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf | 2 +-
 boot/zephyr/external_crypto.conf                         | 2 +-
 boot/zephyr/include/nrf_cleanup.h                        | 2 +-
 boot/zephyr/nrf_cleanup.c                                | 2 +-
 boot/zephyr/prj_minimal.conf                             | 2 +-
 5 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf b/boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf
index 11dd2ab68..dd5468106 100644
--- a/boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf
+++ b/boot/zephyr/boards/nrf5340dk_nrf5340_cpuapp_minimal.conf
@@ -1,7 +1,7 @@
 #
 # Copyright (c) 2021 Nordic Semiconductor ASA
 #
-# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+# SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
 #
 
 # CC3xx is currently not used for nrf53
diff --git a/boot/zephyr/external_crypto.conf b/boot/zephyr/external_crypto.conf
index 934a19720..c362f000a 100644
--- a/boot/zephyr/external_crypto.conf
+++ b/boot/zephyr/external_crypto.conf
@@ -1,7 +1,7 @@
 #
 # Copyright (c) 2021 Nordic Semiconductor ASA
 #
-# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+# SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
 #
 
 # These configurations should be used when using nrf/samples/bootloader
diff --git a/boot/zephyr/include/nrf_cleanup.h b/boot/zephyr/include/nrf_cleanup.h
index 2b175634e..6b04cedfe 100644
--- a/boot/zephyr/include/nrf_cleanup.h
+++ b/boot/zephyr/include/nrf_cleanup.h
@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2020 Nordic Semiconductor ASA
  *
- * SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+ * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
  */
 
 #ifndef H_NRF_CLEANUP_
diff --git a/boot/zephyr/nrf_cleanup.c b/boot/zephyr/nrf_cleanup.c
index a8fff30a8..5bab26b24 100644
--- a/boot/zephyr/nrf_cleanup.c
+++ b/boot/zephyr/nrf_cleanup.c
@@ -1,7 +1,7 @@
 /*
  * Copyright (c) 2020 Nordic Semiconductor ASA
  *
- * SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+ * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
  */
 
 #include <hal/nrf_clock.h>
diff --git a/boot/zephyr/prj_minimal.conf b/boot/zephyr/prj_minimal.conf
index c1a3a065d..719aa7055 100644
--- a/boot/zephyr/prj_minimal.conf
+++ b/boot/zephyr/prj_minimal.conf
@@ -1,7 +1,7 @@
 #
 # Copyright (c) 2021 Nordic Semiconductor ASA
 #
-# SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic
+# SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
 #
 
 CONFIG_MAIN_STACK_SIZE=10240

From 9d2f9b5742c5cabcb87b7f7f22ff5269b13403bf Mon Sep 17 00:00:00 2001
From: Dominik Ermel <dominik.ermel@nordicsemi.no>
Date: Mon, 19 Dec 2022 12:33:17 +0000
Subject: [PATCH 70/72] [nrf fromlist] zephyr: Missing header and definitions
 in boot_serial

... extensions

Moved group definitions to extension source code.

Upstream PR: https://github.com/mcu-tools/mcuboot/pull/1551

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
---
 boot/zephyr/boot_serial_extensions.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/boot/zephyr/boot_serial_extensions.c b/boot/zephyr/boot_serial_extensions.c
index de6e92389..954e40368 100644
--- a/boot/zephyr/boot_serial_extensions.c
+++ b/boot/zephyr/boot_serial_extensions.c
@@ -1,12 +1,11 @@
 /*
- * Copyright (c) 2021 Nordic Semiconductor ASA
+ * Copyright (c) 2021-2022 Nordic Semiconductor ASA
  *
  * SPDX-License-Identifier: Apache-2.0
  */
 
 #include <zephyr/kernel.h>
 #include <zephyr/drivers/flash.h>
-#include <zephyr/mgmt/mcumgr/zephyr_groups.h>
 
 #include <flash_map_backend/flash_map_backend.h>
 #include <sysflash/sysflash.h>
@@ -21,6 +20,9 @@
 
 BOOT_LOG_MODULE_DECLARE(mcuboot);
 
+#define ZEPHYR_MGMT_GRP_BASIC (MGMT_GROUP_ID_PERUSER - 1)
+#define ZEPHYR_MGMT_GRP_BASIC_CMD_ERASE_STORAGE 0
+
 #ifdef CONFIG_BOOT_MGMT_CUSTOM_STORAGE_ERASE
 static int bs_custom_storage_erase(zcbor_state_t *cs)
 {
@@ -140,7 +142,7 @@ int bs_peruser_system_specific(const struct nmgr_hdr *hdr, const char *buffer,
 {
     int mgmt_rc = MGMT_ERR_ENOTSUP;
 
-    if (hdr->nh_group == ZEPHYR_MGMT_GRP_BASE) {
+    if (hdr->nh_group == ZEPHYR_MGMT_GRP_BASIC) {
         if (hdr->nh_op == NMGR_OP_WRITE) {
 #ifdef CONFIG_BOOT_MGMT_CUSTOM_STORAGE_ERASE
             if (hdr->nh_id == ZEPHYR_MGMT_GRP_BASIC_CMD_ERASE_STORAGE) {

From 4f775a87611a084a2f6ad9a8a5034e080ddcc579 Mon Sep 17 00:00:00 2001
From: Joakim Andersson <joakim.andersson@nordicsemi.no>
Date: Tue, 13 Dec 2022 16:43:34 +0100
Subject: [PATCH 71/72] [nrf noup] treewide: Update comment to not mention SPM

fixup! [nrf noup] treewide: add NCS partition manager support

Update comment to not mention the removed SPM secure firmware solution.

Signed-off-by: Joakim Andersson <joakim.andersson@nordicsemi.no>
---
 boot/zephyr/pm.yml | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot/zephyr/pm.yml b/boot/zephyr/pm.yml
index 80ca3d946..125b8813c 100644
--- a/boot/zephyr/pm.yml
+++ b/boot/zephyr/pm.yml
@@ -64,8 +64,8 @@ mcuboot_scratch:
 # Padding placed before image to boot. This reserves space for the MCUboot image header
 # and it ensures that the boot image gets linked with the correct address offset in flash.
 mcuboot_pad:
-    # MCUboot pad must be placed before the 'spm' partition if that is present.
-    # If 'spm' partition is not present, it must be placed before the 'app'.
+    # MCUboot pad must be placed before the primary application partition.
+    # The primary application partition includes the secure firmware if present.
   size: CONFIG_PM_PARTITION_SIZE_MCUBOOT_PAD
   placement:
     before: [mcuboot_primary_app]

From 7147affd2561de7ac79117a0abce175cc4e4fcf2 Mon Sep 17 00:00:00 2001
From: Farhang <fjalilian@carmanah.com>
Date: Mon, 23 Jan 2023 16:41:47 -0800
Subject: [PATCH 72/72] fix: boot_set_confirmed_multi() ignores set/confirm
 command if "unset"

allow boot_set_confirmed_multi() to set mcuboot magic if "unset"
---
 boot/bootutil/src/bootutil_public.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/boot/bootutil/src/bootutil_public.c b/boot/bootutil/src/bootutil_public.c
index c567892da..04f8d80bf 100644
--- a/boot/bootutil/src/bootutil_public.c
+++ b/boot/bootutil/src/bootutil_public.c
@@ -618,8 +618,8 @@ boot_set_confirmed_multi(int image_index)
         break;
 
     case BOOT_MAGIC_UNSET:
-        /* Already confirmed. */
-        goto done;
+        /* Confirm needed; proceed. */
+        break;
 
     case BOOT_MAGIC_BAD:
         /* Unexpected state. */