pm_impl.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  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. #elif CONFIG_IDF_TARGET_ESP32S2
  41. #include "esp32s2/clk.h"
  42. #include "esp32s2/pm.h"
  43. #elif CONFIG_IDF_TARGET_ESP32S3
  44. #include "esp32s3/clk.h"
  45. #include "esp32s3/pm.h"
  46. #endif
  47. #define MHZ (1000000)
  48. /* CCOMPARE update timeout, in CPU cycles. Any value above ~600 cycles will work
  49. * for the purpose of detecting a deadlock.
  50. */
  51. #define CCOMPARE_UPDATE_TIMEOUT 1000000
  52. /* When changing CCOMPARE, don't allow changes if the difference is less
  53. * than this. This is to prevent setting CCOMPARE below CCOUNT.
  54. */
  55. #define CCOMPARE_MIN_CYCLES_IN_FUTURE 1000
  56. /* When light sleep is used, wake this number of microseconds earlier than
  57. * the next tick.
  58. */
  59. #define LIGHT_SLEEP_EARLY_WAKEUP_US 100
  60. #if CONFIG_IDF_TARGET_ESP32
  61. /* Minimal divider at which REF_CLK_FREQ can be obtained */
  62. #define REF_CLK_DIV_MIN 10
  63. #define DEFAULT_CPU_FREQ CONFIG_ESP32_DEFAULT_CPU_FREQ_MHZ
  64. #elif CONFIG_IDF_TARGET_ESP32S2
  65. /* Minimal divider at which REF_CLK_FREQ can be obtained */
  66. #define REF_CLK_DIV_MIN 2
  67. #define DEFAULT_CPU_FREQ CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ
  68. #elif CONFIG_IDF_TARGET_ESP32S3
  69. /* Minimal divider at which REF_CLK_FREQ can be obtained */
  70. #define REF_CLK_DIV_MIN 2
  71. #define DEFAULT_CPU_FREQ CONFIG_ESP32S3_DEFAULT_CPU_FREQ_MHZ
  72. #endif
  73. #ifdef CONFIG_PM_PROFILING
  74. #define WITH_PROFILING
  75. #endif
  76. static portMUX_TYPE s_switch_lock = portMUX_INITIALIZER_UNLOCKED;
  77. /* The following state variables are protected using s_switch_lock: */
  78. /* Current sleep mode; When switching, contains old mode until switch is complete */
  79. static pm_mode_t s_mode = PM_MODE_CPU_MAX;
  80. /* True when switch is in progress */
  81. static volatile bool s_is_switching;
  82. /* When switch is in progress, this is the mode we are switching into */
  83. static pm_mode_t s_new_mode = PM_MODE_CPU_MAX;
  84. /* Number of times each mode was locked */
  85. static size_t s_mode_lock_counts[PM_MODE_COUNT];
  86. /* Bit mask of locked modes. BIT(i) is set iff s_mode_lock_counts[i] > 0. */
  87. static uint32_t s_mode_mask;
  88. /* Divider and multiplier used to adjust (ccompare - ccount) duration.
  89. * Only set to non-zero values when switch is in progress.
  90. */
  91. static uint32_t s_ccount_div;
  92. static uint32_t s_ccount_mul;
  93. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  94. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  95. #define PERIPH_SKIP_LIGHT_SLEEP_NO 1
  96. /* Indicates if light sleep shoule be skipped by peripherals. */
  97. static skip_light_sleep_cb_t s_periph_skip_light_sleep_cb[PERIPH_SKIP_LIGHT_SLEEP_NO];
  98. #endif
  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. return ESP_OK;
  241. }
  242. static pm_mode_t IRAM_ATTR get_lowest_allowed_mode(void)
  243. {
  244. /* TODO: optimize using ffs/clz */
  245. if (s_mode_mask >= BIT(PM_MODE_CPU_MAX)) {
  246. return PM_MODE_CPU_MAX;
  247. } else if (s_mode_mask >= BIT(PM_MODE_APB_MAX)) {
  248. return PM_MODE_APB_MAX;
  249. } else if (s_mode_mask >= BIT(PM_MODE_APB_MIN) || !s_light_sleep_en) {
  250. return PM_MODE_APB_MIN;
  251. } else {
  252. return PM_MODE_LIGHT_SLEEP;
  253. }
  254. }
  255. void IRAM_ATTR esp_pm_impl_switch_mode(pm_mode_t mode,
  256. pm_mode_switch_t lock_or_unlock, pm_time_t now)
  257. {
  258. bool need_switch = false;
  259. uint32_t mode_mask = BIT(mode);
  260. portENTER_CRITICAL_SAFE(&s_switch_lock);
  261. uint32_t count;
  262. if (lock_or_unlock == MODE_LOCK) {
  263. count = ++s_mode_lock_counts[mode];
  264. } else {
  265. count = s_mode_lock_counts[mode]--;
  266. }
  267. if (count == 1) {
  268. if (lock_or_unlock == MODE_LOCK) {
  269. s_mode_mask |= mode_mask;
  270. } else {
  271. s_mode_mask &= ~mode_mask;
  272. }
  273. need_switch = true;
  274. }
  275. pm_mode_t new_mode = s_mode;
  276. if (need_switch) {
  277. new_mode = get_lowest_allowed_mode();
  278. #ifdef WITH_PROFILING
  279. if (s_last_mode_change_time != 0) {
  280. pm_time_t diff = now - s_last_mode_change_time;
  281. s_time_in_mode[s_mode] += diff;
  282. }
  283. s_last_mode_change_time = now;
  284. #endif // WITH_PROFILING
  285. }
  286. portEXIT_CRITICAL_SAFE(&s_switch_lock);
  287. if (need_switch && new_mode != s_mode) {
  288. do_switch(new_mode);
  289. }
  290. }
  291. /**
  292. * @brief Update clock dividers in esp_timer and FreeRTOS, and adjust CCOMPARE
  293. * values on both CPUs.
  294. * @param old_ticks_per_us old CPU frequency
  295. * @param ticks_per_us new CPU frequency
  296. */
  297. static void IRAM_ATTR on_freq_update(uint32_t old_ticks_per_us, uint32_t ticks_per_us)
  298. {
  299. uint32_t old_apb_ticks_per_us = MIN(old_ticks_per_us, 80);
  300. uint32_t apb_ticks_per_us = MIN(ticks_per_us, 80);
  301. /* Update APB frequency value used by the timer */
  302. if (old_apb_ticks_per_us != apb_ticks_per_us) {
  303. esp_timer_private_update_apb_freq(apb_ticks_per_us);
  304. }
  305. /* Calculate new tick divisor */
  306. _xt_tick_divisor = ticks_per_us * MHZ / XT_TICK_PER_SEC;
  307. int core_id = xPortGetCoreID();
  308. if (s_rtos_lock_handle[core_id] != NULL) {
  309. ESP_PM_TRACE_ENTER(CCOMPARE_UPDATE, core_id);
  310. /* ccount_div and ccount_mul are used in esp_pm_impl_update_ccompare
  311. * to calculate new CCOMPARE value.
  312. */
  313. s_ccount_div = old_ticks_per_us;
  314. s_ccount_mul = ticks_per_us;
  315. /* Update CCOMPARE value on this CPU */
  316. update_ccompare();
  317. #if portNUM_PROCESSORS == 2
  318. /* Send interrupt to the other CPU to update CCOMPARE value */
  319. int other_core_id = (core_id == 0) ? 1 : 0;
  320. s_need_update_ccompare[other_core_id] = true;
  321. esp_crosscore_int_send_freq_switch(other_core_id);
  322. int timeout = 0;
  323. while (s_need_update_ccompare[other_core_id]) {
  324. if (++timeout == CCOMPARE_UPDATE_TIMEOUT) {
  325. assert(false && "failed to update CCOMPARE, possible deadlock");
  326. }
  327. }
  328. #endif // portNUM_PROCESSORS == 2
  329. s_ccount_mul = 0;
  330. s_ccount_div = 0;
  331. ESP_PM_TRACE_EXIT(CCOMPARE_UPDATE, core_id);
  332. }
  333. }
  334. /**
  335. * Perform the switch to new power mode.
  336. * Currently only changes the CPU frequency and adjusts clock dividers.
  337. * No light sleep yet.
  338. * @param new_mode mode to switch to
  339. */
  340. static void IRAM_ATTR do_switch(pm_mode_t new_mode)
  341. {
  342. const int core_id = xPortGetCoreID();
  343. do {
  344. portENTER_CRITICAL_ISR(&s_switch_lock);
  345. if (!s_is_switching) {
  346. break;
  347. }
  348. if (s_new_mode <= new_mode) {
  349. portEXIT_CRITICAL_ISR(&s_switch_lock);
  350. return;
  351. }
  352. if (s_need_update_ccompare[core_id]) {
  353. s_need_update_ccompare[core_id] = false;
  354. }
  355. portEXIT_CRITICAL_ISR(&s_switch_lock);
  356. } while (true);
  357. s_new_mode = new_mode;
  358. s_is_switching = true;
  359. bool config_changed = s_config_changed;
  360. s_config_changed = false;
  361. portEXIT_CRITICAL_ISR(&s_switch_lock);
  362. rtc_cpu_freq_config_t new_config = s_cpu_freq_by_mode[new_mode];
  363. rtc_cpu_freq_config_t old_config;
  364. if (!config_changed) {
  365. old_config = s_cpu_freq_by_mode[s_mode];
  366. } else {
  367. rtc_clk_cpu_freq_get_config(&old_config);
  368. }
  369. if (new_config.freq_mhz != old_config.freq_mhz) {
  370. uint32_t old_ticks_per_us = old_config.freq_mhz;
  371. uint32_t new_ticks_per_us = new_config.freq_mhz;
  372. bool switch_down = new_ticks_per_us < old_ticks_per_us;
  373. ESP_PM_TRACE_ENTER(FREQ_SWITCH, core_id);
  374. if (switch_down) {
  375. on_freq_update(old_ticks_per_us, new_ticks_per_us);
  376. }
  377. rtc_clk_cpu_freq_set_config_fast(&new_config);
  378. if (!switch_down) {
  379. on_freq_update(old_ticks_per_us, new_ticks_per_us);
  380. }
  381. ESP_PM_TRACE_EXIT(FREQ_SWITCH, core_id);
  382. }
  383. portENTER_CRITICAL_ISR(&s_switch_lock);
  384. s_mode = new_mode;
  385. s_is_switching = false;
  386. portEXIT_CRITICAL_ISR(&s_switch_lock);
  387. }
  388. /**
  389. * @brief Calculate new CCOMPARE value based on s_ccount_{mul,div}
  390. *
  391. * Adjusts CCOMPARE value so that the interrupt happens at the same time as it
  392. * would happen without the frequency change.
  393. * Assumes that the new_frequency = old_frequency * s_ccount_mul / s_ccount_div.
  394. */
  395. static void IRAM_ATTR update_ccompare(void)
  396. {
  397. uint32_t ccount = cpu_hal_get_cycle_count();
  398. uint32_t ccompare = XTHAL_GET_CCOMPARE(XT_TIMER_INDEX);
  399. if ((ccompare - CCOMPARE_MIN_CYCLES_IN_FUTURE) - ccount < UINT32_MAX / 2) {
  400. uint32_t diff = ccompare - ccount;
  401. uint32_t diff_scaled = (diff * s_ccount_mul + s_ccount_div - 1) / s_ccount_div;
  402. if (diff_scaled < _xt_tick_divisor) {
  403. uint32_t new_ccompare = ccount + diff_scaled;
  404. XTHAL_SET_CCOMPARE(XT_TIMER_INDEX, new_ccompare);
  405. }
  406. }
  407. }
  408. static void IRAM_ATTR leave_idle(void)
  409. {
  410. int core_id = xPortGetCoreID();
  411. if (s_core_idle[core_id]) {
  412. // TODO: possible optimization: raise frequency here first
  413. esp_pm_lock_acquire(s_rtos_lock_handle[core_id]);
  414. s_core_idle[core_id] = false;
  415. }
  416. }
  417. void esp_pm_impl_idle_hook(void)
  418. {
  419. int core_id = xPortGetCoreID();
  420. uint32_t state = portENTER_CRITICAL_NESTED();
  421. if (!s_core_idle[core_id]) {
  422. esp_pm_lock_release(s_rtos_lock_handle[core_id]);
  423. s_core_idle[core_id] = true;
  424. }
  425. portEXIT_CRITICAL_NESTED(state);
  426. ESP_PM_TRACE_ENTER(IDLE, core_id);
  427. }
  428. void IRAM_ATTR esp_pm_impl_isr_hook(void)
  429. {
  430. int core_id = xPortGetCoreID();
  431. ESP_PM_TRACE_ENTER(ISR_HOOK, core_id);
  432. /* Prevent higher level interrupts (than the one this function was called from)
  433. * from happening in this section, since they will also call into esp_pm_impl_isr_hook.
  434. */
  435. uint32_t state = portENTER_CRITICAL_NESTED();
  436. #if portNUM_PROCESSORS == 2
  437. if (s_need_update_ccompare[core_id]) {
  438. update_ccompare();
  439. s_need_update_ccompare[core_id] = false;
  440. } else {
  441. leave_idle();
  442. }
  443. #else
  444. leave_idle();
  445. #endif // portNUM_PROCESSORS == 2
  446. portEXIT_CRITICAL_NESTED(state);
  447. ESP_PM_TRACE_EXIT(ISR_HOOK, core_id);
  448. }
  449. void esp_pm_impl_waiti(void)
  450. {
  451. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  452. int core_id = xPortGetCoreID();
  453. if (s_skipped_light_sleep[core_id]) {
  454. asm("waiti 0");
  455. /* Interrupt took the CPU out of waiti and s_rtos_lock_handle[core_id]
  456. * is now taken. However since we are back to idle task, we can release
  457. * the lock so that vApplicationSleep can attempt to enter light sleep.
  458. */
  459. esp_pm_impl_idle_hook();
  460. s_skipped_light_sleep[core_id] = false;
  461. }
  462. #else
  463. asm("waiti 0");
  464. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  465. }
  466. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  467. #if CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  468. esp_err_t esp_pm_register_skip_light_sleep_callback(skip_light_sleep_cb_t cb)
  469. {
  470. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  471. if (s_periph_skip_light_sleep_cb[i] == cb) {
  472. return ESP_OK;
  473. } else if (s_periph_skip_light_sleep_cb[i] == NULL) {
  474. s_periph_skip_light_sleep_cb[i] = cb;
  475. return ESP_OK;
  476. }
  477. }
  478. return ESP_ERR_NO_MEM;
  479. }
  480. esp_err_t esp_pm_unregister_skip_light_sleep_callback(skip_light_sleep_cb_t cb)
  481. {
  482. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  483. if (s_periph_skip_light_sleep_cb[i] == cb) {
  484. s_periph_skip_light_sleep_cb[i] = NULL;
  485. return ESP_OK;
  486. }
  487. }
  488. return ESP_ERR_INVALID_STATE;
  489. }
  490. static inline bool IRAM_ATTR periph_should_skip_light_sleep(void)
  491. {
  492. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  493. if (s_periph_skip_light_sleep_cb[i]) {
  494. if (s_periph_skip_light_sleep_cb[i]() == true) {
  495. return true;
  496. }
  497. }
  498. }
  499. return false;
  500. }
  501. #endif
  502. static inline bool IRAM_ATTR should_skip_light_sleep(int core_id)
  503. {
  504. #if portNUM_PROCESSORS == 2
  505. if (s_skip_light_sleep[core_id]) {
  506. s_skip_light_sleep[core_id] = false;
  507. s_skipped_light_sleep[core_id] = true;
  508. return true;
  509. }
  510. #endif // portNUM_PROCESSORS == 2
  511. #if CONFIG_IDF_TARGET_ESP32
  512. if (s_mode != PM_MODE_LIGHT_SLEEP || s_is_switching) {
  513. #elif CONFIG_IDF_TARGET_ESP32S2 || CONFIG_IDF_TARGET_ESP32S3
  514. if (s_mode != PM_MODE_LIGHT_SLEEP || s_is_switching || periph_should_skip_light_sleep()) {
  515. #endif
  516. s_skipped_light_sleep[core_id] = true;
  517. } else {
  518. s_skipped_light_sleep[core_id] = false;
  519. }
  520. return s_skipped_light_sleep[core_id];
  521. }
  522. static inline void IRAM_ATTR other_core_should_skip_light_sleep(int core_id)
  523. {
  524. #if portNUM_PROCESSORS == 2
  525. s_skip_light_sleep[!core_id] = true;
  526. #endif
  527. }
  528. void IRAM_ATTR vApplicationSleep( TickType_t xExpectedIdleTime )
  529. {
  530. portENTER_CRITICAL(&s_switch_lock);
  531. int core_id = xPortGetCoreID();
  532. if (!should_skip_light_sleep(core_id)) {
  533. /* Calculate how much we can sleep */
  534. int64_t next_esp_timer_alarm = esp_timer_get_next_alarm();
  535. int64_t now = esp_timer_get_time();
  536. int64_t time_until_next_alarm = next_esp_timer_alarm - now;
  537. int64_t wakeup_delay_us = portTICK_PERIOD_MS * 1000LL * xExpectedIdleTime;
  538. int64_t sleep_time_us = MIN(wakeup_delay_us, time_until_next_alarm);
  539. if (sleep_time_us >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP * portTICK_PERIOD_MS * 1000LL) {
  540. esp_sleep_enable_timer_wakeup(sleep_time_us - LIGHT_SLEEP_EARLY_WAKEUP_US);
  541. #ifdef CONFIG_PM_TRACE
  542. /* to force tracing GPIOs to keep state */
  543. esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
  544. #endif
  545. /* Enter sleep */
  546. ESP_PM_TRACE_ENTER(SLEEP, core_id);
  547. int64_t sleep_start = esp_timer_get_time();
  548. esp_light_sleep_start();
  549. int64_t slept_us = esp_timer_get_time() - sleep_start;
  550. ESP_PM_TRACE_EXIT(SLEEP, core_id);
  551. uint32_t slept_ticks = slept_us / (portTICK_PERIOD_MS * 1000LL);
  552. if (slept_ticks > 0) {
  553. /* Adjust RTOS tick count based on the amount of time spent in sleep */
  554. vTaskStepTick(slept_ticks);
  555. /* Trigger tick interrupt, since sleep time was longer
  556. * than portTICK_PERIOD_MS. Note that setting INTSET does not
  557. * work for timer interrupt, and changing CCOMPARE would clear
  558. * the interrupt flag.
  559. */
  560. cpu_hal_set_cycle_count(XTHAL_GET_CCOMPARE(XT_TIMER_INDEX) - 16);
  561. while (!(XTHAL_GET_INTERRUPT() & BIT(XT_TIMER_INTNUM))) {
  562. ;
  563. }
  564. }
  565. other_core_should_skip_light_sleep(core_id);
  566. }
  567. }
  568. portEXIT_CRITICAL(&s_switch_lock);
  569. }
  570. #endif //CONFIG_FREERTOS_USE_TICKLESS_IDLE
  571. #ifdef WITH_PROFILING
  572. void esp_pm_impl_dump_stats(FILE* out)
  573. {
  574. pm_time_t time_in_mode[PM_MODE_COUNT];
  575. portENTER_CRITICAL_ISR(&s_switch_lock);
  576. memcpy(time_in_mode, s_time_in_mode, sizeof(time_in_mode));
  577. pm_time_t last_mode_change_time = s_last_mode_change_time;
  578. pm_mode_t cur_mode = s_mode;
  579. pm_time_t now = pm_get_time();
  580. portEXIT_CRITICAL_ISR(&s_switch_lock);
  581. time_in_mode[cur_mode] += now - last_mode_change_time;
  582. fprintf(out, "Mode stats:\n");
  583. for (int i = 0; i < PM_MODE_COUNT; ++i) {
  584. if (i == PM_MODE_LIGHT_SLEEP && !s_light_sleep_en) {
  585. /* don't display light sleep mode if it's not enabled */
  586. continue;
  587. }
  588. fprintf(out, "%8s %3dM %12lld %2d%%\n",
  589. s_mode_names[i],
  590. s_cpu_freq_by_mode[i].freq_mhz,
  591. time_in_mode[i],
  592. (int) (time_in_mode[i] * 100 / now));
  593. }
  594. }
  595. #endif // WITH_PROFILING
  596. void esp_pm_impl_init(void)
  597. {
  598. #if defined(CONFIG_ESP_CONSOLE_UART)
  599. //This clock source should be a source which won't be affected by DFS
  600. uint32_t clk_source;
  601. #if CONFIG_IDF_TARGET_ESP32 || CONFIG_IDF_TARGET_ESP32S2
  602. clk_source = UART_SCLK_REF_TICK;
  603. #else
  604. clk_source = UART_SCLK_XTAL;
  605. #endif
  606. while(!uart_ll_is_tx_idle(UART_LL_GET_HW(CONFIG_ESP_CONSOLE_UART_NUM)));
  607. /* When DFS is enabled, override system setting and use REFTICK as UART clock source */
  608. uart_ll_set_sclk(UART_LL_GET_HW(CONFIG_ESP_CONSOLE_UART_NUM), clk_source);
  609. uart_ll_set_baudrate(UART_LL_GET_HW(CONFIG_ESP_CONSOLE_UART_NUM), CONFIG_ESP_CONSOLE_UART_BAUDRATE);
  610. #endif // CONFIG_ESP_CONSOLE_UART
  611. #ifdef CONFIG_PM_TRACE
  612. esp_pm_trace_init();
  613. #endif
  614. ESP_ERROR_CHECK(esp_pm_lock_create(ESP_PM_CPU_FREQ_MAX, 0, "rtos0",
  615. &s_rtos_lock_handle[0]));
  616. ESP_ERROR_CHECK(esp_pm_lock_acquire(s_rtos_lock_handle[0]));
  617. #if portNUM_PROCESSORS == 2
  618. ESP_ERROR_CHECK(esp_pm_lock_create(ESP_PM_CPU_FREQ_MAX, 0, "rtos1",
  619. &s_rtos_lock_handle[1]));
  620. ESP_ERROR_CHECK(esp_pm_lock_acquire(s_rtos_lock_handle[1]));
  621. #endif // portNUM_PROCESSORS == 2
  622. /* Configure all modes to use the default CPU frequency.
  623. * This will be modified later by a call to esp_pm_configure.
  624. */
  625. rtc_cpu_freq_config_t default_config;
  626. if (!rtc_clk_cpu_freq_mhz_to_config(DEFAULT_CPU_FREQ, &default_config)) {
  627. assert(false && "unsupported frequency");
  628. }
  629. for (size_t i = 0; i < PM_MODE_COUNT; ++i) {
  630. s_cpu_freq_by_mode[i] = default_config;
  631. }
  632. #ifdef CONFIG_PM_DFS_INIT_AUTO
  633. int xtal_freq = (int) rtc_clk_xtal_freq_get();
  634. #if CONFIG_IDF_TARGET_ESP32
  635. esp_pm_config_esp32_t cfg = {
  636. #elif CONFIG_IDF_TARGET_ESP32S2
  637. esp_pm_config_esp32s2_t cfg = {
  638. #elif CONFIG_IDF_TARGET_ESP32S3
  639. esp_pm_config_esp32s3_t cfg = {
  640. #endif
  641. .max_freq_mhz = DEFAULT_CPU_FREQ,
  642. .min_freq_mhz = xtal_freq,
  643. };
  644. esp_pm_configure(&cfg);
  645. #endif //CONFIG_PM_DFS_INIT_AUTO
  646. }