]> granicus.if.org Git - esp-idf/blob - components/esp32/sleep_modes.c
sleep: optimize light sleep wakeup latency
[esp-idf] / components / esp32 / sleep_modes.c
1 // Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <stddef.h>
16 #include <sys/lock.h>
17 #include <sys/param.h>
18 #include "esp_attr.h"
19 #include "esp_sleep.h"
20 #include "esp_timer_impl.h"
21 #include "esp_log.h"
22 #include "esp_clk.h"
23 #include "esp_newlib.h"
24 #include "esp_spi_flash.h"
25 #include "rom/cache.h"
26 #include "rom/rtc.h"
27 #include "rom/uart.h"
28 #include "soc/cpu.h"
29 #include "soc/rtc.h"
30 #include "soc/rtc_cntl_reg.h"
31 #include "soc/rtc_io_reg.h"
32 #include "soc/spi_reg.h"
33 #include "soc/sens_reg.h"
34 #include "soc/dport_reg.h"
35 #include "driver/rtc_io.h"
36 #include "freertos/FreeRTOS.h"
37 #include "freertos/task.h"
38 #include "sdkconfig.h"
39
40 // If light sleep time is less than that, don't power down flash
41 #define FLASH_PD_MIN_SLEEP_TIME_US  2000
42
43 // Time from VDD_SDIO power up to first flash read in ROM code
44 #define VDD_SDIO_POWERUP_TO_FLASH_READ_US 700
45
46 // Extra time it takes to enter and exit light sleep and deep sleep
47 // For deep sleep, this is until the wake stub runs (not the app).
48 #ifdef CONFIG_ESP32_RTC_CLOCK_SOURCE_EXTERNAL_CRYSTAL
49 #define LIGHT_SLEEP_TIME_OVERHEAD_US (650 + 30 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
50 #define DEEP_SLEEP_TIME_OVERHEAD_US (650 + 100 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
51 #else
52 #define LIGHT_SLEEP_TIME_OVERHEAD_US (250 + 30 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
53 #define DEEP_SLEEP_TIME_OVERHEAD_US (250 + 100 * 240 / CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ)
54 #endif // CONFIG_ESP32_RTC_CLOCK_SOURCE
55
56 // Minimal amount of time we can sleep for
57 #define LIGHT_SLEEP_MIN_TIME_US 200
58
59 #define CHECK_SOURCE(source, value, mask) ((s_config.wakeup_triggers & mask) && \
60                                             (source == value))
61
62 /**
63  * Internal structure which holds all requested deep sleep parameters
64  */
65 typedef struct {
66     esp_sleep_pd_option_t pd_options[ESP_PD_DOMAIN_MAX];
67     uint64_t sleep_duration;
68     uint32_t wakeup_triggers : 11;
69     uint32_t ext1_trigger_mode : 1;
70     uint32_t ext1_rtc_gpio_mask : 18;
71     uint32_t ext0_trigger_level : 1;
72     uint32_t ext0_rtc_gpio_num : 5;
73     uint32_t sleep_time_adjustment;
74     uint64_t rtc_ticks_at_sleep_start;
75 } sleep_config_t;
76
77 static sleep_config_t s_config = {
78     .pd_options = { ESP_PD_OPTION_AUTO, ESP_PD_OPTION_AUTO, ESP_PD_OPTION_AUTO },
79     .wakeup_triggers = 0
80 };
81
82 /* Updating RTC_MEMORY_CRC_REG register via set_rtc_memory_crc()
83    is not thread-safe. */
84 static _lock_t lock_rtc_memory_crc;
85
86 static const char* TAG = "sleep";
87
88 static uint32_t get_power_down_flags();
89 static void ext0_wakeup_prepare();
90 static void ext1_wakeup_prepare();
91 static void timer_wakeup_prepare();
92
93 /* Wake from deep sleep stub
94    See esp_deepsleep.h esp_wake_deep_sleep() comments for details.
95 */
96 esp_deep_sleep_wake_stub_fn_t esp_get_deep_sleep_wake_stub(void)
97 {
98     _lock_acquire(&lock_rtc_memory_crc);
99     uint32_t stored_crc = REG_READ(RTC_MEMORY_CRC_REG);
100     set_rtc_memory_crc();
101     uint32_t calc_crc = REG_READ(RTC_MEMORY_CRC_REG);
102     REG_WRITE(RTC_MEMORY_CRC_REG, stored_crc);
103     _lock_release(&lock_rtc_memory_crc);
104
105     if(stored_crc == calc_crc) {
106         return (esp_deep_sleep_wake_stub_fn_t)REG_READ(RTC_ENTRY_ADDR_REG);
107     } else {
108         return NULL;
109     }
110 }
111
112 void esp_set_deep_sleep_wake_stub(esp_deep_sleep_wake_stub_fn_t new_stub)
113 {
114     _lock_acquire(&lock_rtc_memory_crc);
115     REG_WRITE(RTC_ENTRY_ADDR_REG, (uint32_t)new_stub);
116     set_rtc_memory_crc();
117     _lock_release(&lock_rtc_memory_crc);
118 }
119
120 void RTC_IRAM_ATTR esp_default_wake_deep_sleep(void) {
121     /* Clear MMU for CPU 0 */
122     _DPORT_REG_WRITE(DPORT_PRO_CACHE_CTRL1_REG,
123             _DPORT_REG_READ(DPORT_PRO_CACHE_CTRL1_REG) | DPORT_PRO_CACHE_MMU_IA_CLR);
124     _DPORT_REG_WRITE(DPORT_PRO_CACHE_CTRL1_REG,
125             _DPORT_REG_READ(DPORT_PRO_CACHE_CTRL1_REG) & (~DPORT_PRO_CACHE_MMU_IA_CLR));
126 #if CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY > 0
127     // ROM code has not started yet, so we need to set delay factor
128     // used by ets_delay_us first.
129     ets_update_cpu_frequency_rom(ets_get_detected_xtal_freq() / 1000000);
130     // This delay is configured in menuconfig, it can be used to give
131     // the flash chip some time to become ready.
132     ets_delay_us(CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY);
133 #endif
134 }
135
136 void __attribute__((weak, alias("esp_default_wake_deep_sleep"))) esp_wake_deep_sleep(void);
137
138 void esp_deep_sleep(uint64_t time_in_us)
139 {
140     esp_sleep_enable_timer_wakeup(time_in_us);
141     esp_deep_sleep_start();
142 }
143
144 static void IRAM_ATTR suspend_uarts()
145 {
146     for (int i = 0; i < 3; ++i) {
147         REG_SET_BIT(UART_FLOW_CONF_REG(i), UART_FORCE_XOFF);
148         uart_tx_wait_idle(i);
149     }
150 }
151
152 static void IRAM_ATTR resume_uarts()
153 {
154     for (int i = 0; i < 3; ++i) {
155         REG_CLR_BIT(UART_FLOW_CONF_REG(i), UART_FORCE_XOFF);
156         REG_SET_BIT(UART_FLOW_CONF_REG(i), UART_FORCE_XON);
157         REG_CLR_BIT(UART_FLOW_CONF_REG(i), UART_FORCE_XON);
158     }
159 }
160
161 static uint32_t IRAM_ATTR esp_sleep_start(uint32_t pd_flags)
162 {
163     // Stop UART output so that output is not lost due to APB frequency change
164     suspend_uarts();
165
166     // Save current frequency and switch to XTAL
167     rtc_cpu_freq_t cpu_freq = rtc_clk_cpu_freq_get();
168     rtc_clk_cpu_freq_set(RTC_CPU_FREQ_XTAL);
169
170     // Configure pins for external wakeup
171     if (s_config.wakeup_triggers & RTC_EXT0_TRIG_EN) {
172         ext0_wakeup_prepare();
173     }
174     if (s_config.wakeup_triggers & RTC_EXT1_TRIG_EN) {
175         ext1_wakeup_prepare();
176     }
177     // Enable ULP wakeup
178     if (s_config.wakeup_triggers & RTC_ULP_TRIG_EN) {
179         SET_PERI_REG_MASK(RTC_CNTL_STATE0_REG, RTC_CNTL_ULP_CP_WAKEUP_FORCE_EN);
180     }
181
182     // Enter sleep
183     rtc_sleep_config_t config = RTC_SLEEP_CONFIG_DEFAULT(pd_flags);
184     rtc_sleep_init(config);
185
186     // Configure timer wakeup
187     if ((s_config.wakeup_triggers & RTC_TIMER_TRIG_EN) &&
188         s_config.sleep_duration > 0) {
189         timer_wakeup_prepare();
190     }
191     uint32_t result = rtc_sleep_start(s_config.wakeup_triggers, 0);
192
193     // Restore CPU frequency
194     rtc_clk_cpu_freq_set(cpu_freq);
195
196     // re-enable UART output
197     resume_uarts();
198
199     return result;
200 }
201
202 void IRAM_ATTR esp_deep_sleep_start()
203 {
204     // record current RTC time
205     s_config.rtc_ticks_at_sleep_start = rtc_time_get();
206
207     // Configure wake stub
208     if (esp_get_deep_sleep_wake_stub() == NULL) {
209         esp_set_deep_sleep_wake_stub(esp_wake_deep_sleep);
210     }
211
212     // Decide which power domains can be powered down
213     uint32_t pd_flags = get_power_down_flags();
214
215     // Correct the sleep time
216     s_config.sleep_time_adjustment = DEEP_SLEEP_TIME_OVERHEAD_US;
217
218     // Enter sleep
219     esp_sleep_start(RTC_SLEEP_PD_DIG | RTC_SLEEP_PD_VDDSDIO | RTC_SLEEP_PD_XTAL | pd_flags);
220
221     // Because RTC is in a slower clock domain than the CPU, it
222     // can take several CPU cycles for the sleep mode to start.
223     while (1) {
224         ;
225     }
226 }
227
228 static void rtc_wdt_enable(int time_ms)
229 {
230     WRITE_PERI_REG(RTC_CNTL_WDTWPROTECT_REG, RTC_CNTL_WDT_WKEY_VALUE);
231     WRITE_PERI_REG(RTC_CNTL_WDTFEED_REG, 1);
232     REG_SET_FIELD(RTC_CNTL_WDTCONFIG0_REG, RTC_CNTL_WDT_SYS_RESET_LENGTH, 7);
233     REG_SET_FIELD(RTC_CNTL_WDTCONFIG0_REG, RTC_CNTL_WDT_CPU_RESET_LENGTH, 7);
234     REG_SET_FIELD(RTC_CNTL_WDTCONFIG0_REG, RTC_CNTL_WDT_STG0, RTC_WDT_STG_SEL_RESET_RTC);
235     WRITE_PERI_REG(RTC_CNTL_WDTCONFIG1_REG, rtc_clk_slow_freq_get_hz() * time_ms / 1000);
236     SET_PERI_REG_MASK(RTC_CNTL_WDTCONFIG0_REG, RTC_CNTL_WDT_EN | RTC_CNTL_WDT_PAUSE_IN_SLP);
237     WRITE_PERI_REG(RTC_CNTL_WDTWPROTECT_REG, 0);
238 }
239
240 static void rtc_wdt_disable()
241 {
242     WRITE_PERI_REG(RTC_CNTL_WDTWPROTECT_REG, RTC_CNTL_WDT_WKEY_VALUE);
243     WRITE_PERI_REG(RTC_CNTL_WDTFEED_REG, 1);
244     REG_SET_FIELD(RTC_CNTL_WDTCONFIG0_REG, RTC_CNTL_WDT_STG0, RTC_WDT_STG_SEL_OFF);
245     REG_CLR_BIT(RTC_CNTL_WDTCONFIG0_REG, RTC_CNTL_WDT_EN);
246     WRITE_PERI_REG(RTC_CNTL_WDTWPROTECT_REG, 0);
247 }
248
249 /**
250  * Helper function which handles entry to and exit from light sleep
251  * Placed into IRAM as flash may need some time to be powered on.
252  */
253 static esp_err_t esp_light_sleep_inner(uint32_t pd_flags,
254         uint32_t flash_enable_time_us,
255         rtc_vddsdio_config_t vddsdio_config) IRAM_ATTR __attribute__((noinline));
256
257 static esp_err_t esp_light_sleep_inner(uint32_t pd_flags,
258         uint32_t flash_enable_time_us,
259         rtc_vddsdio_config_t vddsdio_config)
260 {
261     // Enter sleep
262     esp_err_t err = esp_sleep_start(pd_flags);
263
264     // If VDDSDIO regulator was controlled by RTC registers before sleep,
265     // restore the configuration.
266     if (vddsdio_config.force) {
267         rtc_vddsdio_set_config(vddsdio_config);
268     }
269
270     // If SPI flash was powered down, wait for it to become ready
271     if (pd_flags & RTC_SLEEP_PD_VDDSDIO) {
272         // Wait for the flash chip to start up
273         ets_delay_us(flash_enable_time_us);
274     }
275     return err;
276 }
277
278 esp_err_t esp_light_sleep_start()
279 {
280     static portMUX_TYPE light_sleep_lock = portMUX_INITIALIZER_UNLOCKED;
281     portENTER_CRITICAL(&light_sleep_lock);
282     s_config.rtc_ticks_at_sleep_start = rtc_time_get();
283     uint64_t frc_time_at_start = esp_timer_get_time();
284     DPORT_STALL_OTHER_CPU_START();
285
286     // Decide which power domains can be powered down
287     uint32_t pd_flags = get_power_down_flags();
288
289     // Amount of time to subtract from actual sleep time.
290     // This is spent on entering and leaving light sleep.
291     s_config.sleep_time_adjustment = LIGHT_SLEEP_TIME_OVERHEAD_US;
292
293     // Decide if VDD_SDIO needs to be powered down;
294     // If it needs to be powered down, adjust sleep time.
295     const uint32_t flash_enable_time_us = VDD_SDIO_POWERUP_TO_FLASH_READ_US
296                                           + CONFIG_ESP32_DEEP_SLEEP_WAKEUP_DELAY;
297
298 #ifndef CONFIG_SPIRAM_SUPPORT
299     const uint32_t vddsdio_pd_sleep_duration = MAX(FLASH_PD_MIN_SLEEP_TIME_US,
300             flash_enable_time_us + LIGHT_SLEEP_TIME_OVERHEAD_US + LIGHT_SLEEP_MIN_TIME_US);
301
302     if (s_config.sleep_duration > vddsdio_pd_sleep_duration) {
303         pd_flags |= RTC_SLEEP_PD_VDDSDIO;
304         s_config.sleep_time_adjustment += flash_enable_time_us;
305     }
306 #endif //CONFIG_SPIRAM_SUPPORT
307
308     rtc_vddsdio_config_t vddsdio_config = rtc_vddsdio_get_config();
309
310     // Safety net: enable WDT in case exit from light sleep fails
311     rtc_wdt_enable(1000);
312
313     // Enter sleep, then wait for flash to be ready on wakeup
314     esp_err_t err = esp_light_sleep_inner(pd_flags,
315             flash_enable_time_us, vddsdio_config);
316
317     // FRC1 has been clock gated for the duration of the sleep, correct for that.
318     uint64_t rtc_ticks_at_end = rtc_time_get();
319     uint64_t frc_time_at_end = esp_timer_get_time();
320
321     uint64_t rtc_time_diff = rtc_time_slowclk_to_us(rtc_ticks_at_end - s_config.rtc_ticks_at_sleep_start,
322                                     esp_clk_slowclk_cal_get());
323     uint64_t frc_time_diff = frc_time_at_end - frc_time_at_start;
324
325     int64_t time_diff = rtc_time_diff - frc_time_diff;
326     /* Small negative values (up to 1 RTC_SLOW clock period) are possible,
327      * for very small values of sleep_duration. Ignore those to keep esp_timer
328      * monotonic.
329      */
330     if (time_diff > 0) {
331         esp_timer_impl_advance(time_diff);
332     }
333     esp_set_time_from_rtc();
334
335     DPORT_STALL_OTHER_CPU_END();
336     rtc_wdt_disable();
337     portEXIT_CRITICAL(&light_sleep_lock);
338     return err;
339 }
340
341 void system_deep_sleep(uint64_t) __attribute__((alias("esp_deep_sleep")));
342
343 esp_err_t esp_sleep_disable_wakeup_source(esp_sleep_source_t source)
344 {
345     // For most of sources it is enough to set trigger mask in local
346     // configuration structure. The actual RTC wake up options
347     // will be updated by esp_sleep_start().
348     if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_TIMER, RTC_TIMER_TRIG_EN)) {
349         s_config.wakeup_triggers &= ~RTC_TIMER_TRIG_EN;
350         s_config.sleep_duration = 0;
351     }
352     else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_EXT0, RTC_EXT0_TRIG_EN)) {
353         s_config.ext0_rtc_gpio_num = 0;
354         s_config.ext0_trigger_level = 0;
355         s_config.wakeup_triggers &= ~RTC_EXT0_TRIG_EN;
356     }
357     else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_EXT1, RTC_EXT1_TRIG_EN)) {
358         s_config.ext1_rtc_gpio_mask = 0;
359         s_config.ext1_trigger_mode = 0;
360         s_config.wakeup_triggers &= ~RTC_EXT1_TRIG_EN;
361     }
362     else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_TOUCHPAD, RTC_TOUCH_TRIG_EN)) {
363         s_config.wakeup_triggers &= ~RTC_TOUCH_TRIG_EN;
364     }
365 #ifdef CONFIG_ULP_COPROC_ENABLED
366     else if (CHECK_SOURCE(source, ESP_SLEEP_WAKEUP_ULP, RTC_ULP_TRIG_EN)) {
367         s_config.wakeup_triggers &= ~RTC_ULP_TRIG_EN;
368     }
369 #endif
370     else {
371         ESP_LOGE(TAG, "Incorrect wakeup source (%d) to disable.", (int) source);
372         return ESP_ERR_INVALID_STATE;
373     }
374     return ESP_OK;
375 }
376
377 esp_err_t esp_sleep_enable_ulp_wakeup()
378 {
379 #ifdef CONFIG_ULP_COPROC_ENABLED
380     if(s_config.wakeup_triggers & RTC_EXT0_TRIG_EN) {
381         ESP_LOGE(TAG, "Conflicting wake-up trigger: ext0");
382         return ESP_ERR_INVALID_STATE;
383     }
384     s_config.wakeup_triggers |= RTC_ULP_TRIG_EN;
385     return ESP_OK;
386 #else
387     return ESP_ERR_INVALID_STATE;
388 #endif
389 }
390
391 esp_err_t esp_sleep_enable_timer_wakeup(uint64_t time_in_us)
392 {
393     s_config.wakeup_triggers |= RTC_TIMER_TRIG_EN;
394     s_config.sleep_duration = time_in_us;
395     return ESP_OK;
396 }
397
398 static void timer_wakeup_prepare()
399 {
400     uint32_t period = esp_clk_slowclk_cal_get();
401     int64_t sleep_duration = (int64_t) s_config.sleep_duration - (int64_t) s_config.sleep_time_adjustment;
402     if (sleep_duration < 0) {
403         sleep_duration = 0;
404     }
405     int64_t rtc_count_delta = rtc_time_us_to_slowclk(sleep_duration, period);
406
407     rtc_sleep_set_wakeup_time(s_config.rtc_ticks_at_sleep_start + rtc_count_delta);
408 }
409
410 esp_err_t esp_sleep_enable_touchpad_wakeup()
411 {
412     if (s_config.wakeup_triggers & (RTC_EXT0_TRIG_EN)) {
413         ESP_LOGE(TAG, "Conflicting wake-up trigger: ext0");
414         return ESP_ERR_INVALID_STATE;
415     }
416     s_config.wakeup_triggers |= RTC_TOUCH_TRIG_EN;
417     return ESP_OK;
418 }
419
420 touch_pad_t esp_sleep_get_touchpad_wakeup_status()
421 {
422     if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_TOUCHPAD) {
423         return TOUCH_PAD_MAX;
424     }
425     uint32_t touch_mask = REG_GET_FIELD(SENS_SAR_TOUCH_CTRL2_REG, SENS_TOUCH_MEAS_EN);
426     assert(touch_mask != 0 && "wakeup reason is RTC_TOUCH_TRIG_EN but SENS_TOUCH_MEAS_EN is zero");
427     return (touch_pad_t) (__builtin_ffs(touch_mask) - 1);
428 }
429
430 esp_err_t esp_sleep_enable_ext0_wakeup(gpio_num_t gpio_num, int level)
431 {
432     if (level < 0 || level > 1) {
433         return ESP_ERR_INVALID_ARG;
434     }
435     if (!RTC_GPIO_IS_VALID_GPIO(gpio_num)) {
436         return ESP_ERR_INVALID_ARG;
437     }
438     if (s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) {
439         ESP_LOGE(TAG, "Conflicting wake-up triggers: touch / ULP");
440         return ESP_ERR_INVALID_STATE;
441     }
442     s_config.ext0_rtc_gpio_num = rtc_gpio_desc[gpio_num].rtc_num;
443     s_config.ext0_trigger_level = level;
444     s_config.wakeup_triggers |= RTC_EXT0_TRIG_EN;
445     return ESP_OK;
446 }
447
448 static void ext0_wakeup_prepare()
449 {
450     int rtc_gpio_num = s_config.ext0_rtc_gpio_num;
451     // Set GPIO to be used for wakeup
452     REG_SET_FIELD(RTC_IO_EXT_WAKEUP0_REG, RTC_IO_EXT_WAKEUP0_SEL, rtc_gpio_num);
453     // Set level which will trigger wakeup
454     SET_PERI_REG_BITS(RTC_CNTL_EXT_WAKEUP_CONF_REG, 0x1,
455             s_config.ext0_trigger_level, RTC_CNTL_EXT_WAKEUP0_LV_S);
456     // Find GPIO descriptor in the rtc_gpio_desc table and configure the pad
457     for (size_t gpio_num = 0; gpio_num < GPIO_PIN_COUNT; ++gpio_num) {
458         const rtc_gpio_desc_t* desc = &rtc_gpio_desc[gpio_num];
459         if (desc->rtc_num == rtc_gpio_num) {
460             REG_SET_BIT(desc->reg, desc->mux);
461             SET_PERI_REG_BITS(desc->reg, 0x3, 0, desc->func);
462             REG_SET_BIT(desc->reg, desc->slpsel);
463             REG_SET_BIT(desc->reg, desc->slpie);
464             break;
465         }
466     }
467 }
468
469 esp_err_t esp_sleep_enable_ext1_wakeup(uint64_t mask, esp_sleep_ext1_wakeup_mode_t mode)
470 {
471     if (mode > ESP_EXT1_WAKEUP_ANY_HIGH) {
472         return ESP_ERR_INVALID_ARG;
473     }
474     // Translate bit map of GPIO numbers into the bit map of RTC IO numbers
475     uint32_t rtc_gpio_mask = 0;
476     for (int gpio = 0; mask; ++gpio, mask >>= 1) {
477         if ((mask & 1) == 0) {
478             continue;
479         }
480         if (!RTC_GPIO_IS_VALID_GPIO(gpio)) {
481             ESP_LOGE(TAG, "Not an RTC IO: GPIO%d", gpio);
482             return ESP_ERR_INVALID_ARG;
483         }
484         rtc_gpio_mask |= BIT(rtc_gpio_desc[gpio].rtc_num);
485     }
486     s_config.ext1_rtc_gpio_mask = rtc_gpio_mask;
487     s_config.ext1_trigger_mode = mode;
488     s_config.wakeup_triggers |= RTC_EXT1_TRIG_EN;
489     return ESP_OK;
490 }
491
492 static void ext1_wakeup_prepare()
493 {
494     // Configure all RTC IOs selected as ext1 wakeup inputs
495     uint32_t rtc_gpio_mask = s_config.ext1_rtc_gpio_mask;
496     for (int gpio = 0; gpio < GPIO_PIN_COUNT && rtc_gpio_mask != 0; ++gpio) {
497         int rtc_pin = rtc_gpio_desc[gpio].rtc_num;
498         if ((rtc_gpio_mask & BIT(rtc_pin)) == 0) {
499             continue;
500         }
501         const rtc_gpio_desc_t* desc = &rtc_gpio_desc[gpio];
502         // Route pad to RTC
503         REG_SET_BIT(desc->reg, desc->mux);
504         SET_PERI_REG_BITS(desc->reg, 0x3, 0, desc->func);
505         // Pad configuration depends on RTC_PERIPH state in sleep mode
506         if (s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] == ESP_PD_OPTION_ON) {
507             // set input enable in sleep mode
508             REG_SET_BIT(desc->reg, desc->slpie);
509             // allow sleep status signal to control IE/SLPIE mux
510             REG_SET_BIT(desc->reg, desc->slpsel);
511         } else {
512             // RTC_PERIPH will be disabled, so need to enable input and
513             // lock pad configuration. Pullups/pulldowns also need to be disabled.
514             REG_SET_BIT(desc->reg, desc->ie);
515             REG_CLR_BIT(desc->reg, desc->pulldown);
516             REG_CLR_BIT(desc->reg, desc->pullup);
517             REG_SET_BIT(RTC_CNTL_HOLD_FORCE_REG, desc->hold_force);
518         }
519         // Keep track of pins which are processed to bail out early
520         rtc_gpio_mask &= ~BIT(rtc_pin);
521     }
522     // Clear state from previous wakeup
523     REG_SET_BIT(RTC_CNTL_EXT_WAKEUP1_REG, RTC_CNTL_EXT_WAKEUP1_STATUS_CLR);
524     // Set pins to be used for wakeup
525     REG_SET_FIELD(RTC_CNTL_EXT_WAKEUP1_REG, RTC_CNTL_EXT_WAKEUP1_SEL, s_config.ext1_rtc_gpio_mask);
526     // Set logic function (any low, all high)
527     SET_PERI_REG_BITS(RTC_CNTL_EXT_WAKEUP_CONF_REG, 0x1,
528             s_config.ext1_trigger_mode, RTC_CNTL_EXT_WAKEUP1_LV_S);
529 }
530
531 uint64_t esp_sleep_get_ext1_wakeup_status()
532 {
533     if (esp_sleep_get_wakeup_cause() != ESP_SLEEP_WAKEUP_EXT1) {
534         return 0;
535     }
536     uint32_t status = REG_GET_FIELD(RTC_CNTL_EXT_WAKEUP1_STATUS_REG, RTC_CNTL_EXT_WAKEUP1_STATUS);
537     // Translate bit map of RTC IO numbers into the bit map of GPIO numbers
538     uint64_t gpio_mask = 0;
539     for (int gpio = 0; gpio < GPIO_PIN_COUNT; ++gpio) {
540         if (!RTC_GPIO_IS_VALID_GPIO(gpio)) {
541             continue;
542         }
543         int rtc_pin = rtc_gpio_desc[gpio].rtc_num;
544         if ((status & BIT(rtc_pin)) == 0) {
545             continue;
546         }
547         gpio_mask |= 1ULL << gpio;
548     }
549     return gpio_mask;
550 }
551
552 esp_sleep_wakeup_cause_t esp_sleep_get_wakeup_cause()
553 {
554     if (rtc_get_reset_reason(0) != DEEPSLEEP_RESET) {
555         return ESP_SLEEP_WAKEUP_UNDEFINED;
556     }
557
558     uint32_t wakeup_cause = REG_GET_FIELD(RTC_CNTL_WAKEUP_STATE_REG, RTC_CNTL_WAKEUP_CAUSE);
559     if (wakeup_cause & RTC_EXT0_TRIG_EN) {
560         return ESP_SLEEP_WAKEUP_EXT0;
561     } else if (wakeup_cause & RTC_EXT1_TRIG_EN) {
562         return ESP_SLEEP_WAKEUP_EXT1;
563     } else if (wakeup_cause & RTC_TIMER_TRIG_EN) {
564         return ESP_SLEEP_WAKEUP_TIMER;
565     } else if (wakeup_cause & RTC_TOUCH_TRIG_EN) {
566         return ESP_SLEEP_WAKEUP_TOUCHPAD;
567     } else if (wakeup_cause & RTC_ULP_TRIG_EN) {
568         return ESP_SLEEP_WAKEUP_ULP;
569     } else {
570         return ESP_SLEEP_WAKEUP_UNDEFINED;
571     }
572 }
573
574 esp_err_t esp_sleep_pd_config(esp_sleep_pd_domain_t domain,
575                                    esp_sleep_pd_option_t option)
576 {
577     if (domain >= ESP_PD_DOMAIN_MAX || option > ESP_PD_OPTION_AUTO) {
578         return ESP_ERR_INVALID_ARG;
579     }
580     s_config.pd_options[domain] = option;
581     return ESP_OK;
582 }
583
584 static uint32_t get_power_down_flags()
585 {
586     // Where needed, convert AUTO options to ON. Later interpret AUTO as OFF.
587
588     // RTC_SLOW_MEM is needed for the ULP, so keep RTC_SLOW_MEM powered up if ULP
589     // is used and RTC_SLOW_MEM is Auto.
590     // If there is any data placed into .rtc.data or .rtc.bss segments, and
591     // RTC_SLOW_MEM is Auto, keep it powered up as well.
592
593     // These labels are defined in the linker script:
594     extern int _rtc_data_start, _rtc_data_end, _rtc_bss_start, _rtc_bss_end;
595
596     if (s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM] == ESP_PD_OPTION_AUTO ||
597             &_rtc_data_end > &_rtc_data_start ||
598             &_rtc_bss_end > &_rtc_bss_start) {
599         s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM] = ESP_PD_OPTION_ON;
600     }
601
602     // RTC_FAST_MEM is needed for deep sleep stub.
603     // If RTC_FAST_MEM is Auto, keep it powered on, so that deep sleep stub
604     // can run.
605     // In the new chip revision, deep sleep stub will be optional,
606     // and this can be changed.
607     if (s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM] == ESP_PD_OPTION_AUTO) {
608         s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM] = ESP_PD_OPTION_ON;
609     }
610
611     // RTC_PERIPH is needed for EXT0 wakeup.
612     // If RTC_PERIPH is auto, and EXT0 isn't enabled, power down RTC_PERIPH.
613     if (s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] == ESP_PD_OPTION_AUTO) {
614         if (s_config.wakeup_triggers & RTC_EXT0_TRIG_EN) {
615             s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] = ESP_PD_OPTION_ON;
616         } else if (s_config.wakeup_triggers & (RTC_TOUCH_TRIG_EN | RTC_ULP_TRIG_EN)) {
617             // In both rev. 0 and rev. 1 of ESP32, forcing power up of RTC_PERIPH
618             // prevents ULP timer and touch FSMs from working correctly.
619             s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] = ESP_PD_OPTION_OFF;
620         }
621     }
622
623     if (s_config.pd_options[ESP_PD_DOMAIN_XTAL] == ESP_PD_OPTION_AUTO) {
624         s_config.pd_options[ESP_PD_DOMAIN_XTAL] = ESP_PD_OPTION_OFF;
625     }
626
627     const char* option_str[] = {"OFF", "ON", "AUTO(OFF)" /* Auto works as OFF */};
628     ESP_LOGD(TAG, "RTC_PERIPH: %s, RTC_SLOW_MEM: %s, RTC_FAST_MEM: %s",
629             option_str[s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH]],
630             option_str[s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM]],
631             option_str[s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM]]);
632
633     // Prepare flags based on the selected options
634     uint32_t pd_flags = 0;
635     if (s_config.pd_options[ESP_PD_DOMAIN_RTC_FAST_MEM] != ESP_PD_OPTION_ON) {
636         pd_flags |= RTC_SLEEP_PD_RTC_FAST_MEM;
637     }
638     if (s_config.pd_options[ESP_PD_DOMAIN_RTC_SLOW_MEM] != ESP_PD_OPTION_ON) {
639         pd_flags |= RTC_SLEEP_PD_RTC_SLOW_MEM;
640     }
641     if (s_config.pd_options[ESP_PD_DOMAIN_RTC_PERIPH] != ESP_PD_OPTION_ON) {
642         pd_flags |= RTC_SLEEP_PD_RTC_PERIPH;
643     }
644     if (s_config.pd_options[ESP_PD_DOMAIN_XTAL] != ESP_PD_OPTION_ON) {
645         pd_flags |= RTC_SLEEP_PD_XTAL;
646     }
647     return pd_flags;
648 }