1#![allow(dead_code)]
4
5use esp_sync::NonReentrantMutex;
6
7#[cfg(soc_multi_core_enabled)]
8pub(crate) mod multi_core;
9#[cfg(all(soc_multi_core_enabled, feature = "unstable"))]
10pub use multi_core::*;
11
12implement_peripheral_clocks!();
14
15impl Peripheral {
16 pub const fn try_from(value: u8) -> Option<Peripheral> {
17 if value >= Peripheral::COUNT as u8 {
18 return None;
19 }
20
21 Some(unsafe { core::mem::transmute::<u8, Peripheral>(value) })
22 }
23}
24
25struct RefCounts {
26 counts: [usize; Peripheral::COUNT],
27}
28
29impl RefCounts {
30 pub const fn new() -> Self {
31 Self {
32 counts: [0; Peripheral::COUNT],
33 }
34 }
35}
36
37static PERIPHERAL_REF_COUNT: NonReentrantMutex<RefCounts> =
38 NonReentrantMutex::new(RefCounts::new());
39
40#[cfg_attr(not(feature = "rt"), expect(dead_code))]
44pub(crate) fn disable_peripherals() {
45 PERIPHERAL_REF_COUNT.with(|refcounts| {
47 for p in Peripheral::KEEP_ENABLED {
48 refcounts.counts[*p as usize] += 1;
49 }
50 for p in Peripheral::ALL {
51 let ref_count = refcounts.counts[*p as usize];
52 if ref_count == 0 {
53 PeripheralClockControl::enable_forced_with_counts(*p, false, true, refcounts);
54 }
55 }
56 })
57}
58
59#[derive(Debug, PartialEq, Eq)]
60#[cfg_attr(feature = "defmt", derive(defmt::Format))]
61pub(crate) struct PeripheralGuard {
62 peripheral: Peripheral,
63}
64
65impl PeripheralGuard {
66 pub(crate) fn new_with(p: Peripheral, init: fn()) -> Self {
67 PeripheralClockControl::request_peripheral(p, init);
68
69 Self { peripheral: p }
70 }
71
72 pub(crate) fn new(p: Peripheral) -> Self {
73 Self::new_with(p, || {})
74 }
75}
76
77impl Clone for PeripheralGuard {
78 fn clone(&self) -> Self {
79 Self::new(self.peripheral)
80 }
81
82 fn clone_from(&mut self, _source: &Self) {
83 }
85}
86
87impl Drop for PeripheralGuard {
88 fn drop(&mut self) {
89 PeripheralClockControl::disable(self.peripheral);
90 }
91}
92
93#[derive(Debug)]
94#[cfg_attr(feature = "defmt", derive(defmt::Format))]
95pub(crate) struct GenericPeripheralGuard<const P: u8> {}
96
97impl<const P: u8> GenericPeripheralGuard<P> {
98 pub(crate) fn new_with(init: fn()) -> Self {
99 let p = const { Peripheral::try_from(P).unwrap() };
100 PeripheralClockControl::request_peripheral(p, init);
101
102 Self {}
103 }
104
105 #[cfg_attr(esp32p4, allow(unused))]
106 #[cfg_attr(not(feature = "unstable"), allow(unused))]
107 pub(crate) fn new() -> Self {
108 Self::new_with(|| {})
109 }
110}
111
112impl<const P: u8> Clone for GenericPeripheralGuard<P> {
113 fn clone(&self) -> Self {
114 Self::new()
115 }
116
117 fn clone_from(&mut self, _source: &Self) {
118 }
120}
121
122impl<const P: u8> Drop for GenericPeripheralGuard<P> {
123 fn drop(&mut self) {
124 let peripheral = const { Peripheral::try_from(P).unwrap() };
125 PeripheralClockControl::disable(peripheral);
126 }
127}
128
129pub(crate) struct PeripheralClockControl;
131
132impl PeripheralClockControl {
133 fn request_peripheral(p: Peripheral, init: fn()) {
134 PERIPHERAL_REF_COUNT.with(|ref_counts| {
135 if Self::enable_with_counts(p, ref_counts) {
136 unsafe { Self::reset_racey(p) };
137 init();
138 }
139 });
140 }
141
142 pub(crate) fn enable(peripheral: Peripheral) -> bool {
149 PERIPHERAL_REF_COUNT.with(|ref_counts| Self::enable_with_counts(peripheral, ref_counts))
150 }
151
152 pub(crate) fn set_enabled_untracked(peripheral: Peripheral, enabled: bool) {
154 PERIPHERAL_REF_COUNT.with(|_| unsafe { enable_internal_racey(peripheral, enabled) });
155 }
156
157 fn enable_with_counts(peripheral: Peripheral, ref_counts: &mut RefCounts) -> bool {
164 Self::enable_forced_with_counts(peripheral, true, false, ref_counts)
165 }
166
167 pub(crate) fn disable(peripheral: Peripheral) -> bool {
174 PERIPHERAL_REF_COUNT.with(|ref_counts| {
175 Self::enable_forced_with_counts(peripheral, false, false, ref_counts)
176 })
177 }
178
179 fn enable_forced_with_counts(
180 peripheral: Peripheral,
181 enable: bool,
182 force: bool,
183 ref_counts: &mut RefCounts,
184 ) -> bool {
185 let ref_count = &mut ref_counts.counts[peripheral as usize];
186 if !force {
187 let prev = *ref_count;
188 if enable {
189 *ref_count += 1;
190 trace!("Enable {:?} {} -> {}", peripheral, prev, *ref_count);
191 if prev > 0 {
192 return false;
193 }
194 } else {
195 assert!(prev != 0);
196 *ref_count -= 1;
197 trace!("Disable {:?} {} -> {}", peripheral, prev, *ref_count);
198 if prev > 1 {
199 return false;
200 }
201 };
202 } else if !enable {
203 assert!(*ref_count == 0);
204 }
205
206 debug!("Enable {:?} {}", peripheral, enable);
207 unsafe { enable_internal_racey(peripheral, enable) };
208
209 true
210 }
211
212 pub(crate) unsafe fn reset_racey(peripheral: Peripheral) {
214 debug!("Reset {:?}", peripheral);
215
216 unsafe {
217 assert_peri_reset_racey(peripheral, true);
218 assert_peri_reset_racey(peripheral, false);
219 }
220 }
221
222 pub(crate) fn reset(peripheral: Peripheral) {
224 PERIPHERAL_REF_COUNT.with(|_| unsafe { Self::reset_racey(peripheral) })
225 }
226
227 pub(crate) fn set_reset(peripheral: Peripheral, reset: bool) {
228 PERIPHERAL_REF_COUNT.with(|_| unsafe { assert_peri_reset_racey(peripheral, reset) });
229 }
230}
231
232#[derive(Debug, Copy, Clone, PartialEq, Eq, strum::FromRepr)]
236#[cfg_attr(feature = "defmt", derive(defmt::Format))]
237#[repr(C)]
238pub enum Cpu {
239 ProCpu = 0,
241 #[cfg(multi_core)]
243 AppCpu = 1,
244}
245
246impl Cpu {
247 pub const COUNT: usize = 1 + cfg!(multi_core) as usize;
249
250 #[procmacros::doc_replace]
251 #[inline(always)]
262 pub fn current() -> Self {
263 cfg_select! {
267 multi_core => {
268 if raw_core() == 0 {
269 Cpu::ProCpu
270 } else {
271 Cpu::AppCpu
272 }
273 }
274 _ => Cpu::ProCpu,
275 }
276 }
277
278 #[inline(always)]
280 #[instability::unstable]
281 pub fn other() -> impl Iterator<Item = Self> {
282 cfg_select! {
283 multi_core => match Self::current() {
284 Cpu::ProCpu => [Cpu::AppCpu].into_iter(),
285 Cpu::AppCpu => [Cpu::ProCpu].into_iter(),
286 },
287 _ => [].into_iter(),
288 }
289 }
290
291 #[inline(always)]
293 pub fn all() -> impl Iterator<Item = Self> {
294 cfg_select! {
295 multi_core => [Cpu::ProCpu, Cpu::AppCpu].into_iter(),
296 _ => [Cpu::ProCpu].into_iter(),
297 }
298 }
299}
300
301#[inline(always)]
309pub(crate) fn raw_core() -> usize {
310 cfg_select! {
311 all(multi_core, riscv) => riscv::register::mhartid::read(),
312 all(multi_core, xtensa) => (xtensa_lx::get_processor_id() & 0x2000) as usize,
313 _ => 0,
314 }
315}
316
317use crate::rtc_cntl::SocResetReason;
318
319#[procmacros::doc_replace]
320#[inline]
331pub fn software_reset() -> ! {
332 let _uart0_sclk_guard = ensure_uart0_sclk_enabled();
333 #[cfg(any(esp32h4, esp32p4, esp32s31))]
334 crate::soc::cpu_control::pre_system_reset();
335 crate::rom::software_reset()
336}
337
338#[instability::unstable]
340#[inline]
341pub fn software_reset_cpu(cpu: Cpu) {
342 let _uart0_sclk_guard = ensure_uart0_sclk_enabled();
343 crate::rom::software_reset_cpu(cpu as u32)
344}
345
346#[must_use = "dropping the guard releases the UART0 source clock"]
350pub(crate) struct Uart0SclkGuard {
351 release: bool,
352}
353
354impl Drop for Uart0SclkGuard {
355 fn drop(&mut self) {
356 if self.release {
357 release_uart0_sclk();
358 }
359 }
360}
361
362#[inline(always)]
369pub(crate) fn ensure_uart0_sclk_enabled() -> Uart0SclkGuard {
370 Uart0SclkGuard {
371 release: request_uart0_sclk(),
372 }
373}
374
375#[cfg(soc_has_clock_node_uart_function_clock)]
376fn request_uart0_sclk() -> bool {
377 crate::soc::clocks::ClockTree::with(|clocks| {
378 let uart = crate::soc::clocks::UartInstance::Uart0;
379 if uart.function_clock_config(clocks).is_some() {
380 uart.request_function_clock(clocks);
381 true
382 } else {
383 false
384 }
385 })
386}
387
388#[cfg(not(soc_has_clock_node_uart_function_clock))]
389fn request_uart0_sclk() -> bool {
390 false
391}
392
393#[cfg(soc_has_clock_node_uart_function_clock)]
394fn release_uart0_sclk() {
395 crate::soc::clocks::ClockTree::with(|clocks| {
396 crate::soc::clocks::UartInstance::Uart0.release_function_clock(clocks);
397 });
398}
399
400#[cfg(not(soc_has_clock_node_uart_function_clock))]
401fn release_uart0_sclk() {}
402
403#[cfg(feature = "unstable")]
405#[must_use = "dropping the guard releases the crypto clock"]
406pub(crate) struct CryptoClockGuard;
407
408#[cfg(feature = "unstable")]
409impl CryptoClockGuard {
410 #[inline(always)]
415 pub(crate) fn new() -> Self {
416 Self::request();
417 Self
418 }
419
420 fn request() {
421 cfg_select! {
422 soc_has_clock_node_crypto_clk => {
423 crate::soc::clocks::ClockTree::with(|clocks| {
424 crate::soc::clocks::request_crypto_clk(clocks);
425 });
426 }
427 soc_has_clock_node_crypto_pwm_clk => {
428 crate::soc::clocks::ClockTree::with(|clocks| {
429 crate::soc::clocks::request_crypto_pwm_clk(clocks);
430 });
431 }
432 _ => {}
433 }
434 }
435
436 fn release() {
437 cfg_select! {
438 soc_has_clock_node_crypto_clk => {
439 crate::soc::clocks::ClockTree::with(|clocks| {
440 crate::soc::clocks::release_crypto_clk(clocks);
441 });
442 }
443 soc_has_clock_node_crypto_pwm_clk => {
444 crate::soc::clocks::ClockTree::with(|clocks| {
445 crate::soc::clocks::release_crypto_pwm_clk(clocks);
446 });
447 }
448 _ => {}
449 }
450 }
451}
452
453#[cfg(feature = "unstable")]
454impl Drop for CryptoClockGuard {
455 fn drop(&mut self) {
456 Self::release();
457 }
458}
459
460#[instability::unstable]
463#[inline]
464pub fn reset_reason() -> Option<SocResetReason> {
465 crate::rtc_cntl::reset_reason(Cpu::current())
466}
467
468#[cfg(sleep_driver_supported)]
473#[instability::unstable]
474#[inline]
475pub fn wakeup_cause() -> crate::rtc_cntl::WakeupReason {
476 crate::rtc_cntl::wakeup_cause()
477}