sleep_modes.c 46 KB

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