1 /*
2  * Copyright (c) 2023, Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/devicetree.h>
9 #include <zephyr/retention/retention.h>
10 #include <zephyr/logging/log.h>
11 
12 LOG_MODULE_REGISTER(bootmode, CONFIG_RETENTION_LOG_LEVEL);
13 
14 static const struct device *boot_mode_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_boot_mode));
15 
bootmode_check(uint8_t boot_mode)16 int bootmode_check(uint8_t boot_mode)
17 {
18 	int rc;
19 
20 	rc = retention_is_valid(boot_mode_dev);
21 
22 	if (rc == 1 || rc == -ENOTSUP) {
23 		uint8_t stored_mode;
24 
25 		rc = retention_read(boot_mode_dev, 0, &stored_mode, sizeof(stored_mode));
26 
27 		/* Only check if modes match if there was no error, otherwise return the error */
28 		if (rc == 0) {
29 			if (stored_mode == boot_mode) {
30 				rc = 1;
31 			}
32 		}
33 	}
34 
35 	return rc;
36 }
37 
bootmode_set(uint8_t boot_mode)38 int bootmode_set(uint8_t boot_mode)
39 {
40 	return retention_write(boot_mode_dev, 0, &boot_mode, sizeof(boot_mode));
41 }
42 
bootmode_clear(void)43 int bootmode_clear(void)
44 {
45 	return retention_clear(boot_mode_dev);
46 }
47