esp-hal 1.2.0

Bare-metal HAL for Espressif devices
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! # System Control

#![cfg_attr(esp32s31, allow(dead_code))]

use esp_sync::NonReentrantMutex;

cfg_select! {
    all(soc_multi_core_enabled, feature = "unstable") => {
        pub(crate) mod multi_core;
        pub use multi_core::*;
    }
    _ => {}
}

// Implements the Peripheral enum based on esp-metadata/device.soc/peripheral_clocks
implement_peripheral_clocks!();

impl Peripheral {
    pub const fn try_from(value: u8) -> Option<Peripheral> {
        if value >= Peripheral::COUNT as u8 {
            return None;
        }

        Some(unsafe { core::mem::transmute::<u8, Peripheral>(value) })
    }
}

struct RefCounts {
    counts: [usize; Peripheral::COUNT],
}

impl RefCounts {
    pub const fn new() -> Self {
        Self {
            counts: [0; Peripheral::COUNT],
        }
    }
}

static PERIPHERAL_REF_COUNT: NonReentrantMutex<RefCounts> =
    NonReentrantMutex::new(RefCounts::new());

/// Disables all peripherals.
///
/// Peripherals listed in [KEEP_ENABLED] are NOT disabled.
#[cfg_attr(not(feature = "rt"), expect(dead_code))]
pub(crate) fn disable_peripherals() {
    // Take the critical section up front to avoid taking it multiple times.
    PERIPHERAL_REF_COUNT.with(|refcounts| {
        for p in Peripheral::KEEP_ENABLED {
            refcounts.counts[*p as usize] += 1;
        }
        for p in Peripheral::ALL {
            let ref_count = refcounts.counts[*p as usize];
            if ref_count == 0 {
                PeripheralClockControl::enable_forced_with_counts(*p, false, true, refcounts);
            }
        }
    })
}

#[derive(Debug, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub(crate) struct PeripheralGuard {
    peripheral: Peripheral,
}

impl PeripheralGuard {
    pub(crate) fn new_with(p: Peripheral, init: fn()) -> Self {
        PeripheralClockControl::request_peripheral(p, init);

        Self { peripheral: p }
    }

    pub(crate) fn new(p: Peripheral) -> Self {
        Self::new_with(p, || {})
    }
}

impl Clone for PeripheralGuard {
    fn clone(&self) -> Self {
        Self::new(self.peripheral)
    }

    fn clone_from(&mut self, _source: &Self) {
        // This is a no-op since the ref count for P remains the same.
    }
}

impl Drop for PeripheralGuard {
    fn drop(&mut self) {
        PeripheralClockControl::disable(self.peripheral);
    }
}

#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub(crate) struct GenericPeripheralGuard<const P: u8> {}

impl<const P: u8> GenericPeripheralGuard<P> {
    pub(crate) fn new_with(init: fn()) -> Self {
        let p = const { Peripheral::try_from(P).unwrap() };
        PeripheralClockControl::request_peripheral(p, init);

        Self {}
    }

    #[cfg_attr(esp32p4, allow(unused))]
    #[cfg_attr(not(feature = "unstable"), allow(unused))]
    pub(crate) fn new() -> Self {
        Self::new_with(|| {})
    }
}

impl<const P: u8> Clone for GenericPeripheralGuard<P> {
    fn clone(&self) -> Self {
        Self::new()
    }

    fn clone_from(&mut self, _source: &Self) {
        // This is a no-op since the ref count for P remains the same.
    }
}

impl<const P: u8> Drop for GenericPeripheralGuard<P> {
    fn drop(&mut self) {
        let peripheral = const { Peripheral::try_from(P).unwrap() };
        PeripheralClockControl::disable(peripheral);
    }
}

/// Controls the enablement of peripheral clocks.
pub(crate) struct PeripheralClockControl;

impl PeripheralClockControl {
    fn request_peripheral(p: Peripheral, init: fn()) {
        PERIPHERAL_REF_COUNT.with(|ref_counts| {
            if Self::enable_with_counts(p, ref_counts) {
                unsafe { Self::reset_racey(p) };
                init();
            }
        });
    }

    /// Enables the given peripheral.
    ///
    /// This keeps track of enabling a peripheral - i.e. a peripheral
    /// is only enabled with the first call attempt to enable it.
    ///
    /// Returns whether it actually enabled the peripheral.
    pub(crate) fn enable(peripheral: Peripheral) -> bool {
        PERIPHERAL_REF_COUNT.with(|ref_counts| Self::enable_with_counts(peripheral, ref_counts))
    }

    /// Enables the given peripheral.
    ///
    /// This keeps track of enabling a peripheral - i.e. a peripheral
    /// is only enabled with the first call attempt to enable it.
    ///
    /// Returns whether it actually enabled the peripheral.
    fn enable_with_counts(peripheral: Peripheral, ref_counts: &mut RefCounts) -> bool {
        Self::enable_forced_with_counts(peripheral, true, false, ref_counts)
    }

    /// Disables the given peripheral.
    ///
    /// This keeps track of disabling a peripheral - i.e. it only
    /// gets disabled when the number of enable/disable attempts is balanced.
    ///
    /// Returns whether it actually disabled the peripheral.
    pub(crate) fn disable(peripheral: Peripheral) -> bool {
        PERIPHERAL_REF_COUNT.with(|ref_counts| {
            Self::enable_forced_with_counts(peripheral, false, false, ref_counts)
        })
    }

    fn enable_forced_with_counts(
        peripheral: Peripheral,
        enable: bool,
        force: bool,
        ref_counts: &mut RefCounts,
    ) -> bool {
        let ref_count = &mut ref_counts.counts[peripheral as usize];
        if !force {
            let prev = *ref_count;
            if enable {
                *ref_count += 1;
                trace!("Enable {:?} {} -> {}", peripheral, prev, *ref_count);
                if prev > 0 {
                    return false;
                }
            } else {
                assert!(prev != 0);
                *ref_count -= 1;
                trace!("Disable {:?} {} -> {}", peripheral, prev, *ref_count);
                if prev > 1 {
                    return false;
                }
            };
        } else if !enable {
            assert!(*ref_count == 0);
        }

        debug!("Enable {:?} {}", peripheral, enable);
        unsafe { enable_internal_racey(peripheral, enable) };

        true
    }

    /// Resets the given peripheral.
    pub(crate) unsafe fn reset_racey(peripheral: Peripheral) {
        debug!("Reset {:?}", peripheral);

        unsafe {
            assert_peri_reset_racey(peripheral, true);
            assert_peri_reset_racey(peripheral, false);
        }
    }

    /// Resets the given peripheral.
    pub(crate) fn reset(peripheral: Peripheral) {
        PERIPHERAL_REF_COUNT.with(|_| unsafe { Self::reset_racey(peripheral) })
    }
}

/// Available CPU cores
///
/// The actual number of available cores depends on the target.
#[derive(Debug, Copy, Clone, PartialEq, Eq, strum::FromRepr)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(C)]
pub enum Cpu {
    /// The first core.
    ProCpu = 0,
    /// The second core.
    #[cfg(multi_core)]
    AppCpu = 1,
}

impl Cpu {
    /// The number of available cores.
    pub const COUNT: usize = 1 + cfg!(multi_core) as usize;

    #[procmacros::doc_replace]
    /// Returns the core the application is currently executing on.
    ///
    /// ```rust, no_run
    /// # {before_snippet}
    /// #
    /// use esp_hal::system::Cpu;
    /// let current_cpu = Cpu::current();
    /// #
    /// # {after_snippet}
    /// ```
    #[inline(always)]
    pub fn current() -> Self {
        // This works for both RISCV and Xtensa because both
        // get_raw_core functions return zero, _or_ something
        // greater than zero; 1 in the case of RISCV and 0x2000
        // in the case of Xtensa.
        match raw_core() {
            0 => Cpu::ProCpu,

            #[cfg(all(multi_core, riscv))]
            1 => Cpu::AppCpu,

            #[cfg(all(multi_core, xtensa))]
            0x2000 => Cpu::AppCpu,

            other => unreachable!("unknown core id: {}", other),
        }
    }

    /// Returns an iterator over the "other" cores.
    #[inline(always)]
    #[instability::unstable]
    pub fn other() -> impl Iterator<Item = Self> {
        cfg_select! {
            multi_core => match Self::current() {
                Cpu::ProCpu => [Cpu::AppCpu].into_iter(),
                Cpu::AppCpu => [Cpu::ProCpu].into_iter(),
            },
            _ => [].into_iter(),
        }
    }

    /// Returns an iterator over all cores.
    #[inline(always)]
    pub fn all() -> impl Iterator<Item = Self> {
        cfg_select! {
            multi_core => [Cpu::ProCpu, Cpu::AppCpu].into_iter(),
            _ => [Cpu::ProCpu].into_iter(),
        }
    }
}

/// Returns the raw value of the mhartid register.
///
/// On RISC-V, this is the hardware thread ID.
///
/// On Xtensa, this returns the result of reading the PRID register logically
/// ANDed with 0x2000, the 13th bit in the register. Espressif Xtensa chips use
/// this bit to determine the core id.
#[inline(always)]
pub(crate) fn raw_core() -> usize {
    // This method must never return UNUSED_THREAD_ID_VALUE
    cfg_select! {
        all(multi_core, riscv) => riscv::register::mhartid::read(),
        all(multi_core, xtensa) => (xtensa_lx::get_processor_id() & 0x2000) as usize,
        _ => 0,
    }
}

use crate::rtc_cntl::SocResetReason;

#[procmacros::doc_replace]
/// Performs a software reset on the chip.
///
/// # Examples
///
/// ```rust, no_run
/// # {before_snippet}
/// use esp_hal::system::software_reset;
/// software_reset();
/// # {after_snippet}
/// ```
#[inline]
pub fn software_reset() -> ! {
    let _uart0_sclk_guard = ensure_uart0_sclk_enabled();
    #[cfg(any(esp32p4, esp32s31))]
    crate::soc::cpu_control::pre_system_reset();
    crate::rom::software_reset()
}

/// Resets the given CPU, leaving peripherals unchanged.
#[instability::unstable]
#[inline]
pub fn software_reset_cpu(cpu: Cpu) {
    let _uart0_sclk_guard = ensure_uart0_sclk_enabled();
    crate::rom::software_reset_cpu(cpu as u32)
}

/// Guard for a temporary UART0 source-clock request.
///
/// Drops its request when dropped. If no request was needed, this is a no-op.
#[must_use = "dropping the guard releases the UART0 source clock"]
pub(crate) struct Uart0SclkGuard {
    release: bool,
}

impl Drop for Uart0SclkGuard {
    fn drop(&mut self) {
        if self.release {
            release_uart0_sclk();
        }
    }
}

/// Ensures UART0's source clock stays enabled for boot ROM compatibility.
///
/// On some chips, resetting or waking up while UART0's source clock is disabled
/// can prevent the boot ROM from starting correctly. This only requests the
/// clock when UART0 already has a function-clock configuration; otherwise the
/// returned guard is a no-op.
#[inline(always)]
pub(crate) fn ensure_uart0_sclk_enabled() -> Uart0SclkGuard {
    Uart0SclkGuard {
        release: request_uart0_sclk(),
    }
}

#[cfg(soc_has_clock_node_uart_function_clock)]
fn request_uart0_sclk() -> bool {
    crate::soc::clocks::ClockTree::with(|clocks| {
        let uart = crate::soc::clocks::UartInstance::Uart0;
        if uart.function_clock_config(clocks).is_some() {
            uart.request_function_clock(clocks);
            true
        } else {
            false
        }
    })
}

#[cfg(not(soc_has_clock_node_uart_function_clock))]
fn request_uart0_sclk() -> bool {
    false
}

#[cfg(soc_has_clock_node_uart_function_clock)]
fn release_uart0_sclk() {
    crate::soc::clocks::ClockTree::with(|clocks| {
        crate::soc::clocks::UartInstance::Uart0.release_function_clock(clocks);
    });
}

#[cfg(not(soc_has_clock_node_uart_function_clock))]
fn release_uart0_sclk() {}

/// Retrieves the reason for the last reset as a SocResetReason enum value.
/// Returns `None` if the reset reason cannot be determined.
#[instability::unstable]
#[inline]
pub fn reset_reason() -> Option<SocResetReason> {
    crate::rtc_cntl::reset_reason(Cpu::current())
}

/// Retrieves the cause(s) of the last wakeup event.
///
/// Returns the [`WakeupReason`][crate::rtc_cntl::WakeupReason] describing the source(s) that ended
/// the most recent sleep. The result is empty if the chip was not woken from sleep.
#[cfg(sleep_driver_supported)]
#[instability::unstable]
#[inline]
pub fn wakeup_cause() -> crate::rtc_cntl::WakeupReason {
    crate::rtc_cntl::wakeup_cause()
}