Skip to main content

esp_hal/system/
mod.rs

1//! # System Control
2
3#![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
12// Implements the Peripheral enum based on esp-metadata/device.soc/peripheral_clocks
13implement_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/// Disables all peripherals.
41///
42/// Peripherals listed in [KEEP_ENABLED] are NOT disabled.
43#[cfg_attr(not(feature = "rt"), expect(dead_code))]
44pub(crate) fn disable_peripherals() {
45    // Gating the clock alone leaves the D+ pull-up on, and the host keeps talking to a device that
46    // no longer answers.
47    #[cfg(all(soc_has_usb_device, not(keep_usb_serial_jtag_enabled)))]
48    crate::soc::usb_phy::disconnect_usj();
49
50    // Take the critical section up front to avoid taking it multiple times.
51    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        // This is a no-op since the ref count for P remains the same.
89    }
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        // This is a no-op since the ref count for P remains the same.
124    }
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
134/// Controls the enablement of peripheral clocks.
135pub(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    /// Enables the given peripheral.
148    ///
149    /// This keeps track of enabling a peripheral - i.e. a peripheral
150    /// is only enabled with the first call attempt to enable it.
151    ///
152    /// Returns whether it actually enabled the peripheral.
153    pub(crate) fn enable(peripheral: Peripheral) -> bool {
154        PERIPHERAL_REF_COUNT.with(|ref_counts| Self::enable_with_counts(peripheral, ref_counts))
155    }
156
157    /// Sets a caller-managed clock gate without changing its reference count.
158    pub(crate) fn set_enabled_untracked(peripheral: Peripheral, enabled: bool) {
159        PERIPHERAL_REF_COUNT.with(|_| unsafe { enable_internal_racey(peripheral, enabled) });
160    }
161
162    /// Enables the given peripheral.
163    ///
164    /// This keeps track of enabling a peripheral - i.e. a peripheral
165    /// is only enabled with the first call attempt to enable it.
166    ///
167    /// Returns whether it actually enabled the peripheral.
168    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    /// Disables the given peripheral.
173    ///
174    /// This keeps track of disabling a peripheral - i.e. it only
175    /// gets disabled when the number of enable/disable attempts is balanced.
176    ///
177    /// Returns whether it actually disabled the peripheral.
178    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    /// Resets the given peripheral.
218    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    /// Resets the given peripheral.
228    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/// Available CPU cores
238///
239/// The actual number of available cores depends on the target.
240#[derive(Debug, Copy, Clone, PartialEq, Eq, strum::FromRepr)]
241#[cfg_attr(feature = "defmt", derive(defmt::Format))]
242#[repr(C)]
243pub enum Cpu {
244    /// The first core.
245    ProCpu = 0,
246    /// The second core.
247    #[cfg(multi_core)]
248    AppCpu = 1,
249}
250
251impl Cpu {
252    /// The number of available cores.
253    pub const COUNT: usize = 1 + cfg!(multi_core) as usize;
254
255    #[procmacros::doc_replace]
256    /// Returns the core the application is currently executing on.
257    ///
258    /// ```rust, no_run
259    /// # {before_snippet}
260    /// #
261    /// use esp_hal::system::Cpu;
262    /// let current_cpu = Cpu::current();
263    /// #
264    /// # {after_snippet}
265    /// ```
266    #[inline(always)]
267    pub fn current() -> Self {
268        // `raw_core` returns 0 on the first core, and 1 (RISC-V) or 0x2000 (Xtensa) on the
269        // second core. Code that runs with the caches suspended calls this function, so it
270        // must not panic.
271        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    /// Returns an iterator over the "other" cores.
284    #[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    /// Returns an iterator over all cores.
297    #[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/// Returns the raw value of the mhartid register.
307///
308/// On RISC-V, this is the hardware thread ID.
309///
310/// On Xtensa, this returns the result of reading the PRID register logically
311/// ANDed with 0x2000, the 13th bit in the register. Espressif Xtensa chips use
312/// this bit to determine the core id.
313#[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/// Performs a software reset on the chip.
326///
327/// # Examples
328///
329/// ```rust, no_run
330/// # {before_snippet}
331/// use esp_hal::system::software_reset;
332/// software_reset();
333/// # {after_snippet}
334/// ```
335#[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/// Resets the given CPU, leaving peripherals unchanged.
344#[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/// Guard for a temporary UART0 source-clock request.
352///
353/// Drops its request when dropped. If no request was needed, this is a no-op.
354#[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/// Ensures UART0's source clock stays enabled for boot ROM compatibility.
368///
369/// On some chips, resetting or waking up while UART0's source clock is disabled
370/// can prevent the boot ROM from starting correctly. This only requests the
371/// clock when UART0 already has a function-clock configuration; otherwise the
372/// returned guard is a no-op.
373#[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/// Guard for the clock shared by the crypto accelerators.
409#[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    /// Request the clock that drives the crypto accelerators.
416    ///
417    /// The clock is called `CRYPTO_CLK` on most chips, and `CRYPTO_PWM_CLK` on the ESP32-S3, where
418    /// the MCPWM peripherals share it.
419    #[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/// Retrieves the reason for the last reset as a SocResetReason enum value.
466/// Returns `None` if the reset reason cannot be determined.
467#[instability::unstable]
468#[inline]
469pub fn reset_reason() -> Option<SocResetReason> {
470    crate::rtc_cntl::reset_reason(Cpu::current())
471}
472
473/// Retrieves the cause(s) of the last wakeup event.
474///
475/// Returns the [`WakeupReason`][crate::rtc_cntl::WakeupReason] describing the source(s) that ended
476/// the most recent sleep. The result is empty if the chip was not woken from sleep.
477#[cfg(sleep_driver_supported)]
478#[instability::unstable]
479#[inline]
480pub fn wakeup_cause() -> crate::rtc_cntl::WakeupReason {
481    crate::rtc_cntl::wakeup_cause()
482}