startup.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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_heap_caps_init.h"
  18. #include "spi_flash_mmap.h"
  19. #include "esp_flash_internal.h"
  20. #include "esp_newlib.h"
  21. #include "esp_timer.h"
  22. #include "esp_efuse.h"
  23. #include "esp_flash_encrypt.h"
  24. #include "esp_secure_boot.h"
  25. #include "esp_xt_wdt.h"
  26. #include "esp_cpu.h"
  27. #include "esp_partition.h"
  28. /***********************************************/
  29. // Headers for other components init functions
  30. #if CONFIG_SW_COEXIST_ENABLE || CONFIG_EXTERNAL_COEX_ENABLE
  31. #include "esp_coexist_internal.h"
  32. #endif
  33. #if __has_include("esp_app_desc.h")
  34. #define WITH_APP_IMAGE_INFO
  35. #include "esp_app_desc.h"
  36. #endif
  37. #if CONFIG_ESP_COREDUMP_ENABLE
  38. #include "esp_core_dump.h"
  39. #endif
  40. #include "esp_private/dbg_stubs.h"
  41. #if CONFIG_PM_ENABLE
  42. #include "esp_pm.h"
  43. #include "esp_private/pm_impl.h"
  44. #endif
  45. #if CONFIG_VFS_SUPPORT_IO
  46. #include "esp_vfs_dev.h"
  47. #include "esp_vfs_console.h"
  48. #endif
  49. #include "esp_pthread.h"
  50. #include "esp_private/esp_clk.h"
  51. #include "esp_private/spi_flash_os.h"
  52. #include "esp_private/brownout.h"
  53. #include "esp_rom_caps.h"
  54. #include "esp_rom_sys.h"
  55. #if CONFIG_SPIRAM
  56. #include "esp_psram.h"
  57. #include "esp_private/esp_psram_extram.h"
  58. #endif
  59. #if CONFIG_IDF_RTOS_RTTHREAD
  60. #include "rtthread.h"
  61. #endif
  62. /***********************************************/
  63. #include "esp_private/startup_internal.h"
  64. // Ensure that system configuration matches the underlying number of cores.
  65. // This should enable us to avoid checking for both everytime.
  66. #if !(SOC_CPU_CORES_NUM > 1) && !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  67. #error "System has been configured to run on multiple cores, but target SoC only has a single core."
  68. #endif
  69. // Set efuse ROM_LOG_MODE on first boot
  70. //
  71. // For CONFIG_BOOT_ROM_LOG_ALWAYS_ON (default) or undefined (ESP32), leave
  72. // ROM_LOG_MODE undefined (no need to call this function during startup)
  73. #if CONFIG_BOOT_ROM_LOG_ALWAYS_OFF
  74. #define ROM_LOG_MODE ESP_EFUSE_ROM_LOG_ALWAYS_OFF
  75. #elif CONFIG_BOOT_ROM_LOG_ON_GPIO_LOW
  76. #define ROM_LOG_MODE ESP_EFUSE_ROM_LOG_ON_GPIO_LOW
  77. #elif CONFIG_BOOT_ROM_LOG_ON_GPIO_HIGH
  78. #define ROM_LOG_MODE ESP_EFUSE_ROM_LOG_ON_GPIO_HIGH
  79. #endif
  80. uint64_t g_startup_time = 0;
  81. #if SOC_APB_BACKUP_DMA
  82. // APB DMA lock initialising API
  83. extern void esp_apb_backup_dma_lock_init(void);
  84. #endif
  85. // App entry point for core 0
  86. extern void esp_startup_start_app(void);
  87. // Entry point for core 0 from hardware init (port layer)
  88. void start_cpu0(void) __attribute__((weak, alias("start_cpu0_default"))) __attribute__((noreturn));
  89. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  90. // Entry point for core [1..X] from hardware init (port layer)
  91. void start_cpu_other_cores(void) __attribute__((weak, alias("start_cpu_other_cores_default"))) __attribute__((noreturn));
  92. // App entry point for core [1..X]
  93. void esp_startup_start_app_other_cores(void) __attribute__((weak, alias("esp_startup_start_app_other_cores_default"))) __attribute__((noreturn));
  94. static volatile bool s_system_inited[SOC_CPU_CORES_NUM] = { false };
  95. const sys_startup_fn_t g_startup_fn[SOC_CPU_CORES_NUM] = { [0] = start_cpu0,
  96. #if SOC_CPU_CORES_NUM > 1
  97. [1 ... SOC_CPU_CORES_NUM - 1] = start_cpu_other_cores
  98. #endif
  99. };
  100. static volatile bool s_system_full_inited = false;
  101. #else
  102. const sys_startup_fn_t g_startup_fn[1] = { start_cpu0 };
  103. #endif
  104. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  105. // workaround for C++ exception crashes
  106. void _Unwind_SetNoFunctionContextInstall(unsigned char enable) __attribute__((weak, alias("_Unwind_SetNoFunctionContextInstall_Default")));
  107. // workaround for C++ exception large memory allocation
  108. void _Unwind_SetEnableExceptionFdeSorting(unsigned char enable);
  109. static IRAM_ATTR void _Unwind_SetNoFunctionContextInstall_Default(unsigned char enable __attribute__((unused)))
  110. {
  111. (void)0;
  112. }
  113. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  114. static const char* TAG = "cpu_start";
  115. /**
  116. * This function overwrites a the same function of libsupc++ (part of libstdc++).
  117. * Consequently, libsupc++ will then follow our configured exception emergency pool size.
  118. *
  119. * It will be called even with -fno-exception for user code since the stdlib still uses exceptions.
  120. */
  121. size_t __cxx_eh_arena_size_get(void)
  122. {
  123. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  124. return CONFIG_COMPILER_CXX_EXCEPTIONS_EMG_POOL_SIZE;
  125. #else
  126. return 0;
  127. #endif
  128. }
  129. /**
  130. * Xtensa gcc is configured to emit a .ctors section, RISC-V gcc is configured with --enable-initfini-array
  131. * so it emits an .init_array section instead.
  132. * But the init_priority sections will be sorted for iteration in ascending order during startup.
  133. * The rest of the init_array sections is sorted for iteration in descending order during startup, however.
  134. * Hence a different section is generated for the init_priority functions which is looped
  135. * over in ascending direction instead of descending direction.
  136. * The RISC-V-specific behavior is dependent on the linker script ld/esp32c3/sections.ld.in.
  137. */
  138. static void do_global_ctors(void)
  139. {
  140. #if __riscv
  141. extern void (*__init_priority_array_start)(void);
  142. extern void (*__init_priority_array_end)(void);
  143. #endif
  144. extern void (*__init_array_start)(void);
  145. extern void (*__init_array_end)(void);
  146. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  147. struct object { long placeholder[ 10 ]; };
  148. void __register_frame_info (const void *begin, struct object *ob);
  149. extern char __eh_frame[];
  150. static struct object ob;
  151. __register_frame_info( __eh_frame, &ob );
  152. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  153. void (**p)(void);
  154. #if __riscv
  155. for (p = &__init_priority_array_start; p < &__init_priority_array_end; ++p) {
  156. ESP_LOGD(TAG, "calling init function: %p", *p);
  157. (*p)();
  158. }
  159. #endif
  160. for (p = &__init_array_end - 1; p >= &__init_array_start; --p) {
  161. ESP_LOGD(TAG, "calling init function: %p", *p);
  162. (*p)();
  163. }
  164. }
  165. /**
  166. * @brief Call component init functions defined using ESP_SYSTEM_INIT_Fn macros.
  167. * The esp_system_init_fn_t structures describing these functions are collected into
  168. * an array [_esp_system_init_fn_array_start, _esp_system_init_fn_array_end) by the
  169. * linker. The functions are sorted by their priority value.
  170. * The sequence of the init function calls (sorted by priority) is documented in
  171. * system_init_fn.txt file.
  172. */
  173. static void do_system_init_fn(void)
  174. {
  175. extern esp_system_init_fn_t _esp_system_init_fn_array_start;
  176. extern esp_system_init_fn_t _esp_system_init_fn_array_end;
  177. esp_system_init_fn_t *p;
  178. int core_id = esp_cpu_get_core_id();
  179. for (p = &_esp_system_init_fn_array_start; p < &_esp_system_init_fn_array_end; ++p) {
  180. if (p->cores & BIT(core_id)) {
  181. ESP_LOGD(TAG, "calling init function: %p on core: %d", p->fn, core_id);
  182. esp_err_t err = (*(p->fn))();
  183. if (err != ESP_OK) {
  184. ESP_LOGE(TAG, "init function %p has failed (0x%x), aborting", p->fn, err);
  185. abort();
  186. }
  187. }
  188. }
  189. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  190. s_system_inited[core_id] = true;
  191. #endif
  192. }
  193. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  194. static void esp_startup_start_app_other_cores_default(void)
  195. {
  196. while (1) {
  197. esp_rom_delay_us(UINT32_MAX);
  198. }
  199. }
  200. /* This function has to be in IRAM, as while it is running on CPU1, CPU0 may do some flash operations
  201. * (e.g. initialize the core dump), which means that cache will be disabled.
  202. */
  203. static void IRAM_ATTR start_cpu_other_cores_default(void)
  204. {
  205. do_system_init_fn();
  206. while (!s_system_full_inited) {
  207. esp_rom_delay_us(100);
  208. }
  209. esp_startup_start_app_other_cores();
  210. }
  211. #endif
  212. static void do_core_init(void)
  213. {
  214. /* Initialize heap allocator. WARNING: This *needs* to happen *after* the app cpu has booted.
  215. If the heap allocator is initialized first, it will put free memory linked list items into
  216. memory also used by the ROM. Starting the app cpu will let its ROM initialize that memory,
  217. corrupting those linked lists. Initializing the allocator *after* the app cpu has booted
  218. works around this problem.
  219. With SPI RAM enabled, there's a second reason: half of the SPI RAM will be managed by the
  220. app CPU, and when that is not up yet, the memory will be inaccessible and heap_caps_init may
  221. fail initializing it properly. */
  222. heap_caps_init();
  223. #if CONFIG_IDF_RTOS_RTTHREAD && defined RT_USING_HEAP
  224. extern int __heap_start__;
  225. extern int __heap_end__;
  226. rt_system_heap_init((void *)&__heap_start__, (void *)&__heap_end__);
  227. #endif
  228. // When apptrace module is enabled, there will be SEGGER_SYSVIEW calls in the newlib init.
  229. // SEGGER_SYSVIEW relies on apptrace module
  230. // apptrace module uses esp_timer_get_time to determine timeout conditions.
  231. // esp_timer early initialization is required for esp_timer_get_time to work.
  232. esp_timer_early_init();
  233. esp_newlib_init();
  234. #if CONFIG_SPIRAM_BOOT_INIT && (CONFIG_SPIRAM_USE_CAPS_ALLOC || CONFIG_SPIRAM_USE_MALLOC)
  235. if (esp_psram_is_initialized()) {
  236. esp_err_t r=esp_psram_extram_add_to_heap_allocator();
  237. if (r != ESP_OK) {
  238. ESP_EARLY_LOGE(TAG, "External RAM could not be added to heap!");
  239. abort();
  240. }
  241. #if CONFIG_SPIRAM_USE_MALLOC
  242. heap_caps_malloc_extmem_enable(CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL);
  243. #endif
  244. }
  245. #endif
  246. #if CONFIG_ESP_BROWNOUT_DET
  247. // [refactor-todo] leads to call chain rtc_is_register (driver) -> esp_intr_alloc (esp32/esp32s2) ->
  248. // malloc (newlib) -> heap_caps_malloc (heap), so heap must be at least initialized
  249. esp_brownout_init();
  250. #endif
  251. esp_newlib_time_init();
  252. #if CONFIG_VFS_SUPPORT_IO
  253. // VFS console register.
  254. esp_err_t vfs_err = esp_vfs_console_register();
  255. assert(vfs_err == ESP_OK && "Failed to register vfs console");
  256. #endif
  257. #if defined(CONFIG_VFS_SUPPORT_IO) && !defined(CONFIG_ESP_CONSOLE_NONE)
  258. const static char *default_stdio_dev = "/dev/console/";
  259. esp_reent_init(_GLOBAL_REENT);
  260. _GLOBAL_REENT->_stdin = fopen(default_stdio_dev, "r");
  261. _GLOBAL_REENT->_stdout = fopen(default_stdio_dev, "w");
  262. _GLOBAL_REENT->_stderr = fopen(default_stdio_dev, "w");
  263. #if ESP_ROM_NEEDS_SWSETUP_WORKAROUND
  264. /*
  265. - This workaround for printf functions using 32-bit time_t after the 64-bit time_t upgrade
  266. - The 32-bit time_t usage is triggered through ROM Newlib functions printf related functions calling __swsetup_r() on
  267. the first call to a particular file pointer (i.e., stdin, stdout, stderr)
  268. - Thus, we call the toolchain version of __swsetup_r() now (before any printf calls are made) to setup all of the
  269. file pointers. Thus, the ROM newlib code will never call the ROM version of __swsetup_r().
  270. - See IDFGH-7728 for more details
  271. */
  272. extern int __swsetup_r(struct _reent *, FILE *);
  273. __swsetup_r(_GLOBAL_REENT, _GLOBAL_REENT->_stdout);
  274. __swsetup_r(_GLOBAL_REENT, _GLOBAL_REENT->_stderr);
  275. __swsetup_r(_GLOBAL_REENT, _GLOBAL_REENT->_stdin);
  276. #endif // ESP_ROM_NEEDS_SWSETUP_WORKAROUND
  277. #else // defined(CONFIG_VFS_SUPPORT_IO) && !defined(CONFIG_ESP_CONSOLE_NONE)
  278. _REENT_SMALL_CHECK_INIT(_GLOBAL_REENT);
  279. #endif // defined(CONFIG_VFS_SUPPORT_IO) && !defined(CONFIG_ESP_CONSOLE_NONE)
  280. esp_err_t err __attribute__((unused));
  281. err = esp_pthread_init();
  282. assert(err == ESP_OK && "Failed to init pthread module!");
  283. #if CONFIG_SPI_FLASH_ROM_IMPL
  284. spi_flash_rom_impl_init();
  285. #endif
  286. esp_flash_app_init();
  287. esp_err_t flash_ret = esp_flash_init_default_chip();
  288. assert(flash_ret == ESP_OK);
  289. (void)flash_ret;
  290. #if CONFIG_SPI_FLASH_BROWNOUT_RESET
  291. spi_flash_needs_reset_check();
  292. #endif // CONFIG_SPI_FLASH_BROWNOUT_RESET
  293. #ifdef CONFIG_EFUSE_VIRTUAL
  294. 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!");
  295. #ifdef CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH
  296. const esp_partition_t *efuse_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_EFUSE_EM, NULL);
  297. if (efuse_partition) {
  298. esp_efuse_init_virtual_mode_in_flash(efuse_partition->address, efuse_partition->size);
  299. }
  300. #endif
  301. #endif
  302. #if CONFIG_SECURE_DISABLE_ROM_DL_MODE
  303. err = esp_efuse_disable_rom_download_mode();
  304. assert(err == ESP_OK && "Failed to disable ROM download mode");
  305. #endif
  306. #if CONFIG_SECURE_ENABLE_SECURE_ROM_DL_MODE
  307. err = esp_efuse_enable_rom_secure_download_mode();
  308. assert(err == ESP_OK && "Failed to enable Secure Download mode");
  309. #endif
  310. #if CONFIG_ESP32_DISABLE_BASIC_ROM_CONSOLE
  311. esp_efuse_disable_basic_rom_console();
  312. #endif
  313. #ifdef CONFIG_SECURE_FLASH_ENC_ENABLED
  314. esp_flash_encryption_init_checks();
  315. #endif
  316. #if defined(CONFIG_SECURE_BOOT) || defined(CONFIG_SECURE_SIGNED_ON_UPDATE_NO_SECURE_BOOT)
  317. // Note: in some configs this may read flash, so placed after flash init
  318. esp_secure_boot_init_checks();
  319. #endif
  320. #ifdef ROM_LOG_MODE
  321. esp_efuse_set_rom_log_scheme(ROM_LOG_MODE);
  322. #endif
  323. #if CONFIG_ESP_XT_WDT
  324. esp_xt_wdt_config_t cfg = {
  325. .timeout = CONFIG_ESP_XT_WDT_TIMEOUT,
  326. .auto_backup_clk_enable = CONFIG_ESP_XT_WDT_BACKUP_CLK_ENABLE,
  327. };
  328. err = esp_xt_wdt_init(&cfg);
  329. assert(err == ESP_OK && "Failed to init xtwdt");
  330. #endif
  331. }
  332. static void do_secondary_init(void)
  333. {
  334. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  335. // The port layer transferred control to this function with other cores 'paused',
  336. // resume execution so that cores might execute component initialization functions.
  337. startup_resume_other_cores();
  338. #endif
  339. // Execute initialization functions esp_system_init_fn_t assigned to the main core. While
  340. // this is happening, all other cores are executing the initialization functions
  341. // assigned to them since they have been resumed already.
  342. do_system_init_fn();
  343. #if !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  344. // Wait for all cores to finish secondary init.
  345. volatile bool system_inited = false;
  346. while (!system_inited) {
  347. system_inited = true;
  348. for (int i = 0; i < SOC_CPU_CORES_NUM; i++) {
  349. system_inited &= s_system_inited[i];
  350. }
  351. esp_rom_delay_us(100);
  352. }
  353. #endif
  354. }
  355. static void start_cpu0_default(void)
  356. {
  357. ESP_EARLY_LOGI(TAG, "Pro cpu start user code");
  358. int cpu_freq = esp_clk_cpu_freq();
  359. ESP_EARLY_LOGI(TAG, "cpu freq: %d Hz", cpu_freq);
  360. #ifdef WITH_APP_IMAGE_INFO
  361. // Display information about the current running image.
  362. if (LOG_LOCAL_LEVEL >= ESP_LOG_INFO) {
  363. const esp_app_desc_t *app_desc = esp_app_get_description();
  364. ESP_EARLY_LOGI(TAG, "Application information:");
  365. #ifndef CONFIG_APP_EXCLUDE_PROJECT_NAME_VAR
  366. ESP_EARLY_LOGI(TAG, "Project name: %s", app_desc->project_name);
  367. #endif
  368. #ifndef CONFIG_APP_EXCLUDE_PROJECT_VER_VAR
  369. ESP_EARLY_LOGI(TAG, "App version: %s", app_desc->version);
  370. #endif
  371. #ifdef CONFIG_BOOTLOADER_APP_SECURE_VERSION
  372. ESP_EARLY_LOGI(TAG, "Secure version: %d", app_desc->secure_version);
  373. #endif
  374. #ifdef CONFIG_APP_COMPILE_TIME_DATE
  375. ESP_EARLY_LOGI(TAG, "Compile time: %s %s", app_desc->date, app_desc->time);
  376. #endif
  377. char buf[17];
  378. esp_app_get_elf_sha256(buf, sizeof(buf));
  379. ESP_EARLY_LOGI(TAG, "ELF file SHA256: %s...", buf);
  380. ESP_EARLY_LOGI(TAG, "ESP-IDF: %s", app_desc->idf_ver);
  381. }
  382. #endif
  383. // Initialize core components and services.
  384. do_core_init();
  385. // Execute constructors.
  386. do_global_ctors();
  387. // Execute init functions of other components; blocks
  388. // until all cores finish (when !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE).
  389. do_secondary_init();
  390. // Now that the application is about to start, disable boot watchdog
  391. #ifndef CONFIG_BOOTLOADER_WDT_DISABLE_IN_USER_CODE
  392. wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
  393. wdt_hal_write_protect_disable(&rtc_wdt_ctx);
  394. wdt_hal_disable(&rtc_wdt_ctx);
  395. wdt_hal_write_protect_enable(&rtc_wdt_ctx);
  396. #endif
  397. #if SOC_CPU_CORES_NUM > 1 && !CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE
  398. s_system_full_inited = true;
  399. #endif
  400. esp_startup_start_app();
  401. while (1);
  402. }
  403. ESP_SYSTEM_INIT_FN(init_components0, BIT(0), 200)
  404. {
  405. #if CONFIG_ESP_DEBUG_STUBS_ENABLE
  406. esp_dbg_stubs_init();
  407. #endif
  408. #if defined(CONFIG_PM_ENABLE)
  409. esp_pm_impl_init();
  410. #endif
  411. #if CONFIG_ESP_COREDUMP_ENABLE
  412. esp_core_dump_init();
  413. #endif
  414. #if SOC_APB_BACKUP_DMA
  415. esp_apb_backup_dma_lock_init();
  416. #endif
  417. #if CONFIG_SW_COEXIST_ENABLE || CONFIG_EXTERNAL_COEX_ENABLE
  418. esp_coex_adapter_register(&g_coex_adapter_funcs);
  419. coex_pre_init();
  420. #endif
  421. #ifdef CONFIG_COMPILER_CXX_EXCEPTIONS
  422. ESP_EARLY_LOGD(TAG, "Setting C++ exception workarounds.");
  423. _Unwind_SetNoFunctionContextInstall(1);
  424. _Unwind_SetEnableExceptionFdeSorting(0);
  425. #endif // CONFIG_COMPILER_CXX_EXCEPTIONS
  426. return ESP_OK;
  427. }