1 /*
2  * SPDX-FileCopyrightText: 2024-2025 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "hw_init.h"
8 #include <stdint.h>
9 #include <esp_cpu.h>
10 #include <soc/rtc.h>
11 #include <esp_rom_sys.h>
12 
13 #include <bootloader_clock.h>
14 #include <bootloader_flash.h>
15 #include <esp_flash_internal.h>
16 #include <esp_log.h>
17 
18 #include <console_init.h>
19 #include <flash_init.h>
20 #include <soc_flash_init.h>
21 #include <soc_init.h>
22 #include <soc_random.h>
23 
24 const static char *TAG = "hw_init";
25 
hardware_init(void)26 int hardware_init(void)
27 {
28 	int err = 0;
29 
30 #if XCHAL_ERRATUM_572
31 	uint32_t memctl = XCHAL_CACHE_MEMCTL_DEFAULT;
32 
33 	WSR(MEMCTL, memctl);
34 #endif /*XCHAL_ERRATUM_572*/
35 
36 #ifdef CONFIG_BOOTLOADER_REGION_PROTECTION_ENABLE
37 	esp_cpu_configure_region_protection();
38 #endif
39 #if CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V
40 	rtc_vddsdio_config_t cfg = rtc_vddsdio_get_config();
41 
42 	if (cfg.enable == 1 && cfg.tieh == RTC_VDDSDIO_TIEH_1_8V) {
43 		cfg.drefh = 3;
44 		cfg.drefm = 3;
45 		cfg.drefl = 3;
46 		cfg.force = 1;
47 		rtc_vddsdio_set_config(cfg);
48 		esp_rom_delay_us(10);
49 	}
50 #endif /* CONFIG_BOOTLOADER_VDDSDIO_BOOST_1_9V */
51 
52 	bootloader_clock_configure();
53 
54 #ifdef CONFIG_ESP_CONSOLE
55 	/* initialize console, from now on, we can log */
56 	esp_console_init();
57 	print_banner();
58 #endif /* CONFIG_ESP_CONSOLE */
59 
60 	reset_mmu();
61 
62 	flash_update_id();
63 
64 	err = bootloader_flash_xmc_startup();
65 	if (err != 0) {
66 		ESP_EARLY_LOGE(TAG, "failed when running XMC startup flow, reboot!");
67 		return err;
68 	}
69 
70 	err = read_bootloader_header();
71 	if (err != 0) {
72 		return err;
73 	}
74 
75 	err = check_bootloader_validity();
76 	if (err != 0) {
77 		return err;
78 	}
79 
80 	err = init_spi_flash();
81 	if (err != 0) {
82 		return err;
83 	}
84 
85 	check_wdt_reset();
86 	config_wdt();
87 
88 	soc_random_enable();
89 
90 	return 0;
91 }
92