zephyr: erase flash pages progressively

This commit adds the option to erase flash pages while receiving
the firmware, opposed to bulk-erasing the whole image area at
the beginning of the DFU process. This is required on some
hardware that has long erase times, to prevent a long wait
and possibly a timeout during DFU.

Signed-off-by: Emanuele Di Santo <emdi@nordicsemi.no>
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
diff --git a/boot/boot_serial/src/boot_serial.c b/boot/boot_serial/src/boot_serial.c
index 74ac828..b2be12b 100644
--- a/boot/boot_serial/src/boot_serial.c
+++ b/boot/boot_serial/src/boot_serial.c
@@ -212,6 +212,10 @@
     char name_str[8];
     const struct flash_area *fap = NULL;
     int rc;
+#ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
+    static off_t off_last = -1;
+    struct flash_sector sector;
+#endif
 
     memset(img_data, 0, sizeof(img_data));
 
@@ -323,10 +327,12 @@
         if (data_len > fap->fa_size) {
             goto out_invalid_data;
         }
+#ifndef CONFIG_BOOT_ERASE_PROGRESSIVELY
         rc = flash_area_erase(fap, 0, fap->fa_size);
         if (rc) {
             goto out_invalid_data;
         }
+#endif
         img_size = data_len;
     }
     if (off != curr_off) {
@@ -339,6 +345,25 @@
             img_blen -= rem_bytes;
         }
     }
+
+#ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
+    rc = flash_area_sector_from_off(curr_off + img_blen, &sector);
+    if (rc) {
+        BOOT_LOG_ERR("Unable to determine flash sector size");
+        goto out;
+    }
+    if (off_last != sector.fs_off) {
+        off_last = sector.fs_off;
+        BOOT_LOG_INF("Moving to sector 0x%x", sector.fs_off);
+        rc = flash_area_erase(fap, sector.fs_off, sector.fs_size);
+        if (rc) {
+            BOOT_LOG_ERR("Error %d while erasing sector", rc);
+            goto out;
+        }
+    }
+#endif
+
+    BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_blen);
     rc = flash_area_write(fap, curr_off, img_data, img_blen);
     if (rc == 0) {
         curr_off += img_blen;
@@ -346,6 +371,7 @@
     out_invalid_data:
         rc = MGMT_ERR_EINVAL;
     }
+
 out:
     BOOT_LOG_INF("RX: 0x%x", rc);
     cbor_encoder_create_map(&bs_root, &bs_rsp, CborIndefiniteLength);