pm_impl.c 31 KB

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