pm_impl.c 30 KB

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