pm_impl.c 26 KB

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