sleep_modes.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stddef.h>
  7. #include <string.h>
  8. #include <sys/lock.h>
  9. #include <sys/param.h>
  10. #include "esp_attr.h"
  11. #include "esp_sleep.h"
  12. #include "esp_private/esp_timer_private.h"
  13. #include "esp_private/system_internal.h"
  14. #include "esp_log.h"
  15. #include "esp_newlib.h"
  16. #include "esp_timer.h"
  17. #include "esp_ipc_isr.h"
  18. #include "freertos/FreeRTOS.h"
  19. #include "freertos/task.h"
  20. #include "soc/soc_caps.h"
  21. #include "driver/rtc_io.h"
  22. #include "hal/rtc_io_hal.h"
  23. #include "driver/uart.h"
  24. #include "soc/cpu.h"
  25. #include "soc/rtc.h"
  26. #include "soc/soc_caps.h"
  27. #include "hal/wdt_hal.h"
  28. #include "hal/rtc_hal.h"
  29. #include "hal/uart_hal.h"
  30. #if SOC_TOUCH_SENSOR_NUM > 0
  31. #include "hal/touch_sensor_hal.h"
  32. #include "driver/touch_sensor.h"
  33. #include "driver/touch_sensor_common.h"
  34. #endif
  35. #include "hal/clk_gate_ll.h"
  36. #include "sdkconfig.h"
  37. #include "esp_rom_uart.h"
  38. #include "esp_rom_sys.h"
  39. #include "brownout.h"
  40. #include "esp_private/sleep_retention.h"
  41. #ifdef CONFIG_IDF_TARGET_ESP32
  42. #include "esp32/rom/cache.h"
  43. #include "esp32/rom/rtc.h"
  44. #include "esp32/clk.h"
  45. #include "esp_private/gpio.h"
  46. #include "esp_private/sleep_gpio.h"
  47. #elif CONFIG_IDF_TARGET_ESP32S2
  48. #include "esp32s2/clk.h"
  49. #include "esp32s2/rom/cache.h"
  50. #include "esp32s2/rom/rtc.h"
  51. #include "soc/extmem_reg.h"
  52. #include "esp_private/gpio.h"
  53. #elif CONFIG_IDF_TARGET_ESP32S3
  54. #include "esp32s3/clk.h"
  55. #include "esp32s3/rom/cache.h"
  56. #include "esp32s3/rom/rtc.h"
  57. #include "soc/extmem_reg.h"
  58. #include "esp_private/sleep_mac_bb.h"
  59. #elif CONFIG_IDF_TARGET_ESP32C3
  60. #include "esp32c3/clk.h"
  61. #include "esp32c3/rom/cache.h"
  62. #include "esp32c3/rom/rtc.h"
  63. #include "soc/extmem_reg.h"
  64. #include "esp_private/sleep_mac_bb.h"
  65. #elif CONFIG_IDF_TARGET_ESP32H2
  66. #include "esp32h2/clk.h"
  67. #include "esp32h2/rom/cache.h"
  68. #include "esp32h2/rom/rtc.h"
  69. #include "soc/extmem_reg.h"
  70. #endif
  71. // If light sleep time is less than that, don't power down flash
  72. #define FLASH_PD_MIN_SLEEP_TIME_US 2000
  73. // Time from VDD_SDIO power up to first flash read in ROM code
  74. #define VDD_SDIO_POWERUP_TO_FLASH_READ_US 700
  75. // Cycles for RTC Timer clock source (internal oscillator) calibrate
  76. #define RTC_CLK_SRC_CAL_CYCLES (10)
  77. #ifdef CONFIG_IDF_TARGET_ESP32
  78. #define DEFAULT_CPU_FREQ_MHZ CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ
  79. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (212)
  80. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (60)
  81. #elif CONFIG_IDF_TARGET_ESP32S2
  82. #define DEFAULT_CPU_FREQ_MHZ CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ
  83. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (147)
  84. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (28)
  85. #elif CONFIG_IDF_TARGET_ESP32S3
  86. #define DEFAULT_CPU_FREQ_MHZ CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ
  87. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (382)
  88. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (133)
  89. #elif CONFIG_IDF_TARGET_ESP32C3
  90. #define DEFAULT_CPU_FREQ_MHZ CONFIG_ESP32C3_DEFAULT_CPU_FREQ_MHZ
  91. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (105)
  92. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (37)
  93. #elif CONFIG_IDF_TARGET_ESP32H2
  94. #define DEFAULT_CPU_FREQ_MHZ CONFIG_ESP32H2_DEFAULT_CPU_FREQ_MHZ
  95. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (105)
  96. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (37)
  97. #endif
  98. #define LIGHT_SLEEP_TIME_OVERHEAD_US DEFAULT_HARDWARE_OUT_OVERHEAD_US
  99. #ifdef CONFIG_ESP_SYSTEM_RTC_EXT_XTAL
  100. #define DEEP_SLEEP_TIME_OVERHEAD_US (650 + 100 * 240 / DEFAULT_CPU_FREQ_MHZ)
  101. #else
  102. #define DEEP_SLEEP_TIME_OVERHEAD_US (250 + 100 * 240 / DEFAULT_CPU_FREQ_MHZ)
  103. #endif
  104. #if defined(CONFIG_IDF_TARGET_ESP32) && defined(CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY)
  105. #define DEEP_SLEEP_WAKEUP_DELAY CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY
  106. #elif defined(CONFIG_IDF_TARGET_ESP32S3) && defined(CONFIG_ESP32S3_DEEP_SLEEP_WAKEUP_DELAY)
  107. #define DEEP_SLEEP_WAKEUP_DELAY CONFIG_ESP32S3_DEEP_SLEEP_WAKEUP_DELAY
  108. #else
  109. #define DEEP_SLEEP_WAKEUP_DELAY 0
  110. #endif
  111. extern void periph_inform_out_light_sleep_overhead(uint32_t out_light_sleep_time);
  112. // Minimal amount of time we can sleep for
  113. #define LIGHT_SLEEP_MIN_TIME_US 200
  114. #define RTC_MODULE_SLEEP_PREPARE_CYCLES (6)
  115. #define CHECK_SOURCE(source, value, mask) ((s_config.wakeup_triggers & mask) && \
  116. (source == value))
  117. /**
  118. * Internal structure which holds all requested deep sleep parameters
  119. */
  120. typedef struct {
  121. esp_sleep_pd_option_t pd_options[ESP_PD_DOMAIN_MAX];
  122. uint64_t sleep_duration;
  123. uint32_t wakeup_triggers : 15;
  124. uint32_t ext1_trigger_mode : 1;
  125. uint32_t ext1_rtc_gpio_mask : 18;
  126. uint32_t ext0_trigger_level : 1;
  127. uint32_t ext0_rtc_gpio_num : 5;
  128. uint32_t gpio_wakeup_mask : 6;
  129. uint32_t gpio_trigger_mode : 6;
  130. uint32_t sleep_time_adjustment;
  131. uint32_t ccount_ticks_record;
  132. uint32_t sleep_time_overhead_out;
  133. uint32_t rtc_clk_cal_period;
  134. uint64_t rtc_ticks_at_sleep_start;
  135. } sleep_config_t;
  136. static sleep_config_t s_config = {
  137. .pd_options = {
  138. ESP_PD_OPTION_AUTO, ESP_PD_OPTION_AUTO, ESP_PD_OPTION_AUTO, ESP_PD_OPTION_AUTO,
  139. #if SOC_PM_SUPPORT_CPU_PD
  140. ESP_PD_OPTION_AUTO,
  141. #endif
  142. ESP_PD_OPTION_AUTO, ESP_PD_OPTION_AUTO
  143. },
  144. .ccount_ticks_record = 0,
  145. .sleep_time_overhead_out = DEFAULT_SLEEP_OUT_OVERHEAD_US,
  146. .wakeup_triggers = 0
  147. };
  148. /* Internal variable used to track if light sleep wakeup sources are to be
  149. expected when determining wakeup cause. */
  150. static bool s_light_sleep_wakeup = false;
  151. /* Updating RTC_MEMORY_CRC_REG register via set_rtc_memory_crc()
  152. is not thread-safe, so we need to disable interrupts before going to deep sleep. */
  153. static portMUX_TYPE spinlock_rtc_deep_sleep = portMUX_INITIALIZER_UNLOCKED;
  154. static const char *TAG = "sleep";
  155. static uint32_t get_power_down_flags(void);
  156. #if SOC_PM_SUPPORT_EXT_WAKEUP
  157. static void ext0_wakeup_prepare(void);
  158. static void ext1_wakeup_prepare(void);
  159. #endif
  160. static void timer_wakeup_prepare(void);
  161. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  162. static void touch_wakeup_prepare(void);
  163. #endif
  164. #if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  165. static void esp_deep_sleep_wakeup_prepare(void);
  166. #endif
  167. #if SOC_PM_SUPPORT_DEEPSLEEP_VERIFY_STUB_ONLY
  168. static RTC_FAST_ATTR esp_deep_sleep_wake_stub_fn_t wake_stub_fn_handler = NULL;
  169. static void RTC_IRAM_ATTR __attribute__((used, noinline)) esp_wake_stub_start(void)
  170. {
  171. if (wake_stub_fn_handler) {
  172. (*wake_stub_fn_handler)();
  173. }
  174. }
  175. /* We must have a default deep sleep wake stub entry function, which must be
  176. * located at the start address of the RTC fast memory, and its implementation
  177. * must be simple enough to ensure that there is no litteral data before the
  178. * wake stub entry, otherwise, the litteral data before the wake stub entry
  179. * will not be CRC checked. */
  180. static void __attribute__((section(".rtc.entry.text"))) esp_wake_stub_entry(void)
  181. {
  182. #define _SYM2STR(s) # s
  183. #define SYM2STR(s) _SYM2STR(s)
  184. // call4 has a larger effective addressing range (-524284 to 524288 bytes),
  185. // which is sufficient for instruction addressing in RTC fast memory.
  186. __asm__ __volatile__ ("call4 " SYM2STR(esp_wake_stub_start) "\n");
  187. }
  188. #endif // SOC_PM_SUPPORT_DEEPSLEEP_VERIFY_STUB_ONLY
  189. /* Wake from deep sleep stub
  190. See esp_deepsleep.h esp_wake_deep_sleep() comments for details.
  191. */
  192. esp_deep_sleep_wake_stub_fn_t esp_get_deep_sleep_wake_stub(void)
  193. {
  194. #if SOC_PM_SUPPORT_DEEPSLEEP_VERIFY_STUB_ONLY
  195. esp_deep_sleep_wake_stub_fn_t stub_ptr = wake_stub_fn_handler;
  196. #else
  197. esp_deep_sleep_wake_stub_fn_t stub_ptr = (esp_deep_sleep_wake_stub_fn_t) REG_READ(RTC_ENTRY_ADDR_REG);
  198. #endif
  199. if (!esp_ptr_executable(stub_ptr)) {
  200. return NULL;
  201. }
  202. return stub_ptr;
  203. }
  204. void esp_set_deep_sleep_wake_stub(esp_deep_sleep_wake_stub_fn_t new_stub)
  205. {
  206. #if SOC_PM_SUPPORT_DEEPSLEEP_VERIFY_STUB_ONLY
  207. wake_stub_fn_handler = new_stub;
  208. #else
  209. REG_WRITE(RTC_ENTRY_ADDR_REG, (uint32_t)new_stub);
  210. #endif
  211. }
  212. void RTC_IRAM_ATTR esp_default_wake_deep_sleep(void)
  213. {
  214. /* Clear MMU for CPU 0 */
  215. #if CONFIG_IDF_TARGET_ESP32
  216. _DPORT_REG_WRITE(DPORT_PRO_CACHE_CTRL1_REG,
  217. _DPORT_REG_READ(DPORT_PRO_CACHE_CTRL1_REG) | DPORT_PRO_CACHE_MMU_IA_CLR);
  218. _DPORT_REG_WRITE(DPORT_PRO_CACHE_CTRL1_REG,
  219. _DPORT_REG_READ(DPORT_PRO_CACHE_CTRL1_REG) & (~DPORT_PRO_CACHE_MMU_IA_CLR));
  220. #if DEEP_SLEEP_WAKEUP_DELAY > 0
  221. // ROM code has not started yet, so we need to set delay factor
  222. // used by esp_rom_delay_us first.
  223. ets_update_cpu_frequency_rom(ets_get_detected_xtal_freq() / 1000000);
  224. // This delay is configured in menuconfig, it can be used to give
  225. // the flash chip some time to become ready.
  226. esp_rom_delay_us(DEEP_SLEEP_WAKEUP_DELAY);
  227. #endif
  228. #elif CONFIG_IDF_TARGET_ESP32S2
  229. REG_SET_BIT(EXTMEM_CACHE_DBG_INT_ENA_REG, EXTMEM_CACHE_DBG_EN);
  230. #endif
  231. }
  232. void __attribute__((weak, alias("esp_default_wake_deep_sleep"))) esp_wake_deep_sleep(void);
  233. void esp_deep_sleep(uint64_t time_in_us)
  234. {
  235. esp_sleep_enable_timer_wakeup(time_in_us);
  236. esp_deep_sleep_start();
  237. }
  238. // [refactor-todo] provide target logic for body of uart functions below
  239. static void IRAM_ATTR flush_uarts(void)
  240. {
  241. for (int i = 0; i < SOC_UART_NUM; ++i) {
  242. #ifdef CONFIG_IDF_TARGET_ESP32
  243. esp_rom_uart_tx_wait_idle(i);
  244. #else
  245. if (periph_ll_periph_enabled(PERIPH_UART0_MODULE + i)) {
  246. esp_rom_uart_tx_wait_idle(i);
  247. }
  248. #endif
  249. }
  250. }
  251. static void IRAM_ATTR suspend_uarts(void)
  252. {
  253. for (int i = 0; i < SOC_UART_NUM; ++i) {
  254. #ifndef CONFIG_IDF_TARGET_ESP32
  255. if (!periph_ll_periph_enabled(PERIPH_UART0_MODULE + i)) {
  256. continue;
  257. }
  258. #endif
  259. uart_ll_force_xoff(i);
  260. #if SOC_UART_SUPPORT_FSM_TX_WAIT_SEND
  261. uint32_t uart_fsm = 0;
  262. do {
  263. uart_fsm = uart_ll_get_fsm_status(i);
  264. } while (!(uart_fsm == UART_LL_FSM_IDLE || uart_fsm == UART_LL_FSM_TX_WAIT_SEND));
  265. #else
  266. while (uart_ll_get_fsm_status(i) != 0) {}
  267. #endif
  268. }
  269. }
  270. static void IRAM_ATTR resume_uarts(void)
  271. {
  272. for (int i = 0; i < SOC_UART_NUM; ++i) {
  273. #ifndef CONFIG_IDF_TARGET_ESP32
  274. if (!periph_ll_periph_enabled(PERIPH_UART0_MODULE + i)) {
  275. continue;
  276. }
  277. #endif
  278. uart_ll_force_xon(i);
  279. }
  280. }
  281. inline static void IRAM_ATTR misc_modules_sleep_prepare(void)
  282. {
  283. #if CONFIG_MAC_BB_PD
  284. mac_bb_power_down_cb_execute();
  285. #endif
  286. #if CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL
  287. gpio_sleep_mode_config_apply();
  288. #endif
  289. #if SOC_PM_SUPPORT_CPU_PD || SOC_PM_SUPPORT_TAGMEM_PD
  290. sleep_enable_memory_retention();
  291. #endif
  292. }
  293. inline static void IRAM_ATTR misc_modules_wake_prepare(void)
  294. {
  295. #if SOC_PM_SUPPORT_CPU_PD || SOC_PM_SUPPORT_TAGMEM_PD
  296. sleep_disable_memory_retention();
  297. #endif
  298. #if CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL
  299. gpio_sleep_mode_config_unapply();
  300. #endif
  301. #if CONFIG_MAC_BB_PD
  302. mac_bb_power_up_cb_execute();
  303. #endif
  304. }
  305. inline static uint32_t IRAM_ATTR call_rtc_sleep_start(uint32_t reject_triggers, uint32_t lslp_mem_inf_fpu);
  306. static uint32_t IRAM_ATTR esp_sleep_start(uint32_t pd_flags)
  307. {
  308. // Stop UART output so that output is not lost due to APB frequency change.
  309. // For light sleep, suspend UART output — it will resume after wakeup.
  310. // For deep sleep, wait for the contents of UART FIFO to be sent.
  311. bool deep_sleep = pd_flags & RTC_SLEEP_PD_DIG;
  312. if (deep_sleep) {
  313. flush_uarts();
  314. } else {
  315. suspend_uarts();
  316. }
  317. // Save current frequency and switch to XTAL
  318. rtc_cpu_freq_config_t cpu_freq_config;
  319. rtc_clk_cpu_freq_get_config(&cpu_freq_config);
  320. rtc_clk_cpu_freq_set_xtal();
  321. #if SOC_PM_SUPPORT_EXT_WAKEUP
  322. // Configure pins for external wakeup
  323. if (s_config.wakeup_triggers & RTC_EXT0_TRIG_EN) {
  324. ext0_wakeup_prepare();
  325. }
  326. if (s_config.wakeup_triggers & RTC_EXT1_TRIG_EN) {
  327. ext1_wakeup_prepare();
  328. }
  329. #endif
  330. #if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  331. if (s_config.wakeup_triggers & RTC_GPIO_TRIG_EN) {
  332. esp_deep_sleep_wakeup_prepare();
  333. }
  334. #endif
  335. #ifdef CONFIG_IDF_TARGET_ESP32
  336. // Enable ULP wakeup
  337. if (s_config.wakeup_triggers & RTC_ULP_TRIG_EN) {
  338. rtc_hal_ulp_wakeup_enable();
  339. }
  340. #endif
  341. if (!deep_sleep) {
  342. misc_modules_sleep_prepare();
  343. }
  344. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  345. if (deep_sleep) {
  346. if (s_config.wakeup_triggers & RTC_TOUCH_TRIG_EN) {
  347. touch_wakeup_prepare();
  348. #if CONFIG_IDF_TARGET_ESP32S2
  349. /* Workaround: In deep sleep, for ESP32S2, Power down the RTC_PERIPH will change the slope configuration of Touch sensor sleep pad.
  350. * The configuration change will change the reading of the sleep pad, which will cause the touch wake-up sensor to trigger falsely.
  351. */
  352. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  353. #endif
  354. }
  355. } else {
  356. /* In light sleep, the RTC_PERIPH power domain should be in the power-on state (Power on the touch circuit in light sleep),
  357. * otherwise the touch sensor FSM will be cleared, causing touch sensor false triggering.
  358. */
  359. if (touch_ll_get_fsm_state()) { // Check if the touch sensor is working properly.
  360. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  361. }
  362. }
  363. #endif
  364. uint32_t reject_triggers = 0;
  365. if ((pd_flags & RTC_SLEEP_PD_DIG) == 0 && (s_config.wakeup_triggers & RTC_GPIO_TRIG_EN)) {
  366. /* Light sleep, enable sleep reject for faster return from this function,
  367. * in case the wakeup is already triggerred.
  368. */
  369. #if CONFIG_IDF_TARGET_ESP32
  370. reject_triggers = RTC_CNTL_LIGHT_SLP_REJECT_EN_M | RTC_CNTL_GPIO_REJECT_EN_M;
  371. #else
  372. reject_triggers = s_config.wakeup_triggers;
  373. #endif
  374. }
  375. // Enter sleep
  376. rtc_sleep_config_t config = RTC_SLEEP_CONFIG_DEFAULT(pd_flags);
  377. rtc_sleep_init(config);
  378. // Set state machine time for light sleep
  379. if (!deep_sleep) {
  380. rtc_sleep_low_init(s_config.rtc_clk_cal_period);
  381. }
  382. // Configure timer wakeup
  383. if (s_config.wakeup_triggers & RTC_TIMER_TRIG_EN) {
  384. timer_wakeup_prepare();
  385. }
  386. uint32_t result;
  387. if (deep_sleep) {
  388. /* Disable interrupts in case another task writes to RTC memory while we
  389. * calculate RTC memory CRC
  390. *
  391. * Note: for ESP32-S3 running in dual core mode this is currently not enough,
  392. * see the assert at top of this function.
  393. */
  394. portENTER_CRITICAL(&spinlock_rtc_deep_sleep);
  395. #if SOC_PM_SUPPORT_DEEPSLEEP_VERIFY_STUB_ONLY
  396. extern char _rtc_text_start[];
  397. #if CONFIG_ESP32S3_RTCDATA_IN_FAST_MEM
  398. extern char _rtc_noinit_end[];
  399. size_t rtc_fast_length = (size_t)_rtc_noinit_end - (size_t)_rtc_text_start;
  400. #else
  401. extern char _rtc_force_fast_end[];
  402. size_t rtc_fast_length = (size_t)_rtc_force_fast_end - (size_t)_rtc_text_start;
  403. #endif
  404. esp_rom_set_rtc_wake_addr((esp_rom_wake_func_t)esp_wake_stub_entry, rtc_fast_length);
  405. result = call_rtc_sleep_start(reject_triggers, config.lslp_mem_inf_fpu);
  406. #else
  407. #if !CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP
  408. /* If not possible stack is in RTC FAST memory, use the ROM function to calculate the CRC and save ~140 bytes IRAM */
  409. set_rtc_memory_crc();
  410. result = call_rtc_sleep_start(reject_triggers, config.lslp_mem_inf_fpu);
  411. #else
  412. /* Otherwise, need to call the dedicated soc function for this */
  413. result = rtc_deep_sleep_start(s_config.wakeup_triggers, reject_triggers);
  414. #endif
  415. #endif // SOC_PM_SUPPORT_DEEPSLEEP_VERIFY_STUB_ONLY
  416. portEXIT_CRITICAL(&spinlock_rtc_deep_sleep);
  417. } else {
  418. result = call_rtc_sleep_start(reject_triggers, config.lslp_mem_inf_fpu);
  419. }
  420. // Restore CPU frequency
  421. rtc_clk_cpu_freq_set_config(&cpu_freq_config);
  422. if (!deep_sleep) {
  423. s_config.ccount_ticks_record = cpu_ll_get_cycle_count();
  424. misc_modules_wake_prepare();
  425. }
  426. // re-enable UART output
  427. resume_uarts();
  428. return result;
  429. }
  430. inline static uint32_t IRAM_ATTR call_rtc_sleep_start(uint32_t reject_triggers, uint32_t lslp_mem_inf_fpu)
  431. {
  432. #ifdef CONFIG_IDF_TARGET_ESP32
  433. return rtc_sleep_start(s_config.wakeup_triggers, reject_triggers);
  434. #else
  435. return rtc_sleep_start(s_config.wakeup_triggers, reject_triggers, lslp_mem_inf_fpu);
  436. #endif
  437. }
  438. void IRAM_ATTR esp_deep_sleep_start(void)
  439. {
  440. #if CONFIG_IDF_TARGET_ESP32S2
  441. /* Due to hardware limitations, on S2 the brownout detector sometimes trigger during deep sleep
  442. to circumvent this we disable the brownout detector before sleeping */
  443. esp_brownout_disable();
  444. #endif //CONFIG_IDF_TARGET_ESP32S2
  445. esp_sync_counters_rtc_and_frc();
  446. /* Disable interrupts and stall another core in case another task writes
  447. * to RTC memory while we calculate RTC memory CRC.
  448. */
  449. portENTER_CRITICAL(&spinlock_rtc_deep_sleep);
  450. esp_ipc_isr_stall_other_cpu();
  451. // record current RTC time
  452. s_config.rtc_ticks_at_sleep_start = rtc_time_get();
  453. // Configure wake stub
  454. if (esp_get_deep_sleep_wake_stub() == NULL) {
  455. esp_set_deep_sleep_wake_stub(esp_wake_deep_sleep);
  456. }
  457. // Decide which power domains can be powered down
  458. uint32_t pd_flags = get_power_down_flags();
  459. s_config.rtc_clk_cal_period = esp_clk_slowclk_cal_get();
  460. // Correct the sleep time
  461. s_config.sleep_time_adjustment = DEEP_SLEEP_TIME_OVERHEAD_US;
  462. uint32_t force_pd_flags = RTC_SLEEP_PD_DIG | RTC_SLEEP_PD_VDDSDIO;
  463. #if SOC_PM_SUPPORT_WIFI_PD
  464. force_pd_flags |= RTC_SLEEP_PD_WIFI;
  465. #endif
  466. #if SOC_PM_SUPPORT_BT_PD
  467. force_pd_flags |= RTC_SLEEP_PD_BT;
  468. #endif
  469. // Enter sleep
  470. esp_sleep_start(force_pd_flags | pd_flags);
  471. // Because RTC is in a slower clock domain than the CPU, it
  472. // can take several CPU cycles for the sleep mode to start.
  473. while (1) {
  474. ;
  475. }
  476. // Never returns here
  477. esp_ipc_isr_release_other_cpu();
  478. portEXIT_CRITICAL(&spinlock_rtc_deep_sleep);
  479. }
  480. /**
  481. * Helper function which handles entry to and exit from light sleep
  482. * Placed into IRAM as flash may need some time to be powered on.
  483. */
  484. static esp_err_t esp_light_sleep_inner(uint32_t pd_flags,
  485. uint32_t flash_enable_time_us,
  486. rtc_vddsdio_config_t vddsdio_config) IRAM_ATTR __attribute__((noinline));
  487. static esp_err_t esp_light_sleep_inner(uint32_t pd_flags,
  488. uint32_t flash_enable_time_us,
  489. rtc_vddsdio_config_t vddsdio_config)
  490. {
  491. // Enter sleep
  492. esp_err_t err = esp_sleep_start(pd_flags);
  493. // If VDDSDIO regulator was controlled by RTC registers before sleep,
  494. // restore the configuration.
  495. if (vddsdio_config.force) {
  496. rtc_vddsdio_set_config(vddsdio_config);
  497. }
  498. // If SPI flash was powered down, wait for it to become ready
  499. if (pd_flags & RTC_SLEEP_PD_VDDSDIO) {
  500. // Wait for the flash chip to start up
  501. esp_rom_delay_us(flash_enable_time_us);
  502. }
  503. return err;
  504. }
  505. esp_err_t esp_light_sleep_start(void)
  506. {
  507. s_config.ccount_ticks_record = cpu_ll_get_cycle_count();
  508. static portMUX_TYPE light_sleep_lock = portMUX_INITIALIZER_UNLOCKED;
  509. portENTER_CRITICAL(&light_sleep_lock);
  510. /* We will be calling esp_timer_private_advance inside DPORT access critical
  511. * section. Make sure the code on the other CPU is not holding esp_timer
  512. * lock, otherwise there will be deadlock.
  513. */
  514. esp_timer_private_lock();
  515. s_config.rtc_ticks_at_sleep_start = rtc_time_get();
  516. uint32_t ccount_at_sleep_start = cpu_ll_get_cycle_count();
  517. uint64_t frc_time_at_start = esp_system_get_time();
  518. uint32_t sleep_time_overhead_in = (ccount_at_sleep_start - s_config.ccount_ticks_record) / (esp_clk_cpu_freq() / 1000000ULL);
  519. esp_ipc_isr_stall_other_cpu();
  520. // Decide which power domains can be powered down
  521. uint32_t pd_flags = get_power_down_flags();
  522. #ifdef CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND
  523. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  524. #endif
  525. // Re-calibrate the RTC Timer clock
  526. #ifdef CONFIG_ESP_SYSTEM_RTC_EXT_XTAL
  527. uint64_t time_per_us = 1000000ULL;
  528. s_config.rtc_clk_cal_period = (time_per_us << RTC_CLK_CAL_FRACT) / rtc_clk_slow_freq_get_hz();
  529. #elif defined(CONFIG_ESP32S2_RTC_CLK_SRC_INT_RC)
  530. s_config.rtc_clk_cal_period = rtc_clk_cal_cycling(RTC_CAL_RTC_MUX, RTC_CLK_SRC_CAL_CYCLES);
  531. esp_clk_slowclk_cal_set(s_config.rtc_clk_cal_period);
  532. #else
  533. s_config.rtc_clk_cal_period = rtc_clk_cal(RTC_CAL_RTC_MUX, RTC_CLK_SRC_CAL_CYCLES);
  534. esp_clk_slowclk_cal_set(s_config.rtc_clk_cal_period);
  535. #endif
  536. /*
  537. * Adjustment time consists of parts below:
  538. * 1. Hardware time waiting for internal 8M oscilate clock and XTAL;
  539. * 2. Hardware state swithing time of the rtc main state machine;
  540. * 3. Code execution time when clock is not stable;
  541. * 4. Code execution time which can be measured;
  542. */
  543. uint32_t rtc_cntl_xtl_buf_wait_slp_cycles = rtc_time_us_to_slowclk(RTC_CNTL_XTL_BUF_WAIT_SLP_US, s_config.rtc_clk_cal_period);
  544. s_config.sleep_time_adjustment = LIGHT_SLEEP_TIME_OVERHEAD_US + sleep_time_overhead_in + s_config.sleep_time_overhead_out
  545. + rtc_time_slowclk_to_us(rtc_cntl_xtl_buf_wait_slp_cycles + RTC_CNTL_CK8M_WAIT_SLP_CYCLES + RTC_CNTL_WAKEUP_DELAY_CYCLES, s_config.rtc_clk_cal_period);
  546. // Decide if VDD_SDIO needs to be powered down;
  547. // If it needs to be powered down, adjust sleep time.
  548. const uint32_t flash_enable_time_us = VDD_SDIO_POWERUP_TO_FLASH_READ_US + DEEP_SLEEP_WAKEUP_DELAY;
  549. /**
  550. * If VDD_SDIO power domain is requested to be turned off, bit `RTC_SLEEP_PD_VDDSDIO`
  551. * will be set in `pd_flags`.
  552. */
  553. if (pd_flags & RTC_SLEEP_PD_VDDSDIO) {
  554. /*
  555. * When VDD_SDIO power domain has to be turned off, the minimum sleep time of the
  556. * system needs to meet the sum below:
  557. * 1. Wait time for the flash power-on after waking up;
  558. * 2. The execution time of codes between RTC Timer get start time
  559. * with hardware starts to switch state to sleep;
  560. * 3. The hardware state switching time of the rtc state machine during
  561. * sleep and wake-up. This process requires 6 cycles to complete.
  562. * The specific hardware state switching process and the cycles
  563. * consumed are rtc_cpu_run_stall(1), cut_pll_rtl(2), cut_8m(1),
  564. * min_protect(2);
  565. * 4. All the adjustment time which is s_config.sleep_time_adjustment below.
  566. */
  567. const uint32_t vddsdio_pd_sleep_duration = MAX(FLASH_PD_MIN_SLEEP_TIME_US,
  568. flash_enable_time_us + LIGHT_SLEEP_MIN_TIME_US + s_config.sleep_time_adjustment
  569. + rtc_time_slowclk_to_us(RTC_MODULE_SLEEP_PREPARE_CYCLES, s_config.rtc_clk_cal_period));
  570. if (s_config.sleep_duration > vddsdio_pd_sleep_duration) {
  571. if (s_config.sleep_time_overhead_out < flash_enable_time_us) {
  572. s_config.sleep_time_adjustment += flash_enable_time_us;
  573. }
  574. } else {
  575. /**
  576. * Minimum sleep time is not enough, then keep the VDD_SDIO power
  577. * domain on.
  578. */
  579. pd_flags &= ~RTC_SLEEP_PD_VDDSDIO;
  580. if (s_config.sleep_time_overhead_out > flash_enable_time_us) {
  581. s_config.sleep_time_adjustment -= flash_enable_time_us;
  582. }
  583. }
  584. }
  585. periph_inform_out_light_sleep_overhead(s_config.sleep_time_adjustment - sleep_time_overhead_in);
  586. rtc_vddsdio_config_t vddsdio_config = rtc_vddsdio_get_config();
  587. // Safety net: enable WDT in case exit from light sleep fails
  588. wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
  589. bool wdt_was_enabled = wdt_hal_is_enabled(&rtc_wdt_ctx); // If WDT was enabled in the user code, then do not change it here.
  590. if (!wdt_was_enabled) {
  591. wdt_hal_init(&rtc_wdt_ctx, WDT_RWDT, 0, false);
  592. uint32_t stage_timeout_ticks = (uint32_t)(1000ULL * rtc_clk_slow_freq_get_hz() / 1000ULL);
  593. wdt_hal_write_protect_disable(&rtc_wdt_ctx);
  594. wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
  595. wdt_hal_enable(&rtc_wdt_ctx);
  596. wdt_hal_write_protect_enable(&rtc_wdt_ctx);
  597. }
  598. // Enter sleep, then wait for flash to be ready on wakeup
  599. esp_err_t err = esp_light_sleep_inner(pd_flags,
  600. flash_enable_time_us, vddsdio_config);
  601. s_light_sleep_wakeup = true;
  602. // FRC1 has been clock gated for the duration of the sleep, correct for that.
  603. #ifdef CONFIG_IDF_TARGET_ESP32C3
  604. /**
  605. * On esp32c3, rtc_time_get() is non-blocking, esp_system_get_time() is
  606. * blocking, and the measurement data shows that this order is better.
  607. */
  608. uint64_t frc_time_at_end = esp_system_get_time();
  609. uint64_t rtc_ticks_at_end = rtc_time_get();
  610. #else
  611. uint64_t rtc_ticks_at_end = rtc_time_get();
  612. uint64_t frc_time_at_end = esp_system_get_time();
  613. #endif
  614. uint64_t rtc_time_diff = rtc_time_slowclk_to_us(rtc_ticks_at_end - s_config.rtc_ticks_at_sleep_start, s_config.rtc_clk_cal_period);
  615. uint64_t frc_time_diff = frc_time_at_end - frc_time_at_start;
  616. int64_t time_diff = rtc_time_diff - frc_time_diff;
  617. /* Small negative values (up to 1 RTC_SLOW clock period) are possible,
  618. * for very small values of sleep_duration. Ignore those to keep esp_timer
  619. * monotonic.
  620. */
  621. if (time_diff > 0) {
  622. esp_timer_private_advance(time_diff);
  623. }
  624. esp_set_time_from_rtc();
  625. esp_timer_private_unlock();
  626. esp_ipc_isr_release_other_cpu();
  627. if (!wdt_was_enabled) {
  628. wdt_hal_write_protect_disable(&rtc_wdt_ctx);
  629. wdt_hal_disable(&rtc_wdt_ctx);
  630. wdt_hal_write_protect_enable(&rtc_wdt_ctx);
  631. }
  632. portEXIT_CRITICAL(&light_sleep_lock);
  633. s_config.sleep_time_overhead_out = (cpu_ll_get_cycle_count() - s_config.ccount_ticks_record) / (esp_clk_cpu_freq() / 1000000ULL);
  634. return err;
  635. }
  636. esp_err_t esp_sleep_disable_wakeup_source(esp_sleep_source_t source)
  637. {
  638. // For most of sources it is enough to set trigger mask in local
  639. // configuration structure. The actual RTC wake up options
  640. // will be updated by esp_sleep_start().
  641. if (source == ESP_SLEEP_WAKEUP_ALL) {
  642. s_config.wakeup_triggers = 0;
  643. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_TIMER, RTC_TIMER_TRIG_EN)) {
  644. s_config.wakeup_triggers &= ~RTC_TIMER_TRIG_EN;
  645. s_config.sleep_duration = 0;
  646. #if SOC_PM_SUPPORT_EXT_WAKEUP
  647. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_EXT0, RTC_EXT0_TRIG_EN)) {
  648. s_config.ext0_rtc_gpio_num = 0;
  649. s_config.ext0_trigger_level = 0;
  650. s_config.wakeup_triggers &= ~RTC_EXT0_TRIG_EN;
  651. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_EXT1, RTC_EXT1_TRIG_EN)) {
  652. s_config.ext1_rtc_gpio_mask = 0;
  653. s_config.ext1_trigger_mode = 0;
  654. s_config.wakeup_triggers &= ~RTC_EXT1_TRIG_EN;
  655. #endif
  656. #if SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP
  657. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_TOUCHPAD, RTC_TOUCH_TRIG_EN)) {
  658. s_config.wakeup_triggers &= ~RTC_TOUCH_TRIG_EN;
  659. #endif
  660. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_GPIO, RTC_GPIO_TRIG_EN)) {
  661. s_config.wakeup_triggers &= ~RTC_GPIO_TRIG_EN;
  662. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_UART, (RTC_UART0_TRIG_EN | RTC_UART1_TRIG_EN))) {
  663. s_config.wakeup_triggers &= ~(RTC_UART0_TRIG_EN | RTC_UART1_TRIG_EN);
  664. }
  665. #if defined(CONFIG_ESP32_ULP_COPROC_ENABLED) || defined(CONFIG_ESP32S2_ULP_COPROC_ENABLED)
  666. else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_ULP, RTC_ULP_TRIG_EN)) {
  667. s_config.wakeup_triggers &= ~RTC_ULP_TRIG_EN;
  668. }
  669. #endif
  670. else {
  671. ESP_LOGE(TAG, "Incorrect wakeup source (%d) to disable.", (int) source);
  672. return ESP_ERR_INVALID_STATE;
  673. }
  674. return ESP_OK;
  675. }
  676. esp_err_t esp_sleep_enable_ulp_wakeup(void)
  677. {
  678. #if CONFIG_IDF_TARGET_ESP32
  679. #if ((defined CONFIG_ESP32_RTC_EXT_CRYST_ADDIT_CURRENT) || (defined CONFIG_ESP32_RTC_EXT_CRYST_ADDIT_CURRENT_V2))
  680. ESP_LOGE(TAG, "Failed to enable wakeup when provide current to external 32kHz crystal");
  681. return ESP_ERR_NOT_SUPPORTED;
  682. #endif
  683. #ifdef CONFIG_ESP32_ULP_COPROC_ENABLED
  684. if (s_config.wakeup_triggers & RTC_EXT0_TRIG_EN) {
  685. ESP_LOGE(TAG, "Conflicting wake-up trigger: ext0");
  686. return ESP_ERR_INVALID_STATE;
  687. }
  688. s_config.wakeup_triggers |= RTC_ULP_TRIG_EN;
  689. return ESP_OK;
  690. #else // CONFIG_ESP32_ULP_COPROC_ENABLED
  691. return ESP_ERR_INVALID_STATE;
  692. #endif // CONFIG_ESP32_ULP_COPROC_ENABLED
  693. #elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  694. s_config.wakeup_triggers |= (RTC_ULP_TRIG_EN | RTC_COCPU_TRIG_EN | RTC_COCPU_TRAP_TRIG_EN);
  695. return ESP_OK;
  696. #else
  697. return ESP_ERR_NOT_SUPPORTED;
  698. #endif
  699. }
  700. esp_err_t esp_sleep_enable_timer_wakeup(uint64_t time_in_us)
  701. {
  702. s_config.wakeup_triggers |= RTC_TIMER_TRIG_EN;
  703. s_config.sleep_duration = time_in_us;
  704. return ESP_OK;
  705. }
  706. static void timer_wakeup_prepare(void)
  707. {
  708. int64_t sleep_duration = (int64_t) s_config.sleep_duration - (int64_t) s_config.sleep_time_adjustment;
  709. if (sleep_duration < 0) {
  710. sleep_duration = 0;
  711. }
  712. int64_t ticks = rtc_time_us_to_slowclk(sleep_duration, s_config.rtc_clk_cal_period);
  713. rtc_hal_set_wakeup_timer(s_config.rtc_ticks_at_sleep_start + ticks);
  714. }
  715. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  716. /* In deep sleep mode, only the sleep channel is supported, and other touch channels should be turned off. */
  717. static void touch_wakeup_prepare(void)
  718. {
  719. uint16_t sleep_cycle = 0;
  720. uint16_t meas_times = 0;
  721. touch_pad_t touch_num = TOUCH_PAD_NUM0;
  722. touch_ll_sleep_get_channel_num(&touch_num); // Check if the sleep pad is enabled.
  723. if ((touch_num > TOUCH_PAD_NUM0) && (touch_num < TOUCH_PAD_MAX) && touch_ll_get_fsm_state()) {
  724. touch_ll_stop_fsm();
  725. touch_ll_clear_channel_mask(TOUCH_PAD_BIT_MASK_ALL);
  726. touch_ll_intr_clear(TOUCH_PAD_INTR_MASK_ALL); // Clear state from previous wakeup
  727. touch_hal_sleep_channel_get_work_time(&sleep_cycle, &meas_times);
  728. touch_ll_set_meas_times(meas_times);
  729. touch_ll_set_sleep_time(sleep_cycle);
  730. touch_ll_set_channel_mask(BIT(touch_num));
  731. touch_ll_start_fsm();
  732. }
  733. }
  734. #endif
  735. #if SOC_TOUCH_SENSOR_NUM > 0
  736. esp_err_t esp_sleep_enable_touchpad_wakeup(void)
  737. {
  738. #if ((defined CONFIG_ESP32_RTC_EXT_CRYST_ADDIT_CURRENT) || (defined CONFIG_ESP32_RTC_EXT_CRYST_ADDIT_CURRENT_V2))
  739. ESP_LOGE(TAG, "Failed to enable wakeup when provide current to external 32kHz crystal");
  740. return ESP_ERR_NOT_SUPPORTED;
  741. #endif
  742. if (s_config.wakeup_triggers & (RTC_EXT0_TRIG_EN)) {
  743. ESP_LOGE(TAG, "Conflicting wake-up trigger: ext0");
  744. return ESP_ERR_INVALID_STATE;
  745. }
  746. s_config.wakeup_triggers |= RTC_TOUCH_TRIG_EN;
  747. return ESP_OK;
  748. }
  749. touch_pad_t esp_sleep_get_touchpad_wakeup_status(void)
  750. {
  751. if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_TOUCHPAD) {
  752. return TOUCH_PAD_MAX;
  753. }
  754. touch_pad_t pad_num;
  755. esp_err_t ret = touch_pad_get_wakeup_status(&pad_num); //TODO 723diff commit id:fda9ada1b
  756. assert(ret == ESP_OK && "wakeup reason is RTC_TOUCH_TRIG_EN but SENS_TOUCH_MEAS_EN is zero");
  757. return (ret == ESP_OK) ? pad_num : TOUCH_PAD_MAX;
  758. }
  759. #endif // SOC_TOUCH_SENSOR_NUM > 0
  760. bool esp_sleep_is_valid_wakeup_gpio(gpio_num_t gpio_num)
  761. {
  762. #if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED
  763. return RTC_GPIO_IS_VALID_GPIO(gpio_num);
  764. #else
  765. return GPIO_IS_DEEP_SLEEP_WAKEUP_VALID_GPIO(gpio_num);
  766. #endif // SOC_RTCIO_INPUT_OUTPUT_SUPPORTED
  767. }
  768. #if SOC_PM_SUPPORT_EXT_WAKEUP
  769. esp_err_t esp_sleep_enable_ext0_wakeup(gpio_num_t gpio_num, int level)
  770. {
  771. if (level < 0 || level > 1) {
  772. return ESP_ERR_INVALID_ARG;
  773. }
  774. if (!esp_sleep_is_valid_wakeup_gpio(gpio_num)) {
  775. return ESP_ERR_INVALID_ARG;
  776. }
  777. if (s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) {
  778. ESP_LOGE(TAG, "Conflicting wake-up triggers: touch / ULP");
  779. return ESP_ERR_INVALID_STATE;
  780. }
  781. s_config.ext0_rtc_gpio_num = rtc_io_number_get(gpio_num);
  782. s_config.ext0_trigger_level = level;
  783. s_config.wakeup_triggers |= RTC_EXT0_TRIG_EN;
  784. return ESP_OK;
  785. }
  786. static void ext0_wakeup_prepare(void)
  787. {
  788. int rtc_gpio_num = s_config.ext0_rtc_gpio_num;
  789. rtcio_hal_ext0_set_wakeup_pin(rtc_gpio_num, s_config.ext0_trigger_level);
  790. rtcio_hal_function_select(rtc_gpio_num, RTCIO_FUNC_RTC);
  791. rtcio_hal_input_enable(rtc_gpio_num);
  792. }
  793. esp_err_t esp_sleep_enable_ext1_wakeup(uint64_t mask, esp_sleep_ext1_wakeup_mode_t mode)
  794. {
  795. if (mode > ESP_EXT1_WAKEUP_ANY_HIGH) {
  796. return ESP_ERR_INVALID_ARG;
  797. }
  798. // Translate bit map of GPIO numbers into the bit map of RTC IO numbers
  799. uint32_t rtc_gpio_mask = 0;
  800. for (int gpio = 0; mask; ++gpio, mask >>= 1) {
  801. if ((mask & 1) == 0) {
  802. continue;
  803. }
  804. if (!esp_sleep_is_valid_wakeup_gpio(gpio)) {
  805. ESP_LOGE(TAG, "Not an RTC IO: GPIO%d", gpio);
  806. return ESP_ERR_INVALID_ARG;
  807. }
  808. rtc_gpio_mask |= BIT(rtc_io_number_get(gpio));
  809. }
  810. s_config.ext1_rtc_gpio_mask = rtc_gpio_mask;
  811. s_config.ext1_trigger_mode = mode;
  812. s_config.wakeup_triggers |= RTC_EXT1_TRIG_EN;
  813. return ESP_OK;
  814. }
  815. static void ext1_wakeup_prepare(void)
  816. {
  817. // Configure all RTC IOs selected as ext1 wakeup inputs
  818. uint32_t rtc_gpio_mask = s_config.ext1_rtc_gpio_mask;
  819. for (int gpio = 0; gpio < GPIO_PIN_COUNT && rtc_gpio_mask != 0; ++gpio) {
  820. int rtc_pin = rtc_io_number_get(gpio);
  821. if ((rtc_gpio_mask & BIT(rtc_pin)) == 0) {
  822. continue;
  823. }
  824. #if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED
  825. // Route pad to RTC
  826. rtcio_hal_function_select(rtc_pin, RTCIO_FUNC_RTC);
  827. // set input enable in sleep mode
  828. rtcio_hal_input_enable(rtc_pin);
  829. #endif
  830. // Pad configuration depends on RTC_PERIPH state in sleep mode
  831. if (s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] != ESP_PD_OPTION_ON) {
  832. #if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED
  833. // RTC_PERIPH will be powered down, so RTC_IO_ registers will
  834. // loose their state. Lock pad configuration.
  835. // Pullups/pulldowns also need to be disabled.
  836. rtcio_hal_pullup_disable(rtc_pin);
  837. rtcio_hal_pulldown_disable(rtc_pin);
  838. #endif
  839. rtcio_hal_hold_enable(rtc_pin);
  840. }
  841. // Keep track of pins which are processed to bail out early
  842. rtc_gpio_mask &= ~BIT(rtc_pin);
  843. }
  844. // Clear state from previous wakeup
  845. rtc_hal_ext1_clear_wakeup_pins();
  846. // Set RTC IO pins and mode (any high, all low) to be used for wakeup
  847. rtc_hal_ext1_set_wakeup_pins(s_config.ext1_rtc_gpio_mask, s_config.ext1_trigger_mode);
  848. }
  849. uint64_t esp_sleep_get_ext1_wakeup_status(void)
  850. {
  851. if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_EXT1) {
  852. return 0;
  853. }
  854. uint32_t status = rtc_hal_ext1_get_wakeup_pins();
  855. // Translate bit map of RTC IO numbers into the bit map of GPIO numbers
  856. uint64_t gpio_mask = 0;
  857. for (int gpio = 0; gpio < GPIO_PIN_COUNT; ++gpio) {
  858. if (!esp_sleep_is_valid_wakeup_gpio(gpio)) {
  859. continue;
  860. }
  861. int rtc_pin = rtc_io_number_get(gpio);
  862. if ((status & BIT(rtc_pin)) == 0) {
  863. continue;
  864. }
  865. gpio_mask |= 1ULL << gpio;
  866. }
  867. return gpio_mask;
  868. }
  869. #endif // SOC_PM_SUPPORT_EXT_WAKEUP
  870. #if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  871. uint64_t esp_sleep_get_gpio_wakeup_status(void)
  872. {
  873. if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_GPIO) {
  874. return 0;
  875. }
  876. return rtc_hal_gpio_get_wakeup_pins();
  877. }
  878. static void esp_deep_sleep_wakeup_prepare(void)
  879. {
  880. for (gpio_num_t gpio_idx = GPIO_NUM_0; gpio_idx < GPIO_NUM_MAX; gpio_idx++) {
  881. if (((1ULL << gpio_idx) & s_config.gpio_wakeup_mask) == 0) {
  882. continue;
  883. }
  884. if (s_config.gpio_trigger_mode & BIT(gpio_idx)) {
  885. ESP_ERROR_CHECK(gpio_pullup_dis(gpio_idx));
  886. ESP_ERROR_CHECK(gpio_pulldown_en(gpio_idx));
  887. } else {
  888. ESP_ERROR_CHECK(gpio_pullup_en(gpio_idx));
  889. ESP_ERROR_CHECK(gpio_pulldown_dis(gpio_idx));
  890. }
  891. rtc_hal_gpio_set_wakeup_pins();
  892. ESP_ERROR_CHECK(gpio_hold_en(gpio_idx));
  893. }
  894. }
  895. esp_err_t esp_deep_sleep_enable_gpio_wakeup(uint64_t gpio_pin_mask, esp_deepsleep_gpio_wake_up_mode_t mode)
  896. {
  897. if (mode > ESP_GPIO_WAKEUP_GPIO_HIGH) {
  898. ESP_LOGE(TAG, "invalid mode");
  899. return ESP_ERR_INVALID_ARG;
  900. }
  901. gpio_int_type_t intr_type = ((mode == ESP_GPIO_WAKEUP_GPIO_LOW) ? GPIO_INTR_LOW_LEVEL : GPIO_INTR_HIGH_LEVEL);
  902. esp_err_t err = ESP_OK;
  903. for (gpio_num_t gpio_idx = GPIO_NUM_0; gpio_idx < GPIO_NUM_MAX; gpio_idx++, gpio_pin_mask >>= 1) {
  904. if ((gpio_pin_mask & 1) == 0) {
  905. continue;
  906. }
  907. if (!esp_sleep_is_valid_wakeup_gpio(gpio_idx)) {
  908. ESP_LOGE(TAG, "invalid mask, please ensure gpio number is no more than 5");
  909. return ESP_ERR_INVALID_ARG;
  910. }
  911. err = gpio_deep_sleep_wakeup_enable(gpio_idx, intr_type);
  912. s_config.gpio_wakeup_mask |= BIT(gpio_idx);
  913. if (mode == ESP_GPIO_WAKEUP_GPIO_HIGH) {
  914. s_config.gpio_trigger_mode |= (mode << gpio_idx);
  915. } else {
  916. s_config.gpio_trigger_mode &= ~(mode << gpio_idx);
  917. }
  918. }
  919. s_config.wakeup_triggers |= RTC_GPIO_TRIG_EN;
  920. rtc_hal_gpio_clear_wakeup_pins();
  921. return err;
  922. }
  923. #endif //SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  924. esp_err_t esp_sleep_enable_gpio_wakeup(void)
  925. {
  926. #if CONFIG_IDF_TARGET_ESP32
  927. if (s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) {
  928. ESP_LOGE(TAG, "Conflicting wake-up triggers: touch / ULP");
  929. return ESP_ERR_INVALID_STATE;
  930. }
  931. #endif
  932. s_config.wakeup_triggers |= RTC_GPIO_TRIG_EN;
  933. return ESP_OK;
  934. }
  935. esp_err_t esp_sleep_enable_uart_wakeup(int uart_num)
  936. {
  937. if (uart_num == UART_NUM_0) {
  938. s_config.wakeup_triggers |= RTC_UART0_TRIG_EN;
  939. } else if (uart_num == UART_NUM_1) {
  940. s_config.wakeup_triggers |= RTC_UART1_TRIG_EN;
  941. } else {
  942. return ESP_ERR_INVALID_ARG;
  943. }
  944. return ESP_OK;
  945. }
  946. esp_err_t esp_sleep_enable_wifi_wakeup(void)
  947. {
  948. #if SOC_PM_SUPPORT_WIFI_WAKEUP
  949. s_config.wakeup_triggers |= RTC_WIFI_TRIG_EN;
  950. return ESP_OK;
  951. #else
  952. return ESP_ERR_NOT_SUPPORTED;
  953. #endif
  954. }
  955. esp_err_t esp_sleep_disable_wifi_wakeup(void)
  956. {
  957. #if SOC_PM_SUPPORT_WIFI_WAKEUP
  958. s_config.wakeup_triggers &= (~RTC_WIFI_TRIG_EN);
  959. return ESP_OK;
  960. #else
  961. return ESP_ERR_NOT_SUPPORTED;
  962. #endif
  963. }
  964. esp_sleep_wakeup_cause_t esp_sleep_get_wakeup_cause(void)
  965. {
  966. if (esp_rom_get_reset_reason(0) != RESET_REASON_CORE_DEEP_SLEEP && !s_light_sleep_wakeup) {
  967. return ESP_SLEEP_WAKEUP_UNDEFINED;
  968. }
  969. #ifdef CONFIG_IDF_TARGET_ESP32
  970. uint32_t wakeup_cause = REG_GET_FIELD(RTC_CNTL_WAKEUP_STATE_REG, RTC_CNTL_WAKEUP_CAUSE);
  971. #else
  972. uint32_t wakeup_cause = REG_GET_FIELD(RTC_CNTL_SLP_WAKEUP_CAUSE_REG, RTC_CNTL_WAKEUP_CAUSE);
  973. #endif
  974. if (wakeup_cause & RTC_TIMER_TRIG_EN) {
  975. return ESP_SLEEP_WAKEUP_TIMER;
  976. } else if (wakeup_cause & RTC_GPIO_TRIG_EN) {
  977. return ESP_SLEEP_WAKEUP_GPIO;
  978. } else if (wakeup_cause & (RTC_UART0_TRIG_EN | RTC_UART1_TRIG_EN)) {
  979. return ESP_SLEEP_WAKEUP_UART;
  980. #if SOC_PM_SUPPORT_EXT_WAKEUP
  981. } else if (wakeup_cause & RTC_EXT0_TRIG_EN) {
  982. return ESP_SLEEP_WAKEUP_EXT0;
  983. } else if (wakeup_cause & RTC_EXT1_TRIG_EN) {
  984. return ESP_SLEEP_WAKEUP_EXT1;
  985. #endif
  986. #if SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP
  987. } else if (wakeup_cause & RTC_TOUCH_TRIG_EN) {
  988. return ESP_SLEEP_WAKEUP_TOUCHPAD;
  989. #endif
  990. #if SOC_ULP_SUPPORTED
  991. } else if (wakeup_cause & RTC_ULP_TRIG_EN) {
  992. return ESP_SLEEP_WAKEUP_ULP;
  993. #endif
  994. #if SOC_PM_SUPPORT_WIFI_WAKEUP
  995. } else if (wakeup_cause & RTC_WIFI_TRIG_EN) {
  996. return ESP_SLEEP_WAKEUP_WIFI;
  997. #endif
  998. #if SOC_PM_SUPPORT_BT_WAKEUP
  999. } else if (wakeup_cause & RTC_BT_TRIG_EN) {
  1000. return ESP_SLEEP_WAKEUP_BT;
  1001. #endif
  1002. #if CONFIG_IDF_TARGET_ESP32S2
  1003. } else if (wakeup_cause & RTC_COCPU_TRIG_EN) {
  1004. return ESP_SLEEP_WAKEUP_ULP;
  1005. } else if (wakeup_cause & RTC_COCPU_TRAP_TRIG_EN) {
  1006. return ESP_SLEEP_WAKEUP_COCPU_TRAP_TRIG;
  1007. #endif
  1008. } else {
  1009. return ESP_SLEEP_WAKEUP_UNDEFINED;
  1010. }
  1011. }
  1012. esp_err_t esp_sleep_pd_config(esp_sleep_pd_domain_t domain,
  1013. esp_sleep_pd_option_t option)
  1014. {
  1015. if (domain >= ESP_PD_DOMAIN_MAX || option > ESP_PD_OPTION_AUTO) {
  1016. return ESP_ERR_INVALID_ARG;
  1017. }
  1018. s_config.pd_options[domain] = option;
  1019. return ESP_OK;
  1020. }
  1021. static uint32_t get_power_down_flags(void)
  1022. {
  1023. // Where needed, convert AUTO options to ON. Later interpret AUTO as OFF.
  1024. // RTC_SLOW_MEM is needed for the ULP, so keep RTC_SLOW_MEM powered up if ULP
  1025. // is used and RTC_SLOW_MEM is Auto.
  1026. // If there is any data placed into .rtc.data or .rtc.bss segments, and
  1027. // RTC_SLOW_MEM is Auto, keep it powered up as well.
  1028. #if SOC_RTC_SLOW_MEM_SUPPORTED && SOC_ULP_SUPPORTED
  1029. // Labels are defined in the linker script
  1030. extern int _rtc_slow_length;
  1031. if ((s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM] == ESP_PD_OPTION_AUTO) &&
  1032. ((size_t) &_rtc_slow_length > 0 ||
  1033. (s_config.wakeup_triggers & RTC_ULP_TRIG_EN))) {
  1034. s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM] = ESP_PD_OPTION_ON;
  1035. }
  1036. #endif
  1037. #if !CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP
  1038. /* RTC_FAST_MEM is needed for deep sleep stub.
  1039. If RTC_FAST_MEM is Auto, keep it powered on, so that deep sleep stub can run.
  1040. In the new chip revision, deep sleep stub will be optional, and this can be changed. */
  1041. if (s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM] == ESP_PD_OPTION_AUTO) {
  1042. s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM] = ESP_PD_OPTION_ON;
  1043. }
  1044. #else
  1045. /* If RTC_FAST_MEM is used for heap, force RTC_FAST_MEM to be powered on. */
  1046. s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM] = ESP_PD_OPTION_ON;
  1047. #endif
  1048. // RTC_PERIPH is needed for EXT0 wakeup and GPIO wakeup.
  1049. // If RTC_PERIPH is auto, and EXT0/GPIO aren't enabled, power down RTC_PERIPH.
  1050. if (s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] == ESP_PD_OPTION_AUTO) {
  1051. #if SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP
  1052. uint32_t wakeup_source = RTC_TOUCH_TRIG_EN;
  1053. #if SOC_ULP_SUPPORTED
  1054. wakeup_source |= RTC_ULP_TRIG_EN;
  1055. #endif
  1056. if (s_config.wakeup_triggers & (RTC_EXT0_TRIG_EN | RTC_GPIO_TRIG_EN)) {
  1057. s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] = ESP_PD_OPTION_ON;
  1058. } else if (s_config.wakeup_triggers & wakeup_source) {
  1059. // In both rev. 0 and rev. 1 of ESP32, forcing power up of RTC_PERIPH
  1060. // prevents ULP timer and touch FSMs from working correctly.
  1061. s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] = ESP_PD_OPTION_OFF;
  1062. }
  1063. #else
  1064. if (s_config.wakeup_triggers & RTC_GPIO_TRIG_EN) {
  1065. s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] = ESP_PD_OPTION_ON;
  1066. } else {
  1067. s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] = ESP_PD_OPTION_OFF;
  1068. }
  1069. #endif // SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP
  1070. }
  1071. #if SOC_PM_SUPPORT_CPU_PD
  1072. if (!cpu_domain_pd_allowed()) {
  1073. s_config.pd_options[ESP_PD_DOMAIN_CPU] = ESP_PD_OPTION_ON;
  1074. }
  1075. #endif
  1076. #ifdef CONFIG_IDF_TARGET_ESP32
  1077. s_config.pd_options[ESP_PD_DOMAIN_XTAL] = ESP_PD_OPTION_OFF;
  1078. #endif
  1079. const char *option_str[] = {"OFF", "ON", "AUTO(OFF)" /* Auto works as OFF */};
  1080. /* This function is called from a critical section, log with ESP_EARLY_LOGD. */
  1081. ESP_EARLY_LOGD(TAG, "RTC_PERIPH: %s", option_str[s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH]]);
  1082. #if SOC_RTC_SLOW_MEM_SUPPORTED
  1083. ESP_EARLY_LOGD(TAG, "RTC_SLOW_MEM: %s", option_str[s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM]]);
  1084. #endif
  1085. ESP_EARLY_LOGD(TAG, "RTC_FAST_MEM: %s", option_str[s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM]]);
  1086. // Prepare flags based on the selected options
  1087. uint32_t pd_flags = 0;
  1088. if (s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM] != ESP_PD_OPTION_ON) {
  1089. pd_flags |= RTC_SLEEP_PD_RTC_FAST_MEM;
  1090. }
  1091. #if SOC_RTC_SLOW_MEM_SUPPORTED
  1092. if (s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM] != ESP_PD_OPTION_ON) {
  1093. pd_flags |= RTC_SLEEP_PD_RTC_SLOW_MEM;
  1094. }
  1095. #endif
  1096. if (s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] != ESP_PD_OPTION_ON) {
  1097. pd_flags |= RTC_SLEEP_PD_RTC_PERIPH;
  1098. }
  1099. #if SOC_PM_SUPPORT_CPU_PD
  1100. if (s_config.pd_options[ESP_PD_DOMAIN_CPU] != ESP_PD_OPTION_ON) {
  1101. pd_flags |= RTC_SLEEP_PD_CPU;
  1102. }
  1103. #endif
  1104. if (s_config.pd_options[ESP_PD_DOMAIN_RTC8M] != ESP_PD_OPTION_ON) {
  1105. pd_flags |= RTC_SLEEP_PD_INT_8M;
  1106. }
  1107. if (s_config.pd_options[ESP_PD_DOMAIN_XTAL] != ESP_PD_OPTION_ON) {
  1108. pd_flags |= RTC_SLEEP_PD_XTAL;
  1109. }
  1110. /**
  1111. * VDD_SDIO power domain shall be kept on during the light sleep
  1112. * when CONFIG_ESP_SLEEP_POWER_DOWN_FLASH is not set and off when it is set.
  1113. * The application can still force the power domain to remain on by calling
  1114. * `esp_sleep_pd_config` before getting into light sleep mode.
  1115. *
  1116. * In deep sleep mode, the power domain will be turned off, regardless the
  1117. * value of this field.
  1118. */
  1119. if (s_config.pd_options[ESP_PD_DOMAIN_VDDSDIO] == ESP_PD_OPTION_AUTO) {
  1120. #ifdef CONFIG_ESP_SLEEP_POWER_DOWN_FLASH
  1121. s_config.pd_options[ESP_PD_DOMAIN_VDDSDIO] = ESP_PD_OPTION_OFF;
  1122. #else
  1123. s_config.pd_options[ESP_PD_DOMAIN_VDDSDIO] = ESP_PD_OPTION_ON;
  1124. #endif
  1125. }
  1126. if (s_config.pd_options[ESP_PD_DOMAIN_VDDSDIO] != ESP_PD_OPTION_ON) {
  1127. pd_flags |= RTC_SLEEP_PD_VDDSDIO;
  1128. }
  1129. #if ((defined CONFIG_ESP32_RTC_CLK_SRC_EXT_CRYS) && (defined CONFIG_ESP32_RTC_EXT_CRYST_ADDIT_CURRENT))
  1130. if ((s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) == 0) {
  1131. // If enabled EXT1 only and enable the additional current by touch, should be keep RTC_PERIPH power on.
  1132. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  1133. }
  1134. #endif
  1135. return pd_flags;
  1136. }
  1137. void esp_deep_sleep_disable_rom_logging(void)
  1138. {
  1139. rtc_suppress_rom_log();
  1140. }