1 /*
2  * Copyright (c) 2019 Leandro A. F. Pereira
3  * Copyright (c) 2020 Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <soc/efuse_reg.h>
9 #include <soc/reset_reasons.h>
10 #include "esp_system.h"
11 #include "rtc.h"
12 
13 #include <zephyr/drivers/hwinfo.h>
14 #include <string.h>
15 
z_impl_hwinfo_get_device_id(uint8_t * buffer,size_t length)16 ssize_t z_impl_hwinfo_get_device_id(uint8_t *buffer, size_t length)
17 {
18 #if !defined(CONFIG_SOC_SERIES_ESP32) && !defined(CONFIG_SOC_SERIES_ESP32_NET)
19 	uint32_t rdata1 = sys_read32(EFUSE_RD_MAC_SPI_SYS_0_REG);
20 	uint32_t rdata2 = sys_read32(EFUSE_RD_MAC_SPI_SYS_1_REG);
21 #else
22 	uint32_t rdata1 = sys_read32(EFUSE_BLK0_RDATA1_REG);
23 	uint32_t rdata2 = sys_read32(EFUSE_BLK0_RDATA2_REG);
24 #endif
25 	uint8_t id[6];
26 
27 	/* The first word provides the lower 32 bits of the MAC
28 	 * address; the low 16 bits of the second word provide the
29 	 * upper 16 bytes of the MAC address.  The upper 16 bits are
30 	 * (apparently) a checksum, and reserved.  See ESP32 Technical
31 	 * Reference Manual V4.1 section 20.5.
32 	 */
33 	id[0] = (uint8_t)(rdata2 >> 8);
34 	id[1] = (uint8_t)(rdata2 >> 0);
35 	id[2] = (uint8_t)(rdata1 >> 24);
36 	id[3] = (uint8_t)(rdata1 >> 16);
37 	id[4] = (uint8_t)(rdata1 >> 8);
38 	id[5] = (uint8_t)(rdata1 >> 0);
39 
40 	if (length > sizeof(id)) {
41 		length = sizeof(id);
42 	}
43 	memcpy(buffer, id, length);
44 
45 	return length;
46 }
47 
z_impl_hwinfo_get_supported_reset_cause(uint32_t * supported)48 int z_impl_hwinfo_get_supported_reset_cause(uint32_t *supported)
49 {
50 	*supported = (RESET_POR
51 		      | RESET_PIN
52 		      | RESET_SOFTWARE
53 		      | RESET_WATCHDOG
54 		      | RESET_LOW_POWER_WAKE
55 		      | RESET_CPU_LOCKUP
56 		      | RESET_BROWNOUT);
57 
58 	return 0;
59 }
60 
z_impl_hwinfo_get_reset_cause(uint32_t * cause)61 int z_impl_hwinfo_get_reset_cause(uint32_t *cause)
62 {
63 	uint32_t reason = esp_reset_reason();
64 
65 	switch (reason) {
66 	case ESP_RST_POWERON:
67 		*cause = RESET_POR;
68 		break;
69 	case ESP_RST_EXT:
70 		*cause = RESET_PIN;
71 		break;
72 	case ESP_RST_SW:
73 		*cause = RESET_SOFTWARE;
74 		break;
75 	case ESP_RST_INT_WDT:
76 	case ESP_RST_TASK_WDT:
77 	case ESP_RST_WDT:
78 		*cause = RESET_WATCHDOG;
79 		break;
80 	case ESP_RST_DEEPSLEEP:
81 		*cause = RESET_LOW_POWER_WAKE;
82 		break;
83 	case ESP_RST_PANIC:
84 		*cause = RESET_CPU_LOCKUP;
85 	case ESP_RST_BROWNOUT:
86 		*cause = RESET_BROWNOUT;
87 		break;
88 	default:
89 		*cause = 0;
90 		break;
91 	}
92 
93 	return 0;
94 }
95