pm_esp32s2.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. // Copyright 2016-2020 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 "esp32s2/clk.h"
  23. #include "esp_private/crosscore_int.h"
  24. #include "soc/rtc.h"
  25. #include "freertos/FreeRTOS.h"
  26. #include "freertos/task.h"
  27. #include "freertos/xtensa_timer.h"
  28. #include "xtensa/core-macros.h"
  29. #include "esp_private/pm_impl.h"
  30. #include "esp_private/pm_trace.h"
  31. #include "esp_private/esp_timer_private.h"
  32. #include "esp32s2/pm.h"
  33. #include "esp_sleep.h"
  34. /* CCOMPARE update timeout, in CPU cycles. Any value above ~600 cycles will work
  35. * for the purpose of detecting a deadlock.
  36. */
  37. #define CCOMPARE_UPDATE_TIMEOUT 1000000
  38. /* When changing CCOMPARE, don't allow changes if the difference is less
  39. * than this. This is to prevent setting CCOMPARE below CCOUNT.
  40. */
  41. #define CCOMPARE_MIN_CYCLES_IN_FUTURE 1000
  42. /* When light sleep is used, wake this number of microseconds earlier than
  43. * the next tick.
  44. */
  45. #define LIGHT_SLEEP_EARLY_WAKEUP_US 100
  46. /* Minimal divider at which REF_CLK_FREQ can be obtained */
  47. #define REF_CLK_DIV_MIN 2
  48. #ifdef CONFIG_PM_PROFILING
  49. #define WITH_PROFILING
  50. #endif
  51. static portMUX_TYPE s_switch_lock = portMUX_INITIALIZER_UNLOCKED;
  52. /* The following state variables are protected using s_switch_lock: */
  53. /* Current sleep mode; When switching, contains old mode until switch is complete */
  54. static pm_mode_t s_mode = PM_MODE_CPU_MAX;
  55. /* True when switch is in progress */
  56. static volatile bool s_is_switching;
  57. /* When switch is in progress, this is the mode we are switching into */
  58. static pm_mode_t s_new_mode = PM_MODE_CPU_MAX;
  59. /* Number of times each mode was locked */
  60. static size_t s_mode_lock_counts[PM_MODE_COUNT];
  61. /* Bit mask of locked modes. BIT(i) is set iff s_mode_lock_counts[i] > 0. */
  62. static uint32_t s_mode_mask;
  63. /* Divider and multiplier used to adjust (ccompare - ccount) duration.
  64. * Only set to non-zero values when switch is in progress.
  65. */
  66. static uint32_t s_ccount_div;
  67. static uint32_t s_ccount_mul;
  68. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  69. #define PERIPH_SKIP_LIGHT_SLEEP_NO 1
  70. /* Indicates if light sleep shoule be skipped by peripherals. */
  71. static skip_light_sleep_cb_t s_periph_skip_light_sleep_cb[PERIPH_SKIP_LIGHT_SLEEP_NO];
  72. /* Indicates if light sleep entry was skipped in vApplicationSleep for given CPU.
  73. * This in turn gets used in IDLE hook to decide if `waiti` needs
  74. * to be invoked or not.
  75. */
  76. static bool s_skipped_light_sleep[portNUM_PROCESSORS];
  77. #if portNUM_PROCESSORS == 2
  78. /* When light sleep is finished on one CPU, it is possible that the other CPU
  79. * will enter light sleep again very soon, before interrupts on the first CPU
  80. * get a chance to run. To avoid such situation, set a flag for the other CPU to
  81. * skip light sleep attempt.
  82. */
  83. static bool s_skip_light_sleep[portNUM_PROCESSORS];
  84. #endif // portNUM_PROCESSORS == 2
  85. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  86. /* Indicates to the ISR hook that CCOMPARE needs to be updated on the given CPU.
  87. * Used in conjunction with cross-core interrupt to update CCOMPARE on the other CPU.
  88. */
  89. static volatile bool s_need_update_ccompare[portNUM_PROCESSORS];
  90. /* A flag indicating that Idle hook has run on a given CPU;
  91. * Next interrupt on the same CPU will take s_rtos_lock_handle.
  92. */
  93. static bool s_core_idle[portNUM_PROCESSORS];
  94. /* When no RTOS tasks are active, these locks are released to allow going into
  95. * a lower power mode. Used by ISR hook and idle hook.
  96. */
  97. static esp_pm_lock_handle_t s_rtos_lock_handle[portNUM_PROCESSORS];
  98. /* Lookup table of CPU frequency configs to be used in each mode.
  99. * Initialized by esp_pm_impl_init and modified by esp_pm_configure.
  100. */
  101. rtc_cpu_freq_config_t s_cpu_freq_by_mode[PM_MODE_COUNT];
  102. /* Whether automatic light sleep is enabled */
  103. static bool s_light_sleep_en = false;
  104. /* When configuration is changed, current frequency may not match the
  105. * newly configured frequency for the current mode. This is an indicator
  106. * to the mode switch code to get the actual current frequency instead of
  107. * relying on the current mode.
  108. */
  109. static bool s_config_changed = false;
  110. #ifdef WITH_PROFILING
  111. /* Time, in microseconds, spent so far in each mode */
  112. static pm_time_t s_time_in_mode[PM_MODE_COUNT];
  113. /* Timestamp, in microseconds, when the mode switch last happened */
  114. static pm_time_t s_last_mode_change_time;
  115. /* User-readable mode names, used by esp_pm_impl_dump_stats */
  116. static const char* s_mode_names[] = {
  117. "SLEEP",
  118. "APB_MIN",
  119. "APB_MAX",
  120. "CPU_MAX"
  121. };
  122. #endif // WITH_PROFILING
  123. static const char* TAG = "pm_esp32s2";
  124. static void update_ccompare(void);
  125. static void do_switch(pm_mode_t new_mode);
  126. static void leave_idle(void);
  127. static void on_freq_update(uint32_t old_ticks_per_us, uint32_t ticks_per_us);
  128. pm_mode_t esp_pm_impl_get_mode(esp_pm_lock_type_t type, int arg)
  129. {
  130. (void) arg;
  131. if (type == ESP_PM_CPU_FREQ_MAX) {
  132. return PM_MODE_CPU_MAX;
  133. } else if (type == ESP_PM_APB_FREQ_MAX) {
  134. return PM_MODE_APB_MAX;
  135. } else if (type == ESP_PM_NO_LIGHT_SLEEP) {
  136. return PM_MODE_APB_MIN;
  137. } else {
  138. // unsupported mode
  139. abort();
  140. }
  141. }
  142. esp_err_t esp_pm_configure(const void* vconfig)
  143. {
  144. #ifndef CONFIG_PM_ENABLE
  145. return ESP_ERR_NOT_SUPPORTED;
  146. #endif
  147. const esp_pm_config_esp32s2_t* config = (const esp_pm_config_esp32s2_t*) vconfig;
  148. #ifndef CONFIG_FREERTOS_USE_TICKLESS_IDLE
  149. if (config->light_sleep_enable) {
  150. return ESP_ERR_NOT_SUPPORTED;
  151. }
  152. #endif
  153. int min_freq_mhz = config->min_freq_mhz;
  154. int max_freq_mhz = config->max_freq_mhz;
  155. if (min_freq_mhz > max_freq_mhz) {
  156. return ESP_ERR_INVALID_ARG;
  157. }
  158. rtc_cpu_freq_config_t freq_config;
  159. if (!rtc_clk_cpu_freq_mhz_to_config(min_freq_mhz, &freq_config)) {
  160. ESP_LOGW(TAG, "invalid min_freq_mhz value (%d)", min_freq_mhz);
  161. return ESP_ERR_INVALID_ARG;
  162. }
  163. int xtal_freq_mhz = (int) rtc_clk_xtal_freq_get();
  164. if (min_freq_mhz < xtal_freq_mhz && min_freq_mhz * MHZ / REF_CLK_FREQ < REF_CLK_DIV_MIN) {
  165. ESP_LOGW(TAG, "min_freq_mhz should be >= %d", REF_CLK_FREQ * REF_CLK_DIV_MIN / MHZ);
  166. return ESP_ERR_INVALID_ARG;
  167. }
  168. if (!rtc_clk_cpu_freq_mhz_to_config(max_freq_mhz, &freq_config)) {
  169. ESP_LOGW(TAG, "invalid max_freq_mhz value (%d)", max_freq_mhz);
  170. return ESP_ERR_INVALID_ARG;
  171. }
  172. int apb_max_freq = MIN(max_freq_mhz, 80); /* CPU frequency in APB_MAX mode */
  173. apb_max_freq = MAX(apb_max_freq, min_freq_mhz);
  174. ESP_LOGI(TAG, "Frequency switching config: "
  175. "CPU_MAX: %d, APB_MAX: %d, APB_MIN: %d, Light sleep: %s",
  176. max_freq_mhz,
  177. apb_max_freq,
  178. min_freq_mhz,
  179. config->light_sleep_enable ? "ENABLED" : "DISABLED");
  180. portENTER_CRITICAL(&s_switch_lock);
  181. bool res;
  182. res = rtc_clk_cpu_freq_mhz_to_config(max_freq_mhz, &s_cpu_freq_by_mode[PM_MODE_CPU_MAX]);
  183. assert(res);
  184. res = rtc_clk_cpu_freq_mhz_to_config(apb_max_freq, &s_cpu_freq_by_mode[PM_MODE_APB_MAX]);
  185. assert(res);
  186. res = rtc_clk_cpu_freq_mhz_to_config(min_freq_mhz, &s_cpu_freq_by_mode[PM_MODE_APB_MIN]);
  187. assert(res);
  188. s_cpu_freq_by_mode[PM_MODE_LIGHT_SLEEP] = s_cpu_freq_by_mode[PM_MODE_APB_MIN];
  189. s_light_sleep_en = config->light_sleep_enable;
  190. s_config_changed = true;
  191. portEXIT_CRITICAL(&s_switch_lock);
  192. return ESP_OK;
  193. }
  194. esp_err_t esp_pm_get_configuration(void* vconfig)
  195. {
  196. if (vconfig == NULL) {
  197. return ESP_ERR_INVALID_ARG;
  198. }
  199. esp_pm_config_esp32s2_t* config = (esp_pm_config_esp32s2_t*) vconfig;
  200. portENTER_CRITICAL(&s_switch_lock);
  201. config->light_sleep_enable = s_light_sleep_en;
  202. config->max_freq_mhz = s_cpu_freq_by_mode[PM_MODE_CPU_MAX].freq_mhz;
  203. config->min_freq_mhz = s_cpu_freq_by_mode[PM_MODE_APB_MIN].freq_mhz;
  204. portEXIT_CRITICAL(&s_switch_lock);
  205. return ESP_OK;
  206. }
  207. static pm_mode_t IRAM_ATTR get_lowest_allowed_mode(void)
  208. {
  209. /* TODO: optimize using ffs/clz */
  210. if (s_mode_mask >= BIT(PM_MODE_CPU_MAX)) {
  211. return PM_MODE_CPU_MAX;
  212. } else if (s_mode_mask >= BIT(PM_MODE_APB_MAX)) {
  213. return PM_MODE_APB_MAX;
  214. } else if (s_mode_mask >= BIT(PM_MODE_APB_MIN) || !s_light_sleep_en) {
  215. return PM_MODE_APB_MIN;
  216. } else {
  217. return PM_MODE_LIGHT_SLEEP;
  218. }
  219. }
  220. void IRAM_ATTR esp_pm_impl_switch_mode(pm_mode_t mode,
  221. pm_mode_switch_t lock_or_unlock, pm_time_t now)
  222. {
  223. bool need_switch = false;
  224. uint32_t mode_mask = BIT(mode);
  225. portENTER_CRITICAL_SAFE(&s_switch_lock);
  226. uint32_t count;
  227. if (lock_or_unlock == MODE_LOCK) {
  228. count = ++s_mode_lock_counts[mode];
  229. } else {
  230. count = s_mode_lock_counts[mode]--;
  231. }
  232. if (count == 1) {
  233. if (lock_or_unlock == MODE_LOCK) {
  234. s_mode_mask |= mode_mask;
  235. } else {
  236. s_mode_mask &= ~mode_mask;
  237. }
  238. need_switch = true;
  239. }
  240. pm_mode_t new_mode = s_mode;
  241. if (need_switch) {
  242. new_mode = get_lowest_allowed_mode();
  243. #ifdef WITH_PROFILING
  244. if (s_last_mode_change_time != 0) {
  245. pm_time_t diff = now - s_last_mode_change_time;
  246. s_time_in_mode[s_mode] += diff;
  247. }
  248. s_last_mode_change_time = now;
  249. #endif // WITH_PROFILING
  250. }
  251. portEXIT_CRITICAL_SAFE(&s_switch_lock);
  252. if (need_switch && new_mode != s_mode) {
  253. do_switch(new_mode);
  254. }
  255. }
  256. /**
  257. * @brief Update clock dividers in esp_timer and FreeRTOS, and adjust CCOMPARE
  258. * values on both CPUs.
  259. * @param old_ticks_per_us old CPU frequency
  260. * @param ticks_per_us new CPU frequency
  261. */
  262. static void IRAM_ATTR on_freq_update(uint32_t old_ticks_per_us, uint32_t ticks_per_us)
  263. {
  264. uint32_t old_apb_ticks_per_us = MIN(old_ticks_per_us, 80);
  265. uint32_t apb_ticks_per_us = MIN(ticks_per_us, 80);
  266. /* Update APB frequency value used by the timer */
  267. if (old_apb_ticks_per_us != apb_ticks_per_us) {
  268. esp_timer_private_update_apb_freq(apb_ticks_per_us);
  269. }
  270. /* Calculate new tick divisor */
  271. _xt_tick_divisor = ticks_per_us * MHZ / XT_TICK_PER_SEC;
  272. int core_id = xPortGetCoreID();
  273. if (s_rtos_lock_handle[core_id] != NULL) {
  274. ESP_PM_TRACE_ENTER(CCOMPARE_UPDATE, core_id);
  275. /* ccount_div and ccount_mul are used in esp_pm_impl_update_ccompare
  276. * to calculate new CCOMPARE value.
  277. */
  278. s_ccount_div = old_ticks_per_us;
  279. s_ccount_mul = ticks_per_us;
  280. /* Update CCOMPARE value on this CPU */
  281. update_ccompare();
  282. #if portNUM_PROCESSORS == 2
  283. /* Send interrupt to the other CPU to update CCOMPARE value */
  284. int other_core_id = (core_id == 0) ? 1 : 0;
  285. s_need_update_ccompare[other_core_id] = true;
  286. esp_crosscore_int_send_freq_switch(other_core_id);
  287. int timeout = 0;
  288. while (s_need_update_ccompare[other_core_id]) {
  289. if (++timeout == CCOMPARE_UPDATE_TIMEOUT) {
  290. assert(false && "failed to update CCOMPARE, possible deadlock");
  291. }
  292. }
  293. #endif // portNUM_PROCESSORS == 2
  294. s_ccount_mul = 0;
  295. s_ccount_div = 0;
  296. ESP_PM_TRACE_EXIT(CCOMPARE_UPDATE, core_id);
  297. }
  298. }
  299. /**
  300. * Perform the switch to new power mode.
  301. * Currently only changes the CPU frequency and adjusts clock dividers.
  302. * No light sleep yet.
  303. * @param new_mode mode to switch to
  304. */
  305. static void IRAM_ATTR do_switch(pm_mode_t new_mode)
  306. {
  307. const int core_id = xPortGetCoreID();
  308. do {
  309. portENTER_CRITICAL_ISR(&s_switch_lock);
  310. if (!s_is_switching) {
  311. break;
  312. }
  313. if (s_new_mode <= new_mode) {
  314. portEXIT_CRITICAL_ISR(&s_switch_lock);
  315. return;
  316. }
  317. if (s_need_update_ccompare[core_id]) {
  318. s_need_update_ccompare[core_id] = false;
  319. }
  320. portEXIT_CRITICAL_ISR(&s_switch_lock);
  321. } while (true);
  322. s_new_mode = new_mode;
  323. s_is_switching = true;
  324. bool config_changed = s_config_changed;
  325. s_config_changed = false;
  326. portEXIT_CRITICAL_ISR(&s_switch_lock);
  327. rtc_cpu_freq_config_t new_config = s_cpu_freq_by_mode[new_mode];
  328. rtc_cpu_freq_config_t old_config;
  329. if (!config_changed) {
  330. old_config = s_cpu_freq_by_mode[s_mode];
  331. } else {
  332. rtc_clk_cpu_freq_get_config(&old_config);
  333. }
  334. if (new_config.freq_mhz != old_config.freq_mhz) {
  335. uint32_t old_ticks_per_us = old_config.freq_mhz;
  336. uint32_t new_ticks_per_us = new_config.freq_mhz;
  337. bool switch_down = new_ticks_per_us < old_ticks_per_us;
  338. ESP_PM_TRACE_ENTER(FREQ_SWITCH, core_id);
  339. if (switch_down) {
  340. on_freq_update(old_ticks_per_us, new_ticks_per_us);
  341. }
  342. rtc_clk_cpu_freq_set_config_fast(&new_config);
  343. if (!switch_down) {
  344. on_freq_update(old_ticks_per_us, new_ticks_per_us);
  345. }
  346. ESP_PM_TRACE_EXIT(FREQ_SWITCH, core_id);
  347. }
  348. portENTER_CRITICAL_ISR(&s_switch_lock);
  349. s_mode = new_mode;
  350. s_is_switching = false;
  351. portEXIT_CRITICAL_ISR(&s_switch_lock);
  352. }
  353. /**
  354. * @brief Calculate new CCOMPARE value based on s_ccount_{mul,div}
  355. *
  356. * Adjusts CCOMPARE value so that the interrupt happens at the same time as it
  357. * would happen without the frequency change.
  358. * Assumes that the new_frequency = old_frequency * s_ccount_mul / s_ccount_div.
  359. */
  360. static void IRAM_ATTR update_ccompare(void)
  361. {
  362. uint32_t ccount = XTHAL_GET_CCOUNT();
  363. uint32_t ccompare = XTHAL_GET_CCOMPARE(XT_TIMER_INDEX);
  364. if ((ccompare - CCOMPARE_MIN_CYCLES_IN_FUTURE) - ccount < UINT32_MAX / 2) {
  365. uint32_t diff = ccompare - ccount;
  366. uint32_t diff_scaled = (diff * s_ccount_mul + s_ccount_div - 1) / s_ccount_div;
  367. if (diff_scaled < _xt_tick_divisor) {
  368. uint32_t new_ccompare = ccount + diff_scaled;
  369. XTHAL_SET_CCOMPARE(XT_TIMER_INDEX, new_ccompare);
  370. }
  371. }
  372. }
  373. static void IRAM_ATTR leave_idle(void)
  374. {
  375. int core_id = xPortGetCoreID();
  376. if (s_core_idle[core_id]) {
  377. // TODO: possible optimization: raise frequency here first
  378. esp_pm_lock_acquire(s_rtos_lock_handle[core_id]);
  379. s_core_idle[core_id] = false;
  380. }
  381. }
  382. void esp_pm_impl_idle_hook(void)
  383. {
  384. int core_id = xPortGetCoreID();
  385. uint32_t state = portENTER_CRITICAL_NESTED();
  386. if (!s_core_idle[core_id]) {
  387. esp_pm_lock_release(s_rtos_lock_handle[core_id]);
  388. s_core_idle[core_id] = true;
  389. }
  390. portEXIT_CRITICAL_NESTED(state);
  391. ESP_PM_TRACE_ENTER(IDLE, core_id);
  392. }
  393. void IRAM_ATTR esp_pm_impl_isr_hook(void)
  394. {
  395. int core_id = xPortGetCoreID();
  396. ESP_PM_TRACE_ENTER(ISR_HOOK, core_id);
  397. /* Prevent higher level interrupts (than the one this function was called from)
  398. * from happening in this section, since they will also call into esp_pm_impl_isr_hook.
  399. */
  400. uint32_t state = portENTER_CRITICAL_NESTED();
  401. #if portNUM_PROCESSORS == 2
  402. if (s_need_update_ccompare[core_id]) {
  403. update_ccompare();
  404. s_need_update_ccompare[core_id] = false;
  405. } else {
  406. leave_idle();
  407. }
  408. #else
  409. leave_idle();
  410. #endif // portNUM_PROCESSORS == 2
  411. portEXIT_CRITICAL_NESTED(state);
  412. ESP_PM_TRACE_EXIT(ISR_HOOK, core_id);
  413. }
  414. void esp_pm_impl_waiti(void)
  415. {
  416. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  417. int core_id = xPortGetCoreID();
  418. if (s_skipped_light_sleep[core_id]) {
  419. asm("waiti 0");
  420. /* Interrupt took the CPU out of waiti and s_rtos_lock_handle[core_id]
  421. * is now taken. However since we are back to idle task, we can release
  422. * the lock so that vApplicationSleep can attempt to enter light sleep.
  423. */
  424. esp_pm_impl_idle_hook();
  425. s_skipped_light_sleep[core_id] = false;
  426. }
  427. #else
  428. asm("waiti 0");
  429. #endif // CONFIG_FREERTOS_USE_TICKLESS_IDLE
  430. }
  431. #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
  432. esp_err_t esp_pm_register_skip_light_sleep_callback(skip_light_sleep_cb_t cb)
  433. {
  434. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  435. if (s_periph_skip_light_sleep_cb[i] == cb) {
  436. return ESP_OK;
  437. } else if (s_periph_skip_light_sleep_cb[i] == NULL) {
  438. s_periph_skip_light_sleep_cb[i] = cb;
  439. return ESP_OK;
  440. }
  441. }
  442. return ESP_ERR_NO_MEM;
  443. }
  444. esp_err_t esp_pm_unregister_skip_light_sleep_callback(skip_light_sleep_cb_t cb)
  445. {
  446. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  447. if (s_periph_skip_light_sleep_cb[i] == cb) {
  448. s_periph_skip_light_sleep_cb[i] = NULL;
  449. return ESP_OK;
  450. }
  451. }
  452. return ESP_ERR_INVALID_STATE;
  453. }
  454. static inline bool IRAM_ATTR periph_should_skip_light_sleep(void)
  455. {
  456. for (int i = 0; i < PERIPH_SKIP_LIGHT_SLEEP_NO; i++) {
  457. if (s_periph_skip_light_sleep_cb[i]) {
  458. if (s_periph_skip_light_sleep_cb[i]() == true) {
  459. return true;
  460. }
  461. }
  462. }
  463. return false;
  464. }
  465. static inline bool IRAM_ATTR should_skip_light_sleep(int core_id)
  466. {
  467. #if portNUM_PROCESSORS == 2
  468. if (s_skip_light_sleep[core_id]) {
  469. s_skip_light_sleep[core_id] = false;
  470. s_skipped_light_sleep[core_id] = true;
  471. return true;
  472. }
  473. #endif // portNUM_PROCESSORS == 2
  474. if (s_mode != PM_MODE_LIGHT_SLEEP || s_is_switching || periph_should_skip_light_sleep()) {
  475. s_skipped_light_sleep[core_id] = true;
  476. } else {
  477. s_skipped_light_sleep[core_id] = false;
  478. }
  479. return s_skipped_light_sleep[core_id];
  480. }
  481. static inline void IRAM_ATTR other_core_should_skip_light_sleep(int core_id)
  482. {
  483. #if portNUM_PROCESSORS == 2
  484. s_skip_light_sleep[!core_id] = true;
  485. #endif
  486. }
  487. void IRAM_ATTR vApplicationSleep( TickType_t xExpectedIdleTime )
  488. {
  489. portENTER_CRITICAL(&s_switch_lock);
  490. int core_id = xPortGetCoreID();
  491. if (!should_skip_light_sleep(core_id)) {
  492. /* Calculate how much we can sleep */
  493. int64_t next_esp_timer_alarm = esp_timer_get_next_alarm();
  494. int64_t now = esp_timer_get_time();
  495. int64_t time_until_next_alarm = next_esp_timer_alarm - now;
  496. int64_t wakeup_delay_us = portTICK_PERIOD_MS * 1000LL * xExpectedIdleTime;
  497. int64_t sleep_time_us = MIN(wakeup_delay_us, time_until_next_alarm);
  498. if (sleep_time_us >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP * portTICK_PERIOD_MS * 1000LL) {
  499. esp_sleep_enable_timer_wakeup(sleep_time_us - LIGHT_SLEEP_EARLY_WAKEUP_US);
  500. #ifdef CONFIG_PM_TRACE
  501. /* to force tracing GPIOs to keep state */
  502. esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
  503. #endif
  504. /* Enter sleep */
  505. ESP_PM_TRACE_ENTER(SLEEP, core_id);
  506. int64_t sleep_start = esp_timer_get_time();
  507. esp_light_sleep_start();
  508. int64_t slept_us = esp_timer_get_time() - sleep_start;
  509. ESP_PM_TRACE_EXIT(SLEEP, core_id);
  510. uint32_t slept_ticks = slept_us / (portTICK_PERIOD_MS * 1000LL);
  511. if (slept_ticks > 0) {
  512. /* Adjust RTOS tick count based on the amount of time spent in sleep */
  513. vTaskStepTick(slept_ticks);
  514. /* Trigger tick interrupt, since sleep time was longer
  515. * than portTICK_PERIOD_MS. Note that setting INTSET does not
  516. * work for timer interrupt, and changing CCOMPARE would clear
  517. * the interrupt flag.
  518. */
  519. XTHAL_SET_CCOUNT(XTHAL_GET_CCOMPARE(XT_TIMER_INDEX) - 16);
  520. while (!(XTHAL_GET_INTERRUPT() & BIT(XT_TIMER_INTNUM))) {
  521. ;
  522. }
  523. }
  524. other_core_should_skip_light_sleep(core_id);
  525. }
  526. }
  527. portEXIT_CRITICAL(&s_switch_lock);
  528. }
  529. #endif //CONFIG_FREERTOS_USE_TICKLESS_IDLE
  530. #ifdef WITH_PROFILING
  531. void esp_pm_impl_dump_stats(FILE* out)
  532. {
  533. pm_time_t time_in_mode[PM_MODE_COUNT];
  534. portENTER_CRITICAL_ISR(&s_switch_lock);
  535. memcpy(time_in_mode, s_time_in_mode, sizeof(time_in_mode));
  536. pm_time_t last_mode_change_time = s_last_mode_change_time;
  537. pm_mode_t cur_mode = s_mode;
  538. pm_time_t now = pm_get_time();
  539. portEXIT_CRITICAL_ISR(&s_switch_lock);
  540. time_in_mode[cur_mode] += now - last_mode_change_time;
  541. fprintf(out, "Mode stats:\n");
  542. for (int i = 0; i < PM_MODE_COUNT; ++i) {
  543. if (i == PM_MODE_LIGHT_SLEEP && !s_light_sleep_en) {
  544. /* don't display light sleep mode if it's not enabled */
  545. continue;
  546. }
  547. fprintf(out, "%8s %3dM %12lld %2d%%\n",
  548. s_mode_names[i],
  549. s_cpu_freq_by_mode[i].freq_mhz,
  550. time_in_mode[i],
  551. (int) (time_in_mode[i] * 100 / now));
  552. }
  553. }
  554. #endif // WITH_PROFILING
  555. void esp_pm_impl_init(void)
  556. {
  557. #ifdef CONFIG_PM_TRACE
  558. esp_pm_trace_init();
  559. #endif
  560. ESP_ERROR_CHECK(esp_pm_lock_create(ESP_PM_CPU_FREQ_MAX, 0, "rtos0",
  561. &s_rtos_lock_handle[0]));
  562. ESP_ERROR_CHECK(esp_pm_lock_acquire(s_rtos_lock_handle[0]));
  563. #if portNUM_PROCESSORS == 2
  564. ESP_ERROR_CHECK(esp_pm_lock_create(ESP_PM_CPU_FREQ_MAX, 0, "rtos1",
  565. &s_rtos_lock_handle[1]));
  566. ESP_ERROR_CHECK(esp_pm_lock_acquire(s_rtos_lock_handle[1]));
  567. #endif // portNUM_PROCESSORS == 2
  568. /* Configure all modes to use the default CPU frequency.
  569. * This will be modified later by a call to esp_pm_configure.
  570. */
  571. rtc_cpu_freq_config_t default_config;
  572. if (!rtc_clk_cpu_freq_mhz_to_config(CONFIG_ESP32S2_DEFAULT_CPU_FREQ_MHZ, &default_config)) {
  573. assert(false && "unsupported frequency");
  574. }
  575. for (size_t i = 0; i < PM_MODE_COUNT; ++i) {
  576. s_cpu_freq_by_mode[i] = default_config;
  577. }
  578. }