sleep_modes.c 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2023 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_memory_utils.h"
  12. #include "esp_sleep.h"
  13. #include "esp_private/esp_sleep_internal.h"
  14. #include "esp_private/esp_timer_private.h"
  15. #include "esp_private/sleep_event.h"
  16. #include "esp_private/system_internal.h"
  17. #include "esp_log.h"
  18. #include "esp_newlib.h"
  19. #include "esp_timer.h"
  20. #include "esp_ipc_isr.h"
  21. #include "freertos/FreeRTOS.h"
  22. #include "freertos/task.h"
  23. #include "soc/soc_caps.h"
  24. #include "driver/rtc_io.h"
  25. #include "hal/rtc_io_hal.h"
  26. #if SOC_PM_SUPPORT_PMU_MODEM_STATE
  27. #include "esp_private/pm_impl.h"
  28. #endif
  29. #if SOC_LP_AON_SUPPORTED
  30. #include "hal/lp_aon_hal.h"
  31. #else
  32. #include "hal/rtc_cntl_ll.h"
  33. #include "hal/rtc_hal.h"
  34. #endif
  35. #include "soc/rtc.h"
  36. #include "soc/soc_caps.h"
  37. #include "regi2c_ctrl.h" //For `REGI2C_ANA_CALI_PD_WORKAROUND`, temp
  38. #include "hal/cache_hal.h"
  39. #include "hal/cache_ll.h"
  40. #include "hal/wdt_hal.h"
  41. #include "hal/uart_hal.h"
  42. #if SOC_TOUCH_SENSOR_SUPPORTED
  43. #include "hal/touch_sensor_hal.h"
  44. #endif
  45. #include "hal/clk_gate_ll.h"
  46. #include "sdkconfig.h"
  47. #include "esp_rom_uart.h"
  48. #include "esp_rom_sys.h"
  49. #include "esp_private/brownout.h"
  50. #include "esp_private/sleep_console.h"
  51. #include "esp_private/sleep_cpu.h"
  52. #include "esp_private/sleep_modem.h"
  53. #include "esp_private/esp_clk.h"
  54. #include "esp_private/esp_task_wdt.h"
  55. #include "esp_private/sar_periph_ctrl.h"
  56. #include "esp_private/mspi_timing_tuning.h"
  57. #ifdef CONFIG_IDF_TARGET_ESP32
  58. #include "esp32/rom/cache.h"
  59. #include "esp32/rom/rtc.h"
  60. #include "esp_private/gpio.h"
  61. #include "esp_private/sleep_gpio.h"
  62. #elif CONFIG_IDF_TARGET_ESP32S2
  63. #include "esp32s2/rom/rtc.h"
  64. #include "soc/extmem_reg.h"
  65. #include "esp_private/gpio.h"
  66. #elif CONFIG_IDF_TARGET_ESP32S3
  67. #include "esp32s3/rom/rtc.h"
  68. #include "esp_private/mspi_timing_tuning.h"
  69. #elif CONFIG_IDF_TARGET_ESP32C3
  70. #include "esp32c3/rom/rtc.h"
  71. #elif CONFIG_IDF_TARGET_ESP32C2
  72. #include "esp32c2/rom/rtc.h"
  73. #elif CONFIG_IDF_TARGET_ESP32C6
  74. #include "esp32c6/rom/rtc.h"
  75. #include "hal/gpio_ll.h"
  76. #elif CONFIG_IDF_TARGET_ESP32H2
  77. #include "esp32h2/rom/rtc.h"
  78. #include "esp32h2/rom/cache.h"
  79. #include "esp32h2/rom/rtc.h"
  80. #include "soc/extmem_reg.h"
  81. #include "hal/gpio_ll.h"
  82. #endif
  83. #if SOC_LP_TIMER_SUPPORTED
  84. #include "hal/lp_timer_hal.h"
  85. #endif
  86. #if SOC_PMU_SUPPORTED
  87. #include "esp_private/esp_pmu.h"
  88. #include "esp_private/sleep_sys_periph.h"
  89. #include "esp_private/sleep_clock.h"
  90. #endif
  91. #if SOC_PM_RETENTION_HAS_REGDMA_POWER_BUG
  92. #include "esp_private/sleep_retention.h"
  93. #endif
  94. // If light sleep time is less than that, don't power down flash
  95. #define FLASH_PD_MIN_SLEEP_TIME_US 2000
  96. // Time from VDD_SDIO power up to first flash read in ROM code
  97. #define VDD_SDIO_POWERUP_TO_FLASH_READ_US 700
  98. // Cycles for RTC Timer clock source (internal oscillator) calibrate
  99. #define RTC_CLK_SRC_CAL_CYCLES (10)
  100. #define FAST_CLK_SRC_CAL_CYCLES (2048) /* ~ 127.4 us */
  101. #ifdef CONFIG_IDF_TARGET_ESP32
  102. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (212)
  103. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (60)
  104. #elif CONFIG_IDF_TARGET_ESP32S2
  105. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (147)
  106. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (28)
  107. #elif CONFIG_IDF_TARGET_ESP32S3
  108. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (382)
  109. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (133)
  110. #elif CONFIG_IDF_TARGET_ESP32C3
  111. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (105)
  112. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (37)
  113. #elif CONFIG_IDF_TARGET_ESP32C2
  114. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (118)
  115. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (9)
  116. #elif CONFIG_IDF_TARGET_ESP32C6
  117. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (318)
  118. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (56)
  119. #elif CONFIG_IDF_TARGET_ESP32H2
  120. #define DEFAULT_SLEEP_OUT_OVERHEAD_US (118)// TODO: IDF-6267
  121. #define DEFAULT_HARDWARE_OUT_OVERHEAD_US (9)
  122. #endif
  123. // Actually costs 80us, using the fastest slow clock 150K calculation takes about 16 ticks
  124. #define SLEEP_TIMER_ALARM_TO_SLEEP_TICKS (16)
  125. #define SLEEP_UART_FLUSH_DONE_TO_SLEEP_US (450)
  126. #if SOC_PM_SUPPORT_TOP_PD
  127. // IDF console uses 8 bits data mode without parity, so each char occupy 8(data)+1(start)+1(stop)=10bits
  128. #define UART_FLUSH_US_PER_CHAR (10*1000*1000 / CONFIG_ESP_CONSOLE_UART_BAUDRATE)
  129. #define CONCATENATE_HELPER(x, y) (x##y)
  130. #define CONCATENATE(x, y) CONCATENATE_HELPER(x, y)
  131. #define CONSOLE_UART_DEV (&CONCATENATE(UART, CONFIG_ESP_CONSOLE_UART_NUM))
  132. #endif
  133. #define LIGHT_SLEEP_TIME_OVERHEAD_US DEFAULT_HARDWARE_OUT_OVERHEAD_US
  134. #ifdef CONFIG_ESP_SYSTEM_RTC_EXT_XTAL
  135. #define DEEP_SLEEP_TIME_OVERHEAD_US (650 + 100 * 240 / CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ)
  136. #else
  137. #define DEEP_SLEEP_TIME_OVERHEAD_US (250 + 100 * 240 / CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ)
  138. #endif
  139. #if CONFIG_ESP_SLEEP_DEEP_SLEEP_WAKEUP_DELAY
  140. #define DEEP_SLEEP_WAKEUP_DELAY CONFIG_ESP_SLEEP_DEEP_SLEEP_WAKEUP_DELAY
  141. #else
  142. #define DEEP_SLEEP_WAKEUP_DELAY 0
  143. #endif
  144. // Minimal amount of time we can sleep for
  145. #define LIGHT_SLEEP_MIN_TIME_US 200
  146. #define RTC_MODULE_SLEEP_PREPARE_CYCLES (6)
  147. #define CHECK_SOURCE(source, value, mask) ((s_config.wakeup_triggers & mask) && \
  148. (source == value))
  149. #define MAX_DSLP_HOOKS 3
  150. static esp_deep_sleep_cb_t s_dslp_cb[MAX_DSLP_HOOKS]={0};
  151. /**
  152. * Internal structure which holds all requested sleep parameters
  153. */
  154. typedef struct {
  155. struct {
  156. esp_sleep_pd_option_t pd_option;
  157. int16_t refs;
  158. uint16_t reserved; /* reserved for 4 bytes aligned */
  159. } domain[ESP_PD_DOMAIN_MAX];
  160. portMUX_TYPE lock;
  161. uint64_t sleep_duration;
  162. uint32_t wakeup_triggers : 15;
  163. #if SOC_PM_SUPPORT_EXT1_WAKEUP
  164. uint32_t ext1_trigger_mode : 22; // 22 is the maximum RTCIO number in all chips
  165. uint32_t ext1_rtc_gpio_mask : 22;
  166. #endif
  167. #if SOC_PM_SUPPORT_EXT0_WAKEUP
  168. uint32_t ext0_trigger_level : 1;
  169. uint32_t ext0_rtc_gpio_num : 5;
  170. #endif
  171. #if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  172. uint32_t gpio_wakeup_mask : 8; // 8 is the maximum RTCIO number in all chips that support GPIO wakeup
  173. uint32_t gpio_trigger_mode : 8;
  174. #endif
  175. uint32_t sleep_time_adjustment;
  176. uint32_t ccount_ticks_record;
  177. uint32_t sleep_time_overhead_out;
  178. uint32_t rtc_clk_cal_period;
  179. uint32_t fast_clk_cal_period;
  180. uint64_t rtc_ticks_at_sleep_start;
  181. } sleep_config_t;
  182. #if CONFIG_ESP_SLEEP_DEBUG
  183. static esp_sleep_context_t *s_sleep_ctx = NULL;
  184. void esp_sleep_set_sleep_context(esp_sleep_context_t *sleep_ctx)
  185. {
  186. s_sleep_ctx = sleep_ctx;
  187. }
  188. #endif
  189. static uint32_t s_lightsleep_cnt = 0;
  190. _Static_assert(22 >= SOC_RTCIO_PIN_COUNT, "Chip has more RTCIOs than 22, should increase ext1_rtc_gpio_mask field size");
  191. static sleep_config_t s_config = {
  192. .domain = {
  193. [0 ... ESP_PD_DOMAIN_MAX - 1] = {
  194. .pd_option = ESP_PD_OPTION_AUTO,
  195. .refs = 0
  196. }
  197. },
  198. .lock = portMUX_INITIALIZER_UNLOCKED,
  199. .ccount_ticks_record = 0,
  200. .sleep_time_overhead_out = DEFAULT_SLEEP_OUT_OVERHEAD_US,
  201. .wakeup_triggers = 0
  202. };
  203. /* Internal variable used to track if light sleep wakeup sources are to be
  204. expected when determining wakeup cause. */
  205. static bool s_light_sleep_wakeup = false;
  206. /* Updating RTC_MEMORY_CRC_REG register via set_rtc_memory_crc()
  207. is not thread-safe, so we need to disable interrupts before going to deep sleep. */
  208. static portMUX_TYPE spinlock_rtc_deep_sleep = portMUX_INITIALIZER_UNLOCKED;
  209. static const char *TAG = "sleep";
  210. static RTC_FAST_ATTR bool s_adc_tsen_enabled = false;
  211. //in this mode, 2uA is saved, but RTC memory can't use at high temperature, and RTCIO can't be used as INPUT.
  212. static bool s_ultra_low_enabled = false;
  213. static bool s_periph_use_8m_flag = false;
  214. void esp_sleep_periph_use_8m(bool use_or_not)
  215. {
  216. s_periph_use_8m_flag = use_or_not;
  217. }
  218. static uint32_t get_power_down_flags(void);
  219. #if SOC_PM_SUPPORT_EXT0_WAKEUP
  220. static void ext0_wakeup_prepare(void);
  221. #endif
  222. #if SOC_PM_SUPPORT_EXT1_WAKEUP
  223. static void ext1_wakeup_prepare(void);
  224. #endif
  225. static esp_err_t timer_wakeup_prepare(int64_t sleep_duration);
  226. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  227. static void touch_wakeup_prepare(void);
  228. #endif
  229. #if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  230. static void gpio_deep_sleep_wakeup_prepare(void);
  231. #endif
  232. #if SOC_RTC_FAST_MEM_SUPPORTED
  233. #if SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY
  234. static RTC_FAST_ATTR esp_deep_sleep_wake_stub_fn_t wake_stub_fn_handler = NULL;
  235. static void RTC_IRAM_ATTR __attribute__((used, noinline)) esp_wake_stub_start(void)
  236. {
  237. if (wake_stub_fn_handler) {
  238. (*wake_stub_fn_handler)();
  239. }
  240. }
  241. /* We must have a default deep sleep wake stub entry function, which must be
  242. * located at the start address of the RTC fast memory, and its implementation
  243. * must be simple enough to ensure that there is no litteral data before the
  244. * wake stub entry, otherwise, the litteral data before the wake stub entry
  245. * will not be CRC checked. */
  246. static void __attribute__((section(".rtc.entry.text"))) esp_wake_stub_entry(void)
  247. {
  248. #define _SYM2STR(s) # s
  249. #define SYM2STR(s) _SYM2STR(s)
  250. #ifdef __riscv
  251. __asm__ __volatile__ (
  252. "addi sp, sp, -16 \n"
  253. "sw ra, 0(sp) \n"
  254. "jal ra, " SYM2STR(esp_wake_stub_start) "\n"
  255. "lw ra, 0(sp) \n"
  256. "addi sp, sp, 16 \n"
  257. );
  258. #else
  259. // call4 has a larger effective addressing range (-524284 to 524288 bytes),
  260. // which is sufficient for instruction addressing in RTC fast memory.
  261. __asm__ __volatile__ ("call4 " SYM2STR(esp_wake_stub_start) "\n");
  262. #endif
  263. }
  264. void RTC_IRAM_ATTR esp_set_deep_sleep_wake_stub_default_entry(void)
  265. {
  266. extern char _rtc_text_start[];
  267. #if CONFIG_ESP32S3_RTCDATA_IN_FAST_MEM
  268. extern char _rtc_noinit_end[];
  269. size_t rtc_fast_length = (size_t)_rtc_noinit_end - (size_t)_rtc_text_start;
  270. #else
  271. extern char _rtc_force_fast_end[];
  272. size_t rtc_fast_length = (size_t)_rtc_force_fast_end - (size_t)_rtc_text_start;
  273. #endif
  274. esp_rom_set_rtc_wake_addr((esp_rom_wake_func_t)esp_wake_stub_entry, rtc_fast_length);
  275. }
  276. #endif // SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY
  277. /* Wake from deep sleep stub
  278. See esp_deepsleep.h esp_wake_deep_sleep() comments for details.
  279. */
  280. esp_deep_sleep_wake_stub_fn_t esp_get_deep_sleep_wake_stub(void)
  281. {
  282. #if SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY
  283. esp_deep_sleep_wake_stub_fn_t stub_ptr = wake_stub_fn_handler;
  284. #else
  285. esp_deep_sleep_wake_stub_fn_t stub_ptr = (esp_deep_sleep_wake_stub_fn_t) REG_READ(RTC_ENTRY_ADDR_REG);
  286. #endif
  287. if (!esp_ptr_executable(stub_ptr)) {
  288. return NULL;
  289. }
  290. return stub_ptr;
  291. }
  292. #if CONFIG_IDF_TARGET_ESP32
  293. /* APP core of esp32 can't access to RTC FAST MEMORY, do not define it with RTC_IRAM_ATTR */
  294. void
  295. #else
  296. void RTC_IRAM_ATTR
  297. #endif
  298. esp_set_deep_sleep_wake_stub(esp_deep_sleep_wake_stub_fn_t new_stub)
  299. {
  300. #if SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY
  301. wake_stub_fn_handler = new_stub;
  302. #else
  303. REG_WRITE(RTC_ENTRY_ADDR_REG, (uint32_t)new_stub);
  304. #endif
  305. }
  306. void RTC_IRAM_ATTR esp_default_wake_deep_sleep(void)
  307. {
  308. /* Clear MMU for CPU 0 */
  309. #if CONFIG_IDF_TARGET_ESP32
  310. _DPORT_REG_WRITE(DPORT_PRO_CACHE_CTRL1_REG,
  311. _DPORT_REG_READ(DPORT_PRO_CACHE_CTRL1_REG) | DPORT_PRO_CACHE_MMU_IA_CLR);
  312. _DPORT_REG_WRITE(DPORT_PRO_CACHE_CTRL1_REG,
  313. _DPORT_REG_READ(DPORT_PRO_CACHE_CTRL1_REG) & (~DPORT_PRO_CACHE_MMU_IA_CLR));
  314. #if DEEP_SLEEP_WAKEUP_DELAY > 0
  315. // ROM code has not started yet, so we need to set delay factor
  316. // used by esp_rom_delay_us first.
  317. ets_update_cpu_frequency_rom(ets_get_detected_xtal_freq() / 1000000);
  318. // This delay is configured in menuconfig, it can be used to give
  319. // the flash chip some time to become ready.
  320. esp_rom_delay_us(DEEP_SLEEP_WAKEUP_DELAY);
  321. #endif
  322. #elif CONFIG_IDF_TARGET_ESP32S2
  323. REG_SET_BIT(EXTMEM_CACHE_DBG_INT_ENA_REG, EXTMEM_CACHE_DBG_EN);
  324. #endif
  325. }
  326. void __attribute__((weak, alias("esp_default_wake_deep_sleep"))) esp_wake_deep_sleep(void);
  327. #endif // SOC_RTC_FAST_MEM_SUPPORTED
  328. void esp_deep_sleep(uint64_t time_in_us)
  329. {
  330. esp_sleep_enable_timer_wakeup(time_in_us);
  331. esp_deep_sleep_start();
  332. }
  333. esp_err_t esp_deep_sleep_try(uint64_t time_in_us)
  334. {
  335. esp_sleep_enable_timer_wakeup(time_in_us);
  336. return esp_deep_sleep_try_to_start();
  337. }
  338. esp_err_t esp_deep_sleep_register_hook(esp_deep_sleep_cb_t new_dslp_cb)
  339. {
  340. portENTER_CRITICAL(&spinlock_rtc_deep_sleep);
  341. for(int n = 0; n < MAX_DSLP_HOOKS; n++){
  342. if (s_dslp_cb[n]==NULL || s_dslp_cb[n]==new_dslp_cb) {
  343. s_dslp_cb[n]=new_dslp_cb;
  344. portEXIT_CRITICAL(&spinlock_rtc_deep_sleep);
  345. return ESP_OK;
  346. }
  347. }
  348. portEXIT_CRITICAL(&spinlock_rtc_deep_sleep);
  349. ESP_LOGE(TAG, "Registered deepsleep callbacks exceeds MAX_DSLP_HOOKS");
  350. return ESP_ERR_NO_MEM;
  351. }
  352. void esp_deep_sleep_deregister_hook(esp_deep_sleep_cb_t old_dslp_cb)
  353. {
  354. portENTER_CRITICAL(&spinlock_rtc_deep_sleep);
  355. for(int n = 0; n < MAX_DSLP_HOOKS; n++){
  356. if(s_dslp_cb[n] == old_dslp_cb) {
  357. s_dslp_cb[n] = NULL;
  358. }
  359. }
  360. portEXIT_CRITICAL(&spinlock_rtc_deep_sleep);
  361. }
  362. static int s_cache_suspend_cnt = 0;
  363. // Must be called from critical sections.
  364. static void IRAM_ATTR suspend_cache(void) {
  365. s_cache_suspend_cnt++;
  366. if (s_cache_suspend_cnt == 1) {
  367. cache_hal_suspend(CACHE_LL_LEVEL_EXT_MEM, CACHE_TYPE_ALL);
  368. }
  369. }
  370. // Must be called from critical sections.
  371. static void IRAM_ATTR resume_cache(void) {
  372. s_cache_suspend_cnt--;
  373. assert(s_cache_suspend_cnt >= 0 && DRAM_STR("cache resume doesn't match suspend ops"));
  374. if (s_cache_suspend_cnt == 0) {
  375. cache_hal_resume(CACHE_LL_LEVEL_EXT_MEM, CACHE_TYPE_ALL);
  376. }
  377. }
  378. // [refactor-todo] provide target logic for body of uart functions below
  379. static void IRAM_ATTR flush_uarts(void)
  380. {
  381. for (int i = 0; i < SOC_UART_HP_NUM; ++i) {
  382. #ifdef CONFIG_IDF_TARGET_ESP32
  383. esp_rom_uart_tx_wait_idle(i);
  384. #else
  385. if (uart_ll_is_enabled(i)) {
  386. esp_rom_uart_tx_wait_idle(i);
  387. }
  388. #endif
  389. }
  390. }
  391. static uint32_t s_suspended_uarts_bmap = 0;
  392. /**
  393. * Suspend enabled uarts and return suspended uarts bit map.
  394. * Must be called from critical sections.
  395. */
  396. FORCE_INLINE_ATTR void suspend_uarts(void)
  397. {
  398. s_suspended_uarts_bmap = 0;
  399. for (int i = 0; i < SOC_UART_HP_NUM; ++i) {
  400. #ifndef CONFIG_IDF_TARGET_ESP32
  401. if (!uart_ll_is_enabled(i)) {
  402. continue;
  403. }
  404. #endif
  405. uart_ll_force_xoff(i);
  406. s_suspended_uarts_bmap |= BIT(i);
  407. #if SOC_UART_SUPPORT_FSM_TX_WAIT_SEND
  408. uint32_t uart_fsm = 0;
  409. do {
  410. uart_fsm = uart_ll_get_tx_fsm_status(i);
  411. } while (!(uart_fsm == UART_LL_FSM_IDLE || uart_fsm == UART_LL_FSM_TX_WAIT_SEND));
  412. #else
  413. while (uart_ll_get_tx_fsm_status(i) != 0) {}
  414. #endif
  415. }
  416. }
  417. // Must be called from critical sections
  418. FORCE_INLINE_ATTR void resume_uarts(void)
  419. {
  420. for (int i = 0; i < SOC_UART_HP_NUM; ++i) {
  421. if (s_suspended_uarts_bmap & 0x1) {
  422. uart_ll_force_xon(i);
  423. }
  424. s_suspended_uarts_bmap >>= 1;
  425. }
  426. }
  427. /*
  428. UART prepare strategy in sleep:
  429. Deepsleep : flush the fifo before enter sleep to avoid data loss
  430. Lightsleep:
  431. Chips not support PD_TOP: Suspend uart before cpu freq switch
  432. Chips support PD_TOP:
  433. For sleep which will not power down the TOP domain (uart belongs it), we can just suspend the UART.
  434. For sleep which will power down the TOP domain, we need to consider whether the uart flushing will
  435. block the sleep process and cause the rtos target tick to be missed upon waking up. It's need to
  436. estimate the flush time based on the number of bytes in the uart FIFO, if the predicted flush
  437. completion time has exceeded the wakeup time, we should abandon the flush, skip the sleep and
  438. return ESP_ERR_SLEEP_REJECT.
  439. */
  440. FORCE_INLINE_ATTR bool light_sleep_uart_prepare(uint32_t pd_flags, int64_t sleep_duration)
  441. {
  442. bool should_skip_sleep = false;
  443. #if !SOC_PM_SUPPORT_TOP_PD || !CONFIG_ESP_CONSOLE_UART
  444. suspend_uarts();
  445. #else
  446. if (pd_flags & PMU_SLEEP_PD_TOP) {
  447. if ((s_config.wakeup_triggers & RTC_TIMER_TRIG_EN) &&
  448. // +1 is for cover the last character flush time
  449. (sleep_duration < (int64_t)((UART_LL_FIFO_DEF_LEN - uart_ll_get_txfifo_len(CONSOLE_UART_DEV) + 1) * UART_FLUSH_US_PER_CHAR) + SLEEP_UART_FLUSH_DONE_TO_SLEEP_US)) {
  450. should_skip_sleep = true;
  451. } else {
  452. /* Only flush the uart_num configured to console, the transmission integrity of
  453. other uarts is guaranteed by the UART driver */
  454. esp_rom_uart_tx_wait_idle(CONFIG_ESP_CONSOLE_UART_NUM);
  455. }
  456. } else {
  457. suspend_uarts();
  458. }
  459. #endif
  460. return should_skip_sleep;
  461. }
  462. /**
  463. * These save-restore workaround should be moved to lower layer
  464. */
  465. FORCE_INLINE_ATTR void misc_modules_sleep_prepare(bool deep_sleep)
  466. {
  467. if (deep_sleep){
  468. for (int n = 0; n < MAX_DSLP_HOOKS; n++) {
  469. if (s_dslp_cb[n] != NULL) {
  470. s_dslp_cb[n]();
  471. }
  472. }
  473. } else {
  474. #if SOC_USB_SERIAL_JTAG_SUPPORTED && !SOC_USB_SERIAL_JTAG_SUPPORT_LIGHT_SLEEP
  475. // Only avoid USJ pad leakage here, USB OTG pad leakage is prevented through USB Host driver.
  476. sleep_console_usj_pad_backup_and_disable();
  477. #endif
  478. #if CONFIG_MAC_BB_PD
  479. mac_bb_power_down_cb_execute();
  480. #endif
  481. #if CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL
  482. gpio_sleep_mode_config_apply();
  483. #endif
  484. #if SOC_PM_SUPPORT_CPU_PD && SOC_PM_CPU_RETENTION_BY_RTCCNTL
  485. sleep_enable_cpu_retention();
  486. #endif
  487. #if REGI2C_ANA_CALI_PD_WORKAROUND
  488. regi2c_analog_cali_reg_read();
  489. #endif
  490. #if SOC_PM_RETENTION_HAS_REGDMA_POWER_BUG
  491. sleep_retention_do_system_retention(true);
  492. #endif
  493. }
  494. // TODO: IDF-7370
  495. if (!(deep_sleep && s_adc_tsen_enabled)){
  496. sar_periph_ctrl_power_disable();
  497. }
  498. }
  499. /**
  500. * These save-restore workaround should be moved to lower layer
  501. */
  502. FORCE_INLINE_ATTR void misc_modules_wake_prepare(void)
  503. {
  504. #if SOC_USB_SERIAL_JTAG_SUPPORTED && !SOC_USB_SERIAL_JTAG_SUPPORT_LIGHT_SLEEP
  505. sleep_console_usj_pad_restore();
  506. #endif
  507. #if SOC_PM_RETENTION_HAS_REGDMA_POWER_BUG
  508. sleep_retention_do_system_retention(false);
  509. #endif
  510. sar_periph_ctrl_power_enable();
  511. #if SOC_PM_SUPPORT_CPU_PD && SOC_PM_CPU_RETENTION_BY_RTCCNTL
  512. sleep_disable_cpu_retention();
  513. #endif
  514. #if CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL
  515. gpio_sleep_mode_config_unapply();
  516. #endif
  517. #if CONFIG_MAC_BB_PD
  518. mac_bb_power_up_cb_execute();
  519. #endif
  520. #if REGI2C_ANA_CALI_PD_WORKAROUND
  521. regi2c_analog_cali_reg_write();
  522. #endif
  523. }
  524. inline static uint32_t call_rtc_sleep_start(uint32_t reject_triggers, uint32_t lslp_mem_inf_fpu, bool dslp);
  525. static esp_err_t IRAM_ATTR esp_sleep_start(uint32_t pd_flags, esp_sleep_mode_t mode, bool allow_sleep_rejection)
  526. {
  527. // Stop UART output so that output is not lost due to APB frequency change.
  528. // For light sleep, suspend UART output — it will resume after wakeup.
  529. // For deep sleep, wait for the contents of UART FIFO to be sent.
  530. bool deep_sleep = (mode == ESP_SLEEP_MODE_DEEP_SLEEP);
  531. bool should_skip_sleep = false;
  532. int64_t sleep_duration = (int64_t) s_config.sleep_duration - (int64_t) s_config.sleep_time_adjustment;
  533. #if SOC_RTC_SLOW_CLK_SUPPORT_RC_FAST_D256
  534. //Keep the RTC8M_CLK on if RTC clock is rc_fast_d256.
  535. bool rtc_using_8md256 = (rtc_clk_slow_src_get() == SOC_RTC_SLOW_CLK_SRC_RC_FAST_D256);
  536. #else
  537. bool rtc_using_8md256 = false;
  538. #endif
  539. //Keep the RTC8M_CLK on if the ledc low-speed channel is clocked by RTC8M_CLK in lightsleep mode
  540. bool periph_using_8m = !deep_sleep && s_periph_use_8m_flag;
  541. //Override user-configured power modes.
  542. if (rtc_using_8md256 || periph_using_8m) {
  543. pd_flags &= ~RTC_SLEEP_PD_INT_8M;
  544. }
  545. // Sleep UART prepare
  546. if (deep_sleep) {
  547. flush_uarts();
  548. } else {
  549. should_skip_sleep = light_sleep_uart_prepare(pd_flags, sleep_duration);
  550. }
  551. // Will switch to XTAL turn down MSPI speed
  552. mspi_timing_change_speed_mode_cache_safe(true);
  553. // Save current frequency and switch to XTAL
  554. rtc_cpu_freq_config_t cpu_freq_config;
  555. rtc_clk_cpu_freq_get_config(&cpu_freq_config);
  556. rtc_clk_cpu_freq_set_xtal();
  557. #if SOC_PM_SUPPORT_EXT0_WAKEUP
  558. // Configure pins for external wakeup
  559. if (s_config.wakeup_triggers & RTC_EXT0_TRIG_EN) {
  560. ext0_wakeup_prepare();
  561. }
  562. #endif
  563. #if SOC_PM_SUPPORT_EXT1_WAKEUP
  564. if (s_config.wakeup_triggers & RTC_EXT1_TRIG_EN) {
  565. ext1_wakeup_prepare();
  566. }
  567. #endif
  568. #if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  569. if (deep_sleep && (s_config.wakeup_triggers & RTC_GPIO_TRIG_EN)) {
  570. gpio_deep_sleep_wakeup_prepare();
  571. }
  572. #endif
  573. #if CONFIG_ULP_COPROC_ENABLED
  574. // Enable ULP wakeup
  575. #if CONFIG_ULP_COPROC_TYPE_FSM
  576. if (s_config.wakeup_triggers & RTC_ULP_TRIG_EN) {
  577. #elif CONFIG_ULP_COPROC_TYPE_RISCV
  578. if (s_config.wakeup_triggers & (RTC_COCPU_TRIG_EN | RTC_COCPU_TRAP_TRIG_EN)) {
  579. #elif CONFIG_ULP_COPROC_TYPE_LP_CORE
  580. if (s_config.wakeup_triggers & RTC_LP_CORE_TRIG_EN) {
  581. #endif
  582. #ifdef CONFIG_IDF_TARGET_ESP32
  583. rtc_hal_ulp_wakeup_enable();
  584. #elif CONFIG_ULP_COPROC_TYPE_LP_CORE
  585. pmu_ll_hp_clear_sw_intr_status(&PMU);
  586. #else
  587. rtc_hal_ulp_int_clear();
  588. #endif
  589. }
  590. #endif // CONFIG_ULP_COPROC_ENABLED
  591. misc_modules_sleep_prepare(deep_sleep);
  592. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  593. if (deep_sleep) {
  594. if (s_config.wakeup_triggers & RTC_TOUCH_TRIG_EN) {
  595. touch_wakeup_prepare();
  596. #if CONFIG_IDF_TARGET_ESP32S2
  597. /* Workaround: In deep sleep, for ESP32S2, Power down the RTC_PERIPH will change the slope configuration of Touch sensor sleep pad.
  598. * The configuration change will change the reading of the sleep pad, which will cause the touch wake-up sensor to trigger falsely.
  599. */
  600. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  601. #endif
  602. }
  603. } else {
  604. /* In light sleep, the RTC_PERIPH power domain should be in the power-on state (Power on the touch circuit in light sleep),
  605. * otherwise the touch sensor FSM will be cleared, causing touch sensor false triggering.
  606. */
  607. if (touch_ll_get_fsm_state()) { // Check if the touch sensor is working properly.
  608. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  609. }
  610. }
  611. #endif
  612. uint32_t reject_triggers = allow_sleep_rejection ? (s_config.wakeup_triggers & RTC_SLEEP_REJECT_MASK) : 0;
  613. if (!deep_sleep) {
  614. /* Enable sleep reject for faster return from this function,
  615. * in case the wakeup is already triggerred.
  616. */
  617. reject_triggers |= sleep_modem_reject_triggers();
  618. }
  619. //Append some flags in addition to power domains
  620. uint32_t sleep_flags = pd_flags;
  621. if (s_adc_tsen_enabled) {
  622. sleep_flags |= RTC_SLEEP_USE_ADC_TESEN_MONITOR;
  623. }
  624. if (!s_ultra_low_enabled) {
  625. sleep_flags |= RTC_SLEEP_NO_ULTRA_LOW;
  626. }
  627. if (periph_using_8m) {
  628. sleep_flags |= RTC_SLEEP_DIG_USE_8M;
  629. }
  630. #if CONFIG_ESP_SLEEP_DEBUG
  631. if (s_sleep_ctx != NULL) {
  632. s_sleep_ctx->sleep_flags = sleep_flags;
  633. }
  634. #endif
  635. // Enter sleep
  636. esp_err_t result;
  637. #if SOC_PMU_SUPPORTED
  638. pmu_sleep_config_t config;
  639. pmu_sleep_init(pmu_sleep_config_default(&config, sleep_flags, s_config.sleep_time_adjustment,
  640. s_config.rtc_clk_cal_period, s_config.fast_clk_cal_period,
  641. deep_sleep), deep_sleep);
  642. #else
  643. rtc_sleep_config_t config;
  644. rtc_sleep_get_default_config(sleep_flags, &config);
  645. rtc_sleep_init(config);
  646. // Set state machine time for light sleep
  647. if (!deep_sleep) {
  648. rtc_sleep_low_init(s_config.rtc_clk_cal_period);
  649. }
  650. #endif
  651. // Configure timer wakeup
  652. if (!should_skip_sleep && (s_config.wakeup_triggers & RTC_TIMER_TRIG_EN)) {
  653. if (timer_wakeup_prepare(sleep_duration) != ESP_OK) {
  654. should_skip_sleep = allow_sleep_rejection ? true : false;
  655. }
  656. }
  657. #if CONFIG_ESP_SLEEP_SYSTIMER_STALL_WORKAROUND
  658. if (!(pd_flags & RTC_SLEEP_PD_XTAL)) {
  659. rtc_sleep_systimer_enable(false);
  660. }
  661. #endif
  662. if (should_skip_sleep) {
  663. result = ESP_ERR_SLEEP_REJECT;
  664. } else {
  665. #if CONFIG_ESP_SLEEP_DEBUG
  666. if (s_sleep_ctx != NULL) {
  667. s_sleep_ctx->wakeup_triggers = s_config.wakeup_triggers;
  668. }
  669. #endif
  670. if (deep_sleep) {
  671. #if !SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP
  672. esp_sleep_isolate_digital_gpio();
  673. #endif
  674. #if SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY
  675. esp_set_deep_sleep_wake_stub_default_entry();
  676. // Enter Deep Sleep
  677. #if SOC_PMU_SUPPORTED
  678. result = call_rtc_sleep_start(reject_triggers, config.power.hp_sys.dig_power.mem_dslp, deep_sleep);
  679. #else
  680. result = call_rtc_sleep_start(reject_triggers, config.lslp_mem_inf_fpu, deep_sleep);
  681. #endif
  682. #else
  683. #if !CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP
  684. /* If not possible stack is in RTC FAST memory, use the ROM function to calculate the CRC and save ~140 bytes IRAM */
  685. #if SOC_RTC_FAST_MEM_SUPPORTED
  686. set_rtc_memory_crc();
  687. #endif
  688. result = call_rtc_sleep_start(reject_triggers, config.lslp_mem_inf_fpu, deep_sleep);
  689. #else
  690. /* Otherwise, need to call the dedicated soc function for this */
  691. result = rtc_deep_sleep_start(s_config.wakeup_triggers, reject_triggers);
  692. #endif
  693. #endif // SOC_PM_SUPPORT_DEEPSLEEP_CHECK_STUB_ONLY
  694. } else {
  695. /* Cache Suspend 1: will wait cache idle in cache suspend */
  696. suspend_cache();
  697. /* On esp32c6, only the lp_aon pad hold function can only hold the GPIO state in the active mode.
  698. In order to avoid the leakage of the SPI cs pin, hold it here */
  699. #if (CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP && CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND)
  700. #if !CONFIG_IDF_TARGET_ESP32H2 // ESP32H2 TODO IDF-7359: related rtcio ll func not supported yet
  701. if(!(pd_flags & RTC_SLEEP_PD_VDDSDIO)) {
  702. /* Cache suspend also means SPI bus IDLE, then we can hold SPI CS pin safely */
  703. gpio_ll_hold_en(&GPIO, SPI_CS0_GPIO_NUM);
  704. }
  705. #endif
  706. #endif
  707. #if SOC_PMU_SUPPORTED
  708. #if SOC_PM_CPU_RETENTION_BY_SW
  709. esp_sleep_execute_event_callbacks(SLEEP_EVENT_HW_GOTO_SLEEP, (void *)0);
  710. if (pd_flags & PMU_SLEEP_PD_CPU) {
  711. result = esp_sleep_cpu_retention(pmu_sleep_start, s_config.wakeup_triggers, reject_triggers, config.power.hp_sys.dig_power.mem_dslp, deep_sleep);
  712. } else
  713. #endif
  714. {
  715. result = call_rtc_sleep_start(reject_triggers, config.power.hp_sys.dig_power.mem_dslp, deep_sleep);
  716. }
  717. esp_sleep_execute_event_callbacks(SLEEP_EVENT_HW_EXIT_SLEEP, (void *)0);
  718. #else
  719. result = call_rtc_sleep_start(reject_triggers, config.lslp_mem_inf_fpu, deep_sleep);
  720. #endif
  721. /* Unhold the SPI CS pin */
  722. #if (CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP && CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND)
  723. #if !CONFIG_IDF_TARGET_ESP32H2 // ESP32H2 TODO IDF-7359: related rtcio ll func not supported yet
  724. if(!(pd_flags & RTC_SLEEP_PD_VDDSDIO)) {
  725. gpio_ll_hold_dis(&GPIO, SPI_CS0_GPIO_NUM);
  726. }
  727. #endif
  728. #endif
  729. /* Cache Resume 1: Resume cache for continue running*/
  730. resume_cache();
  731. }
  732. #if CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION
  733. if (pd_flags & RTC_SLEEP_PD_VDDSDIO) {
  734. /* Cache Suspend 2: If previous sleep powerdowned the flash, suspend cache here so that the
  735. access to flash before flash ready can be explicitly exposed. */
  736. suspend_cache();
  737. }
  738. #endif
  739. #if CONFIG_ESP_SLEEP_SYSTIMER_STALL_WORKAROUND
  740. if (!(pd_flags & RTC_SLEEP_PD_XTAL)) {
  741. rtc_sleep_systimer_enable(true);
  742. }
  743. #endif
  744. }
  745. // Restore CPU frequency
  746. #if SOC_PM_SUPPORT_PMU_MODEM_STATE
  747. if (pmu_sleep_pll_already_enabled()) {
  748. rtc_clk_cpu_freq_to_pll_and_pll_lock_release(esp_pm_impl_get_cpu_freq(PM_MODE_CPU_MAX));
  749. } else
  750. #endif
  751. {
  752. rtc_clk_cpu_freq_set_config(&cpu_freq_config);
  753. }
  754. if (cpu_freq_config.source == SOC_CPU_CLK_SRC_PLL) {
  755. // Turn up MSPI speed if switch to PLL
  756. mspi_timing_change_speed_mode_cache_safe(false);
  757. }
  758. esp_sleep_execute_event_callbacks(SLEEP_EVENT_SW_CLK_READY, (void *)0);
  759. if (!deep_sleep) {
  760. s_config.ccount_ticks_record = esp_cpu_get_cycle_count();
  761. misc_modules_wake_prepare();
  762. }
  763. // re-enable UART output
  764. resume_uarts();
  765. return result ? ESP_ERR_SLEEP_REJECT : ESP_OK;
  766. }
  767. inline static uint32_t IRAM_ATTR call_rtc_sleep_start(uint32_t reject_triggers, uint32_t lslp_mem_inf_fpu, bool dslp)
  768. {
  769. #ifdef CONFIG_IDF_TARGET_ESP32
  770. return rtc_sleep_start(s_config.wakeup_triggers, reject_triggers);
  771. #elif SOC_PMU_SUPPORTED
  772. return pmu_sleep_start(s_config.wakeup_triggers, reject_triggers, lslp_mem_inf_fpu, dslp);
  773. #else
  774. return rtc_sleep_start(s_config.wakeup_triggers, reject_triggers, lslp_mem_inf_fpu);
  775. #endif
  776. }
  777. static esp_err_t IRAM_ATTR deep_sleep_start(bool allow_sleep_rejection)
  778. {
  779. #if CONFIG_IDF_TARGET_ESP32S2
  780. /* Due to hardware limitations, on S2 the brownout detector sometimes trigger during deep sleep
  781. to circumvent this we disable the brownout detector before sleeping */
  782. esp_brownout_disable();
  783. #endif //CONFIG_IDF_TARGET_ESP32S2
  784. esp_sync_timekeeping_timers();
  785. /* Disable interrupts and stall another core in case another task writes
  786. * to RTC memory while we calculate RTC memory CRC.
  787. */
  788. portENTER_CRITICAL(&spinlock_rtc_deep_sleep);
  789. esp_ipc_isr_stall_other_cpu();
  790. // record current RTC time
  791. s_config.rtc_ticks_at_sleep_start = rtc_time_get();
  792. #if SOC_RTC_FAST_MEM_SUPPORTED
  793. // Configure wake stub
  794. if (esp_get_deep_sleep_wake_stub() == NULL) {
  795. esp_set_deep_sleep_wake_stub(esp_wake_deep_sleep);
  796. }
  797. #endif // SOC_RTC_FAST_MEM_SUPPORTED
  798. // Decide which power domains can be powered down
  799. uint32_t pd_flags = get_power_down_flags();
  800. s_config.rtc_clk_cal_period = esp_clk_slowclk_cal_get();
  801. // Correct the sleep time
  802. s_config.sleep_time_adjustment = DEEP_SLEEP_TIME_OVERHEAD_US;
  803. #if SOC_PMU_SUPPORTED
  804. uint32_t force_pd_flags = PMU_SLEEP_PD_TOP | PMU_SLEEP_PD_VDDSDIO | PMU_SLEEP_PD_MODEM | PMU_SLEEP_PD_HP_PERIPH \
  805. | PMU_SLEEP_PD_CPU | PMU_SLEEP_PD_MEM | PMU_SLEEP_PD_XTAL;
  806. #if SOC_PM_SUPPORT_HP_AON_PD
  807. force_pd_flags |= PMU_SLEEP_PD_HP_AON;
  808. #endif
  809. #else
  810. uint32_t force_pd_flags = RTC_SLEEP_PD_DIG | RTC_SLEEP_PD_VDDSDIO | RTC_SLEEP_PD_INT_8M | RTC_SLEEP_PD_XTAL;
  811. #endif
  812. /**
  813. * If all wireless modules share one power domain, we name this power domain "modem".
  814. * If wireless modules have their own power domain, we give these power domains separate
  815. * names.
  816. */
  817. #if SOC_PM_SUPPORT_MODEM_PD
  818. force_pd_flags |= RTC_SLEEP_PD_MODEM;
  819. #endif
  820. #if SOC_PM_SUPPORT_WIFI_PD
  821. force_pd_flags |= RTC_SLEEP_PD_WIFI;
  822. #endif
  823. #if SOC_PM_SUPPORT_BT_PD
  824. force_pd_flags |= RTC_SLEEP_PD_BT;
  825. #endif
  826. // Enter sleep
  827. esp_err_t err = ESP_OK;
  828. if (esp_sleep_start(force_pd_flags | pd_flags, ESP_SLEEP_MODE_DEEP_SLEEP, allow_sleep_rejection) == ESP_ERR_SLEEP_REJECT) {
  829. err = ESP_ERR_SLEEP_REJECT;
  830. #if CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION
  831. /* Cache Resume 2: if CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION is enabled, cache has been suspended in esp_sleep_start */
  832. resume_cache();
  833. #endif
  834. ESP_EARLY_LOGE(TAG, "Deep sleep request is rejected");
  835. } else {
  836. // Because RTC is in a slower clock domain than the CPU, it
  837. // can take several CPU cycles for the sleep mode to start.
  838. while (1) {
  839. ;
  840. }
  841. }
  842. // Never returns here, except that the sleep is rejected.
  843. esp_ipc_isr_release_other_cpu();
  844. portEXIT_CRITICAL(&spinlock_rtc_deep_sleep);
  845. return err;
  846. }
  847. void IRAM_ATTR esp_deep_sleep_start(void)
  848. {
  849. bool allow_sleep_rejection = true;
  850. deep_sleep_start(!allow_sleep_rejection);
  851. // Never returns here
  852. abort();
  853. }
  854. esp_err_t IRAM_ATTR esp_deep_sleep_try_to_start(void)
  855. {
  856. bool allow_sleep_rejection = true;
  857. return deep_sleep_start(allow_sleep_rejection);
  858. }
  859. /**
  860. * Helper function which handles entry to and exit from light sleep
  861. * Placed into IRAM as flash may need some time to be powered on.
  862. */
  863. static esp_err_t esp_light_sleep_inner(uint32_t pd_flags,
  864. uint32_t flash_enable_time_us) IRAM_ATTR __attribute__((noinline));
  865. static esp_err_t esp_light_sleep_inner(uint32_t pd_flags,
  866. uint32_t flash_enable_time_us)
  867. {
  868. #if SOC_CONFIGURABLE_VDDSDIO_SUPPORTED
  869. rtc_vddsdio_config_t vddsdio_config = rtc_vddsdio_get_config();
  870. #endif
  871. // Enter sleep
  872. esp_err_t reject = esp_sleep_start(pd_flags, ESP_SLEEP_MODE_LIGHT_SLEEP, true);
  873. #if SOC_CONFIGURABLE_VDDSDIO_SUPPORTED
  874. // If VDDSDIO regulator was controlled by RTC registers before sleep,
  875. // restore the configuration.
  876. if (vddsdio_config.force) {
  877. rtc_vddsdio_set_config(vddsdio_config);
  878. }
  879. #endif
  880. // If SPI flash was powered down, wait for it to become ready
  881. if (pd_flags & RTC_SLEEP_PD_VDDSDIO) {
  882. // Wait for the flash chip to start up
  883. esp_rom_delay_us(flash_enable_time_us);
  884. }
  885. #if CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION
  886. if (pd_flags & RTC_SLEEP_PD_VDDSDIO) {
  887. /* Cache Resume 2: flash is ready now, we can resume the cache and access flash safely after */
  888. resume_cache();
  889. }
  890. #endif
  891. return reject;
  892. }
  893. /**
  894. * vddsdio is used for power supply of spi flash
  895. *
  896. * pd flash via menuconfig | pd flash via `esp_sleep_pd_config` | result
  897. * ---------------------------------------------------------------------------------------------------
  898. * 0 | 0 | no pd flash
  899. * x | 1 | pd flash with relaxed conditions(force_pd)
  900. * 1 | 0 | pd flash with strict conditions(safe_pd)
  901. */
  902. FORCE_INLINE_ATTR bool can_power_down_vddsdio(uint32_t pd_flags, const uint32_t vddsdio_pd_sleep_duration)
  903. {
  904. bool force_pd = !(s_config.wakeup_triggers & RTC_TIMER_TRIG_EN) || (s_config.sleep_duration > vddsdio_pd_sleep_duration);
  905. bool safe_pd = (s_config.wakeup_triggers == RTC_TIMER_TRIG_EN) && (s_config.sleep_duration > vddsdio_pd_sleep_duration);
  906. return (pd_flags & RTC_SLEEP_PD_VDDSDIO) ? force_pd : safe_pd;
  907. }
  908. esp_err_t esp_light_sleep_start(void)
  909. {
  910. s_config.ccount_ticks_record = esp_cpu_get_cycle_count();
  911. esp_sleep_execute_event_callbacks(SLEEP_EVENT_SW_GOTO_SLEEP, (void *)0);
  912. #if CONFIG_ESP_TASK_WDT_USE_ESP_TIMER
  913. esp_err_t timerret = ESP_OK;
  914. /* If a task watchdog timer is running, we have to stop it. */
  915. timerret = esp_task_wdt_stop();
  916. #endif // CONFIG_ESP_TASK_WDT_USE_ESP_TIMER
  917. portENTER_CRITICAL(&s_config.lock);
  918. /*
  919. Note: We are about to stall the other CPU via the esp_ipc_isr_stall_other_cpu(). However, there is a chance of
  920. deadlock if after stalling the other CPU, we attempt to take spinlocks already held by the other CPU that is.
  921. Thus any functions that we call after stalling the other CPU will need to have the locks taken first to avoid
  922. deadlock.
  923. Todo: IDF-5257
  924. */
  925. /* We will be calling esp_timer_private_set inside DPORT access critical
  926. * section. Make sure the code on the other CPU is not holding esp_timer
  927. * lock, otherwise there will be deadlock.
  928. */
  929. esp_timer_private_lock();
  930. /* We will be calling esp_rtc_get_time_us() below. Make sure the code on the other CPU is not holding the
  931. * esp_rtc_get_time_us() lock, otherwise there will be deadlock. esp_rtc_get_time_us() is called via:
  932. *
  933. * - esp_clk_slowclk_cal_set() -> esp_rtc_get_time_us()
  934. */
  935. esp_clk_private_lock();
  936. s_config.rtc_ticks_at_sleep_start = rtc_time_get();
  937. uint32_t ccount_at_sleep_start = esp_cpu_get_cycle_count();
  938. esp_sleep_execute_event_callbacks(SLEEP_EVENT_HW_TIME_START, (void *)0);
  939. uint64_t high_res_time_at_start = esp_timer_get_time();
  940. uint32_t sleep_time_overhead_in = (ccount_at_sleep_start - s_config.ccount_ticks_record) / (esp_clk_cpu_freq() / 1000000ULL);
  941. #if CONFIG_ESP_SLEEP_DEBUG
  942. if (s_sleep_ctx != NULL) {
  943. s_sleep_ctx->sleep_in_rtc_time_stamp = s_config.rtc_ticks_at_sleep_start;
  944. }
  945. #endif
  946. esp_ipc_isr_stall_other_cpu();
  947. #if CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION && CONFIG_PM_SLP_IRAM_OPT
  948. /* Cache Suspend 0: if CONFIG_PM_SLP_IRAM_OPT is enabled, suspend cache here so that the access to flash
  949. during the sleep process can be explicitly exposed. */
  950. suspend_cache();
  951. #endif
  952. // Decide which power domains can be powered down
  953. uint32_t pd_flags = get_power_down_flags();
  954. #ifdef CONFIG_ESP_SLEEP_RTC_BUS_ISO_WORKAROUND
  955. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  956. #endif
  957. // Re-calibrate the RTC Timer clock
  958. #ifdef CONFIG_ESP_SYSTEM_RTC_EXT_XTAL
  959. if (rtc_clk_slow_src_get() == SOC_RTC_SLOW_CLK_SRC_XTAL32K) {
  960. uint64_t time_per_us = 1000000ULL;
  961. s_config.rtc_clk_cal_period = (time_per_us << RTC_CLK_CAL_FRACT) / rtc_clk_slow_freq_get_hz();
  962. } else {
  963. // If the external 32 kHz XTAL does not exist, use the internal 150 kHz RC oscillator
  964. // as the RTC slow clock source.
  965. s_config.rtc_clk_cal_period = rtc_clk_cal(RTC_CAL_RTC_MUX, RTC_CLK_SRC_CAL_CYCLES);
  966. esp_clk_slowclk_cal_set(s_config.rtc_clk_cal_period);
  967. }
  968. #elif CONFIG_RTC_CLK_SRC_INT_RC && CONFIG_IDF_TARGET_ESP32S2
  969. s_config.rtc_clk_cal_period = rtc_clk_cal_cycling(RTC_CAL_RTC_MUX, RTC_CLK_SRC_CAL_CYCLES);
  970. esp_clk_slowclk_cal_set(s_config.rtc_clk_cal_period);
  971. #else
  972. #if CONFIG_PM_ENABLE
  973. if (s_lightsleep_cnt % CONFIG_PM_LIGHTSLEEP_RTC_OSC_CAL_INTERVAL == 0)
  974. #endif
  975. {
  976. s_config.rtc_clk_cal_period = rtc_clk_cal(RTC_CAL_RTC_MUX, RTC_CLK_SRC_CAL_CYCLES);
  977. esp_clk_slowclk_cal_set(s_config.rtc_clk_cal_period);
  978. }
  979. #endif
  980. /*
  981. * Adjustment time consists of parts below:
  982. * 1. Hardware time waiting for internal 8M oscilate clock and XTAL;
  983. * 2. Hardware state swithing time of the rtc main state machine;
  984. * 3. Code execution time when clock is not stable;
  985. * 4. Code execution time which can be measured;
  986. */
  987. #if SOC_PMU_SUPPORTED
  988. #if CONFIG_PM_ENABLE
  989. if (s_lightsleep_cnt % CONFIG_PM_LIGHTSLEEP_RTC_OSC_CAL_INTERVAL == 0)
  990. #endif
  991. {
  992. s_config.fast_clk_cal_period = rtc_clk_cal(RTC_CAL_RC_FAST, FAST_CLK_SRC_CAL_CYCLES);
  993. }
  994. int sleep_time_sw_adjustment = LIGHT_SLEEP_TIME_OVERHEAD_US + sleep_time_overhead_in + s_config.sleep_time_overhead_out;
  995. int sleep_time_hw_adjustment = pmu_sleep_calculate_hw_wait_time(pd_flags, s_config.rtc_clk_cal_period, s_config.fast_clk_cal_period);
  996. s_config.sleep_time_adjustment = sleep_time_sw_adjustment + sleep_time_hw_adjustment;
  997. #else
  998. 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);
  999. s_config.sleep_time_adjustment = LIGHT_SLEEP_TIME_OVERHEAD_US + sleep_time_overhead_in + s_config.sleep_time_overhead_out
  1000. + 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);
  1001. #endif
  1002. #if CONFIG_IDF_TARGET_ESP32C6 // TODO: IDF-6930
  1003. const uint32_t flash_enable_time_us = 0;
  1004. #else
  1005. // Decide if VDD_SDIO needs to be powered down;
  1006. // If it needs to be powered down, adjust sleep time.
  1007. const uint32_t flash_enable_time_us = VDD_SDIO_POWERUP_TO_FLASH_READ_US + DEEP_SLEEP_WAKEUP_DELAY;
  1008. /**
  1009. * If VDD_SDIO power domain is requested to be turned off, bit `RTC_SLEEP_PD_VDDSDIO`
  1010. * will be set in `pd_flags`.
  1011. */
  1012. if (pd_flags & RTC_SLEEP_PD_VDDSDIO) {
  1013. /*
  1014. * When VDD_SDIO power domain has to be turned off, the minimum sleep time of the
  1015. * system needs to meet the sum below:
  1016. * 1. Wait time for the flash power-on after waking up;
  1017. * 2. The execution time of codes between RTC Timer get start time
  1018. * with hardware starts to switch state to sleep;
  1019. * 3. The hardware state switching time of the rtc state machine during
  1020. * sleep and wake-up. This process requires 6 cycles to complete.
  1021. * The specific hardware state switching process and the cycles
  1022. * consumed are rtc_cpu_run_stall(1), cut_pll_rtl(2), cut_8m(1),
  1023. * min_protect(2);
  1024. * 4. All the adjustment time which is s_config.sleep_time_adjustment below.
  1025. */
  1026. const uint32_t vddsdio_pd_sleep_duration = MAX(FLASH_PD_MIN_SLEEP_TIME_US,
  1027. flash_enable_time_us + LIGHT_SLEEP_MIN_TIME_US + s_config.sleep_time_adjustment
  1028. + rtc_time_slowclk_to_us(RTC_MODULE_SLEEP_PREPARE_CYCLES, s_config.rtc_clk_cal_period));
  1029. if (can_power_down_vddsdio(pd_flags, vddsdio_pd_sleep_duration)) {
  1030. if (s_config.sleep_time_overhead_out < flash_enable_time_us) {
  1031. s_config.sleep_time_adjustment += flash_enable_time_us;
  1032. }
  1033. } else {
  1034. /**
  1035. * Minimum sleep time is not enough, then keep the VDD_SDIO power
  1036. * domain on.
  1037. */
  1038. pd_flags &= ~RTC_SLEEP_PD_VDDSDIO;
  1039. if (s_config.sleep_time_overhead_out > flash_enable_time_us) {
  1040. s_config.sleep_time_adjustment -= flash_enable_time_us;
  1041. }
  1042. }
  1043. }
  1044. #endif
  1045. periph_inform_out_light_sleep_overhead(s_config.sleep_time_adjustment - sleep_time_overhead_in);
  1046. // Safety net: enable WDT in case exit from light sleep fails
  1047. wdt_hal_context_t rtc_wdt_ctx = RWDT_HAL_CONTEXT_DEFAULT();
  1048. 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.
  1049. if (!wdt_was_enabled) {
  1050. wdt_hal_init(&rtc_wdt_ctx, WDT_RWDT, 0, false);
  1051. uint32_t stage_timeout_ticks = (uint32_t)(1000ULL * rtc_clk_slow_freq_get_hz() / 1000ULL);
  1052. wdt_hal_write_protect_disable(&rtc_wdt_ctx);
  1053. wdt_hal_config_stage(&rtc_wdt_ctx, WDT_STAGE0, stage_timeout_ticks, WDT_STAGE_ACTION_RESET_RTC);
  1054. wdt_hal_enable(&rtc_wdt_ctx);
  1055. wdt_hal_write_protect_enable(&rtc_wdt_ctx);
  1056. }
  1057. esp_err_t err = ESP_OK;
  1058. int64_t final_sleep_duration_us = (int64_t)s_config.sleep_duration - (int64_t)s_config.sleep_time_adjustment;
  1059. int64_t min_sleep_duration_us = rtc_time_slowclk_to_us(RTC_CNTL_MIN_SLP_VAL_MIN, s_config.rtc_clk_cal_period);
  1060. // reset light sleep wakeup flag before a new light sleep
  1061. s_light_sleep_wakeup = false;
  1062. s_lightsleep_cnt++;
  1063. #if CONFIG_ESP_SLEEP_DEBUG
  1064. if (s_sleep_ctx != NULL) {
  1065. s_sleep_ctx->lightsleep_cnt = s_lightsleep_cnt;
  1066. }
  1067. #endif
  1068. // if rtc timer wakeup source is enabled, need to compare final sleep duration and min sleep duration to avoid late wakeup
  1069. if ((s_config.wakeup_triggers & RTC_TIMER_TRIG_EN) && (final_sleep_duration_us <= min_sleep_duration_us)) {
  1070. err = ESP_ERR_SLEEP_TOO_SHORT_SLEEP_DURATION;
  1071. } else {
  1072. // Enter sleep, then wait for flash to be ready on wakeup
  1073. err = esp_light_sleep_inner(pd_flags, flash_enable_time_us);
  1074. }
  1075. // light sleep wakeup flag only makes sense after a successful light sleep
  1076. s_light_sleep_wakeup = (err == ESP_OK);
  1077. // System timer has been stopped for the duration of the sleep, correct for that.
  1078. uint64_t rtc_ticks_at_end = rtc_time_get();
  1079. 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);
  1080. #if CONFIG_ESP_SLEEP_DEBUG
  1081. if (s_sleep_ctx != NULL) {
  1082. s_sleep_ctx->sleep_out_rtc_time_stamp = rtc_ticks_at_end;
  1083. }
  1084. #endif
  1085. /**
  1086. * If sleep duration is too small(less than 1 rtc_slow_clk cycle), rtc_time_diff will be zero.
  1087. * In this case, just ignore the time compensation and keep esp_timer monotonic.
  1088. */
  1089. if (rtc_time_diff > 0) {
  1090. esp_timer_private_set(high_res_time_at_start + rtc_time_diff);
  1091. }
  1092. esp_set_time_from_rtc();
  1093. esp_clk_private_unlock();
  1094. esp_timer_private_unlock();
  1095. #if CONFIG_ESP_SLEEP_CACHE_SAFE_ASSERTION && CONFIG_PM_SLP_IRAM_OPT
  1096. /* Cache Resume 0: sleep process done, resume cache for continue running */
  1097. resume_cache();
  1098. #endif
  1099. esp_ipc_isr_release_other_cpu();
  1100. if (!wdt_was_enabled) {
  1101. wdt_hal_write_protect_disable(&rtc_wdt_ctx);
  1102. wdt_hal_disable(&rtc_wdt_ctx);
  1103. wdt_hal_write_protect_enable(&rtc_wdt_ctx);
  1104. }
  1105. portEXIT_CRITICAL(&s_config.lock);
  1106. #if CONFIG_ESP_TASK_WDT_USE_ESP_TIMER
  1107. /* Restart the Task Watchdog timer as it was stopped before sleeping. */
  1108. if (timerret == ESP_OK) {
  1109. esp_task_wdt_restart();
  1110. }
  1111. #endif // CONFIG_ESP_TASK_WDT_USE_ESP_TIMER
  1112. esp_sleep_execute_event_callbacks(SLEEP_EVENT_SW_EXIT_SLEEP, (void *)0);
  1113. s_config.sleep_time_overhead_out = (esp_cpu_get_cycle_count() - s_config.ccount_ticks_record) / (esp_clk_cpu_freq() / 1000000ULL);
  1114. #if CONFIG_ESP_SLEEP_DEBUG
  1115. if (s_sleep_ctx != NULL) {
  1116. s_sleep_ctx->sleep_request_result = err;
  1117. }
  1118. #endif
  1119. return err;
  1120. }
  1121. esp_err_t esp_sleep_disable_wakeup_source(esp_sleep_source_t source)
  1122. {
  1123. // For most of sources it is enough to set trigger mask in local
  1124. // configuration structure. The actual RTC wake up options
  1125. // will be updated by esp_sleep_start().
  1126. if (source == ESP_SLEEP_WAKEUP_ALL) {
  1127. s_config.wakeup_triggers = 0;
  1128. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_TIMER, RTC_TIMER_TRIG_EN)) {
  1129. s_config.wakeup_triggers &= ~RTC_TIMER_TRIG_EN;
  1130. s_config.sleep_duration = 0;
  1131. #if SOC_PM_SUPPORT_EXT0_WAKEUP
  1132. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_EXT0, RTC_EXT0_TRIG_EN)) {
  1133. s_config.ext0_rtc_gpio_num = 0;
  1134. s_config.ext0_trigger_level = 0;
  1135. s_config.wakeup_triggers &= ~RTC_EXT0_TRIG_EN;
  1136. #endif
  1137. #if SOC_PM_SUPPORT_EXT1_WAKEUP
  1138. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_EXT1, RTC_EXT1_TRIG_EN)) {
  1139. s_config.ext1_rtc_gpio_mask = 0;
  1140. s_config.ext1_trigger_mode = 0;
  1141. s_config.wakeup_triggers &= ~RTC_EXT1_TRIG_EN;
  1142. #endif
  1143. #if SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP
  1144. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_TOUCHPAD, RTC_TOUCH_TRIG_EN)) {
  1145. s_config.wakeup_triggers &= ~RTC_TOUCH_TRIG_EN;
  1146. #endif
  1147. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_GPIO, RTC_GPIO_TRIG_EN)) {
  1148. s_config.wakeup_triggers &= ~RTC_GPIO_TRIG_EN;
  1149. } else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_UART, (RTC_UART0_TRIG_EN | RTC_UART1_TRIG_EN))) {
  1150. s_config.wakeup_triggers &= ~(RTC_UART0_TRIG_EN | RTC_UART1_TRIG_EN);
  1151. }
  1152. #if CONFIG_ULP_COPROC_TYPE_FSM
  1153. else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_ULP, RTC_ULP_TRIG_EN)) {
  1154. s_config.wakeup_triggers &= ~RTC_ULP_TRIG_EN;
  1155. }
  1156. #endif
  1157. else {
  1158. ESP_LOGE(TAG, "Incorrect wakeup source (%d) to disable.", (int) source);
  1159. return ESP_ERR_INVALID_STATE;
  1160. }
  1161. return ESP_OK;
  1162. }
  1163. esp_err_t esp_sleep_enable_ulp_wakeup(void)
  1164. {
  1165. #ifndef CONFIG_ULP_COPROC_ENABLED
  1166. return ESP_ERR_INVALID_STATE;
  1167. #endif // CONFIG_ULP_COPROC_ENABLED
  1168. #if CONFIG_IDF_TARGET_ESP32
  1169. #if ((defined CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT) || (defined CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_V2))
  1170. ESP_LOGE(TAG, "Failed to enable wakeup when provide current to external 32kHz crystal");
  1171. return ESP_ERR_NOT_SUPPORTED;
  1172. #endif
  1173. if (s_config.wakeup_triggers & RTC_EXT0_TRIG_EN) {
  1174. ESP_LOGE(TAG, "Conflicting wake-up trigger: ext0");
  1175. return ESP_ERR_INVALID_STATE;
  1176. }
  1177. #endif //CONFIG_IDF_TARGET_ESP32
  1178. #if CONFIG_ULP_COPROC_TYPE_FSM
  1179. s_config.wakeup_triggers |= RTC_ULP_TRIG_EN;
  1180. return ESP_OK;
  1181. #elif CONFIG_ULP_COPROC_TYPE_RISCV
  1182. s_config.wakeup_triggers |= (RTC_COCPU_TRIG_EN | RTC_COCPU_TRAP_TRIG_EN);
  1183. return ESP_OK;
  1184. #elif CONFIG_ULP_COPROC_TYPE_LP_CORE
  1185. s_config.wakeup_triggers |= RTC_LP_CORE_TRIG_EN;
  1186. return ESP_OK;
  1187. #else
  1188. return ESP_ERR_NOT_SUPPORTED;
  1189. #endif //CONFIG_ULP_COPROC_TYPE_FSM
  1190. }
  1191. esp_err_t esp_sleep_enable_timer_wakeup(uint64_t time_in_us)
  1192. {
  1193. s_config.wakeup_triggers |= RTC_TIMER_TRIG_EN;
  1194. s_config.sleep_duration = time_in_us;
  1195. return ESP_OK;
  1196. }
  1197. static esp_err_t timer_wakeup_prepare(int64_t sleep_duration)
  1198. {
  1199. if (sleep_duration < 0) {
  1200. sleep_duration = 0;
  1201. }
  1202. int64_t ticks = rtc_time_us_to_slowclk(sleep_duration, s_config.rtc_clk_cal_period);
  1203. int64_t target_wakeup_tick = s_config.rtc_ticks_at_sleep_start + ticks;
  1204. #if SOC_LP_TIMER_SUPPORTED
  1205. #if CONFIG_PM_POWER_DOWN_PERIPHERAL_IN_LIGHT_SLEEP
  1206. // Last timer wake-up validity check
  1207. if ((sleep_duration == 0) || \
  1208. (target_wakeup_tick < rtc_time_get() + SLEEP_TIMER_ALARM_TO_SLEEP_TICKS)) {
  1209. // Treat too short sleep duration setting as timer reject
  1210. return ESP_ERR_SLEEP_REJECT;
  1211. }
  1212. #endif
  1213. lp_timer_hal_set_alarm_target(0, target_wakeup_tick);
  1214. #else
  1215. rtc_hal_set_wakeup_timer(target_wakeup_tick);
  1216. #endif
  1217. return ESP_OK;
  1218. }
  1219. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  1220. /* In deep sleep mode, only the sleep channel is supported, and other touch channels should be turned off. */
  1221. static void touch_wakeup_prepare(void)
  1222. {
  1223. uint16_t sleep_cycle = 0;
  1224. uint16_t meas_times = 0;
  1225. touch_pad_t touch_num = TOUCH_PAD_NUM0;
  1226. touch_ll_sleep_get_channel_num(&touch_num); // Check if the sleep pad is enabled.
  1227. if ((touch_num > TOUCH_PAD_NUM0) && (touch_num < TOUCH_PAD_MAX) && touch_ll_get_fsm_state()) {
  1228. touch_ll_stop_fsm();
  1229. touch_ll_clear_channel_mask(TOUCH_PAD_BIT_MASK_ALL);
  1230. touch_ll_intr_clear(TOUCH_PAD_INTR_MASK_ALL); // Clear state from previous wakeup
  1231. touch_hal_sleep_channel_get_work_time(&sleep_cycle, &meas_times);
  1232. touch_ll_set_meas_times(meas_times);
  1233. touch_ll_set_sleep_time(sleep_cycle);
  1234. touch_ll_set_channel_mask(BIT(touch_num));
  1235. touch_ll_start_fsm();
  1236. }
  1237. }
  1238. #endif
  1239. #if SOC_TOUCH_SENSOR_SUPPORTED
  1240. esp_err_t esp_sleep_enable_touchpad_wakeup(void)
  1241. {
  1242. #if CONFIG_IDF_TARGET_ESP32
  1243. #if ((defined CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT) || (defined CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT_V2))
  1244. ESP_LOGE(TAG, "Failed to enable wakeup when provide current to external 32kHz crystal");
  1245. return ESP_ERR_NOT_SUPPORTED;
  1246. #endif
  1247. if (s_config.wakeup_triggers & (RTC_EXT0_TRIG_EN)) {
  1248. ESP_LOGE(TAG, "Conflicting wake-up trigger: ext0");
  1249. return ESP_ERR_INVALID_STATE;
  1250. }
  1251. #endif //CONFIG_IDF_TARGET_ESP32
  1252. s_config.wakeup_triggers |= RTC_TOUCH_TRIG_EN;
  1253. return ESP_OK;
  1254. }
  1255. touch_pad_t esp_sleep_get_touchpad_wakeup_status(void)
  1256. {
  1257. if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_TOUCHPAD) {
  1258. return TOUCH_PAD_MAX;
  1259. }
  1260. touch_pad_t pad_num;
  1261. touch_hal_get_wakeup_status(&pad_num);
  1262. return pad_num;
  1263. }
  1264. #endif // SOC_TOUCH_SENSOR_SUPPORTED
  1265. bool esp_sleep_is_valid_wakeup_gpio(gpio_num_t gpio_num)
  1266. {
  1267. #if SOC_RTCIO_PIN_COUNT > 0
  1268. return RTC_GPIO_IS_VALID_GPIO(gpio_num);
  1269. #else
  1270. return GPIO_IS_DEEP_SLEEP_WAKEUP_VALID_GPIO(gpio_num);
  1271. #endif
  1272. }
  1273. #if SOC_PM_SUPPORT_EXT0_WAKEUP
  1274. esp_err_t esp_sleep_enable_ext0_wakeup(gpio_num_t gpio_num, int level)
  1275. {
  1276. if (level < 0 || level > 1) {
  1277. return ESP_ERR_INVALID_ARG;
  1278. }
  1279. if (!esp_sleep_is_valid_wakeup_gpio(gpio_num)) {
  1280. return ESP_ERR_INVALID_ARG;
  1281. }
  1282. #if CONFIG_IDF_TARGET_ESP32
  1283. if (s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) {
  1284. ESP_LOGE(TAG, "Conflicting wake-up triggers: touch / ULP");
  1285. return ESP_ERR_INVALID_STATE;
  1286. }
  1287. #endif //CONFIG_IDF_TARGET_ESP32
  1288. s_config.ext0_rtc_gpio_num = rtc_io_number_get(gpio_num);
  1289. s_config.ext0_trigger_level = level;
  1290. s_config.wakeup_triggers |= RTC_EXT0_TRIG_EN;
  1291. return ESP_OK;
  1292. }
  1293. static void ext0_wakeup_prepare(void)
  1294. {
  1295. int rtc_gpio_num = s_config.ext0_rtc_gpio_num;
  1296. rtcio_hal_ext0_set_wakeup_pin(rtc_gpio_num, s_config.ext0_trigger_level);
  1297. rtcio_hal_function_select(rtc_gpio_num, RTCIO_LL_FUNC_RTC);
  1298. rtcio_hal_input_enable(rtc_gpio_num);
  1299. }
  1300. #endif // SOC_PM_SUPPORT_EXT0_WAKEUP
  1301. #if SOC_PM_SUPPORT_EXT1_WAKEUP
  1302. esp_err_t esp_sleep_enable_ext1_wakeup(uint64_t io_mask, esp_sleep_ext1_wakeup_mode_t level_mode)
  1303. {
  1304. if (level_mode > ESP_EXT1_WAKEUP_ANY_HIGH) {
  1305. return ESP_ERR_INVALID_ARG;
  1306. }
  1307. // Translate bit map of GPIO numbers into the bit map of RTC IO numbers
  1308. uint32_t rtc_gpio_mask = 0;
  1309. for (int gpio = 0; io_mask; ++gpio, io_mask >>= 1) {
  1310. if ((io_mask & 1) == 0) {
  1311. continue;
  1312. }
  1313. if (!esp_sleep_is_valid_wakeup_gpio(gpio)) {
  1314. ESP_LOGE(TAG, "Not an RTC IO: GPIO%d", gpio);
  1315. return ESP_ERR_INVALID_ARG;
  1316. }
  1317. rtc_gpio_mask |= BIT(rtc_io_number_get(gpio));
  1318. }
  1319. s_config.ext1_rtc_gpio_mask = rtc_gpio_mask;
  1320. if (level_mode) {
  1321. s_config.ext1_trigger_mode = rtc_gpio_mask;
  1322. } else {
  1323. s_config.ext1_trigger_mode = 0;
  1324. }
  1325. s_config.wakeup_triggers |= RTC_EXT1_TRIG_EN;
  1326. return ESP_OK;
  1327. }
  1328. #if SOC_PM_SUPPORT_EXT1_WAKEUP_MODE_PER_PIN
  1329. esp_err_t esp_sleep_enable_ext1_wakeup_with_level_mask(uint64_t io_mask, uint64_t level_mask)
  1330. {
  1331. if ((level_mask & io_mask) != level_mask) {
  1332. return ESP_ERR_INVALID_ARG;
  1333. }
  1334. // Translate bit map of GPIO numbers into the bit map of RTC IO numbers
  1335. // Translate bit map of GPIO wakeup mode into the bit map of RTC IO wakeup mode
  1336. uint32_t rtc_gpio_mask = 0, rtc_gpio_wakeup_mode_mask = 0;
  1337. for (int gpio = 0; io_mask; ++gpio, io_mask >>= 1, level_mask >>= 1) {
  1338. if ((io_mask & 1) == 0) {
  1339. continue;
  1340. }
  1341. if (!esp_sleep_is_valid_wakeup_gpio(gpio)) {
  1342. ESP_LOGE(TAG, "Not an RTC IO Considering io_mask: GPIO%d", gpio);
  1343. return ESP_ERR_INVALID_ARG;
  1344. }
  1345. rtc_gpio_mask |= BIT(rtc_io_number_get(gpio));
  1346. if ((level_mask & 1) == 1) {
  1347. rtc_gpio_wakeup_mode_mask |= BIT(rtc_io_number_get(gpio));
  1348. }
  1349. }
  1350. s_config.ext1_rtc_gpio_mask = rtc_gpio_mask;
  1351. s_config.ext1_trigger_mode = rtc_gpio_wakeup_mode_mask;
  1352. s_config.wakeup_triggers |= RTC_EXT1_TRIG_EN;
  1353. return ESP_OK;
  1354. }
  1355. #endif
  1356. static void ext1_wakeup_prepare(void)
  1357. {
  1358. // Configure all RTC IOs selected as ext1 wakeup inputs
  1359. uint32_t rtc_gpio_mask = s_config.ext1_rtc_gpio_mask;
  1360. for (int gpio = 0; gpio < GPIO_PIN_COUNT && rtc_gpio_mask != 0; ++gpio) {
  1361. int rtc_pin = rtc_io_number_get(gpio);
  1362. if ((rtc_gpio_mask & BIT(rtc_pin)) == 0) {
  1363. continue;
  1364. }
  1365. #if SOC_RTCIO_INPUT_OUTPUT_SUPPORTED
  1366. // Route pad to RTC
  1367. rtcio_hal_function_select(rtc_pin, RTCIO_LL_FUNC_RTC);
  1368. // set input enable in sleep mode
  1369. rtcio_hal_input_enable(rtc_pin);
  1370. #if SOC_PM_SUPPORT_RTC_PERIPH_PD
  1371. // Pad configuration depends on RTC_PERIPH state in sleep mode
  1372. if (s_config.domain[ESP_PD_DOMAIN_RTC_PERIPH].pd_option != ESP_PD_OPTION_ON) {
  1373. rtcio_hal_hold_enable(rtc_pin);
  1374. }
  1375. #endif
  1376. #else
  1377. /* ESP32H2 use hp iomux to config rtcio, and there is no complete
  1378. * rtcio functionality. In the case of EXT1 wakeup, rtcio only provides
  1379. * a pathway to EXT1. */
  1380. // Route pad to DIGITAL
  1381. rtcio_hal_function_select(rtc_pin, RTCIO_LL_FUNC_DIGITAL);
  1382. // set input enable
  1383. gpio_ll_input_enable(&GPIO, gpio);
  1384. // hold rtc_pin to use it during sleep state
  1385. rtcio_hal_hold_enable(rtc_pin);
  1386. #endif
  1387. // Keep track of pins which are processed to bail out early
  1388. rtc_gpio_mask &= ~BIT(rtc_pin);
  1389. }
  1390. // Clear state from previous wakeup
  1391. rtc_hal_ext1_clear_wakeup_status();
  1392. // Set RTC IO pins and mode to be used for wakeup
  1393. rtc_hal_ext1_set_wakeup_pins(s_config.ext1_rtc_gpio_mask, s_config.ext1_trigger_mode);
  1394. }
  1395. uint64_t esp_sleep_get_ext1_wakeup_status(void)
  1396. {
  1397. if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_EXT1) {
  1398. return 0;
  1399. }
  1400. uint32_t status = rtc_hal_ext1_get_wakeup_status();
  1401. // Translate bit map of RTC IO numbers into the bit map of GPIO numbers
  1402. uint64_t gpio_mask = 0;
  1403. for (int gpio = 0; gpio < GPIO_PIN_COUNT; ++gpio) {
  1404. if (!esp_sleep_is_valid_wakeup_gpio(gpio)) {
  1405. continue;
  1406. }
  1407. int rtc_pin = rtc_io_number_get(gpio);
  1408. if ((status & BIT(rtc_pin)) == 0) {
  1409. continue;
  1410. }
  1411. gpio_mask |= 1ULL << gpio;
  1412. }
  1413. return gpio_mask;
  1414. }
  1415. #endif // SOC_PM_SUPPORT_EXT1_WAKEUP
  1416. #if SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  1417. uint64_t esp_sleep_get_gpio_wakeup_status(void)
  1418. {
  1419. if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_GPIO) {
  1420. return 0;
  1421. }
  1422. return rtc_hal_gpio_get_wakeup_status();
  1423. }
  1424. static void gpio_deep_sleep_wakeup_prepare(void)
  1425. {
  1426. for (gpio_num_t gpio_idx = GPIO_NUM_0; gpio_idx < GPIO_NUM_MAX; gpio_idx++) {
  1427. if (((1ULL << gpio_idx) & s_config.gpio_wakeup_mask) == 0) {
  1428. continue;
  1429. }
  1430. #if CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS
  1431. if (s_config.gpio_trigger_mode & BIT(gpio_idx)) {
  1432. ESP_ERROR_CHECK(gpio_pullup_dis(gpio_idx));
  1433. ESP_ERROR_CHECK(gpio_pulldown_en(gpio_idx));
  1434. } else {
  1435. ESP_ERROR_CHECK(gpio_pullup_en(gpio_idx));
  1436. ESP_ERROR_CHECK(gpio_pulldown_dis(gpio_idx));
  1437. }
  1438. #endif
  1439. ESP_ERROR_CHECK(gpio_hold_en(gpio_idx));
  1440. }
  1441. // Clear state from previous wakeup
  1442. rtc_hal_gpio_clear_wakeup_status();
  1443. }
  1444. esp_err_t esp_deep_sleep_enable_gpio_wakeup(uint64_t gpio_pin_mask, esp_deepsleep_gpio_wake_up_mode_t mode)
  1445. {
  1446. if (mode > ESP_GPIO_WAKEUP_GPIO_HIGH) {
  1447. ESP_LOGE(TAG, "invalid mode");
  1448. return ESP_ERR_INVALID_ARG;
  1449. }
  1450. gpio_int_type_t intr_type = ((mode == ESP_GPIO_WAKEUP_GPIO_LOW) ? GPIO_INTR_LOW_LEVEL : GPIO_INTR_HIGH_LEVEL);
  1451. esp_err_t err = ESP_OK;
  1452. for (gpio_num_t gpio_idx = GPIO_NUM_0; gpio_idx < GPIO_NUM_MAX; gpio_idx++, gpio_pin_mask >>= 1) {
  1453. if ((gpio_pin_mask & 1) == 0) {
  1454. continue;
  1455. }
  1456. if (!esp_sleep_is_valid_wakeup_gpio(gpio_idx)) {
  1457. ESP_LOGE(TAG, "gpio %d is an invalid deep sleep wakeup IO", gpio_idx);
  1458. return ESP_ERR_INVALID_ARG;
  1459. }
  1460. err = gpio_deep_sleep_wakeup_enable(gpio_idx, intr_type);
  1461. s_config.gpio_wakeup_mask |= BIT(gpio_idx);
  1462. if (mode == ESP_GPIO_WAKEUP_GPIO_HIGH) {
  1463. s_config.gpio_trigger_mode |= (mode << gpio_idx);
  1464. } else {
  1465. s_config.gpio_trigger_mode &= ~(mode << gpio_idx);
  1466. }
  1467. }
  1468. s_config.wakeup_triggers |= RTC_GPIO_TRIG_EN;
  1469. return err;
  1470. }
  1471. #endif //SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP
  1472. esp_err_t esp_sleep_enable_gpio_wakeup(void)
  1473. {
  1474. #if CONFIG_IDF_TARGET_ESP32
  1475. if (s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) {
  1476. ESP_LOGE(TAG, "Conflicting wake-up triggers: touch / ULP");
  1477. return ESP_ERR_INVALID_STATE;
  1478. }
  1479. #endif
  1480. s_config.wakeup_triggers |= RTC_GPIO_TRIG_EN;
  1481. return ESP_OK;
  1482. }
  1483. esp_err_t esp_sleep_enable_uart_wakeup(int uart_num)
  1484. {
  1485. if (uart_num == UART_NUM_0) {
  1486. s_config.wakeup_triggers |= RTC_UART0_TRIG_EN;
  1487. } else if (uart_num == UART_NUM_1) {
  1488. s_config.wakeup_triggers |= RTC_UART1_TRIG_EN;
  1489. } else {
  1490. return ESP_ERR_INVALID_ARG;
  1491. }
  1492. return ESP_OK;
  1493. }
  1494. esp_err_t esp_sleep_enable_wifi_wakeup(void)
  1495. {
  1496. #if SOC_PM_SUPPORT_WIFI_WAKEUP
  1497. s_config.wakeup_triggers |= RTC_WIFI_TRIG_EN;
  1498. return ESP_OK;
  1499. #else
  1500. return ESP_ERR_NOT_SUPPORTED;
  1501. #endif
  1502. }
  1503. esp_err_t esp_sleep_disable_wifi_wakeup(void)
  1504. {
  1505. #if SOC_PM_SUPPORT_WIFI_WAKEUP
  1506. s_config.wakeup_triggers &= (~RTC_WIFI_TRIG_EN);
  1507. return ESP_OK;
  1508. #else
  1509. return ESP_ERR_NOT_SUPPORTED;
  1510. #endif
  1511. }
  1512. esp_err_t esp_sleep_enable_wifi_beacon_wakeup(void)
  1513. {
  1514. #if SOC_PM_SUPPORT_BEACON_WAKEUP
  1515. s_config.wakeup_triggers |= PMU_WIFI_BEACON_WAKEUP_EN;
  1516. return ESP_OK;
  1517. #else
  1518. return ESP_ERR_NOT_SUPPORTED;
  1519. #endif
  1520. }
  1521. esp_err_t esp_sleep_disable_wifi_beacon_wakeup(void)
  1522. {
  1523. #if SOC_PM_SUPPORT_BEACON_WAKEUP
  1524. s_config.wakeup_triggers &= (~PMU_WIFI_BEACON_WAKEUP_EN);
  1525. return ESP_OK;
  1526. #else
  1527. return ESP_ERR_NOT_SUPPORTED;
  1528. #endif
  1529. }
  1530. esp_err_t esp_sleep_enable_bt_wakeup(void)
  1531. {
  1532. #if SOC_PM_SUPPORT_BT_WAKEUP
  1533. s_config.wakeup_triggers |= RTC_BT_TRIG_EN;
  1534. return ESP_OK;
  1535. #else
  1536. return ESP_ERR_NOT_SUPPORTED;
  1537. #endif
  1538. }
  1539. esp_err_t esp_sleep_disable_bt_wakeup(void)
  1540. {
  1541. #if SOC_PM_SUPPORT_BT_WAKEUP
  1542. s_config.wakeup_triggers &= (~RTC_BT_TRIG_EN);
  1543. return ESP_OK;
  1544. #else
  1545. return ESP_ERR_NOT_SUPPORTED;
  1546. #endif
  1547. }
  1548. esp_sleep_wakeup_cause_t esp_sleep_get_wakeup_cause(void)
  1549. {
  1550. if (esp_rom_get_reset_reason(0) != RESET_REASON_CORE_DEEP_SLEEP && !s_light_sleep_wakeup) {
  1551. return ESP_SLEEP_WAKEUP_UNDEFINED;
  1552. }
  1553. #if SOC_PMU_SUPPORTED
  1554. uint32_t wakeup_cause = pmu_ll_hp_get_wakeup_cause(&PMU);
  1555. #else
  1556. uint32_t wakeup_cause = rtc_cntl_ll_get_wakeup_cause();
  1557. #endif
  1558. if (wakeup_cause & RTC_TIMER_TRIG_EN) {
  1559. return ESP_SLEEP_WAKEUP_TIMER;
  1560. } else if (wakeup_cause & RTC_GPIO_TRIG_EN) {
  1561. return ESP_SLEEP_WAKEUP_GPIO;
  1562. } else if (wakeup_cause & (RTC_UART0_TRIG_EN | RTC_UART1_TRIG_EN)) {
  1563. return ESP_SLEEP_WAKEUP_UART;
  1564. #if SOC_PM_SUPPORT_EXT0_WAKEUP
  1565. } else if (wakeup_cause & RTC_EXT0_TRIG_EN) {
  1566. return ESP_SLEEP_WAKEUP_EXT0;
  1567. #endif
  1568. #if SOC_PM_SUPPORT_EXT1_WAKEUP
  1569. } else if (wakeup_cause & RTC_EXT1_TRIG_EN) {
  1570. return ESP_SLEEP_WAKEUP_EXT1;
  1571. #endif
  1572. #if SOC_PM_SUPPORT_TOUCH_SENSOR_WAKEUP
  1573. } else if (wakeup_cause & RTC_TOUCH_TRIG_EN) {
  1574. return ESP_SLEEP_WAKEUP_TOUCHPAD;
  1575. #endif
  1576. #if SOC_ULP_FSM_SUPPORTED
  1577. } else if (wakeup_cause & RTC_ULP_TRIG_EN) {
  1578. return ESP_SLEEP_WAKEUP_ULP;
  1579. #endif
  1580. #if SOC_PM_SUPPORT_WIFI_WAKEUP
  1581. } else if (wakeup_cause & RTC_WIFI_TRIG_EN) {
  1582. return ESP_SLEEP_WAKEUP_WIFI;
  1583. #endif
  1584. #if SOC_PM_SUPPORT_BT_WAKEUP
  1585. } else if (wakeup_cause & RTC_BT_TRIG_EN) {
  1586. return ESP_SLEEP_WAKEUP_BT;
  1587. #endif
  1588. #if SOC_RISCV_COPROC_SUPPORTED
  1589. } else if (wakeup_cause & RTC_COCPU_TRIG_EN) {
  1590. return ESP_SLEEP_WAKEUP_ULP;
  1591. } else if (wakeup_cause & RTC_COCPU_TRAP_TRIG_EN) {
  1592. return ESP_SLEEP_WAKEUP_COCPU_TRAP_TRIG;
  1593. #endif
  1594. #if SOC_LP_CORE_SUPPORTED
  1595. } else if (wakeup_cause & RTC_LP_CORE_TRIG_EN) {
  1596. return ESP_SLEEP_WAKEUP_ULP;
  1597. #endif
  1598. } else {
  1599. return ESP_SLEEP_WAKEUP_UNDEFINED;
  1600. }
  1601. }
  1602. esp_err_t esp_sleep_pd_config(esp_sleep_pd_domain_t domain, esp_sleep_pd_option_t option)
  1603. {
  1604. if (domain >= ESP_PD_DOMAIN_MAX || option > ESP_PD_OPTION_AUTO) {
  1605. return ESP_ERR_INVALID_ARG;
  1606. }
  1607. portENTER_CRITICAL_SAFE(&s_config.lock);
  1608. int refs = (option == ESP_PD_OPTION_ON) ? s_config.domain[domain].refs++ \
  1609. : (option == ESP_PD_OPTION_OFF) ? --s_config.domain[domain].refs \
  1610. : s_config.domain[domain].refs;
  1611. if (refs == 0) {
  1612. s_config.domain[domain].pd_option = option;
  1613. }
  1614. portEXIT_CRITICAL_SAFE(&s_config.lock);
  1615. assert(refs >= 0);
  1616. return ESP_OK;
  1617. }
  1618. /**
  1619. * The modules in the CPU and modem power domains still depend on the top power domain.
  1620. * To be safe, the CPU and Modem power domains must also be powered off and saved when
  1621. * the TOP is powered off. If not power down XTAL, power down TOP is meaningless, and
  1622. * the XTAL clock control of some chips(esp32c6/esp32h2) depends on the top domain.
  1623. */
  1624. #if SOC_PM_SUPPORT_TOP_PD
  1625. FORCE_INLINE_ATTR bool top_domain_pd_allowed(void) {
  1626. return (cpu_domain_pd_allowed() && \
  1627. clock_domain_pd_allowed() && \
  1628. peripheral_domain_pd_allowed() && \
  1629. modem_domain_pd_allowed() && \
  1630. s_config.domain[ESP_PD_DOMAIN_XTAL].pd_option != ESP_PD_OPTION_ON);
  1631. }
  1632. #endif
  1633. static uint32_t get_power_down_flags(void)
  1634. {
  1635. // Where needed, convert AUTO options to ON. Later interpret AUTO as OFF.
  1636. // RTC_SLOW_MEM is needed for the ULP, so keep RTC_SLOW_MEM powered up if ULP
  1637. // is used and RTC_SLOW_MEM is Auto.
  1638. // If there is any data placed into .rtc.data or .rtc.bss segments, and
  1639. // RTC_SLOW_MEM is Auto, keep it powered up as well.
  1640. #if SOC_PM_SUPPORT_RTC_SLOW_MEM_PD && SOC_ULP_SUPPORTED
  1641. // Labels are defined in the linker script
  1642. extern int _rtc_slow_length, _rtc_reserved_length;
  1643. /**
  1644. * Compiler considers "(size_t) &_rtc_slow_length > 0" to always be true.
  1645. * So use a volatile variable to prevent compiler from doing this optimization.
  1646. */
  1647. volatile size_t rtc_slow_mem_used = (size_t)&_rtc_slow_length + (size_t)&_rtc_reserved_length;
  1648. if ((s_config.domain[ESP_PD_DOMAIN_RTC_SLOW_MEM].pd_option == ESP_PD_OPTION_AUTO) &&
  1649. (rtc_slow_mem_used > 0 || (s_config.wakeup_triggers & RTC_ULP_TRIG_EN))) {
  1650. s_config.domain[ESP_PD_DOMAIN_RTC_SLOW_MEM].pd_option = ESP_PD_OPTION_ON;
  1651. }
  1652. #endif
  1653. #if SOC_PM_SUPPORT_RTC_FAST_MEM_PD
  1654. #if !CONFIG_ESP_SYSTEM_ALLOW_RTC_FAST_MEM_AS_HEAP
  1655. /* RTC_FAST_MEM is needed for deep sleep stub.
  1656. If RTC_FAST_MEM is Auto, keep it powered on, so that deep sleep stub can run.
  1657. In the new chip revision, deep sleep stub will be optional, and this can be changed. */
  1658. if (s_config.domain[ESP_PD_DOMAIN_RTC_FAST_MEM].pd_option == ESP_PD_OPTION_AUTO) {
  1659. s_config.domain[ESP_PD_DOMAIN_RTC_FAST_MEM].pd_option = ESP_PD_OPTION_ON;
  1660. }
  1661. #else
  1662. /* If RTC_FAST_MEM is used for heap, force RTC_FAST_MEM to be powered on. */
  1663. s_config.domain[ESP_PD_DOMAIN_RTC_FAST_MEM].pd_option = ESP_PD_OPTION_ON;
  1664. #endif
  1665. #endif
  1666. #if SOC_PM_SUPPORT_RTC_PERIPH_PD
  1667. // RTC_PERIPH is needed for EXT0 wakeup and GPIO wakeup.
  1668. // If RTC_PERIPH is left auto (EXT0/GPIO aren't enabled), RTC_PERIPH will be powered off by default.
  1669. if (s_config.domain[ESP_PD_DOMAIN_RTC_PERIPH].pd_option == ESP_PD_OPTION_AUTO) {
  1670. if (s_config.wakeup_triggers & (RTC_EXT0_TRIG_EN | RTC_GPIO_TRIG_EN)) {
  1671. s_config.domain[ESP_PD_DOMAIN_RTC_PERIPH].pd_option = ESP_PD_OPTION_ON;
  1672. }
  1673. #if CONFIG_IDF_TARGET_ESP32
  1674. else if (s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) {
  1675. // On ESP32, forcing power up of RTC_PERIPH
  1676. // prevents ULP timer and touch FSMs from working correctly.
  1677. s_config.domain[ESP_PD_DOMAIN_RTC_PERIPH].pd_option = ESP_PD_OPTION_OFF;
  1678. }
  1679. #endif //CONFIG_IDF_TARGET_ESP32
  1680. #if SOC_LP_CORE_SUPPORTED
  1681. else if (s_config.wakeup_triggers & RTC_LP_CORE_TRIG_EN) {
  1682. // Need to keep RTC_PERIPH on to allow lp core to wakeup during sleep (e.g. from lp timer)
  1683. s_config.domain[ESP_PD_DOMAIN_RTC_PERIPH].pd_option = ESP_PD_OPTION_ON;
  1684. }
  1685. #endif //CONFIG_IDF_TARGET_ESP32
  1686. }
  1687. #endif // SOC_PM_SUPPORT_RTC_PERIPH_PD
  1688. /**
  1689. * VDD_SDIO power domain shall be kept on during the light sleep
  1690. * when CONFIG_ESP_SLEEP_POWER_DOWN_FLASH is not set and off when it is set.
  1691. * The application can still force the power domain to remain on by calling
  1692. * `esp_sleep_pd_config` before getting into light sleep mode.
  1693. *
  1694. * In deep sleep mode, the power domain will be turned off, regardless the
  1695. * value of this field.
  1696. */
  1697. #if SOC_PM_SUPPORT_VDDSDIO_PD
  1698. if (s_config.domain[ESP_PD_DOMAIN_VDDSDIO].pd_option == ESP_PD_OPTION_AUTO) {
  1699. #ifndef CONFIG_ESP_SLEEP_POWER_DOWN_FLASH
  1700. s_config.domain[ESP_PD_DOMAIN_VDDSDIO].pd_option = ESP_PD_OPTION_ON;
  1701. #endif
  1702. }
  1703. #endif
  1704. #ifdef CONFIG_IDF_TARGET_ESP32
  1705. s_config.domain[ESP_PD_DOMAIN_XTAL].pd_option = ESP_PD_OPTION_OFF;
  1706. #endif
  1707. // Prepare flags based on the selected options
  1708. uint32_t pd_flags = 0;
  1709. #if SOC_PM_SUPPORT_RTC_FAST_MEM_PD
  1710. if (s_config.domain[ESP_PD_DOMAIN_RTC_FAST_MEM].pd_option != ESP_PD_OPTION_ON) {
  1711. pd_flags |= RTC_SLEEP_PD_RTC_FAST_MEM;
  1712. }
  1713. #endif
  1714. #if SOC_PM_SUPPORT_RTC_SLOW_MEM_PD
  1715. if (s_config.domain[ESP_PD_DOMAIN_RTC_SLOW_MEM].pd_option != ESP_PD_OPTION_ON) {
  1716. pd_flags |= RTC_SLEEP_PD_RTC_SLOW_MEM;
  1717. }
  1718. #endif
  1719. #if SOC_PM_SUPPORT_RTC_PERIPH_PD
  1720. if (s_config.domain[ESP_PD_DOMAIN_RTC_PERIPH].pd_option != ESP_PD_OPTION_ON) {
  1721. pd_flags |= RTC_SLEEP_PD_RTC_PERIPH;
  1722. }
  1723. #endif
  1724. #if SOC_PM_SUPPORT_CPU_PD
  1725. if ((s_config.domain[ESP_PD_DOMAIN_CPU].pd_option != ESP_PD_OPTION_ON) && cpu_domain_pd_allowed()) {
  1726. pd_flags |= RTC_SLEEP_PD_CPU;
  1727. }
  1728. #endif
  1729. #if SOC_PM_SUPPORT_XTAL32K_PD
  1730. if (s_config.domain[ESP_PD_DOMAIN_XTAL32K].pd_option != ESP_PD_OPTION_ON) {
  1731. pd_flags |= PMU_SLEEP_PD_XTAL32K;
  1732. }
  1733. #endif
  1734. #if SOC_PM_SUPPORT_RC32K_PD
  1735. if (s_config.domain[ESP_PD_DOMAIN_RC32K].pd_option != ESP_PD_OPTION_ON) {
  1736. pd_flags |= PMU_SLEEP_PD_RC32K;
  1737. }
  1738. #endif
  1739. #if SOC_PM_SUPPORT_RC_FAST_PD
  1740. if (s_config.domain[ESP_PD_DOMAIN_RC_FAST].pd_option != ESP_PD_OPTION_ON) {
  1741. pd_flags |= RTC_SLEEP_PD_INT_8M;
  1742. }
  1743. #endif
  1744. if (s_config.domain[ESP_PD_DOMAIN_XTAL].pd_option != ESP_PD_OPTION_ON) {
  1745. pd_flags |= RTC_SLEEP_PD_XTAL;
  1746. }
  1747. #if SOC_PM_SUPPORT_TOP_PD
  1748. if ((s_config.domain[ESP_PD_DOMAIN_TOP].pd_option != ESP_PD_OPTION_ON) && top_domain_pd_allowed()) {
  1749. pd_flags |= PMU_SLEEP_PD_TOP;
  1750. }
  1751. #endif
  1752. #if SOC_PM_SUPPORT_MODEM_PD
  1753. if ((s_config.domain[ESP_PD_DOMAIN_MODEM].pd_option != ESP_PD_OPTION_ON) && modem_domain_pd_allowed()) {
  1754. pd_flags |= RTC_SLEEP_PD_MODEM;
  1755. }
  1756. #endif
  1757. #if SOC_PM_SUPPORT_VDDSDIO_PD
  1758. if (s_config.domain[ESP_PD_DOMAIN_VDDSDIO].pd_option != ESP_PD_OPTION_ON) {
  1759. pd_flags |= RTC_SLEEP_PD_VDDSDIO;
  1760. }
  1761. #endif
  1762. #if ((defined CONFIG_RTC_CLK_SRC_EXT_CRYS) && (defined CONFIG_RTC_EXT_CRYST_ADDIT_CURRENT) && (SOC_PM_SUPPORT_RTC_PERIPH_PD))
  1763. if ((s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) == 0) {
  1764. // If enabled EXT1 only and enable the additional current by touch, should be keep RTC_PERIPH power on.
  1765. pd_flags &= ~RTC_SLEEP_PD_RTC_PERIPH;
  1766. }
  1767. #endif
  1768. return pd_flags;
  1769. }
  1770. #if CONFIG_IDF_TARGET_ESP32
  1771. /* APP core of esp32 can't access to RTC FAST MEMORY, do not define it with RTC_IRAM_ATTR */
  1772. void
  1773. #else
  1774. void RTC_IRAM_ATTR
  1775. #endif
  1776. esp_deep_sleep_disable_rom_logging(void)
  1777. {
  1778. rtc_suppress_rom_log();
  1779. }
  1780. void esp_sleep_enable_adc_tsens_monitor(bool enable)
  1781. {
  1782. s_adc_tsen_enabled = enable;
  1783. }
  1784. void rtc_sleep_enable_ultra_low(bool enable)
  1785. {
  1786. s_ultra_low_enabled = enable;
  1787. }