1 /*
2  * Copyright (c) 2021-2023 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdio.h>
8 #include <zephyr/kernel.h>
9 #include <zephyr/drivers/flash.h>
10 #include <zephyr/mgmt/mcumgr/mgmt/mgmt_defines.h>
11 #include <zephyr/mgmt/mcumgr/grp/zephyr/zephyr_basic.h>
12 #include <../subsys/mgmt/mcumgr/transport/include/mgmt/mcumgr/transport/smp_internal.h>
13 
14 #include <flash_map_backend/flash_map_backend.h>
15 #include <sysflash/sysflash.h>
16 
17 #include "bootutil/bootutil_log.h"
18 #include "../boot_serial/src/boot_serial_priv.h"
19 #include <zcbor_encode.h>
20 
21 #include "bootutil/image.h"
22 #include "bootutil/bootutil_public.h"
23 #include "bootutil/boot_hooks.h"
24 
25 #include <boot_serial/boot_serial_extensions.h>
26 
27 BOOT_LOG_MODULE_DECLARE(mcuboot);
28 
29 #ifdef CONFIG_BOOT_MGMT_CUSTOM_STORAGE_ERASE
bs_custom_storage_erase(const struct nmgr_hdr * hdr,const char * buffer,int len,zcbor_state_t * cs)30 static int bs_custom_storage_erase(const struct nmgr_hdr *hdr,
31                                    const char *buffer, int len,
32                                    zcbor_state_t *cs)
33 {
34     int rc;
35     const struct flash_area *fa;
36 
37     (void)buffer;
38     (void)len;
39 
40     if (hdr->nh_group != ZEPHYR_MGMT_GRP_BASIC || hdr->nh_op != NMGR_OP_WRITE ||
41         hdr->nh_id != ZEPHYR_MGMT_GRP_BASIC_CMD_ERASE_STORAGE) {
42         return MGMT_ERR_ENOTSUP;
43     }
44 
45     rc = flash_area_open(FIXED_PARTITION_ID(storage_partition), &fa);
46 
47     if (rc < 0) {
48         BOOT_LOG_ERR("failed to open flash area");
49     } else {
50         rc = flash_area_erase(fa, 0, flash_area_get_size(fa));
51         if (rc < 0) {
52             BOOT_LOG_ERR("failed to erase flash area");
53         }
54         flash_area_close(fa);
55     }
56     if (rc == 0) {
57         rc = MGMT_ERR_OK;
58     } else {
59         rc = MGMT_ERR_EUNKNOWN;
60     }
61 
62     zcbor_map_start_encode(cs, 10);
63     zcbor_tstr_put_lit(cs, "rc");
64     zcbor_uint32_put(cs, rc);
65     zcbor_map_end_encode(cs, 10);
66 
67     return rc;
68 }
69 
70 MCUMGR_HANDLER_DEFINE(storage_erase, bs_custom_storage_erase);
71 #endif
72