pm_impl.c 30 KB

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