pm_impl.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780
  1. // Copyright 2016-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. #include <stdlib.h>
  15. #include <stdbool.h>
  16. #include <string.h>
  17. #include <sys/param.h>
  18. #include "esp_attr.h"
  19. #include "esp_err.h"
  20. #include "esp_pm.h"
  21. #include "esp_log.h"
  22. #include "esp_private/crosscore_int.h"
  23. #include "soc/rtc.h"
  24. #include "hal/cpu_hal.h"
  25. #include "hal/uart_ll.h"
  26. #include "hal/uart_types.h"
  27. #include "freertos/FreeRTOS.h"
  28. #include "freertos/task.h"
  29. #include "freertos/xtensa_timer.h"
  30. #include "xtensa/core-macros.h"
  31. #include "esp_private/pm_impl.h"
  32. #include "esp_private/pm_trace.h"
  33. #include "esp_private/esp_timer_private.h"
  34. #include "esp_sleep.h"
  35. #include "sdkconfig.h"
  36. // [refactor-todo] opportunity for further refactor
  37. #if CONFIG_IDF_TARGET_ESP32
  38. #include "esp32/clk.h"
  39. #include "esp32/pm.h"
  40. #include "driver/gpio.h"
  41. #elif CONFIG_IDF_TARGET_ESP32S2
  42. #include "esp32s2/clk.h"
  43. #include "esp32s2/pm.h"
  44. #include "driver/gpio.h"
  45. #elif CONFIG_IDF_TARGET_ESP32S3
  46. #include "esp32s3/clk.h"
  47. #include "esp32s3/pm.h"
  48. #endif
  49. #define MHZ (1000000)
  50. /* CCOMPARE update timeout, in CPU cycles. Any value above ~600 cycles will work
  51. * for the purpose of detecting a deadlock.
  52. */
  53. #define CCOMPARE_UPDATE_TIMEOUT 1000000
  54. /* When changing CCOMPARE, don't allow changes if the difference is less
  55. * than this. This is to prevent setting CCOMPARE below CCOUNT.
  56. */
  57. #define CCOMPARE_MIN_CYCLES_IN_FUTURE 1000
  58. /* When light sleep is used, wake this number of microseconds earlier than
  59. * the next tick.
  60. */
  61. #define LIGHT_SLEEP_EARLY_WAKEUP_US 100
  62. #if CONFIG_IDF_TARGET_ESP32
  63. /* Minimal divider at which REF_CLK_FREQ can be obtained */
  64. #define REF_CLK_DIV_MIN 10
  65. #define DEFAULT_CPU_FREQ CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ
  66. #elif CONFIG_IDF_TARGET_ESP32S2
  67. /* Minimal divider at which REF_CLK_FREQ can be obtained */
  68. #define REF_CLK_DIV_MIN 2
  69. #define DEFAULT_CPU_FREQ CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ
  70. #elif CONFIG_IDF_TARGET_ESP32S3
  71. /* Minimal divider at which REF_CLK_FREQ can be obtained */
  72. #define REF_CLK_DIV_MIN 2
  73. #define DEFAULT_CPU_FREQ CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ
  74. #endif
  75. #ifdef CONFIG_PM_PROFILING
  76. #define WITH_PROFILING
  77. #endif
  78. static portMUX_TYPE s_switch_lock = portMUX_INITIALIZER_UNLOCKED;
  79. /* The following state variables are protected using s_switch_lock: */
  80. /* Current sleep mode; When switching, contains old mode until switch is complete */
  81. static pm_mode_t s_mode = PM_MODE_CPU_MAX;
  82. /* True when switch is in progress */
  83. static volatile bool s_is_switching;
  84. /* When switch is in progress, this is the mode we are switching into */
  85. static pm_mode_t s_new_mode = PM_MODE_CPU_MAX;
  86. /* Number of times each mode was locked */
  87. static size_t s_mode_lock_counts[PM_MODE_COUNT];
  88. /* Bit mask of locked modes. BIT(i) is set iff s_mode_lock_counts[i] > 0. */
  89. static uint32_t s_mode_mask;
  90. /* Divider and multiplier used to adjust (ccompare - ccount) duration.
  91. * Only set to non-zero values when switch is in progress.
  92. */
  93. static uint32_t s_ccount_div;
  94. static uint32_t s_ccount_mul;
  95. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  96. #define PERIPH_SKIP_LIGHT_SLEEP_NO 1
  97. /* Indicates if light sleep shoule be skipped by peripherals. */
  98. static skip_light_sleep_cb_t s_periph_skip_light_sleep_cb[PERIPH_SKIP_LIGHT_SLEEP_NO];
  99. /* Indicates if light sleep entry was skipped in vApplicationSleep for given CPU.
  100. * This in turn gets used in IDLE hook to decide if `waiti` needs
  101. * to be invoked or not.
  102. */
  103. static bool s_skipped_light_sleep[portNUM_PROCESSORS];
  104. #if portNUM_PROCESSORS == 2
  105. /* When light sleep is finished on one CPU, it is possible that the other CPU
  106. * will enter light sleep again very soon, before interrupts on the first CPU
  107. * get a chance to run. To avoid such situation, set a flag for the other CPU to
  108. * skip light sleep attempt.
  109. */
  110. static bool s_skip_light_sleep[portNUM_PROCESSORS];
  111. #endif // portNUM_PROCESSORS == 2
  112. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  113. /* Indicates to the ISR hook that CCOMPARE needs to be updated on the given CPU.
  114. * Used in conjunction with cross-core interrupt to update CCOMPARE on the other CPU.
  115. */
  116. static volatile bool s_need_update_ccompare[portNUM_PROCESSORS];
  117. /* A flag indicating that Idle hook has run on a given CPU;
  118. * Next interrupt on the same CPU will take s_rtos_lock_handle.
  119. */
  120. static bool s_core_idle[portNUM_PROCESSORS];
  121. /* When no RTOS tasks are active, these locks are released to allow going into
  122. * a lower power mode. Used by ISR hook and idle hook.
  123. */
  124. static esp_pm_lock_handle_t s_rtos_lock_handle[portNUM_PROCESSORS];
  125. /* Lookup table of CPU frequency configs to be used in each mode.
  126. * Initialized by esp_pm_impl_init and modified by esp_pm_configure.
  127. */
  128. rtc_cpu_freq_config_t s_cpu_freq_by_mode[PM_MODE_COUNT];
  129. /* Whether automatic light sleep is enabled */
  130. static bool s_light_sleep_en = false;
  131. /* When configuration is changed, current frequency may not match the
  132. * newly configured frequency for the current mode. This is an indicator
  133. * to the mode switch code to get the actual current frequency instead of
  134. * relying on the current mode.
  135. */
  136. static bool s_config_changed = false;
  137. #ifdef WITH_PROFILING
  138. /* Time, in microseconds, spent so far in each mode */
  139. static pm_time_t s_time_in_mode[PM_MODE_COUNT];
  140. /* Timestamp, in microseconds, when the mode switch last happened */
  141. static pm_time_t s_last_mode_change_time;
  142. /* User-readable mode names, used by esp_pm_impl_dump_stats */
  143. static const char* s_mode_names[] = {
  144. "SLEEP",
  145. "APB_MIN",
  146. "APB_MAX",
  147. "CPU_MAX"
  148. };
  149. #endif // WITH_PROFILING
  150. static const char* TAG = "pm_" CONFIG_IDF_TARGET;
  151. static void update_ccompare(void);
  152. static void do_switch(pm_mode_t new_mode);
  153. static void leave_idle(void);
  154. static void on_freq_update(uint32_t old_ticks_per_us, uint32_t ticks_per_us);
  155. pm_mode_t esp_pm_impl_get_mode(esp_pm_lock_type_t type, int arg)
  156. {
  157. (void) arg;
  158. if (type == ESP_PM_CPU_FREQ_MAX) {
  159. return PM_MODE_CPU_MAX;
  160. } else if (type == ESP_PM_APB_FREQ_MAX) {
  161. return PM_MODE_APB_MAX;
  162. } else if (type == ESP_PM_NO_LIGHT_SLEEP) {
  163. return PM_MODE_APB_MIN;
  164. } else {
  165. // unsupported mode
  166. abort();
  167. }
  168. }
  169. esp_err_t esp_pm_configure(const void* vconfig)
  170. {
  171. #ifndef CONFIG_PM_ENABLE
  172. return ESP_ERR_NOT_SUPPORTED;
  173. #endif
  174. #if CONFIG_IDF_TARGET_ESP32
  175. const esp_pm_config_esp32_t* config = (const esp_pm_config_esp32_t*) vconfig;
  176. #elif CONFIG_IDF_TARGET_ESP32S2
  177. const esp_pm_config_esp32s2_t* config = (const esp_pm_config_esp32s2_t*) vconfig;
  178. #elif CONFIG_IDF_TARGET_ESP32S3
  179. const esp_pm_config_esp32s3_t* config = (const esp_pm_config_esp32s3_t*) vconfig;
  180. #endif
  181. #ifndef CONFIG_FREERTOS_USE_TICKLESS_IDLE
  182. if (config->light_sleep_enable) {
  183. return ESP_ERR_NOT_SUPPORTED;
  184. }
  185. #endif
  186. int min_freq_mhz = config->min_freq_mhz;
  187. int max_freq_mhz = config->max_freq_mhz;
  188. if (min_freq_mhz > max_freq_mhz) {
  189. return ESP_ERR_INVALID_ARG;
  190. }
  191. rtc_cpu_freq_config_t freq_config;
  192. if (!rtc_clk_cpu_freq_mhz_to_config(min_freq_mhz, &freq_config)) {
  193. ESP_LOGW(TAG, "invalid min_freq_mhz value (%d)", min_freq_mhz);
  194. return ESP_ERR_INVALID_ARG;
  195. }
  196. int xtal_freq_mhz = (int) rtc_clk_xtal_freq_get();
  197. if (min_freq_mhz < xtal_freq_mhz && min_freq_mhz * MHZ / REF_CLK_FREQ < REF_CLK_DIV_MIN) {
  198. ESP_LOGW(TAG, "min_freq_mhz should be >= %d", REF_CLK_FREQ * REF_CLK_DIV_MIN / MHZ);
  199. return ESP_ERR_INVALID_ARG;
  200. }
  201. if (!rtc_clk_cpu_freq_mhz_to_config(max_freq_mhz, &freq_config)) {
  202. ESP_LOGW(TAG, "invalid max_freq_mhz value (%d)", max_freq_mhz);
  203. return ESP_ERR_INVALID_ARG;
  204. }
  205. #if CONFIG_IDF_TARGET_ESP32
  206. int apb_max_freq = max_freq_mhz; /* CPU frequency in APB_MAX mode */
  207. if (max_freq_mhz == 240) {
  208. /* We can't switch between 240 and 80/160 without disabling PLL,
  209. * so use 240MHz CPU frequency when 80MHz APB frequency is requested.
  210. */
  211. apb_max_freq = 240;
  212. } else if (max_freq_mhz == 160 || max_freq_mhz == 80) {
  213. /* Otherwise, can use 80MHz
  214. * CPU frequency when 80MHz APB frequency is requested.
  215. */
  216. apb_max_freq = 80;
  217. }
  218. #elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  219. int apb_max_freq = MIN(max_freq_mhz, 80); /* CPU frequency in APB_MAX mode */
  220. #endif
  221. apb_max_freq = MAX(apb_max_freq, min_freq_mhz);
  222. ESP_LOGI(TAG, "Frequency switching config: "
  223. "CPU_MAX: %d, APB_MAX: %d, APB_MIN: %d, Light sleep: %s",
  224. max_freq_mhz,
  225. apb_max_freq,
  226. min_freq_mhz,
  227. config->light_sleep_enable ? "ENABLED" : "DISABLED");
  228. portENTER_CRITICAL(&s_switch_lock);
  229. bool res = false;
  230. res = rtc_clk_cpu_freq_mhz_to_config(max_freq_mhz, &s_cpu_freq_by_mode[PM_MODE_CPU_MAX]);
  231. assert(res);
  232. res = rtc_clk_cpu_freq_mhz_to_config(apb_max_freq, &s_cpu_freq_by_mode[PM_MODE_APB_MAX]);
  233. assert(res);
  234. res = rtc_clk_cpu_freq_mhz_to_config(min_freq_mhz, &s_cpu_freq_by_mode[PM_MODE_APB_MIN]);
  235. assert(res);
  236. s_cpu_freq_by_mode[PM_MODE_LIGHT_SLEEP] = s_cpu_freq_by_mode[PM_MODE_APB_MIN];
  237. s_light_sleep_en = config->light_sleep_enable;
  238. s_config_changed = true;
  239. portEXIT_CRITICAL(&s_switch_lock);
  240. #if CONFIG_PM_SLP_DISABLE_GPIO && SOC_GPIO_SUPPORT_SLP_SWITCH
  241. esp_sleep_gpio_status_switch_configure(config->light_sleep_enable);
  242. #endif
  243. return ESP_OK;
  244. }
  245. static pm_mode_t IRAM_ATTR get_lowest_allowed_mode(void)
  246. {
  247. /* TODO: optimize using ffs/clz */
  248. if (s_mode_mask >= BIT(PM_MODE_CPU_MAX)) {
  249. return PM_MODE_CPU_MAX;
  250. } else if (s_mode_mask >= BIT(PM_MODE_APB_MAX)) {
  251. return PM_MODE_APB_MAX;
  252. } else if (s_mode_mask >= BIT(PM_MODE_APB_MIN) || !s_light_sleep_en) {
  253. return PM_MODE_APB_MIN;
  254. } else {
  255. return PM_MODE_LIGHT_SLEEP;
  256. }
  257. }
  258. void IRAM_ATTR esp_pm_impl_switch_mode(pm_mode_t mode,
  259. pm_mode_switch_t lock_or_unlock, pm_time_t now)
  260. {
  261. bool need_switch = false;
  262. uint32_t mode_mask = BIT(mode);
  263. portENTER_CRITICAL_SAFE(&s_switch_lock);
  264. uint32_t count;
  265. if (lock_or_unlock == MODE_LOCK) {
  266. count = ++s_mode_lock_counts[mode];
  267. } else {
  268. count = s_mode_lock_counts[mode]--;
  269. }
  270. if (count == 1) {
  271. if (lock_or_unlock == MODE_LOCK) {
  272. s_mode_mask |= mode_mask;
  273. } else {
  274. s_mode_mask &= ~mode_mask;
  275. }
  276. need_switch = true;
  277. }
  278. pm_mode_t new_mode = s_mode;
  279. if (need_switch) {
  280. new_mode = get_lowest_allowed_mode();
  281. #ifdef WITH_PROFILING
  282. if (s_last_mode_change_time != 0) {
  283. pm_time_t diff = now - s_last_mode_change_time;
  284. s_time_in_mode[s_mode] += diff;
  285. }
  286. s_last_mode_change_time = now;
  287. #endif // WITH_PROFILING
  288. }
  289. portEXIT_CRITICAL_SAFE(&s_switch_lock);
  290. if (need_switch && new_mode != s_mode) {
  291. do_switch(new_mode);
  292. }
  293. }
  294. /**
  295. * @brief Update clock dividers in esp_timer and FreeRTOS, and adjust CCOMPARE
  296. * values on both CPUs.
  297. * @param old_ticks_per_us old CPU frequency
  298. * @param ticks_per_us new CPU frequency
  299. */
  300. static void IRAM_ATTR on_freq_update(uint32_t old_ticks_per_us, uint32_t ticks_per_us)
  301. {
  302. uint32_t old_apb_ticks_per_us = MIN(old_ticks_per_us, 80);
  303. uint32_t apb_ticks_per_us = MIN(ticks_per_us, 80);
  304. /* Update APB frequency value used by the timer */
  305. if (old_apb_ticks_per_us != apb_ticks_per_us) {
  306. esp_timer_private_update_apb_freq(apb_ticks_per_us);
  307. }
  308. /* Calculate new tick divisor */
  309. _xt_tick_divisor = ticks_per_us * MHZ / XT_TICK_PER_SEC;
  310. int core_id = xPortGetCoreID();
  311. if (s_rtos_lock_handle[core_id] != NULL) {
  312. ESP_PM_TRACE_ENTER(CCOMPARE_UPDATE, core_id);
  313. /* ccount_div and ccount_mul are used in esp_pm_impl_update_ccompare
  314. * to calculate new CCOMPARE value.
  315. */
  316. s_ccount_div = old_ticks_per_us;
  317. s_ccount_mul = ticks_per_us;
  318. /* Update CCOMPARE value on this CPU */
  319. update_ccompare();
  320. #if portNUM_PROCESSORS == 2
  321. /* Send interrupt to the other CPU to update CCOMPARE value */
  322. int other_core_id = (core_id == 0) ? 1 : 0;
  323. s_need_update_ccompare[other_core_id] = true;
  324. esp_crosscore_int_send_freq_switch(other_core_id);
  325. int timeout = 0;
  326. while (s_need_update_ccompare[other_core_id]) {
  327. if (++timeout == CCOMPARE_UPDATE_TIMEOUT) {
  328. assert(false && "failed to update CCOMPARE, possible deadlock");
  329. }
  330. }
  331. #endif // portNUM_PROCESSORS == 2
  332. s_ccount_mul = 0;
  333. s_ccount_div = 0;
  334. ESP_PM_TRACE_EXIT(CCOMPARE_UPDATE, core_id);
  335. }
  336. }
  337. /**
  338. * Perform the switch to new power mode.
  339. * Currently only changes the CPU frequency and adjusts clock dividers.
  340. * No light sleep yet.
  341. * @param new_mode mode to switch to
  342. */
  343. static void IRAM_ATTR do_switch(pm_mode_t new_mode)
  344. {
  345. const int core_id = xPortGetCoreID();
  346. do {
  347. portENTER_CRITICAL_ISR(&s_switch_lock);
  348. if (!s_is_switching) {
  349. break;
  350. }
  351. if (s_new_mode <= new_mode) {
  352. portEXIT_CRITICAL_ISR(&s_switch_lock);
  353. return;
  354. }
  355. if (s_need_update_ccompare[core_id]) {
  356. s_need_update_ccompare[core_id] = false;
  357. }
  358. portEXIT_CRITICAL_ISR(&s_switch_lock);
  359. } while (true);
  360. s_new_mode = new_mode;
  361. s_is_switching = true;
  362. bool config_changed = s_config_changed;
  363. s_config_changed = false;
  364. portEXIT_CRITICAL_ISR(&s_switch_lock);
  365. rtc_cpu_freq_config_t new_config = s_cpu_freq_by_mode[new_mode];
  366. rtc_cpu_freq_config_t old_config;
  367. if (!config_changed) {
  368. old_config = s_cpu_freq_by_mode[s_mode];
  369. } else {
  370. rtc_clk_cpu_freq_get_config(&old_config);
  371. }
  372. if (new_config.freq_mhz != old_config.freq_mhz) {
  373. uint32_t old_ticks_per_us = old_config.freq_mhz;
  374. uint32_t new_ticks_per_us = new_config.freq_mhz;
  375. bool switch_down = new_ticks_per_us < old_ticks_per_us;
  376. ESP_PM_TRACE_ENTER(FREQ_SWITCH, core_id);
  377. if (switch_down) {
  378. on_freq_update(old_ticks_per_us, new_ticks_per_us);
  379. }
  380. rtc_clk_cpu_freq_set_config_fast(&new_config);
  381. if (!switch_down) {
  382. on_freq_update(old_ticks_per_us, new_ticks_per_us);
  383. }
  384. ESP_PM_TRACE_EXIT(FREQ_SWITCH, core_id);
  385. }
  386. portENTER_CRITICAL_ISR(&s_switch_lock);
  387. s_mode = new_mode;
  388. s_is_switching = false;
  389. portEXIT_CRITICAL_ISR(&s_switch_lock);
  390. }
  391. /**
  392. * @brief Calculate new CCOMPARE value based on s_ccount_{mul,div}
  393. *
  394. * Adjusts CCOMPARE value so that the interrupt happens at the same time as it
  395. * would happen without the frequency change.
  396. * Assumes that the new_frequency = old_frequency * s_ccount_mul / s_ccount_div.
  397. */
  398. static void IRAM_ATTR update_ccompare(void)
  399. {
  400. uint32_t ccount = cpu_hal_get_cycle_count();
  401. uint32_t ccompare = XTHAL_GET_CCOMPARE(XT_TIMER_INDEX);
  402. if ((ccompare - CCOMPARE_MIN_CYCLES_IN_FUTURE) - ccount < UINT32_MAX / 2) {
  403. uint32_t diff = ccompare - ccount;
  404. uint32_t diff_scaled = (diff * s_ccount_mul + s_ccount_div - 1) / s_ccount_div;
  405. if (diff_scaled < _xt_tick_divisor) {
  406. uint32_t new_ccompare = ccount + diff_scaled;
  407. XTHAL_SET_CCOMPARE(XT_TIMER_INDEX, new_ccompare);
  408. }
  409. }
  410. }
  411. static void IRAM_ATTR leave_idle(void)
  412. {
  413. int core_id = xPortGetCoreID();
  414. if (s_core_idle[core_id]) {
  415. // TODO: possible optimization: raise frequency here first
  416. esp_pm_lock_acquire(s_rtos_lock_handle[core_id]);
  417. s_core_idle[core_id] = false;
  418. }
  419. }
  420. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  421. esp_err_t esp_pm_register_skip_light_sleep_callback(skip_light_sleep_cb_t cb)
  422. {
  423. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  424. if (s_periph_skip_light_sleep_cb[i] == cb) {
  425. return ESP_OK;
  426. } else if (s_periph_skip_light_sleep_cb[i] == NULL) {
  427. s_periph_skip_light_sleep_cb[i] = cb;
  428. return ESP_OK;
  429. }
  430. }
  431. return ESP_ERR_NO_MEM;
  432. }
  433. esp_err_t esp_pm_unregister_skip_light_sleep_callback(skip_light_sleep_cb_t cb)
  434. {
  435. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  436. if (s_periph_skip_light_sleep_cb[i] == cb) {
  437. s_periph_skip_light_sleep_cb[i] = NULL;
  438. return ESP_OK;
  439. }
  440. }
  441. return ESP_ERR_INVALID_STATE;
  442. }
  443. static inline bool IRAM_ATTR periph_should_skip_light_sleep(void)
  444. {
  445. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  446. if (s_periph_skip_light_sleep_cb[i]) {
  447. if (s_periph_skip_light_sleep_cb[i]() == true) {
  448. return true;
  449. }
  450. }
  451. }
  452. return false;
  453. }
  454. static inline bool IRAM_ATTR should_skip_light_sleep(int core_id)
  455. {
  456. #if portNUM_PROCESSORS == 2
  457. if (s_skip_light_sleep[core_id]) {
  458. s_skip_light_sleep[core_id] = false;
  459. s_skipped_light_sleep[core_id] = true;
  460. return true;
  461. }
  462. #endif // portNUM_PROCESSORS == 2
  463. if (s_mode != PM_MODE_LIGHT_SLEEP || s_is_switching || periph_should_skip_light_sleep()) {
  464. s_skipped_light_sleep[core_id] = true;
  465. } else {
  466. s_skipped_light_sleep[core_id] = false;
  467. }
  468. return s_skipped_light_sleep[core_id];
  469. }
  470. static inline void IRAM_ATTR other_core_should_skip_light_sleep(int core_id)
  471. {
  472. #if portNUM_PROCESSORS == 2
  473. s_skip_light_sleep[!core_id] = true;
  474. #endif
  475. }
  476. void IRAM_ATTR vApplicationSleep( TickType_t xExpectedIdleTime )
  477. {
  478. portENTER_CRITICAL(&s_switch_lock);
  479. int core_id = xPortGetCoreID();
  480. if (!should_skip_light_sleep(core_id)) {
  481. /* Calculate how much we can sleep */
  482. int64_t next_esp_timer_alarm = esp_timer_get_next_alarm();
  483. int64_t now = esp_timer_get_time();
  484. int64_t time_until_next_alarm = next_esp_timer_alarm - now;
  485. int64_t wakeup_delay_us = portTICK_PERIOD_MS * 1000LL * xExpectedIdleTime;
  486. int64_t sleep_time_us = MIN(wakeup_delay_us, time_until_next_alarm);
  487. if (sleep_time_us >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP * portTICK_PERIOD_MS * 1000LL) {
  488. esp_sleep_enable_timer_wakeup(sleep_time_us - LIGHT_SLEEP_EARLY_WAKEUP_US);
  489. #ifdef CONFIG_PM_TRACE
  490. /* to force tracing GPIOs to keep state */
  491. esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
  492. #endif
  493. /* Enter sleep */
  494. ESP_PM_TRACE_ENTER(SLEEP, core_id);
  495. int64_t sleep_start = esp_timer_get_time();
  496. esp_light_sleep_start();
  497. int64_t slept_us = esp_timer_get_time() - sleep_start;
  498. ESP_PM_TRACE_EXIT(SLEEP, core_id);
  499. uint32_t slept_ticks = slept_us / (portTICK_PERIOD_MS * 1000LL);
  500. if (slept_ticks > 0) {
  501. /* Adjust RTOS tick count based on the amount of time spent in sleep */
  502. vTaskStepTick(slept_ticks);
  503. /* Trigger tick interrupt, since sleep time was longer
  504. * than portTICK_PERIOD_MS. Note that setting INTSET does not
  505. * work for timer interrupt, and changing CCOMPARE would clear
  506. * the interrupt flag.
  507. */
  508. cpu_hal_set_cycle_count(XTHAL_GET_CCOMPARE(XT_TIMER_INDEX) - 16);
  509. while (!(XTHAL_GET_INTERRUPT() & BIT(XT_TIMER_INTNUM))) {
  510. ;
  511. }
  512. }
  513. other_core_should_skip_light_sleep(core_id);
  514. }
  515. }
  516. portEXIT_CRITICAL(&s_switch_lock);
  517. }
  518. #endif //CONFIG_FREERTOS_USE_TICKLESS_IDLE
  519. #ifdef WITH_PROFILING
  520. void esp_pm_impl_dump_stats(FILE* out)
  521. {
  522. pm_time_t time_in_mode[PM_MODE_COUNT];
  523. portENTER_CRITICAL_ISR(&s_switch_lock);
  524. memcpy(time_in_mode, s_time_in_mode, sizeof(time_in_mode));
  525. pm_time_t last_mode_change_time = s_last_mode_change_time;
  526. pm_mode_t cur_mode = s_mode;
  527. pm_time_t now = pm_get_time();
  528. portEXIT_CRITICAL_ISR(&s_switch_lock);
  529. time_in_mode[cur_mode] += now - last_mode_change_time;
  530. fprintf(out, "Mode stats:\n");
  531. for (int i = 0; i < PM_MODE_COUNT; ++i) {
  532. if (i == PM_MODE_LIGHT_SLEEP && !s_light_sleep_en) {
  533. /* don't display light sleep mode if it's not enabled */
  534. continue;
  535. }
  536. fprintf(out, "%8s %3dM %12lld %2d%%\n",
  537. s_mode_names[i],
  538. s_cpu_freq_by_mode[i].freq_mhz,
  539. time_in_mode[i],
  540. (int) (time_in_mode[i] * 100 / now));
  541. }
  542. }
  543. #endif // WITH_PROFILING
  544. void esp_pm_impl_init(void)
  545. {
  546. #if defined(CONFIG_ESP_CONSOLE_UART)
  547. //This clock source should be a source which won't be affected by DFS
  548. uint32_t clk_source;
  549. #if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
  550. clk_source = UART_SCLK_REF_TICK;
  551. #else
  552. clk_source = UART_SCLK_XTAL;
  553. #endif
  554. while(!uart_ll_is_tx_idle(UART_LL_GET_HW(CONFIG_ESP_CONSOLE_UART_NUM)));
  555. /* When DFS is enabled, override system setting and use REFTICK as UART clock source */
  556. uart_ll_set_sclk(UART_LL_GET_HW(CONFIG_ESP_CONSOLE_UART_NUM), clk_source);
  557. uart_ll_set_baudrate(UART_LL_GET_HW(CONFIG_ESP_CONSOLE_UART_NUM), CONFIG_ESP_CONSOLE_UART_BAUDRATE);
  558. #endif // CONFIG_ESP_CONSOLE_UART
  559. #ifdef CONFIG_PM_TRACE
  560. esp_pm_trace_init();
  561. #endif
  562. #if CONFIG_PM_SLP_DISABLE_GPIO && SOC_GPIO_SUPPORT_SLP_SWITCH
  563. esp_sleep_gpio_status_init();
  564. #endif
  565. ESP_ERROR_CHECK(esp_pm_lock_create(ESP_PM_CPU_FREQ_MAX, 0, "rtos0",
  566. &s_rtos_lock_handle[0]));
  567. ESP_ERROR_CHECK(esp_pm_lock_acquire(s_rtos_lock_handle[0]));
  568. #if portNUM_PROCESSORS == 2
  569. ESP_ERROR_CHECK(esp_pm_lock_create(ESP_PM_CPU_FREQ_MAX, 0, "rtos1",
  570. &s_rtos_lock_handle[1]));
  571. ESP_ERROR_CHECK(esp_pm_lock_acquire(s_rtos_lock_handle[1]));
  572. #endif // portNUM_PROCESSORS == 2
  573. /* Configure all modes to use the default CPU frequency.
  574. * This will be modified later by a call to esp_pm_configure.
  575. */
  576. rtc_cpu_freq_config_t default_config;
  577. if (!rtc_clk_cpu_freq_mhz_to_config(DEFAULT_CPU_FREQ, &default_config)) {
  578. assert(false && "unsupported frequency");
  579. }
  580. for (size_t i = 0; i < PM_MODE_COUNT; ++i) {
  581. s_cpu_freq_by_mode[i] = default_config;
  582. }
  583. #ifdef CONFIG_PM_DFS_INIT_AUTO
  584. int xtal_freq = (int) rtc_clk_xtal_freq_get();
  585. #if CONFIG_IDF_TARGET_ESP32
  586. esp_pm_config_esp32_t cfg = {
  587. #elif CONFIG_IDF_TARGET_ESP32S2
  588. esp_pm_config_esp32s2_t cfg = {
  589. #elif CONFIG_IDF_TARGET_ESP32S3
  590. esp_pm_config_esp32s3_t cfg = {
  591. #endif
  592. .max_freq_mhz = DEFAULT_CPU_FREQ,
  593. .min_freq_mhz = xtal_freq,
  594. };
  595. esp_pm_configure(&cfg);
  596. #endif //CONFIG_PM_DFS_INIT_AUTO
  597. }
  598. void esp_pm_impl_idle_hook(void)
  599. {
  600. int core_id = xPortGetCoreID();
  601. uint32_t state = portENTER_CRITICAL_NESTED();
  602. if (!s_core_idle[core_id]
  603. #ifdef CONFIG_FREERTOS_USE_TICKLESS_IDLE
  604. && !periph_should_skip_light_sleep()
  605. #endif
  606. ) {
  607. esp_pm_lock_release(s_rtos_lock_handle[core_id]);
  608. s_core_idle[core_id] = true;
  609. }
  610. portEXIT_CRITICAL_NESTED(state);
  611. ESP_PM_TRACE_ENTER(IDLE, core_id);
  612. }
  613. void IRAM_ATTR esp_pm_impl_isr_hook(void)
  614. {
  615. int core_id = xPortGetCoreID();
  616. ESP_PM_TRACE_ENTER(ISR_HOOK, core_id);
  617. /* Prevent higher level interrupts (than the one this function was called from)
  618. * from happening in this section, since they will also call into esp_pm_impl_isr_hook.
  619. */
  620. uint32_t state = portENTER_CRITICAL_NESTED();
  621. #if portNUM_PROCESSORS == 2
  622. if (s_need_update_ccompare[core_id]) {
  623. update_ccompare();
  624. s_need_update_ccompare[core_id] = false;
  625. } else {
  626. leave_idle();
  627. }
  628. #else
  629. leave_idle();
  630. #endif // portNUM_PROCESSORS == 2
  631. portEXIT_CRITICAL_NESTED(state);
  632. ESP_PM_TRACE_EXIT(ISR_HOOK, core_id);
  633. }
  634. void esp_pm_impl_waiti(void)
  635. {
  636. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  637. int core_id = xPortGetCoreID();
  638. if (s_skipped_light_sleep[core_id]) {
  639. asm("waiti 0");
  640. /* Interrupt took the CPU out of waiti and s_rtos_lock_handle[core_id]
  641. * is now taken. However since we are back to idle task, we can release
  642. * the lock so that vApplicationSleep can attempt to enter light sleep.
  643. */
  644. esp_pm_impl_idle_hook();
  645. s_skipped_light_sleep[core_id] = false;
  646. }
  647. #else
  648. asm("waiti 0");
  649. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  650. }
  651. #define PERIPH_INFORM_OUT_LIGHT_SLEEP_OVERHEAD_NO 1
  652. /* Inform peripherals of light sleep wakeup overhead time */
  653. static inform_out_light_sleep_overhead_cb_t s_periph_inform_out_light_sleep_overhead_cb[PERIPH_INFORM_OUT_LIGHT_SLEEP_OVERHEAD_NO];
  654. esp_err_t esp_pm_register_inform_out_light_sleep_overhead_callback(inform_out_light_sleep_overhead_cb_t cb)
  655. {
  656. for (int i = 0; i < PERIPH_INFORM_OUT_LIGHT_SLEEP_OVERHEAD_NO; i++) {
  657. if (s_periph_inform_out_light_sleep_overhead_cb[i] == cb) {
  658. return ESP_OK;
  659. } else if (s_periph_inform_out_light_sleep_overhead_cb[i] == NULL) {
  660. s_periph_inform_out_light_sleep_overhead_cb[i] = cb;
  661. return ESP_OK;
  662. }
  663. }
  664. return ESP_ERR_NO_MEM;
  665. }
  666. esp_err_t esp_pm_unregister_inform_out_light_sleep_overhead_callback(inform_out_light_sleep_overhead_cb_t cb)
  667. {
  668. for (int i = 0; i < PERIPH_INFORM_OUT_LIGHT_SLEEP_OVERHEAD_NO; i++) {
  669. if (s_periph_inform_out_light_sleep_overhead_cb[i] == cb) {
  670. s_periph_inform_out_light_sleep_overhead_cb[i] = NULL;
  671. return ESP_OK;
  672. }
  673. }
  674. return ESP_ERR_INVALID_STATE;
  675. }
  676. void periph_inform_out_light_sleep_overhead(uint32_t out_light_sleep_time)
  677. {
  678. for (int i = 0; i < PERIPH_INFORM_OUT_LIGHT_SLEEP_OVERHEAD_NO; i++) {
  679. if (s_periph_inform_out_light_sleep_overhead_cb[i]) {
  680. s_periph_inform_out_light_sleep_overhead_cb[i](out_light_sleep_time);
  681. }
  682. }
  683. }