zephyr: Add support for direct image upload

The commit enables direct image upload for the Zephyr platform.

Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
diff --git a/boot/zephyr/Kconfig b/boot/zephyr/Kconfig
index 0c11519..82fc143 100644
--- a/boot/zephyr/Kconfig
+++ b/boot/zephyr/Kconfig
@@ -493,6 +493,21 @@
 
 endchoice
 
+config MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD
+	bool "Allow to select image number for DFU"
+	help
+	  With the option enabled, the mcuboot serial recovery will
+	  respect the "image" field in mcumgr image update frame
+	  header.
+	  The mapping of image number to partition is as follows:
+	    0 -> default behaviour, same as 1;
+	    1 -> image-0 (primary slot of the first image);
+	    2 -> image-1 (secondary slot of the first image);
+	    3 -> image-2;
+	    4 -> image-3.
+	  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
diff --git a/boot/zephyr/flash_map_extended.c b/boot/zephyr/flash_map_extended.c
index e27c3c6..eb1e6bc 100644
--- a/boot/zephyr/flash_map_extended.c
+++ b/boot/zephyr/flash_map_extended.c
@@ -93,6 +93,30 @@
     return flash_area_id_to_multi_image_slot(0, area_id);
 }
 
+#if defined(CONFIG_MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
+int flash_area_id_from_direct_image(int image_id)
+{
+    switch (image_id) {
+    case 0:
+    case 1:
+        return FLASH_AREA_ID(image_0);
+#if DT_HAS_FIXED_PARTITION_LABEL(image_1)
+    case 2:
+        return FLASH_AREA_ID(image_1);
+#endif
+#if DT_HAS_FIXED_PARTITION_LABEL(image_2)
+    case 3:
+        return FLASH_AREA_ID(image_2);
+#endif
+#if DT_HAS_FIXED_PARTITION_LABEL(image_3)
+    case 4:
+        return FLASH_AREA_ID(image_3);
+#endif
+    }
+    return -EINVAL;
+}
+#endif
+
 int flash_area_sector_from_off(off_t off, struct flash_sector *sector)
 {
     int rc;
diff --git a/boot/zephyr/include/mcuboot_config/mcuboot_config.h b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
index 30e8ee9..3e4bd02 100644
--- a/boot/zephyr/include/mcuboot_config/mcuboot_config.h
+++ b/boot/zephyr/include/mcuboot_config/mcuboot_config.h
@@ -152,6 +152,14 @@
 #endif
 
 /*
+ * The configuration option enables direct image upload with the
+ * serial recovery.
+ */
+#ifdef CONFIG_MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD
+#define MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD
+#endif
+
+/*
  * Enabling this option uses newer flash map APIs. This saves RAM and
  * avoids deprecated API usage.
  *