Skip to main content

esp_hal/
system.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    // Take the critical section up front to avoid taking it multiple times.
46    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        // This is a no-op since the ref count for P remains the same.
84    }
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        // This is a no-op since the ref count for P remains the same.
119    }
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
129/// Controls the enablement of peripheral clocks.
130pub(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    /// Enables the given peripheral.
143    ///
144    /// This keeps track of enabling a peripheral - i.e. a peripheral
145    /// is only enabled with the first call attempt to enable it.
146    ///
147    /// Returns whether it actually enabled the peripheral.
148    pub(crate) fn enable(peripheral: Peripheral) -> bool {
149        PERIPHERAL_REF_COUNT.with(|ref_counts| Self::enable_with_counts(peripheral, ref_counts))
150    }
151
152    /// Sets a caller-managed clock gate without changing its reference count.
153    pub(crate) fn set_enabled_untracked(peripheral: Peripheral, enabled: bool) {
154        PERIPHERAL_REF_COUNT.with(|_| unsafe { enable_internal_racey(peripheral, enabled) });
155    }
156
157    /// Enables the given peripheral.
158    ///
159    /// This keeps track of enabling a peripheral - i.e. a peripheral
160    /// is only enabled with the first call attempt to enable it.
161    ///
162    /// Returns whether it actually enabled the peripheral.
163    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    /// Disables the given peripheral.
168    ///
169    /// This keeps track of disabling a peripheral - i.e. it only
170    /// gets disabled when the number of enable/disable attempts is balanced.
171    ///
172    /// Returns whether it actually disabled the peripheral.
173    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    /// Resets the given peripheral.
213    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    /// Resets the given peripheral.
223    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/// Available CPU cores
233///
234/// The actual number of available cores depends on the target.
235#[derive(Debug, Copy, Clone, PartialEq, Eq, strum::FromRepr)]
236#[cfg_attr(feature = "defmt", derive(defmt::Format))]
237#[repr(C)]
238pub enum Cpu {
239    /// The first core.
240    ProCpu = 0,
241    /// The second core.
242    #[cfg(multi_core)]
243    AppCpu = 1,
244}
245
246impl Cpu {
247    /// The number of available cores.
248    pub const COUNT: usize = 1 + cfg!(multi_core) as usize;
249
250    #[procmacros::doc_replace]
251    /// Returns the core the application is currently executing on.
252    ///
253    /// ```rust, no_run
254    /// # {before_snippet}
255    /// #
256    /// use esp_hal::system::Cpu;
257    /// let current_cpu = Cpu::current();
258    /// #
259    /// # {after_snippet}
260    /// ```
261    #[inline(always)]
262    pub fn current() -> Self {
263        // `raw_core` returns 0 on the first core, and 1 (RISC-V) or 0x2000 (Xtensa) on the
264        // second core. Code that runs with the caches suspended calls this function, so it
265        // must not panic.
266        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    /// Returns an iterator over the "other" cores.
279    #[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    /// Returns an iterator over all cores.
292    #[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/// Returns the raw value of the mhartid register.
302///
303/// On RISC-V, this is the hardware thread ID.
304///
305/// On Xtensa, this returns the result of reading the PRID register logically
306/// ANDed with 0x2000, the 13th bit in the register. Espressif Xtensa chips use
307/// this bit to determine the core id.
308#[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/// Performs a software reset on the chip.
321///
322/// # Examples
323///
324/// ```rust, no_run
325/// # {before_snippet}
326/// use esp_hal::system::software_reset;
327/// software_reset();
328/// # {after_snippet}
329/// ```
330#[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/// Resets the given CPU, leaving peripherals unchanged.
339#[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/// Guard for a temporary UART0 source-clock request.
347///
348/// Drops its request when dropped. If no request was needed, this is a no-op.
349#[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/// Ensures UART0's source clock stays enabled for boot ROM compatibility.
363///
364/// On some chips, resetting or waking up while UART0's source clock is disabled
365/// can prevent the boot ROM from starting correctly. This only requests the
366/// clock when UART0 already has a function-clock configuration; otherwise the
367/// returned guard is a no-op.
368#[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/// Guard for the clock shared by the crypto accelerators.
404#[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    /// Request the clock that drives the crypto accelerators.
411    ///
412    /// The clock is called `CRYPTO_CLK` on most chips, and `CRYPTO_PWM_CLK` on the ESP32-S3, where
413    /// the MCPWM peripherals share it.
414    #[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/// Retrieves the reason for the last reset as a SocResetReason enum value.
461/// Returns `None` if the reset reason cannot be determined.
462#[instability::unstable]
463#[inline]
464pub fn reset_reason() -> Option<SocResetReason> {
465    crate::rtc_cntl::reset_reason(Cpu::current())
466}
467
468/// Retrieves the cause(s) of the last wakeup event.
469///
470/// Returns the [`WakeupReason`][crate::rtc_cntl::WakeupReason] describing the source(s) that ended
471/// the most recent sleep. The result is empty if the chip was not woken from sleep.
472#[cfg(sleep_driver_supported)]
473#[instability::unstable]
474#[inline]
475pub fn wakeup_cause() -> crate::rtc_cntl::WakeupReason {
476    crate::rtc_cntl::wakeup_cause()
477}