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