1 /*
2 * Copyright (c) 2023 O.S.Systems
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_DECLARE(updatehub, CONFIG_UPDATEHUB_LOG_LEVEL);
9
10 #include <zephyr/dfu/mcuboot.h>
11
12 #include "updatehub_storage.h"
13
updatehub_storage_is_partition_good(struct updatehub_storage_context * ctx)14 int updatehub_storage_is_partition_good(struct updatehub_storage_context *ctx)
15 {
16 bool ret;
17
18 if (ctx == NULL) {
19 return -EINVAL;
20 }
21
22 ret = boot_is_img_confirmed() == 0;
23
24 return ret ? 0 : -EIO;
25 }
26
updatehub_storage_init(struct updatehub_storage_context * ctx,const uint32_t partition_id)27 int updatehub_storage_init(struct updatehub_storage_context *ctx,
28 const uint32_t partition_id)
29 {
30 if (ctx == NULL) {
31 return -EINVAL;
32 }
33
34 if (boot_erase_img_bank(partition_id)) {
35 return -EIO;
36 }
37
38 return flash_img_init(&ctx->flash_ctx);
39 }
40
updatehub_storage_write(struct updatehub_storage_context * ctx,const uint8_t * data,const size_t size,const bool flush)41 int updatehub_storage_write(struct updatehub_storage_context *ctx,
42 const uint8_t *data, const size_t size,
43 const bool flush)
44 {
45 if (ctx == NULL || (size > 0 && data == NULL)) {
46 return -EINVAL;
47 }
48
49 LOG_DBG("Flash: Address: 0x%08x, Size: %d, Flush: %s",
50 ctx->flash_ctx.stream.bytes_written, size,
51 flush ? "True" : "False");
52
53 return flash_img_buffered_write(&ctx->flash_ctx, data, size, flush);
54 }
55
updatehub_storage_check(struct updatehub_storage_context * ctx,const uint32_t partition_id,const uint8_t * hash,const size_t size)56 int updatehub_storage_check(struct updatehub_storage_context *ctx,
57 const uint32_t partition_id,
58 const uint8_t *hash, const size_t size)
59 {
60 if (ctx == NULL || hash == NULL || size == 0) {
61 return -EINVAL;
62 }
63
64 const struct flash_img_check fic = { .match = hash, .clen = size };
65
66 return flash_img_check(&ctx->flash_ctx, &fic, partition_id);
67 }
68
updatehub_storage_mark_partition_to_upgrade(struct updatehub_storage_context * ctx,const uint32_t partition_id)69 int updatehub_storage_mark_partition_to_upgrade(struct updatehub_storage_context *ctx,
70 const uint32_t partition_id)
71 {
72 if (ctx == NULL) {
73 return -EINVAL;
74 }
75
76 return boot_request_upgrade(BOOT_UPGRADE_TEST);
77 }
78
updatehub_storage_mark_partition_as_confirmed(const uint32_t partition_id)79 int updatehub_storage_mark_partition_as_confirmed(const uint32_t partition_id)
80 {
81 return boot_write_img_confirmed();
82 }
83