pm_impl.c 30 KB

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