pm_impl.c 30 KB

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