pm_impl.c 29 KB

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