blob: 03c438c3e57e6f9997c44d3d05d6a71a64c8a6df [file] [log] [blame]
David Vincze060968d2019-05-23 01:13:14 +02001/*
2 * Copyright (c) 2019, Arm Limited. All rights reserved.
3 *
4 * SPDX-License-Identifier: BSD-3-Clause
5 *
6 */
7
8#include "../ext/mcuboot/include/security_cnt.h"
9#include "../../platform/include/tfm_plat_nv_counters.h"
10#include "../../platform/include/tfm_plat_defs.h"
11#include <stdint.h>
12
13#define TFM_BOOT_NV_COUNTER_0 PLAT_NV_COUNTER_3 /* NV counter of Image 0 */
14#define TFM_BOOT_NV_COUNTER_MAX PLAT_NV_COUNTER_MAX
15
16static enum tfm_nv_counter_t get_nv_counter_from_image_id(uint32_t image_id)
17{
18 uint32_t nv_counter;
19
20 /* Avoid integer overflow */
21 if ((UINT32_MAX - TFM_BOOT_NV_COUNTER_0) < image_id) {
22 return TFM_BOOT_NV_COUNTER_MAX;
23 }
24
25 nv_counter = TFM_BOOT_NV_COUNTER_0 + image_id;
26
27 /* Check the existence of the enumerated counter value */
28 if (nv_counter >= TFM_BOOT_NV_COUNTER_MAX) {
29 return TFM_BOOT_NV_COUNTER_MAX;
30 }
31
32 return (enum tfm_nv_counter_t)nv_counter;
33}
34
35int32_t boot_nv_security_counter_init(void)
36{
37 enum tfm_plat_err_t err;
38
39 err = tfm_plat_init_nv_counter();
40 if (err != TFM_PLAT_ERR_SUCCESS) {
41 return -1;
42 }
43
44 return 0;
45}
46
47int32_t boot_nv_security_counter_get(uint32_t image_id, uint32_t *security_cnt)
48{
49 enum tfm_nv_counter_t nv_counter;
50 enum tfm_plat_err_t err;
51
52 /* Check if it's a null-pointer. */
53 if (!security_cnt) {
54 return -1;
55 }
56
57 nv_counter = get_nv_counter_from_image_id(image_id);
58 if (nv_counter == TFM_BOOT_NV_COUNTER_MAX) {
59 return -1;
60 }
61
62 err = tfm_plat_read_nv_counter(nv_counter,
63 sizeof(*security_cnt),
64 (uint8_t *)security_cnt);
65 if (err != TFM_PLAT_ERR_SUCCESS) {
66 return -1;
67 }
68
69 return 0;
70}
71
72int32_t boot_nv_security_counter_update(uint32_t image_id,
73 uint32_t img_security_cnt)
74{
75 enum tfm_nv_counter_t nv_counter;
76 enum tfm_plat_err_t err;
77
78 nv_counter = get_nv_counter_from_image_id(image_id);
79 if (nv_counter == TFM_BOOT_NV_COUNTER_MAX) {
80 return -1;
81 }
82
83 err = tfm_plat_set_nv_counter(nv_counter, img_security_cnt);
84 if (err != TFM_PLAT_ERR_SUCCESS) {
85 return -1;
86 }
87
88 return 0;
89}