pm_impl.c 26 KB

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