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 <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 
40 	bootloader_clock_configure();
41 
42 #ifdef CONFIG_ESP_CONSOLE
43 	/* initialize console, from now on, we can log */
44 	esp_console_init();
45 	print_banner();
46 #endif /* CONFIG_ESP_CONSOLE */
47 
48 	cache_hal_init();
49 
50 	mmu_hal_init();
51 
52 	/* Workaround: normal ROM bootloader exits with DROM0 cache unmasked, but 2nd bootloader
53 	 * exits with it masked.
54 	 */
55 	REG_CLR_BIT(EXTMEM_PRO_ICACHE_CTRL1_REG, EXTMEM_PRO_ICACHE_MASK_DROM0);
56 
57 	flash_update_id();
58 
59 	err = bootloader_flash_xmc_startup();
60 	if (err != 0) {
61 		ESP_EARLY_LOGE(TAG, "failed when running XMC startup flow, reboot!");
62 		return err;
63 	}
64 
65 	err = read_bootloader_header();
66 	if (err != 0) {
67 		return err;
68 	}
69 
70 	err = check_bootloader_validity();
71 	if (err != 0) {
72 		return err;
73 	}
74 
75 	err = init_spi_flash();
76 	if (err != 0) {
77 		return err;
78 	}
79 
80 	check_wdt_reset();
81 	config_wdt();
82 
83 	soc_random_enable();
84 
85 	return 0;
86 }
87