m5stack_core/stack.rs
1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! The main stack's high-water, by paint and scan.
3//!
4//! **Identical in `m5stack-core` and `korvo1-bsp` on purpose**, as `monitor`
5//! is: change it in one, change it in the other, and `cmp` them.
6//!
7//! `esp_rtos::stack_usage` reports heap-allocated task stacks only; the main
8//! stack is linker-provided (`.stack`) and already in use when the scheduler
9//! starts, so nothing reports it unless it is painted before it is used. A
10//! margin read off `.stack`'s size is not a margin: on these chips the region
11//! is the linker's slack, and nothing but a reading separates a comfortable
12//! build from one that faults mid-session.
13
14use core::sync::atomic::{AtomicBool, Ordering};
15
16/// The paint. Not zero, so a word a callee zeroed reads as touched; not
17/// esp-hal's guard value, so the guard word can never read as paint.
18const PAINT: u32 = 0xA5A5_A5A5;
19
20/// Left unpainted at the bottom: esp-hal writes its stack-guard word
21/// `ESP_HAL_CONFIG_STACK_GUARD_OFFSET` bytes above `_stack_end` (60 by default)
22/// and watches it, and painting over it would disarm that.
23const GUARD_RESERVE: usize = 64;
24
25/// Left unpainted below the stack pointer, for the painting loop's own frame.
26const BELOW_SP: usize = 256;
27
28/// Whether [`paint_main_stack`] ran, so [`main_stack_margin`] never reports a
29/// number read off memory nobody painted.
30static PAINTED: AtomicBool = AtomicBool::new(false);
31
32fn bounds() -> (usize, usize) {
33 unsafe extern "C" {
34 static _stack_start_cpu0: u32;
35 static _stack_end_cpu0: u32;
36 }
37 let bottom = &raw const _stack_end_cpu0 as usize;
38 let top = &raw const _stack_start_cpu0 as usize;
39 (bottom, top)
40}
41
42/// The stack pointer.
43fn stack_pointer() -> usize {
44 let sp: usize;
45 #[cfg(target_arch = "riscv32")]
46 // SAFETY: reads a register, touches no memory.
47 unsafe {
48 core::arch::asm!("mv {0}, sp", out(reg) sp, options(nomem, nostack, preserves_flags));
49 }
50 #[cfg(target_arch = "xtensa")]
51 // SAFETY: reads a register, touches no memory.
52 unsafe {
53 core::arch::asm!("mov {0}, sp", out(reg) sp, options(nomem, nostack, preserves_flags));
54 }
55 sp
56}
57
58/// Paint the main stack below the stack pointer.
59///
60/// The top of the paint is the stack pointer, not a constant, because how deep
61/// the boot path already is differs per chip and per entry macro. Nor is it a
62/// local's address: inlined into its caller, a local sits wherever that frame
63/// puts it — on the ESP32-S31, 2 KiB above `sp` in the embassy main task — and
64/// painting up to it overwrote the live frame below. `inline(never)` keeps
65/// this frame the deepest live one. Call it before any interrupt is routed
66/// (the boards' `init` does, ahead of `esp_hal::init`): the sweep writes below
67/// the stack pointer, where an interrupt frame would otherwise land.
68#[inline(never)]
69pub fn paint_main_stack() {
70 let (bottom, top) = bounds();
71 let sp = stack_pointer();
72 if !(bottom..top).contains(&sp) {
73 return;
74 }
75 let mut addr = (bottom + GUARD_RESERVE + 3) & !3;
76 let end = sp.saturating_sub(BELOW_SP);
77 while addr < end {
78 // SAFETY: a 4-byte-aligned word inside the linker's `.stack`, above the
79 // guard word and below the stack pointer, with the margin under it for
80 // this loop's own frame; no interrupt is routed yet.
81 unsafe { (addr as *mut u32).write_volatile(PAINT) };
82 addr += 4;
83 }
84 PAINTED.store(true, Ordering::Release);
85}
86
87/// Bytes between the bottom of the main stack and its deepest use so far, or
88/// `None` if it was never painted.
89///
90/// A high-water mark: it only falls. One limit: a callee that wrote [`PAINT`]
91/// itself reads as untouched, which can only overstate the margin by the
92/// words that held it.
93#[must_use]
94pub fn main_stack_margin() -> Option<usize> {
95 if !PAINTED.load(Ordering::Acquire) {
96 return None;
97 }
98 let (bottom, top) = bounds();
99 let mut addr = (bottom + GUARD_RESERVE + 3) & !3;
100 while addr < top {
101 // SAFETY: the painted range, read-only.
102 if unsafe { (addr as *const u32).read_volatile() } != PAINT {
103 break;
104 }
105 addr += 4;
106 }
107 Some(addr - bottom)
108}
109
110/// The main stack's size: `.stack`, as linked.
111#[must_use]
112pub fn main_stack_size() -> usize {
113 let (bottom, top) = bounds();
114 top - bottom
115}