1 /*
2  * SPDX-FileCopyrightText: 2024 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 <soc/extmem_reg.h>
12 #include <esp_rom_sys.h>
13 
14 #include <hal/cache_hal.h>
15 #include <hal/mmu_hal.h>
16 
17 #include <bootloader_clock.h>
18 #include <bootloader_flash.h>
19 #include <esp_flash_internal.h>
20 #include <esp_log.h>
21 
22 #include <console_init.h>
23 #include <flash_init.h>
24 #include <soc_flash_init.h>
25 #include <soc_init.h>
26 #include <soc_random.h>
27 
28 const static char *TAG = "hw_init";
29 
hardware_init(void)30 int hardware_init(void)
31 {
32 	int err = 0;
33 
34 	super_wdt_auto_feed();
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 	/* initialize console, from now on, we can log */
55 	esp_console_init();
56 	print_banner();
57 
58 	spi_flash_init_chip_state();
59 	err = esp_flash_init_default_chip();
60 	if (err != 0) {
61 		ESP_EARLY_LOGE(TAG, "Failed to init flash chip, error %d", err);
62 		return err;
63 	}
64 
65 	cache_hal_init();
66 	mmu_hal_init();
67 
68 	/* Workaround: normal ROM bootloader exits with DROM0 cache unmasked, but 2nd bootloader
69 	 * exits with it masked.
70 	 */
71 	REG_CLR_BIT(EXTMEM_PRO_ICACHE_CTRL1_REG, EXTMEM_PRO_ICACHE_MASK_DROM0);
72 
73 	flash_update_id();
74 
75 	err = bootloader_flash_xmc_startup();
76 	if (err != 0) {
77 		ESP_EARLY_LOGE(TAG, "failed when running XMC startup flow, reboot!");
78 		return err;
79 	}
80 
81 	err = read_bootloader_header();
82 	if (err != 0) {
83 		return err;
84 	}
85 
86 	err = check_bootloader_validity();
87 	if (err != 0) {
88 		return err;
89 	}
90 
91 	err = init_spi_flash();
92 	if (err != 0) {
93 		return err;
94 	}
95 
96 	check_wdt_reset();
97 	config_wdt();
98 
99 	soc_random_enable();
100 
101 	return 0;
102 }
103