pm_impl.c 30 KB

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