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 #[cfg(all(soc_has_usb_device, not(keep_usb_serial_jtag_enabled)))]
48 crate::soc::usb_phy::disconnect_usj();
49
50 PERIPHERAL_REF_COUNT.with(|refcounts| {
52 for p in Peripheral::KEEP_ENABLED {
53 refcounts.counts[*p as usize] += 1;
54 }
55 for p in Peripheral::ALL {
56 let ref_count = refcounts.counts[*p as usize];
57 if ref_count == 0 {
58 PeripheralClockControl::enable_forced_with_counts(*p, false, true, refcounts);
59 }
60 }
61 })
62}
63
64#[derive(Debug, PartialEq, Eq)]
65#[cfg_attr(feature = "defmt", derive(defmt::Format))]
66pub(crate) struct PeripheralGuard {
67 peripheral: Peripheral,
68}
69
70impl PeripheralGuard {
71 pub(crate) fn new_with(p: Peripheral, init: fn()) -> Self {
72 PeripheralClockControl::request_peripheral(p, init);
73
74 Self { peripheral: p }
75 }
76
77 pub(crate) fn new(p: Peripheral) -> Self {
78 Self::new_with(p, || {})
79 }
80}
81
82impl Clone for PeripheralGuard {
83 fn clone(&self) -> Self {
84 Self::new(self.peripheral)
85 }
86
87 fn clone_from(&mut self, _source: &Self) {
88 }
90}
91
92impl Drop for PeripheralGuard {
93 fn drop(&mut self) {
94 PeripheralClockControl::disable(self.peripheral);
95 }
96}
97
98#[derive(Debug)]
99#[cfg_attr(feature = "defmt", derive(defmt::Format))]
100pub(crate) struct GenericPeripheralGuard<const P: u8> {}
101
102impl<const P: u8> GenericPeripheralGuard<P> {
103 pub(crate) fn new_with(init: fn()) -> Self {
104 let p = const { Peripheral::try_from(P).unwrap() };
105 PeripheralClockControl::request_peripheral(p, init);
106
107 Self {}
108 }
109
110 #[cfg_attr(esp32p4, allow(unused))]
111 #[cfg_attr(not(feature = "unstable"), allow(unused))]
112 pub(crate) fn new() -> Self {
113 Self::new_with(|| {})
114 }
115}
116
117impl<const P: u8> Clone for GenericPeripheralGuard<P> {
118 fn clone(&self) -> Self {
119 Self::new()
120 }
121
122 fn clone_from(&mut self, _source: &Self) {
123 }
125}
126
127impl<const P: u8> Drop for GenericPeripheralGuard<P> {
128 fn drop(&mut self) {
129 let peripheral = const { Peripheral::try_from(P).unwrap() };
130 PeripheralClockControl::disable(peripheral);
131 }
132}
133
134pub(crate) struct PeripheralClockControl;
136
137impl PeripheralClockControl {
138 fn request_peripheral(p: Peripheral, init: fn()) {
139 PERIPHERAL_REF_COUNT.with(|ref_counts| {
140 if Self::enable_with_counts(p, ref_counts) {
141 unsafe { Self::reset_racey(p) };
142 init();
143 }
144 });
145 }
146
147 pub(crate) fn enable(peripheral: Peripheral) -> bool {
154 PERIPHERAL_REF_COUNT.with(|ref_counts| Self::enable_with_counts(peripheral, ref_counts))
155 }
156
157 pub(crate) fn set_enabled_untracked(peripheral: Peripheral, enabled: bool) {
159 PERIPHERAL_REF_COUNT.with(|_| unsafe { enable_internal_racey(peripheral, enabled) });
160 }
161
162 fn enable_with_counts(peripheral: Peripheral, ref_counts: &mut RefCounts) -> bool {
169 Self::enable_forced_with_counts(peripheral, true, false, ref_counts)
170 }
171
172 pub(crate) fn disable(peripheral: Peripheral) -> bool {
179 PERIPHERAL_REF_COUNT.with(|ref_counts| {
180 Self::enable_forced_with_counts(peripheral, false, false, ref_counts)
181 })
182 }
183
184 fn enable_forced_with_counts(
185 peripheral: Peripheral,
186 enable: bool,
187 force: bool,
188 ref_counts: &mut RefCounts,
189 ) -> bool {
190 let ref_count = &mut ref_counts.counts[peripheral as usize];
191 if !force {
192 let prev = *ref_count;
193 if enable {
194 *ref_count += 1;
195 trace!("Enable {:?} {} -> {}", peripheral, prev, *ref_count);
196 if prev > 0 {
197 return false;
198 }
199 } else {
200 assert!(prev != 0);
201 *ref_count -= 1;
202 trace!("Disable {:?} {} -> {}", peripheral, prev, *ref_count);
203 if prev > 1 {
204 return false;
205 }
206 };
207 } else if !enable {
208 assert!(*ref_count == 0);
209 }
210
211 debug!("Enable {:?} {}", peripheral, enable);
212 unsafe { enable_internal_racey(peripheral, enable) };
213
214 true
215 }
216
217 pub(crate) unsafe fn reset_racey(peripheral: Peripheral) {
219 debug!("Reset {:?}", peripheral);
220
221 unsafe {
222 assert_peri_reset_racey(peripheral, true);
223 assert_peri_reset_racey(peripheral, false);
224 }
225 }
226
227 pub(crate) fn reset(peripheral: Peripheral) {
229 PERIPHERAL_REF_COUNT.with(|_| unsafe { Self::reset_racey(peripheral) })
230 }
231
232 pub(crate) fn set_reset(peripheral: Peripheral, reset: bool) {
233 PERIPHERAL_REF_COUNT.with(|_| unsafe { assert_peri_reset_racey(peripheral, reset) });
234 }
235}
236
237#[derive(Debug, Copy, Clone, PartialEq, Eq, strum::FromRepr)]
241#[cfg_attr(feature = "defmt", derive(defmt::Format))]
242#[repr(C)]
243pub enum Cpu {
244 ProCpu = 0,
246 #[cfg(multi_core)]
248 AppCpu = 1,
249}
250
251impl Cpu {
252 pub const COUNT: usize = 1 + cfg!(multi_core) as usize;
254
255 #[procmacros::doc_replace]
256 #[inline(always)]
267 pub fn current() -> Self {
268 cfg_select! {
272 multi_core => {
273 if raw_core() == 0 {
274 Cpu::ProCpu
275 } else {
276 Cpu::AppCpu
277 }
278 }
279 _ => Cpu::ProCpu,
280 }
281 }
282
283 #[inline(always)]
285 #[instability::unstable]
286 pub fn other() -> impl Iterator<Item = Self> {
287 cfg_select! {
288 multi_core => match Self::current() {
289 Cpu::ProCpu => [Cpu::AppCpu].into_iter(),
290 Cpu::AppCpu => [Cpu::ProCpu].into_iter(),
291 },
292 _ => [].into_iter(),
293 }
294 }
295
296 #[inline(always)]
298 pub fn all() -> impl Iterator<Item = Self> {
299 cfg_select! {
300 multi_core => [Cpu::ProCpu, Cpu::AppCpu].into_iter(),
301 _ => [Cpu::ProCpu].into_iter(),
302 }
303 }
304}
305
306#[inline(always)]
314pub(crate) fn raw_core() -> usize {
315 cfg_select! {
316 all(multi_core, riscv) => riscv::register::mhartid::read(),
317 all(multi_core, xtensa) => (xtensa_lx::get_processor_id() & 0x2000) as usize,
318 _ => 0,
319 }
320}
321
322use crate::rtc_cntl::SocResetReason;
323
324#[procmacros::doc_replace]
325#[inline]
336pub fn software_reset() -> ! {
337 let _uart0_sclk_guard = ensure_uart0_sclk_enabled();
338 #[cfg(any(esp32h4, esp32p4, esp32s31))]
339 crate::soc::cpu_control::pre_system_reset();
340 crate::rom::software_reset()
341}
342
343#[instability::unstable]
345#[inline]
346pub fn software_reset_cpu(cpu: Cpu) {
347 let _uart0_sclk_guard = ensure_uart0_sclk_enabled();
348 crate::rom::software_reset_cpu(cpu as u32)
349}
350
351#[must_use = "dropping the guard releases the UART0 source clock"]
355pub(crate) struct Uart0SclkGuard {
356 release: bool,
357}
358
359impl Drop for Uart0SclkGuard {
360 fn drop(&mut self) {
361 if self.release {
362 release_uart0_sclk();
363 }
364 }
365}
366
367#[inline(always)]
374pub(crate) fn ensure_uart0_sclk_enabled() -> Uart0SclkGuard {
375 Uart0SclkGuard {
376 release: request_uart0_sclk(),
377 }
378}
379
380#[cfg(soc_has_clock_node_uart_function_clock)]
381fn request_uart0_sclk() -> bool {
382 crate::soc::clocks::ClockTree::with(|clocks| {
383 let uart = crate::soc::clocks::UartInstance::Uart0;
384 if uart.function_clock_config(clocks).is_some() {
385 uart.request_function_clock(clocks);
386 true
387 } else {
388 false
389 }
390 })
391}
392
393#[cfg(not(soc_has_clock_node_uart_function_clock))]
394fn request_uart0_sclk() -> bool {
395 false
396}
397
398#[cfg(soc_has_clock_node_uart_function_clock)]
399fn release_uart0_sclk() {
400 crate::soc::clocks::ClockTree::with(|clocks| {
401 crate::soc::clocks::UartInstance::Uart0.release_function_clock(clocks);
402 });
403}
404
405#[cfg(not(soc_has_clock_node_uart_function_clock))]
406fn release_uart0_sclk() {}
407
408#[cfg(feature = "unstable")]
410#[must_use = "dropping the guard releases the crypto clock"]
411pub(crate) struct CryptoClockGuard;
412
413#[cfg(feature = "unstable")]
414impl CryptoClockGuard {
415 #[inline(always)]
420 pub(crate) fn new() -> Self {
421 Self::request();
422 Self
423 }
424
425 fn request() {
426 cfg_select! {
427 soc_has_clock_node_crypto_clk => {
428 crate::soc::clocks::ClockTree::with(|clocks| {
429 crate::soc::clocks::request_crypto_clk(clocks);
430 });
431 }
432 soc_has_clock_node_crypto_pwm_clk => {
433 crate::soc::clocks::ClockTree::with(|clocks| {
434 crate::soc::clocks::request_crypto_pwm_clk(clocks);
435 });
436 }
437 _ => {}
438 }
439 }
440
441 fn release() {
442 cfg_select! {
443 soc_has_clock_node_crypto_clk => {
444 crate::soc::clocks::ClockTree::with(|clocks| {
445 crate::soc::clocks::release_crypto_clk(clocks);
446 });
447 }
448 soc_has_clock_node_crypto_pwm_clk => {
449 crate::soc::clocks::ClockTree::with(|clocks| {
450 crate::soc::clocks::release_crypto_pwm_clk(clocks);
451 });
452 }
453 _ => {}
454 }
455 }
456}
457
458#[cfg(feature = "unstable")]
459impl Drop for CryptoClockGuard {
460 fn drop(&mut self) {
461 Self::release();
462 }
463}
464
465#[instability::unstable]
468#[inline]
469pub fn reset_reason() -> Option<SocResetReason> {
470 crate::rtc_cntl::reset_reason(Cpu::current())
471}
472
473#[cfg(sleep_driver_supported)]
478#[instability::unstable]
479#[inline]
480pub fn wakeup_cause() -> crate::rtc_cntl::WakeupReason {
481 crate::rtc_cntl::wakeup_cause()
482}