forked from esp-rs/esp-hal
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsystem.rs
More file actions
390 lines (344 loc) · 10.9 KB
/
system.rs
File metadata and controls
390 lines (344 loc) · 10.9 KB
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
//! # System Control
use esp_sync::NonReentrantMutex;
cfg_if::cfg_if! {
if #[cfg(all(soc_multi_core_enabled, feature = "unstable"))] {
pub(crate) mod multi_core;
#[cfg(feature = "unstable")]
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());
/// Disable 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(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 `true` if 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 `true` if 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 `true` if 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,
_ => unreachable!(),
}
}
/// Returns an iterator over the "other" cores.
#[inline(always)]
#[instability::unstable]
pub fn other() -> impl Iterator<Item = Self> {
cfg_if::cfg_if! {
if #[cfg(multi_core)] {
match Self::current() {
Cpu::ProCpu => [Cpu::AppCpu].into_iter(),
Cpu::AppCpu => [Cpu::ProCpu].into_iter(),
}
} else {
[].into_iter()
}
}
}
/// Returns an iterator over all cores.
#[inline(always)]
pub fn all() -> impl Iterator<Item = Self> {
cfg_if::cfg_if! {
if #[cfg(multi_core)] {
[Cpu::ProCpu, Cpu::AppCpu].into_iter()
} else {
[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_if::cfg_if! {
if #[cfg(all(multi_core, riscv))] {
riscv::register::mhartid::read()
} else if #[cfg(all(multi_core, xtensa))] {
(xtensa_lx::get_processor_id() & 0x2000) as usize
} else {
0
}
}
}
use crate::rtc_cntl::SocResetReason;
/// Source of the wakeup event
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[instability::unstable]
pub enum SleepSource {
/// In case of deep sleep, reset was not caused by exit from deep sleep
Undefined = 0,
/// Not a wakeup cause, used to disable all wakeup sources with
/// esp_sleep_disable_wakeup_source
All,
/// Wakeup caused by external signal using RTC_IO
Ext0,
/// Wakeup caused by external signal using RTC_CNTL
Ext1,
/// Wakeup caused by timer
Timer,
/// Wakeup caused by touchpad
TouchPad,
/// Wakeup caused by ULP program
Ulp,
/// Wakeup caused by GPIO (light sleep only on ESP32, S2 and S3)
Gpio,
/// Wakeup caused by UART (light sleep only)
Uart,
/// Wakeup caused by WIFI (light sleep only)
Wifi,
/// Wakeup caused by COCPU int
Cocpu,
/// Wakeup caused by COCPU crash
CocpuTrapTrig,
/// Wakeup caused by BT (light sleep only)
BT,
}
#[procmacros::doc_replace]
/// Performs a software reset on the chip.
///
/// # Example
///
/// ```rust, no_run
/// # {before_snippet}
/// use esp_hal::system::software_reset;
/// software_reset();
/// # {after_snippet}
/// ```
#[inline]
pub fn software_reset() -> ! {
crate::rom::software_reset()
}
/// Resets the given CPU, leaving peripherals unchanged.
#[instability::unstable]
#[inline]
pub fn software_reset_cpu(cpu: Cpu) {
crate::rom::software_reset_cpu(cpu as u32)
}
/// 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 of the last wakeup event as a SleepSource enum value.
#[instability::unstable]
#[inline]
pub fn wakeup_cause() -> SleepSource {
crate::rtc_cntl::wakeup_cause()
}