pm_impl.c 32 KB

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