startup.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdint.h>
  7. #include <string.h>
  8. #include "esp_attr.h"
  9. #include "esp_err.h"
  10. #include "esp_system.h"
  11. #include "esp_log.h"
  12. #include "sdkconfig.h"
  13. #include "soc/soc_caps.h"
  14. #include "hal/wdt_hal.h"
  15. #include "hal/uart_types.h"
  16. #include "hal/uart_ll.h"
  17. #include "esp_system.h"
  18. #include "esp_log.h"
  19. #include "esp_heap_caps_init.h"
  20. #include "esp_spi_flash.h"
  21. #include "esp_flash_internal.h"
  22. #include "esp_newlib.h"
  23. #include "esp_vfs_dev.h"
  24. #include "esp_timer.h"
  25. #include "esp_efuse.h"
  26. #include "esp_flash_encrypt.h"
  27. #include "esp_secure_boot.h"
  28. #include "esp_sleep.h"
  29. #include "esp_xt_wdt.h"
  30. #if __has_include("esp_ota_ops.h")
  31. #include "esp_ota_ops.h"
  32. #define HAS_ESP_OTA 1
  33. #endif
  34. /***********************************************/
  35. // Headers for other components init functions
  36. #include "esp_coexist_internal.h"
  37. #if CONFIG_ESP_COREDUMP_ENABLE
  38. #include "esp_core_dump.h"
  39. #endif
  40. #if CONFIG_APPTRACE_ENABLE
  41. #include "esp_app_trace.h"
  42. #endif
  43. #include "esp_private/dbg_stubs.h"
  44. #if CONFIG_PM_ENABLE
  45. #include "esp_pm.h"
  46. #include "esp_private/pm_impl.h"
  47. #endif
  48. #include "esp_pthread.h"
  49. #include "esp_vfs_console.h"
  50. #include "esp_private/esp_clk.h"
  51. #include "esp_private/brownout.h"
  52. #include "esp_rom_sys.h"
  53. // [refactor-todo] make this file completely target-independent
  54. #if CONFIG_IDF_TARGET_ESP32
  55. #include "esp32/spiram.h"
  56. #elif CONFIG_IDF_TARGET_ESP32S2
  57. #include "esp32s2/spiram.h"
  58. #elif CONFIG_IDF_TARGET_ESP32S3
  59. #include "esp32s3/spiram.h"
  60. #endif
  61. /***********************************************/
  62. #include "esp_private/startup_internal.h"
  63. // Ensure that system configuration matches the underlying number of cores.
  64. // This should enable us to avoid checking for both everytime.
  65. #if !(SOC_CPU_CORES_NUM > 1) && !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  66. #error "System has been configured to run on multiple cores, but target SoC only has a single core."
  67. #endif
  68. uint64_t g_startup_time = 0;
  69. #if SOC_APB_BACKUP_DMA
  70. // APB DMA lock initialising API
  71. extern void esp_apb_backup_dma_lock_init(void);
  72. #endif
  73. // App entry point for core 0
  74. extern void esp_startup_start_app(void);
  75. // Entry point for core 0 from hardware init (port layer)
  76. void start_cpu0(void) __attribute__((weak, alias("start_cpu0_default"))) __attribute__((noreturn));
  77. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  78. // Entry point for core [1..X] from hardware init (port layer)
  79. void start_cpu_other_cores(void) __attribute__((weak, alias("start_cpu_other_cores_default"))) __attribute__((noreturn));
  80. // App entry point for core [1..X]
  81. void esp_startup_start_app_other_cores(void) __attribute__((weak, alias("esp_startup_start_app_other_cores_default"))) __attribute__((noreturn));
  82. static volatile bool s_system_inited[SOC_CPU_CORES_NUM] = { false };
  83. const sys_startup_fn_t g_startup_fn[SOC_CPU_CORES_NUM] = { [0] = start_cpu0,
  84. #if SOC_CPU_CORES_NUM > 1
  85. [1 ... SOC_CPU_CORES_NUM - 1] = start_cpu_other_cores
  86. #endif
  87. };
  88. static volatile bool s_system_full_inited = false;
  89. #else
  90. const sys_startup_fn_t g_startup_fn[1] = { start_cpu0 };
  91. #endif
  92. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  93. // workaround for C++ exception crashes
  94. void _Unwind_SetNoFunctionContextInstall(unsigned char enable) __attribute__((weak, alias("_Unwind_SetNoFunctionContextInstall_Default")));
  95. // workaround for C++ exception large memory allocation
  96. void _Unwind_SetEnableExceptionFdeSorting(unsigned char enable);
  97. static IRAM_ATTR void _Unwind_SetNoFunctionContextInstall_Default(unsigned char enable __attribute__((unused)))
  98. {
  99. (void)0;
  100. }
  101. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  102. static const char* TAG = "cpu_start";
  103. /**
  104. * This function overwrites a the same function of libsupc++ (part of libstdc++).
  105. * Consequently, libsupc++ will then follow our configured exception emergency pool size.
  106. *
  107. * It will be called even with -fno-exception for user code since the stdlib still uses exceptions.
  108. */
  109. size_t __cxx_eh_arena_size_get(void)
  110. {
  111. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  112. return CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE;
  113. #else
  114. return 0;
  115. #endif
  116. }
  117. /**
  118. * Xtensa gcc is configured to emit a .ctors section, RISC-V gcc is configured with --enable-initfini-array
  119. * so it emits an .init_array section instead.
  120. * But the init_priority sections will be sorted for iteration in ascending order during startup.
  121. * The rest of the init_array sections is sorted for iteration in descending order during startup, however.
  122. * Hence a different section is generated for the init_priority functions which is looped
  123. * over in ascending direction instead of descending direction.
  124. * The RISC-V-specific behavior is dependent on the linker script ld/esp32c3/sections.ld.in.
  125. */
  126. static void do_global_ctors(void)
  127. {
  128. #if __riscv
  129. extern void (*__init_priority_array_start)(void);
  130. extern void (*__init_priority_array_end)(void);
  131. #endif
  132. extern void (*__init_array_start)(void);
  133. extern void (*__init_array_end)(void);
  134. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  135. struct object { long placeholder[ 10 ]; };
  136. void __register_frame_info (const void *begin, struct object *ob);
  137. extern char __eh_frame[];
  138. static struct object ob;
  139. __register_frame_info( __eh_frame, &ob );
  140. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  141. void (**p)(void);
  142. #if __riscv
  143. for (p = &__init_priority_array_start; p < &__init_priority_array_end; ++p) {
  144. ESP_EARLY_LOGD(TAG, "calling init function: %p", *p);
  145. (*p)();
  146. }
  147. #endif
  148. for (p = &__init_array_end - 1; p >= &__init_array_start; --p) {
  149. ESP_EARLY_LOGD(TAG, "calling init function: %p", *p);
  150. (*p)();
  151. }
  152. }
  153. static void do_system_init_fn(void)
  154. {
  155. extern esp_system_init_fn_t _esp_system_init_fn_array_start;
  156. extern esp_system_init_fn_t _esp_system_init_fn_array_end;
  157. esp_system_init_fn_t *p;
  158. for (p = &_esp_system_init_fn_array_end - 1; p >= &_esp_system_init_fn_array_start; --p) {
  159. if (p->cores & BIT(cpu_hal_get_core_id())) {
  160. (*(p->fn))();
  161. }
  162. }
  163. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  164. s_system_inited[cpu_hal_get_core_id()] = true;
  165. #endif
  166. }
  167. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  168. static void esp_startup_start_app_other_cores_default(void)
  169. {
  170. while (1) {
  171. esp_rom_delay_us(UINT32_MAX);
  172. }
  173. }
  174. static void IRAM_ATTR start_cpu_other_cores_default(void)
  175. {
  176. do_system_init_fn();
  177. while (!s_system_full_inited) {
  178. esp_rom_delay_us(100);
  179. }
  180. esp_startup_start_app_other_cores();
  181. }
  182. #endif
  183. static void do_core_init(void)
  184. {
  185. /* Initialize heap allocator. WARNING: This *needs* to happen *after* the app cpu has booted.
  186. If the heap allocator is initialized first, it will put free memory linked list items into
  187. memory also used by the ROM. Starting the app cpu will let its ROM initialize that memory,
  188. corrupting those linked lists. Initializing the allocator *after* the app cpu has booted
  189. works around this problem.
  190. With SPI RAM enabled, there's a second reason: half of the SPI RAM will be managed by the
  191. app CPU, and when that is not up yet, the memory will be inaccessible and heap_caps_init may
  192. fail initializing it properly. */
  193. heap_caps_init();
  194. // When apptrace module is enabled, there will be SEGGER_SYSVIEW calls in the newlib init.
  195. // SEGGER_SYSVIEW relies on apptrace module
  196. // apptrace module uses esp_timer_get_time to determine timeout conditions.
  197. // esp_timer early initialization is required for esp_timer_get_time to work.
  198. esp_timer_early_init();
  199. esp_newlib_init();
  200. if (g_spiram_ok) {
  201. #if CONFIG_SPIRAM_BOOT_INIT && (CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC)
  202. esp_err_t r=esp_spiram_add_to_heapalloc();
  203. if (r != ESP_OK) {
  204. ESP_EARLY_LOGE(TAG, "External RAM could not be added to heap!");
  205. abort();
  206. }
  207. #if CONFIG_SPIRAM_USE_MALLOC
  208. heap_caps_malloc_extmem_enable(CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL);
  209. #endif
  210. #endif
  211. }
  212. #if CONFIG_ESP_BROWNOUT_DET
  213. // [refactor-todo] leads to call chain rtc_is_register (driver) -> esp_intr_alloc (esp32/esp32s2) ->
  214. // malloc (newlib) -> heap_caps_malloc (heap), so heap must be at least initialized
  215. esp_brownout_init();
  216. #endif
  217. esp_newlib_time_init();
  218. #if CONFIG_VFS_SUPPORT_IO
  219. // VFS console register.
  220. esp_err_t vfs_err = esp_vfs_console_register();
  221. assert(vfs_err == ESP_OK && "Failed to register vfs console");
  222. #endif
  223. #if defined(CONFIG_VFS_SUPPORT_IO) && !defined(CONFIG_ESP_CONSOLE_NONE)
  224. const static char *default_stdio_dev = "/dev/console/";
  225. esp_reent_init(_GLOBAL_REENT);
  226. _GLOBAL_REENT->_stdin = fopen(default_stdio_dev, "r");
  227. _GLOBAL_REENT->_stdout = fopen(default_stdio_dev, "w");
  228. _GLOBAL_REENT->_stderr = fopen(default_stdio_dev, "w");
  229. #else // defined(CONFIG_VFS_SUPPORT_IO) && !defined(CONFIG_ESP_CONSOLE_NONE)
  230. _REENT_SMALL_CHECK_INIT(_GLOBAL_REENT);
  231. #endif // defined(CONFIG_VFS_SUPPORT_IO) && !defined(CONFIG_ESP_CONSOLE_NONE)
  232. esp_err_t err __attribute__((unused));
  233. err = esp_pthread_init();
  234. assert(err == ESP_OK && "Failed to init pthread module!");
  235. spi_flash_init();
  236. /* init default OS-aware flash access critical section */
  237. spi_flash_guard_set(&g_flash_guard_default_ops);
  238. esp_flash_app_init();
  239. esp_err_t flash_ret = esp_flash_init_default_chip();
  240. assert(flash_ret == ESP_OK);
  241. (void)flash_ret;
  242. #ifdef CONFIG_EFUSE_VIRTUAL
  243. ESP_LOGW(TAG, "eFuse virtual mode is enabled. If Secure boot or Flash encryption is enabled then it does not provide any security. FOR TESTING ONLY!");
  244. #ifdef CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH
  245. const esp_partition_t *efuse_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_EFUSE_EM, NULL);
  246. if (efuse_partition) {
  247. esp_efuse_init_virtual_mode_in_flash(efuse_partition->address, efuse_partition->size);
  248. }
  249. #endif
  250. #endif
  251. #if CONFIG_SECURE_DISABLE_ROM_DL_MODE
  252. err = esp_efuse_disable_rom_download_mode();
  253. assert(err == ESP_OK && "Failed to disable ROM download mode");
  254. #endif
  255. #if CONFIG_SECURE_ENABLE_SECURE_ROM_DL_MODE
  256. err = esp_efuse_enable_rom_secure_download_mode();
  257. assert(err == ESP_OK && "Failed to enable Secure Download mode");
  258. #endif
  259. #if CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE
  260. esp_efuse_disable_basic_rom_console();
  261. #endif
  262. #ifdef CONFIG_SECURE_FLASH_ENC_ENABLED
  263. esp_flash_encryption_init_checks();
  264. #endif
  265. #if defined(CONFIG_SECURE_BOOT) || defined(CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT)
  266. // Note: in some configs this may read flash, so placed after flash init
  267. esp_secure_boot_init_checks();
  268. #endif
  269. #if CONFIG_ESP_XT_WDT
  270. esp_xt_wdt_config_t cfg = {
  271. .timeout = CONFIG_ESP_XT_WDT_TIMEOUT,
  272. .auto_backup_clk_enable = CONFIG_ESP_XT_WDT_BACKUP_CLK_ENABLE,
  273. };
  274. err = esp_xt_wdt_init(&cfg);
  275. assert(err == ESP_OK && "Failed to init xtwdt");
  276. #endif
  277. }
  278. static void do_secondary_init(void)
  279. {
  280. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  281. // The port layer transferred control to this function with other cores 'paused',
  282. // resume execution so that cores might execute component initialization functions.
  283. startup_resume_other_cores();
  284. #endif
  285. // Execute initialization functions esp_system_init_fn_t assigned to the main core. While
  286. // this is happening, all other cores are executing the initialization functions
  287. // assigned to them since they have been resumed already.
  288. do_system_init_fn();
  289. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  290. // Wait for all cores to finish secondary init.
  291. volatile bool system_inited = false;
  292. while (!system_inited) {
  293. system_inited = true;
  294. for (int i = 0; i < SOC_CPU_CORES_NUM; i++) {
  295. system_inited &= s_system_inited[i];
  296. }
  297. esp_rom_delay_us(100);
  298. }
  299. #endif
  300. }
  301. static void start_cpu0_default(void)
  302. {
  303. ESP_EARLY_LOGI(TAG, "Pro cpu start user code");
  304. int cpu_freq = esp_clk_cpu_freq();
  305. ESP_EARLY_LOGI(TAG, "cpu freq: %d Hz", cpu_freq);
  306. #if HAS_ESP_OTA // [refactor-todo] find a better way to handle this.
  307. // Display information about the current running image.
  308. if (LOG_LOCAL_LEVEL >= ESP_LOG_INFO) {
  309. const esp_app_desc_t *app_desc = esp_ota_get_app_description();
  310. ESP_EARLY_LOGI(TAG, "Application information:");
  311. #ifndef CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR
  312. ESP_EARLY_LOGI(TAG, "Project name: %s", app_desc->project_name);
  313. #endif
  314. #ifndef CONFIG_APP_EXCLUDE_PROJECT_VER_VAR
  315. ESP_EARLY_LOGI(TAG, "App version: %s", app_desc->version);
  316. #endif
  317. #ifdef CONFIG_BOOTLOADER_APP_SECURE_VERSION
  318. ESP_EARLY_LOGI(TAG, "Secure version: %d", app_desc->secure_version);
  319. #endif
  320. #ifdef CONFIG_APP_COMPILE_TIME_DATE
  321. ESP_EARLY_LOGI(TAG, "Compile time: %s %s", app_desc->date, app_desc->time);
  322. #endif
  323. char buf[17];
  324. esp_ota_get_app_elf_sha256(buf, sizeof(buf));
  325. ESP_EARLY_LOGI(TAG, "ELF file SHA256: %s...", buf);
  326. ESP_EARLY_LOGI(TAG, "ESP-IDF: %s", app_desc->idf_ver);
  327. }
  328. #endif //HAS_ESP_OTA
  329. // Initialize core components and services.
  330. do_core_init();
  331. // Execute constructors.
  332. do_global_ctors();
  333. // Execute init functions of other components; blocks
  334. // until all cores finish (when !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE).
  335. do_secondary_init();
  336. // Now that the application is about to start, disable boot watchdog
  337. #ifndef CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE
  338. wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
  339. wdt_hal_write_protect_disable(&rtc_wdt_ctx);
  340. wdt_hal_disable(&rtc_wdt_ctx);
  341. wdt_hal_write_protect_enable(&rtc_wdt_ctx);
  342. #endif
  343. #if SOC_CPU_CORES_NUM > 1 && !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  344. s_system_full_inited = true;
  345. #endif
  346. esp_startup_start_app();
  347. while (1);
  348. }
  349. IRAM_ATTR ESP_SYSTEM_INIT_FN(init_components0, BIT(0))
  350. {
  351. esp_timer_init();
  352. #if CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND && !CONFIG_PM_SLP_DISABLE_GPIO
  353. // Configure to isolate (disable the Input/Output/Pullup/Pulldown
  354. // function of the pin) all GPIO pins in sleep state
  355. esp_sleep_config_gpio_isolate();
  356. // Enable automatic switching of GPIO configuration
  357. esp_sleep_enable_gpio_switch(true);
  358. #endif
  359. #if CONFIG_APPTRACE_ENABLE
  360. esp_err_t err = esp_apptrace_init();
  361. assert(err == ESP_OK && "Failed to init apptrace module on PRO CPU!");
  362. #endif
  363. #if CONFIG_APPTRACE_SV_ENABLE
  364. SEGGER_SYSVIEW_Conf();
  365. #endif
  366. #if CONFIG_ESP_DEBUG_STUBS_ENABLE
  367. esp_dbg_stubs_init();
  368. #endif
  369. #if defined(CONFIG_PM_ENABLE)
  370. esp_pm_impl_init();
  371. #endif
  372. #if CONFIG_ESP_COREDUMP_ENABLE
  373. esp_core_dump_init();
  374. #endif
  375. #if SOC_APB_BACKUP_DMA
  376. esp_apb_backup_dma_lock_init();
  377. #endif
  378. #if CONFIG_SW_COEXIST_ENABLE || CONFIG_EXTERNAL_COEX_ENABLE
  379. esp_coex_adapter_register(&g_coex_adapter_funcs);
  380. coex_pre_init();
  381. #endif
  382. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  383. ESP_EARLY_LOGD(TAG, "Setting C++ exception workarounds.");
  384. _Unwind_SetNoFunctionContextInstall(1);
  385. _Unwind_SetEnableExceptionFdeSorting(0);
  386. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  387. }