pm_impl.c 30 KB

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