Skip to main content

m5stack_core/board/
spi2.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Shared SPI2 bus: on-board ILI9342C display + SD-card slot.
3//!
4//! Both boards route the display and the SD slot over the same SPI2 bus, so
5//! their bring-up is coupled and ordering-sensitive. This module owns that
6//! hardware knowledge; the SD-card *driver* stays with the application (the
7//! `sdspi` crate is not yet on crates.io) and connects through the generic
8//! chip-select + `SpiDevice` returned by [`Spi2Parts::finish`].
9//!
10//! # Bring-up sequence (application side)
11//!
12//! The recommended path is [`Spi2Parts::finish_sd`]: the BSP owns the ≥74-clock
13//! SD power-up idle and hands back a pre-initialised, presence-resolved
14//! [`PreparedCard`]. The app supplies only its SD driver plus retry/degrade
15//! policy — no board detail, no pre-init loop:
16//!
17//! ```ignore
18//! let (mut parts, card_cs) = board.spi2.into_parts(dma_rx_buf, dma_tx_buf)?;
19//! // Display comes up UNCONDITIONALLY (works even with a dead/absent card).
20//! // `CardPresence::ForceAbsent` reaches the SD-absent path with a card in slot.
21//! let (display, prepared) = parts.finish_sd(card_cs, CardPresence::Detect).await?;
22//! let mut sd = SdSpi::new(prepared.into_inner());
23//! // bounded init retries; on failure, degrade (SD absent). Both real-absent
24//! // and ForceAbsent fail here, on the same single degrade path.
25//! ```
26//!
27//! The lower-level [`Spi2Parts::finish`] primitive (no pre-init, plain generic
28//! `card_cs`) remains for callers that drive the exclusive `bus` themselves
29//! before sharing it.
30//!
31//! # CoreS3: GPIO35 is shared between SPI2 MISO and display DC
32//!
33//! The SPI peripheral owns GPIO35 as MISO input (via `with_miso`); the display
34//! DC is driven on the same pad through direct GPIO register writes
35//! ([`Gpio35Dc`](crate::board::cores3::Gpio35Dc)). [`Spi2Parts::finish`] calls
36//! [`gpio35_disable_output`](crate::board::cores3::gpio35_disable_output)
37//! after the display init so the pad returns to high-impedance MISO input —
38//! without it `sd_card.init()` reads garbage on MISO and never completes. At
39//! runtime, every SD operation must re-assert that mux (pass the same function
40//! as the block-device handler's pre-op hook). This is safe only while the
41//! display and the SD card share one task/bus mutex with no `.await` between a
42//! DC write and the SPI transfer.
43//!
44//! # Display/SD task join order differs per chip — do not unify
45//!
46//! When the app joins the display flush loop and the SD block-device handler
47//! in one task: on fire27 (ESP32/PDMA) the SD handler must be polled FIRST so
48//! it grabs the bus mutex preferentially — the mirror order reliably wedges
49//! the SD path. cores3 (ESP32-S3/GDMA) needs the opposite order. The two
50//! chips' interrupt/DMA timing has opposite contention characteristics; don't
51//! change either without re-validating both targets on hardware.
52
53use esp_hal::{
54    Async,
55    dma::{DmaRxBuf, DmaTxBuf},
56    gpio::{AnyPin, Level, Output, OutputConfig},
57    spi::{
58        Mode,
59        master::{AnySpi, Config as SpiConfig, ConfigError, Spi, SpiDma},
60    },
61    time::Rate,
62};
63
64/// The shared bus: descriptor-backed DMA SPI. A plain `Spi::into_async()`
65/// flush goes "usr-stuck" after the first frame on the ESP32 PDMA path, so a
66/// `SpiDma` is required (the CoreS3 uses GDMA for the same reason).
67pub type SpiBusType = SpiDma<'static, Async>;
68
69/// The shared bus and which user the peripheral is configured for, under one
70/// mutex — so the record and the hardware always change together.
71///
72/// A `set_config` from outside marks the settings foreign: the display device
73/// applies its own config per transaction, and the card restates its terms on
74/// the next acquire.
75/// Gated with its users: nothing constructs or reads this without `display`,
76/// and an ungated definition is dead code in a bare board build.
77#[cfg(feature = "display")]
78pub struct Spi2Bus {
79    inner: SpiBusType,
80    card_configured: bool,
81}
82
83#[cfg(feature = "display")]
84impl Spi2Bus {
85    fn new(inner: SpiBusType) -> Self {
86        Self {
87            inner,
88            card_configured: false,
89        }
90    }
91
92    /// The raw bus, for a holder that has already stated its terms.
93    fn bus(&mut self) -> &mut SpiBusType {
94        &mut self.inner
95    }
96
97    /// Apply `config` unless the card already owns the peripheral's settings.
98    ///
99    /// Must stay conditional: the busy poll acquires ~1000x/s, and
100    /// reprogramming at that rate breaks erase.
101    async fn configure_for_card(&mut self, config: &SpiConfig) -> Result<(), ConfigError> {
102        if self.card_configured {
103            return Ok(());
104        }
105        // The bus must be idle before the clock divider is rewritten:
106        // `apply_config` writes it directly, with no idle check, and on esp32
107        // without the clock-gate sequence. Reconfiguring a running peripheral
108        // arms the next transfer without ever completing it — it parks in the
109        // TransferDone wait still holding the bus.
110        AsyncSpiBus::flush(&mut self.inner).await.ok();
111        self.inner.apply_config(config)?;
112        self.card_configured = true;
113        Ok(())
114    }
115
116    /// Apply the card's config unconditionally and record it — the post-init
117    /// clock raise, made from a live guard.
118    fn apply_for_card(&mut self, config: &SpiConfig) -> Result<(), ConfigError> {
119        self.inner.apply_config(config)?;
120        self.card_configured = true;
121        Ok(())
122    }
123
124    /// Forget who owns the settings — the next card acquire must restate them.
125    fn invalidate(&mut self) {
126        self.card_configured = false;
127    }
128}
129
130/// Only with `display`: the impl exists to hook the display device's
131/// per-transaction config, and that device only exists with the feature.
132#[cfg(feature = "display")]
133impl embassy_embedded_hal::SetConfig for Spi2Bus {
134    type Config = SpiConfig;
135    type ConfigError = ConfigError;
136
137    /// Recorded here, not at the call site: this IS the moment the card's
138    /// settings become stale, so the two cannot drift apart.
139    fn set_config(&mut self, config: &Self::Config) -> Result<(), Self::ConfigError> {
140        self.inner.apply_config(config)?;
141        self.card_configured = false;
142        Ok(())
143    }
144}
145
146#[cfg(feature = "display")]
147use embedded_hal_async::spi::SpiBus as AsyncSpiBus;
148
149#[cfg(feature = "display")]
150impl embedded_hal_async::spi::ErrorType for Spi2Bus {
151    type Error = <SpiBusType as embedded_hal_async::spi::ErrorType>::Error;
152}
153
154/// Delegating, and spelled out: `SpiDma` has inherent BLOCKING methods of
155/// the same names, so plain `self.inner.read(..)` silently picks those.
156#[cfg(feature = "display")]
157impl embedded_hal_async::spi::SpiBus for Spi2Bus {
158    async fn read(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
159        AsyncSpiBus::read(&mut self.inner, words).await
160    }
161    async fn write(&mut self, words: &[u8]) -> Result<(), Self::Error> {
162        AsyncSpiBus::write(&mut self.inner, words).await
163    }
164    async fn transfer(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Self::Error> {
165        AsyncSpiBus::transfer(&mut self.inner, read, write).await
166    }
167    async fn transfer_in_place(&mut self, words: &mut [u8]) -> Result<(), Self::Error> {
168        AsyncSpiBus::transfer_in_place(&mut self.inner, words).await
169    }
170    async fn flush(&mut self) -> Result<(), Self::Error> {
171        AsyncSpiBus::flush(&mut self.inner).await
172    }
173}
174
175/// Bus base config: 400 kHz Mode 0 — the clock SD cards require during init.
176/// The app raises the card device's clock (via `SetConfig`) after `init()`.
177pub fn sd_init_config() -> SpiConfig {
178    SpiConfig::default()
179        .with_frequency(Rate::from_khz(400))
180        .with_mode(Mode::_0)
181}
182
183/// Display device config: 40 MHz Mode 0.
184pub fn display_config() -> SpiConfig {
185    sd_init_config().with_frequency(Rate::from_khz(40_000))
186}
187
188/// SPI2 pins + units (CoreS3): SCK=GPIO36, MOSI=GPIO37, MISO/DC=GPIO35,
189/// display CS=GPIO3, card CS=GPIO4, GDMA channel 0.
190#[cfg(feature = "cores3")]
191pub struct Spi2Resources<'a> {
192    pub spi2: AnySpi<'a>,
193    pub spi2_dma: esp_hal::dma::AhbGdmaChannel<'a>,
194    pub sck: AnyPin<'a>,
195    pub mosi: AnyPin<'a>,
196    /// GPIO35 — SPI2 MISO (SD reads) **and** display DC via the register-level
197    /// mux ([`crate::board::cores3::Gpio35Dc`]); see the module docs.
198    pub miso_dc: AnyPin<'a>,
199    pub display_cs: AnyPin<'a>,
200    pub card_cs: AnyPin<'a>,
201}
202
203/// SPI2 pins + units (Fire27): SCK=GPIO18, MOSI=GPIO23, MISO=GPIO19,
204/// display CS=GPIO14 / DC=GPIO27 / RST=GPIO33 / BL=GPIO32, card CS=GPIO4,
205/// PDMA SPI2 channel.
206#[cfg(feature = "fire27")]
207pub struct Spi2Resources<'a> {
208    pub spi2: AnySpi<'a>,
209    pub spi2_dma: esp_hal::dma::SpiDmaChannel<'a>,
210    pub sck: AnyPin<'a>,
211    pub mosi: AnyPin<'a>,
212    pub miso: AnyPin<'a>,
213    pub display_cs: AnyPin<'a>,
214    pub display_dc: AnyPin<'a>,
215    pub display_rst: AnyPin<'a>,
216    pub display_bl: AnyPin<'a>,
217    pub card_cs: AnyPin<'a>,
218}
219
220/// The constructed bus + display pins, between [`Spi2Resources::into_parts`]
221/// and [`Spi2Parts::finish`]. `bus` is still exclusive here — the window for
222/// the app's SD pre-init (see the module docs).
223// Only `finish` consumes the display pins, and it needs the `display` feature;
224// without it they are still held, keeping the pins owned at the levels
225// `into_parts` drove them to.
226#[cfg_attr(not(feature = "display"), allow(dead_code))]
227pub struct Spi2Parts {
228    /// Exclusive DMA bus (not yet shared) for `sdspi::sd_init`.
229    pub bus: SpiBusType,
230    display_cs: Output<'static>,
231    #[cfg(feature = "fire27")]
232    display_dc: Output<'static>,
233    #[cfg(feature = "fire27")]
234    display_rst: Output<'static>,
235    #[cfg(feature = "fire27")]
236    display_bl: Output<'static>,
237}
238
239#[cfg(feature = "cores3")]
240impl Spi2Resources<'static> {
241    /// Build the DMA bus and the CS outputs. The DMA buffers are supplied by
242    /// the app — their sizing is application policy (SD block size for RX,
243    /// display strip size for TX). Returns the card CS separately so the app
244    /// can wrap it (e.g. a HIL "no SD card" kill-switch) before
245    /// [`Spi2Parts::finish`].
246    pub fn into_parts(
247        self,
248        dma_rx_buf: DmaRxBuf,
249        dma_tx_buf: DmaTxBuf,
250    ) -> Result<(Spi2Parts, Output<'static>), ConfigError> {
251        let bus = Spi::new(self.spi2, sd_init_config())?
252            .with_sck(self.sck)
253            .with_mosi(self.mosi)
254            .with_miso(self.miso_dc)
255            .with_dma(self.spi2_dma)
256            .with_buffers(dma_rx_buf, dma_tx_buf)
257            .into_async();
258        let display_cs = Output::new(self.display_cs, Level::High, OutputConfig::default());
259        let card_cs = Output::new(self.card_cs, Level::High, OutputConfig::default());
260        Ok((Spi2Parts { bus, display_cs }, card_cs))
261    }
262}
263
264#[cfg(feature = "fire27")]
265impl Spi2Resources<'static> {
266    /// Build the DMA bus and the CS/DC/RST/BL outputs. The DMA buffers are
267    /// supplied by the app — their sizing is application policy (SD block size
268    /// for RX, display strip size for TX). Returns the card CS separately so
269    /// the app can wrap it (e.g. a HIL "no SD card" kill-switch) before
270    /// [`Spi2Parts::finish`]. The backlight starts LOW (no flicker during
271    /// panel init); `finish` turns it on.
272    pub fn into_parts(
273        self,
274        dma_rx_buf: DmaRxBuf,
275        dma_tx_buf: DmaTxBuf,
276    ) -> Result<(Spi2Parts, Output<'static>), ConfigError> {
277        let bus = Spi::new(self.spi2, sd_init_config())?
278            .with_sck(self.sck)
279            .with_mosi(self.mosi)
280            .with_miso(self.miso)
281            .with_dma(self.spi2_dma)
282            .with_buffers(dma_rx_buf, dma_tx_buf)
283            .into_async();
284        let display_cs = Output::new(self.display_cs, Level::High, OutputConfig::default());
285        let card_cs = Output::new(self.card_cs, Level::High, OutputConfig::default());
286        let display_dc = Output::new(self.display_dc, Level::Low, OutputConfig::default());
287        let display_rst = Output::new(self.display_rst, Level::Low, OutputConfig::default());
288        let display_bl = Output::new(self.display_bl, Level::Low, OutputConfig::default());
289        Ok((
290            Spi2Parts {
291                bus,
292                display_cs,
293                display_dc,
294                display_rst,
295                display_bl,
296            },
297            card_cs,
298        ))
299    }
300}
301
302// --- Device construction + display init (feature `display`) ----------------
303
304#[cfg(feature = "display")]
305pub use devices::*;
306
307#[cfg(feature = "display")]
308mod devices {
309    use super::Spi2Bus;
310    use embassy_embedded_hal::shared_bus::asynch::spi::SpiDeviceWithConfig;
311    use embassy_sync::mutex::Mutex;
312    use embassy_sync::semaphore::{FairSemaphore, Semaphore};
313    use embedded_hal::digital::{ErrorType, OutputPin};
314    use esp_hal::{
315        dma::{DmaRxBuf, DmaTxBuf},
316        gpio::{Level, Output, OutputConfig},
317        spi::master::Spi,
318    };
319    use esp_sync::RawMutex;
320    use lcd_async::interface::{Interface, SpiInterface};
321    use static_cell::StaticCell;
322
323    use super::{
324        ConfigError, Spi2Parts, Spi2Resources, SpiBusType, SpiConfig, display_config,
325        sd_init_config,
326    };
327    use crate::board::display::{self, Ili9342c};
328
329    /// A device on the shared bus with a plain GPIO chip-select (the display).
330    /// The display's SPI device, fairly arbitrated.
331    ///
332    /// Wrapped rather than raw so a panel transfer queues for the same permit
333    /// the card takes. Making only the card fair would have moved the
334    /// starvation to the display instead of removing it.
335    pub type SpiDeviceType<'a> =
336        FairSpiDevice<SpiDeviceWithConfig<'a, RawMutex, Spi2Bus, Output<'a>>>;
337    /// The SD-card device: CS is generic so the app can wrap it.
338    pub type CardSpiDevice<CS> = SpiDeviceWithConfig<'static, RawMutex, Spi2Bus, CS>;
339
340    /// Whether the SD slot should behave as populated or be forced to degrade.
341    ///
342    /// `ForceAbsent` is a general force-degrade capability, **not** a HIL word:
343    /// it makes the card device behave as an empty slot (chip-select never
344    /// asserts), so the app's real `SdSpi::init()` runs and fails *authentically*
345    /// — reaching the same graceful-degrade path as a physically empty slot,
346    /// with a card inserted. Any HIL arming (an RTC one-shot, a `:nosd` verb)
347    /// stays consumer-side; nothing HIL leaks into this surface.
348    #[non_exhaustive]
349    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
350    pub enum CardPresence {
351        /// Drive the chip-select normally: a real card initialises; an empty
352        /// slot degrades on its own.
353        Detect,
354        /// Freeze the chip-select deasserted so the card is never selected —
355        /// `SdSpi::init()` then fails exactly like an empty slot.
356        ForceAbsent,
357    }
358
359    /// Chip-select wrapper that can freeze the card *deasserted* to force the
360    /// absent-card path (see [`CardPresence::ForceAbsent`]).
361    ///
362    /// SD chip-select is active-low, so `set_low` selects: when `frozen` it is
363    /// suppressed (the card is never selected → MISO idles `0xFF` → authentic
364    /// init failure), while `set_high` (deselect) is always honoured. It is
365    /// carried *inside* [`PreparedCard`] because the freeze only bites where the
366    /// CS is first **asserted** — downstream in the app's `SdSpi::init()` CMD0,
367    /// not the CS-deasserted 74-clock pre-init. A single runtime-flag type (not
368    /// a type-level marker) keeps [`Spi2Parts::finish_sd`] monomorphic across a
369    /// runtime [`CardPresence`].
370    pub struct PresenceCs<CS> {
371        pin: CS,
372        frozen: bool,
373    }
374
375    impl<CS: ErrorType> ErrorType for PresenceCs<CS> {
376        type Error = CS::Error;
377    }
378
379    impl<CS: OutputPin> OutputPin for PresenceCs<CS> {
380        fn set_low(&mut self) -> Result<(), Self::Error> {
381            if self.frozen {
382                Ok(()) // suppress SELECT while forced-absent
383            } else {
384                self.pin.set_low()
385            }
386        }
387
388        fn set_high(&mut self) -> Result<(), Self::Error> {
389            self.pin.set_high() // deselect is always honoured
390        }
391    }
392
393    /// A card device on the shared SPI2 bus, pre-initialised by
394    /// [`Spi2Parts::finish_sd`] (the ≥74-clock power-up idle has run) and
395    /// presence-resolved. The BSP owns everything up to here with no SD-driver
396    /// type in its graph; the app supplies only its SD driver:
397    /// `SdSpi::new(prepared.into_inner())`.
398    pub struct PreparedCard<CS: OutputPin> {
399        bus: &'static Mutex<RawMutex, Spi2Bus>,
400        cs: PresenceCs<CS>,
401        /// The card's bus config, re-applied on every acquire.
402        ///
403        /// Load-bearing, and easy to lose: the DISPLAY device applies 40 MHz to
404        /// this same bus on each of its transactions, so a card command that
405        /// does not re-apply its own config runs at whatever the display left
406        /// behind. `SpiDeviceWithConfig` used to do this per transaction; once
407        /// the driver started driving the bus directly, dropping it silently
408        /// put SD init at 40 MHz and every attempt timed out.
409        config: SpiConfig,
410    }
411
412    /// A `SpiDevice` that queues for [`SPI2_FAIR`] before each transaction.
413    ///
414    /// The display holds the bus for a whole panel transfer, so without this the
415    /// card's 1 ms-cadence busy-poll never gets in. With it, both users are
416    /// served in arrival order and neither can monopolise the bus.
417    pub struct FairSpiDevice<D> {
418        inner: D,
419        /// Apply the pending display DC level after taking the permit. Set only
420        /// for the display: doing it for the card would drive GPIO35 as an
421        /// output while the card is being read.
422        applies_dc: bool,
423    }
424
425    impl<D> FairSpiDevice<D> {
426        pub fn new(inner: D) -> Self {
427            Self {
428                inner,
429                applies_dc: false,
430            }
431        }
432
433        /// The display's device: also owns the GPIO35 DC line on CoreS3.
434        pub fn new_display(inner: D) -> Self {
435            Self {
436                inner,
437                applies_dc: true,
438            }
439        }
440    }
441
442    impl<'a, M, BUS, CS> FairSpiDevice<SpiDeviceWithConfig<'a, M, BUS, CS>>
443    where
444        M: embassy_sync::blocking_mutex::raw::RawMutex,
445        BUS: embassy_embedded_hal::SetConfig,
446    {
447        /// Re-configure the underlying device (e.g. raise the SD clock after
448        /// init). Delegates, so callers keep the wrapper — and with it the
449        /// fairness — instead of having to unwrap to reach the setter.
450        pub fn set_config(&mut self, config: BUS::Config) {
451            self.inner.set_config(config)
452        }
453    }
454
455    impl<D: embedded_hal_async::spi::ErrorType> embedded_hal_async::spi::ErrorType
456        for FairSpiDevice<D>
457    {
458        type Error = D::Error;
459    }
460
461    impl<D: embedded_hal_async::spi::SpiDevice> embedded_hal_async::spi::SpiDevice
462        for FairSpiDevice<D>
463    {
464        async fn transaction(
465            &mut self,
466            operations: &mut [embedded_hal_async::spi::Operation<'_, u8>],
467        ) -> Result<(), Self::Error> {
468            let queued = embassy_time::Instant::now();
469            permits::DISP_ENTER.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
470            // A full waiter queue must NOT fall through to an unpermitted
471            // transaction. `let _permit = acquire()` bound the RESULT, so on
472            // `Err` this drove the bus with no mutual exclusion at all, while
473            // the card may have been holding it. Drop the frame instead — the
474            // card path degrades the same way and a lost frame costs a redraw.
475            let Ok(_permit) = SPI2_FAIR.acquire(1).await else {
476                warn!("SPI2: waiter queue full, display dropped a frame");
477                return Ok(());
478            };
479            permits::DISP_GOT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
480            // From a Drop, so a frame cancelled by the caller's timeout still
481            // counts its release.
482            struct RelOnDrop;
483            impl Drop for RelOnDrop {
484                fn drop(&mut self) {
485                    permits::DISP_REL.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
486                }
487            }
488            let _rel = RelOnDrop;
489            let waited = queued.elapsed();
490            // DC is part of the display's turn on the bus, not something that
491            // may happen while another master holds it.
492            #[cfg(feature = "cores3")]
493            if self.applies_dc {
494                crate::board::cores3::apply_pending_dc();
495            }
496            #[cfg(not(feature = "cores3"))]
497            let _ = self.applies_dc;
498            let r = self.inner.transaction(operations).await;
499            let total = queued.elapsed();
500            if total.as_millis() > 100 {
501                warn!(
502                    "SPI2: display transaction {} ms ({} ms of it waiting for the bus)",
503                    total.as_millis(),
504                    waited.as_millis()
505                );
506            }
507            r
508        }
509    }
510
511    /// The SPI2 bus and the card's chip-select, held together.
512    ///
513    /// This exists because chip-select continuity is not expressible from
514    /// outside the BSP. `SpiDevice::transaction` asserts CS on entry and
515    /// deasserts on exit, and one SD command is several transactions — the
516    /// `0xFE` data-token wait is unbounded, so it cannot be folded into a single
517    /// fixed operation list. A driver holding only a `SpiDevice` therefore drops
518    /// CS mid-command no matter how carefully it locks.
519    ///
520    /// The BSP owns both halves, so it can hand them out together: take this
521    /// guard once per command, assert CS yourself, and CS stays low for the
522    /// whole exchange. Drop it between commands (and between busy-poll probes)
523    /// so the display still gets the bus — a full-card erase must not freeze
524    /// the UI.
525    pub struct Spi2CardGuard<'a, CS: OutputPin> {
526        bus: embassy_sync::mutex::MutexGuard<'a, RawMutex, Spi2Bus>,
527        cs: &'a mut PresenceCs<CS>,
528        /// Held for its `Drop`: returning the permit is what releases our turn.
529        _permit:
530            embassy_sync::semaphore::SemaphoreReleaser<'a, FairSemaphore<RawMutex, SPI2_WAITERS>>,
531    }
532
533    impl<CS: OutputPin> Spi2CardGuard<'_, CS> {
534        /// The bus and the chip-select, borrowed together for one command.
535        pub fn split(&mut self) -> (&mut SpiBusType, &mut PresenceCs<CS>) {
536            (self.bus.bus(), self.cs)
537        }
538
539        /// Re-configure the bus while holding it — the SD clock raise after
540        /// `init()`, in practice.
541        ///
542        /// Needed because the card driver no longer holds a `SpiDevice` to
543        /// carry a per-device config: it drives the bus directly, so the clock
544        /// change has to happen here, under the same guard, or the card would
545        /// stay at the 400 kHz init clock for its whole life.
546        pub fn apply_config(&mut self, config: &SpiConfig) -> Result<(), ConfigError> {
547            self.bus.apply_for_card(config)
548        }
549    }
550
551    impl<CS: OutputPin> PreparedCard<CS> {
552        /// Change the config re-applied on every acquire — the post-init clock
553        /// raise. Setting it only on a live guard would last exactly one
554        /// command, because the next acquire re-applies the stored one.
555        pub async fn set_config(&mut self, config: SpiConfig) {
556            self.config = config;
557            // Force the next acquire to apply it, or the clock raise would not
558            // take effect until the display happened to run.
559            self.bus.lock().await.invalidate();
560        }
561    }
562
563    impl<CS: OutputPin> Drop for Spi2CardGuard<'_, CS> {
564        /// Deselect the card as the bus is released.
565        ///
566        /// These are the same event: leaving CS low after the guard drops would
567        /// leave the card selected while another master owns the bus, which is
568        /// worse than the mid-command CS drops this guard exists to remove. It
569        /// also lets the driver assert CS once per command and then use `?`
570        /// freely — every early return releases the card by unwinding here.
571        fn drop(&mut self) {
572            let _ = self.cs.set_high();
573            permits::CARD_REL.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
574        }
575    }
576
577    impl<CS: OutputPin> PreparedCard<CS> {
578        /// Take the bus for ONE command, with the chip-select in hand.
579        ///
580        /// Released on drop. Hold it across a command; drop it between
581        /// commands and between busy probes.
582        pub async fn acquire(&mut self) -> Option<Spi2CardGuard<'_, CS>> {
583            // Permit FIRST, then the mutex. Arrival order decides who goes
584            // next; the mutex is uncontended by the time we take it.
585            //
586            // `None`, not a panic, when the waiter queue is full: a library
587            // crate must never `panic!` (conventions/rust-code.md §6), and this
588            // is SD/bus code where the house rule is warn-and-degrade — a full
589            // queue must cost logging, never the regulator.
590            let cfg = self.config;
591            permits::CARD_ENTER.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
592            let permit = match SPI2_FAIR.acquire(1).await {
593                Ok(p) => p,
594                Err(_) => {
595                    warn!("SPI2: waiter queue full, card could not take the bus");
596                    return None;
597                }
598            };
599            permits::CARD_GOT.fetch_add(1, core::sync::atomic::Ordering::Relaxed);
600            let mut bus = self.bus.lock().await;
601            // Re-apply the CARD's config only if the display has been here
602            // since. Reprogramming the peripheral on every acquire breaks the
603            // erase busy poll, which acquires ~1000x/s.
604            let was_foreign = !bus.card_configured;
605            if let Err(e) = bus.configure_for_card(&cfg).await {
606                warn!("SPI2: card bus config rejected: {e:?}");
607            }
608            if was_foreign {
609                // CoreS3: GPIO35 is MISO *and* the display's DC line. A panel
610                // transfer drives it as an output and leaves it there, so the
611                // card is inaudible until the pad is handed back — every SD
612                // read then sees an idle-high MISO and the card looks silent.
613                //
614                // This has to happen per ACQUIRE, not once at bring-up: the
615                // driver releases the bus between commands, so the display can
616                // intervene in the middle of a command sequence. It cost a
617                // cores3 SD init, which answered CMD0/CMD8 and then went silent
618                // at CMD55 once a flush had run.
619                #[cfg(feature = "cores3")]
620                crate::board::cores3::gpio35_disable_output();
621            }
622            Some(Spi2CardGuard {
623                bus,
624                cs: &mut self.cs,
625                _permit: permit,
626            })
627        }
628
629        /// The presence-resolved card `SpiDevice`, for drivers that do not need
630        /// CS held across a command.
631        ///
632        /// Retained for existing callers. Prefer [`Self::acquire`]: a driver
633        /// built on this cannot keep CS asserted across the data-token wait,
634        /// because each `SpiDevice` call deasserts it.
635        ///
636        /// It IS still fairly arbitrated — the device is wrapped so every
637        /// transaction queues for the same permit the display takes. An earlier
638        /// version handed back the raw `SpiDeviceWithConfig`, which silently
639        /// left the card outside the arbiter: exactly the half-fair
640        /// configuration this change exists to remove, reachable through the
641        /// path the module docs recommend for compatibility.
642        pub fn into_inner(self) -> FairSpiDevice<CardSpiDevice<PresenceCs<CS>>> {
643            FairSpiDevice::new(SpiDeviceWithConfig::new(
644                self.bus,
645                self.cs,
646                sd_init_config(),
647            ))
648        }
649    }
650
651    #[cfg(feature = "cores3")]
652    pub type DisplayInterface =
653        SpiInterface<SpiDeviceType<'static>, crate::board::cores3::Gpio35Dc>;
654    #[cfg(feature = "fire27")]
655    pub type DisplayInterface = SpiInterface<SpiDeviceType<'static>, Output<'static>>;
656
657    /// CoreS3 panel: no GPIO reset (AW9523B pulses it; SPI SoftReset fallback).
658    #[cfg(feature = "cores3")]
659    pub type DisplayType = Ili9342c<DisplayInterface>;
660    /// Fire27 panel: hardware reset pin.
661    #[cfg(feature = "fire27")]
662    pub type DisplayType = Ili9342c<DisplayInterface, Output<'static>>;
663
664    pub type DisplayInitError =
665        lcd_async::InitError<<DisplayInterface as Interface>::Error, core::convert::Infallible>;
666
667    /// Display-only DC pin: a plain [`Output`] on **both** boards. On CoreS3
668    /// this is GPIO35 configured as a real output (which routes the pad) — NOT
669    /// [`Gpio35Dc`](crate::board::cores3::Gpio35Dc), whose register-level mux
670    /// relies on `with_miso()` having routed the pad and would otherwise leave
671    /// it unrouted (black screen). Used by [`Spi2Resources::into_display_only`].
672    pub type DisplayOnlyInterface = SpiInterface<SpiDeviceType<'static>, Output<'static>>;
673
674    /// CoreS3 display-only panel: no GPIO reset (AW9523B pulses it).
675    #[cfg(feature = "cores3")]
676    pub type DisplayOnlyType = Ili9342c<DisplayOnlyInterface>;
677    /// Fire27 display-only panel: hardware reset pin.
678    #[cfg(feature = "fire27")]
679    pub type DisplayOnlyType = Ili9342c<DisplayOnlyInterface, Output<'static>>;
680
681    // Both boards' reset pins are infallible (`NoResetPin` / esp-hal `Output`).
682    pub type DisplayOnlyInitError =
683        lcd_async::InitError<<DisplayOnlyInterface as Interface>::Error, core::convert::Infallible>;
684
685    /// Everything [`Spi2Resources::into_display_only`] can fail on.
686    ///
687    /// The SPI2 configure step used to `.expect()`, which panics a library
688    /// crate on a caller's bad config (`conventions/rust-code.md` §6). It
689    /// cannot use `?` on its own, because `DisplayOnlyInitError` is
690    /// `lcd_async`'s and has no variant for it — hence this wrapper.
691    #[derive(Debug)]
692    pub enum DisplayOnlyError {
693        /// SPI2 rejected the display bus configuration.
694        Config(ConfigError),
695        /// The panel did not initialise.
696        Init(DisplayOnlyInitError),
697    }
698
699    impl From<ConfigError> for DisplayOnlyError {
700        fn from(e: ConfigError) -> Self {
701            Self::Config(e)
702        }
703    }
704
705    impl From<DisplayOnlyInitError> for DisplayOnlyError {
706        fn from(e: DisplayOnlyInitError) -> Self {
707            Self::Init(e)
708        }
709    }
710
711    /// A display brought up on the shared SPI2 DMA bus with **no** SD-card path
712    /// ([`Spi2Resources::into_display_only`]). For LVGL and any DMA display-only
713    /// app that does not touch the SD slot.
714    pub struct DisplayBus {
715        pub display: DisplayOnlyType,
716        /// Backlight pin (GPIO32) — driven high by `into_display_only` once the
717        /// panel init succeeds; the caller keeps it alive.
718        #[cfg(feature = "fire27")]
719        pub backlight: Output<'static>,
720    }
721
722    /// The initialised on-board display (plus, on Fire27, its backlight pin).
723    pub struct DisplayDriver {
724        pub display: DisplayType,
725        #[cfg(feature = "fire27")]
726        bl: Output<'static>,
727    }
728
729    #[cfg(feature = "fire27")]
730    impl DisplayDriver {
731        pub fn bl_on(&mut self) {
732            self.bl.set_high();
733        }
734
735        pub fn bl_off(&mut self) {
736            self.bl.set_low();
737        }
738    }
739
740    static SPI_BUS: StaticCell<Mutex<RawMutex, Spi2Bus>> = StaticCell::new();
741
742    /// Waiter slots: the card and the display, plus slack so a mid-handover
743    /// overlap cannot hit the `MaxWaiters` path.
744    const SPI2_WAITERS: usize = 4;
745
746    /// Fair arbiter in FRONT of the bus mutex.
747    ///
748    /// The mutex is still required — `SpiDeviceWithConfig` takes one — but it is
749    /// not FIFO, and the two users are asymmetric: an SD busy-poll offers the
750    /// bus up every 1 ms and asks for it straight back, while a display flush
751    /// holds it for an entire panel transfer (15-30 ms, longer on fire27 with
752    /// LVGL in SPI PSRAM). The flush therefore won repeatedly and the poll
753    /// starved: an erase the card had long finished took seconds to be
754    /// *observed* as finished, and fire27 `:format` drifted 440 ms -> 9434 ms
755    /// while cores3, which renders faster, sat unchanged at ~2850 ms.
756    ///
757    /// Serving permits in arrival order makes both waits structural rather than
758    /// statistical: the poll waits at most one display transfer, the display at
759    /// most one SD command. Every user takes a permit BEFORE locking the mutex,
760    /// so the mutex is only ever held by the permit holder.
761    static SPI2_FAIR: FairSemaphore<RawMutex, SPI2_WAITERS> = FairSemaphore::new(1);
762
763    /// Private: read them through [`permit_stats`].
764    mod permits {
765        use core::sync::atomic::AtomicU32;
766        pub(super) static CARD_ENTER: AtomicU32 = AtomicU32::new(0);
767        pub(super) static CARD_GOT: AtomicU32 = AtomicU32::new(0);
768        pub(super) static CARD_REL: AtomicU32 = AtomicU32::new(0);
769        pub(super) static DISP_ENTER: AtomicU32 = AtomicU32::new(0);
770        pub(super) static DISP_GOT: AtomicU32 = AtomicU32::new(0);
771        pub(super) static DISP_REL: AtomicU32 = AtomicU32::new(0);
772    }
773
774    /// Arrivals, grants and releases per bus user. `got - rel` is what that
775    /// side holds right now, which separates a holder parked mid-command from
776    /// a permit lost outright from a queue whose head is never polled — three
777    /// failures that look identical from outside.
778    ///
779    /// Diagnostic only — nothing reads these to decide anything, so a torn
780    /// read costs a wrong log line, never behaviour.
781    #[derive(Debug, Clone, Copy)]
782    pub struct PermitStats {
783        /// Card: arrivals at the queue.
784        pub card_enter: u32,
785        /// Card: permits granted.
786        pub card_got: u32,
787        /// Card: permits released.
788        pub card_rel: u32,
789        /// Display: arrivals at the queue.
790        pub disp_enter: u32,
791        /// Display: permits granted.
792        pub disp_got: u32,
793        /// Display: permits released.
794        pub disp_rel: u32,
795    }
796
797    /// Snapshot of [`PermitStats`].
798    pub fn permit_stats() -> PermitStats {
799        use core::sync::atomic::Ordering::Relaxed;
800        PermitStats {
801            card_enter: permits::CARD_ENTER.load(Relaxed),
802            card_got: permits::CARD_GOT.load(Relaxed),
803            card_rel: permits::CARD_REL.load(Relaxed),
804            disp_enter: permits::DISP_ENTER.load(Relaxed),
805            disp_got: permits::DISP_GOT.load(Relaxed),
806            disp_rel: permits::DISP_REL.load(Relaxed),
807        }
808    }
809
810    impl Spi2Parts {
811        /// Share the bus, initialise the display, and build the SD-card
812        /// device.
813        ///
814        /// The display comes up first and unconditionally — it must work even
815        /// when the SD card is dead or absent, so the system keeps a UI. On
816        /// CoreS3 this also restores GPIO35 to high-impedance MISO input
817        /// afterwards (see the module docs); on Fire27 it turns the backlight
818        /// on after a successful init.
819        ///
820        /// On CoreS3 the panel must be out of reset before this is called:
821        /// wait for [`power_display_reset`](crate::board::cores3::power_display_reset)
822        /// (AW9523B `LCD_RST` pulse) — bounded, so a wedged I2C init can't
823        /// freeze the display task forever.
824        pub async fn finish<CS>(
825            self,
826            card_cs: CS,
827        ) -> Result<(DisplayDriver, CardSpiDevice<CS>), DisplayInitError> {
828            let (driver, bus) = self.finish_bus().await?;
829            Ok((
830                driver,
831                SpiDeviceWithConfig::new(bus, card_cs, sd_init_config()),
832            ))
833        }
834
835        /// Display bring-up, yielding the SHARED bus rather than a composed
836        /// device.
837        ///
838        /// Split out of [`Self::finish`] so [`Self::finish_sd`] can keep the bus
839        /// and the chip-select as separate pieces — which is what lets a card
840        /// driver hold CS across a whole command. Not generic over `CS`: the
841        /// display path never needed to be.
842        async fn finish_bus(
843            self,
844        ) -> Result<(DisplayDriver, &'static Mutex<RawMutex, Spi2Bus>), DisplayInitError> {
845            let bus = SPI_BUS.init(Mutex::new(Spi2Bus::new(self.bus)));
846            // Wrapped so every panel transfer queues for the SAME permit the
847            // card takes. Fairness on one side only would just move the
848            // starvation to the other.
849            let display_device = FairSpiDevice::new_display(SpiDeviceWithConfig::new(
850                bus,
851                self.display_cs,
852                display_config(),
853            ));
854
855            #[cfg(feature = "cores3")]
856            let driver = {
857                let di = SpiInterface::new(display_device, crate::board::cores3::Gpio35Dc);
858                let display = display::init_ili9342c(di).await?;
859                // CRITICAL: the display init drove GPIO35 as DC (output).
860                // Restore it to high-impedance MISO input now — otherwise the
861                // app's `sd_card.init()` reads garbage on MISO and never
862                // completes. Runtime SD ops must re-assert this per-op.
863                crate::board::cores3::gpio35_disable_output();
864                DisplayDriver { display }
865            };
866
867            #[cfg(feature = "fire27")]
868            let driver = {
869                let di = SpiInterface::new(display_device, self.display_dc);
870                let display = display::init_ili9342c_with_reset(di, self.display_rst).await?;
871                let mut driver = DisplayDriver {
872                    display,
873                    bl: self.display_bl,
874                };
875                driver.bl_on();
876                driver
877            };
878
879            Ok((driver, bus))
880        }
881
882        /// Publish-safe full SD bring-up, layered on [`finish`].
883        ///
884        /// Runs the mandatory ≥74-clock power-up idle on the still-exclusive
885        /// bus (chip-select deasserted), brings the display up unconditionally
886        /// (see [`finish`]), and hands back a presence-resolved
887        /// [`PreparedCard`]. The app owns only the final
888        /// `SdSpi::new(prepared.into_inner()).init()` plus its retry/degrade
889        /// policy — no SD-driver type enters the BSP graph.
890        ///
891        /// [`CardPresence::ForceAbsent`] reaches the app's normal SD-absent
892        /// degrade path with a card inserted: the freeze takes effect at the
893        /// first CS assert inside `SdSpi::init()`, so real-absent and
894        /// forced-absent share one degrade path.
895        pub async fn finish_sd<CS>(
896            mut self,
897            card_cs: CS,
898            presence: CardPresence,
899        ) -> Result<(DisplayDriver, PreparedCard<CS>), DisplayInitError>
900        where
901            CS: OutputPin,
902        {
903            // ≥74 clock cycles with CS deasserted (card_cs starts High) and DI
904            // high — the SD power-up idle, per the SD-SPI spec. Done on the
905            // still-exclusive bus before `finish` shares it; presence-independent
906            // (the freeze only bites at the first CS assert, downstream). Not
907            // via `sdspi::sd_init` — that fork must not enter the BSP graph.
908            //
909            // `SpiDma::write` here is the inherent BLOCKING method: it returns
910            // `Result`, not a `Future`. Load-bearing: if `bus` ever becomes a
911            // type whose `write` yields a future, this must be `.await`ed or the
912            // idle would silently never run.
913            //
914            // 12 bytes, not 10: this goes down the DMA path, and a length that
915            // is not a multiple of 4 takes the copy path that can stop raising
916            // `TransferDone`. 96 clocks still satisfies the spec's >=74.
917            if let Err(e) = self.bus.write(&[0xFF; 12]) {
918                warn!("SD power-up idle clock failed: {e:?}");
919            }
920            let card_cs = PresenceCs {
921                pin: card_cs,
922                frozen: matches!(presence, CardPresence::ForceAbsent),
923            };
924            let (driver, bus) = self.finish_bus().await?;
925            Ok((
926                driver,
927                PreparedCard {
928                    bus,
929                    cs: card_cs,
930                    config: sd_init_config(),
931                },
932            ))
933        }
934    }
935
936    #[cfg(feature = "cores3")]
937    impl Spi2Resources<'static> {
938        /// Bring up the display **only** on a descriptor-backed `SpiDma`, with
939        /// no SD-card path. The DMA buffers are supplied by the app (TX sized to
940        /// the display stripe; RX unused by a write-only panel). DC is a plain
941        /// `Output` on GPIO35 — a configured output routes the pad, unlike
942        /// [`Gpio35Dc`](crate::board::cores3::Gpio35Dc) which needs `with_miso`.
943        ///
944        /// The panel must already be out of reset: call
945        /// [`power_display_reset`](crate::board::cores3::power_display_reset)
946        /// first (AW9523B `LCD_RST` pulse + AXP2101 backlight).
947        pub async fn into_display_only(
948            self,
949            dma_rx_buf: DmaRxBuf,
950            dma_tx_buf: DmaTxBuf,
951        ) -> Result<DisplayBus, DisplayOnlyError> {
952            // No `.with_miso()`: this path never reads the SD card, so GPIO35 is
953            // free to be a plain DC output (below).
954            let spi = Spi::new(self.spi2, display_config())?
955                .with_sck(self.sck)
956                .with_mosi(self.mosi)
957                .with_dma(self.spi2_dma)
958                .with_buffers(dma_rx_buf, dma_tx_buf)
959                .into_async();
960            let bus = SPI_BUS.init(Mutex::new(Spi2Bus::new(spi)));
961            let display_cs = Output::new(self.display_cs, Level::High, OutputConfig::default());
962            let dc = Output::new(self.miso_dc, Level::Low, OutputConfig::default());
963            // Fair-wrapped like the shared path. These entry points are
964            // display-only today, so nothing contends — but leaving one raw
965            // would mean the place that skips the arbiter is the one nobody
966            // re-checks when a second bus user appears.
967            //
968            // `new`, NOT `new_display`: on THIS path DC is the real `Output`
969            // above, driven directly by `SpiInterface`. `new_display` sets
970            // `applies_dc`, which re-drives GPIO35 from `Gpio35Dc`'s recorded
971            // level on every transaction — and that recorder is only written by
972            // the shared path's `Gpio35Dc`, which this path never constructs. It
973            // therefore stays at its initial value forever and pins DC to one
974            // level, so every init command is clocked in as data and the panel
975            // never comes up: black screen, while flush ops still count.
976            let device =
977                FairSpiDevice::new(SpiDeviceWithConfig::new(bus, display_cs, display_config()));
978            let di = SpiInterface::new(device, dc);
979            let display = display::init_ili9342c(di).await?;
980            Ok(DisplayBus { display })
981        }
982    }
983
984    #[cfg(feature = "fire27")]
985    impl Spi2Resources<'static> {
986        /// Bring up the display **only** on a descriptor-backed `SpiDma`, with
987        /// no SD-card path. The DMA buffers are supplied by the app (TX sized to
988        /// the display stripe; RX unused by a write-only panel). The panel is
989        /// reset via its GPIO RST pin; the backlight (GPIO32) is driven high on
990        /// success and returned in [`DisplayBus`] for the caller to keep alive.
991        pub async fn into_display_only(
992            self,
993            dma_rx_buf: DmaRxBuf,
994            dma_tx_buf: DmaTxBuf,
995        ) -> Result<DisplayBus, DisplayOnlyError> {
996            let spi = Spi::new(self.spi2, display_config())?
997                .with_sck(self.sck)
998                .with_mosi(self.mosi)
999                .with_miso(self.miso)
1000                .with_dma(self.spi2_dma)
1001                .with_buffers(dma_rx_buf, dma_tx_buf)
1002                .into_async();
1003            let bus = SPI_BUS.init(Mutex::new(Spi2Bus::new(spi)));
1004            let display_cs = Output::new(self.display_cs, Level::High, OutputConfig::default());
1005            let dc = Output::new(self.display_dc, Level::Low, OutputConfig::default());
1006            let rst = Output::new(self.display_rst, Level::Low, OutputConfig::default());
1007            let mut backlight = Output::new(self.display_bl, Level::Low, OutputConfig::default());
1008            // Fair-wrapped like the shared path. These entry points are
1009            // display-only today, so nothing contends — but leaving one raw
1010            // would mean the place that skips the arbiter is the one nobody
1011            // re-checks when a second bus user appears.
1012            let device = FairSpiDevice::new_display(SpiDeviceWithConfig::new(
1013                bus,
1014                display_cs,
1015                display_config(),
1016            ));
1017            let di = SpiInterface::new(device, dc);
1018            let display = display::init_ili9342c_with_reset(di, rst).await?;
1019            backlight.set_high();
1020            Ok(DisplayBus { display, backlight })
1021        }
1022    }
1023}