Skip to main content

ch32_hal/
sdio.rs

1//! Secure Digital / MultiMedia Card (SDMMC)
2#![macro_use]
3
4use core::default::Default;
5use core::future::poll_fn;
6use core::marker::PhantomData;
7use core::ops::{Deref, DerefMut};
8use core::task::Poll;
9
10use embassy_sync::waitqueue::AtomicWaker;
11use sdio_host::{BusWidth, CardCapacity, CardStatus, CurrentState, SDStatus, CID, CSD, OCR, SCR};
12
13use crate::dma::NoDma;
14use crate::gpio::{AFType, AnyPin, SealedPin, Speed};
15use crate::internal::drop::OnDrop;
16use crate::interrupt::typelevel::Interrupt;
17use crate::pac::sdio::Sdio as RegBlock;
18use crate::peripheral::RccPeripheral;
19use crate::time::Hertz;
20use crate::{interrupt, peripherals, Peri, PeripheralType};
21
22/// Interrupt handler.
23pub struct InterruptHandler<T: Instance> {
24    _phantom: PhantomData<T>,
25}
26
27impl<T: Instance> InterruptHandler<T> {
28    fn data_interrupts(enable: bool) {
29        let regs = T::regs();
30        regs.mask().write(|w| {
31            w.set_dcrcfailie(enable);
32            w.set_dtimeoutie(enable);
33            w.set_dataendie(enable);
34
35            #[cfg(sdio_v3)]
36            // w.set_stbiterre(enable);
37            w.set_stbiterrie(enable);
38        });
39    }
40}
41
42impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
43    unsafe fn on_interrupt() {
44        Self::data_interrupts(false);
45        T::state().wake();
46    }
47}
48
49/// Frequency used for SD Card initialization. Must be no higher than 400 kHz.
50const SD_INIT_FREQ: Hertz = Hertz(400_000);
51
52/// The signalling scheme used on the SDMMC bus
53#[non_exhaustive]
54#[allow(missing_docs)]
55#[derive(Debug, Copy, Clone, PartialEq, Eq)]
56#[cfg_attr(feature = "defmt", derive(defmt::Format))]
57pub enum Signalling {
58    SDR12,
59    SDR25,
60    SDR50,
61    SDR104,
62    DDR50,
63}
64
65impl Default for Signalling {
66    fn default() -> Self {
67        Signalling::SDR12
68    }
69}
70
71/// Aligned data block for SDMMC transfers.
72///
73/// This is a 512-byte array, aligned to 4 bytes to satisfy DMA requirements.
74#[repr(align(4))]
75#[derive(Debug, Clone, PartialEq, Eq)]
76#[cfg_attr(feature = "defmt", derive(defmt::Format))]
77pub struct DataBlock(pub [u8; 512]);
78
79impl Deref for DataBlock {
80    type Target = [u8; 512];
81
82    fn deref(&self) -> &Self::Target {
83        &self.0
84    }
85}
86
87impl DerefMut for DataBlock {
88    fn deref_mut(&mut self) -> &mut Self::Target {
89        &mut self.0
90    }
91}
92
93/// Errors
94#[non_exhaustive]
95#[derive(Debug, Copy, Clone, PartialEq, Eq)]
96#[cfg_attr(feature = "defmt", derive(defmt::Format))]
97pub enum Error {
98    /// Timeout reported by the hardware
99    Timeout,
100    /// Timeout reported by the software driver.
101    SoftwareTimeout,
102    /// Unsupported card version.
103    UnsupportedCardVersion,
104    /// Unsupported card type.
105    UnsupportedCardType,
106    /// CRC error.
107    Crc,
108    /// No card inserted.
109    NoCard,
110    /// Bad clock supplied to the SDMMC peripheral.
111    BadClock,
112    /// Signaling switch failed.
113    SignalingSwitchFailed,
114    /// ST bit error.
115    #[cfg(sdio_v3)]
116    StBitErr,
117}
118
119/// A SD command
120struct Cmd {
121    cmd: u8,
122    arg: u32,
123    resp: Response,
124}
125
126#[derive(Clone, Copy, Debug, Default)]
127/// SD Card
128pub struct Card {
129    /// The type of this card
130    pub card_type: CardCapacity,
131    /// Operation Conditions Register
132    pub ocr: OCR,
133    /// Relative Card Address
134    pub rca: u32,
135    /// Card ID
136    pub cid: CID,
137    /// Card Specific Data
138    pub csd: CSD,
139    /// SD CARD Configuration Register
140    pub scr: SCR,
141    /// SD Status
142    pub status: SDStatus,
143}
144
145impl Card {
146    /// Size in bytes
147    pub fn size(&self) -> u64 {
148        // SDHC / SDXC / SDUC
149        u64::from(self.csd.block_count()) * 512
150    }
151}
152
153#[repr(u8)]
154enum PowerCtrl {
155    Off = 0b00,
156    On = 0b11,
157}
158
159#[repr(u32)]
160#[allow(dead_code)]
161#[allow(non_camel_case_types)]
162enum CmdAppOper {
163    VOLTAGE_WINDOW_SD = 0x8010_0000,
164    HIGH_CAPACITY = 0x4000_0000,
165    SDMMC_STD_CAPACITY = 0x0000_0000,
166    SDMMC_CHECK_PATTERN = 0x0000_01AA,
167    SD_SWITCH_1_8V_CAPACITY = 0x0100_0000,
168}
169
170#[derive(Eq, PartialEq, Copy, Clone)]
171enum Response {
172    None = 0,
173    Short = 1,
174    Long = 3,
175}
176
177/// Calculate clock divisor. Returns a SDMMC_CK less than or equal to
178/// `sdmmc_ck` in Hertz.
179///
180/// Returns `(bypass, clk_div, clk_f)`, where `bypass` enables clock divisor bypass (only sdio_v3),
181/// `clk_div` is the divisor register value and `clk_f` is the resulting new clock frequency.
182#[cfg(sdio_v3)]
183fn clk_div(ker_ck: Hertz, sdmmc_ck: u32) -> Result<(bool, u8, Hertz), Error> {
184    // sdio_v3 maximum clock is 50 MHz
185    if sdmmc_ck > 50_000_000 {
186        return Err(Error::BadClock);
187    }
188
189    // bypass divisor
190    if ker_ck.0 <= sdmmc_ck {
191        return Ok((true, 0, ker_ck));
192    }
193
194    // `ker_ck / sdmmc_ck` rounded up
195    let clk_div = match (ker_ck.0 + sdmmc_ck - 1) / sdmmc_ck {
196        0 | 1 => Ok(0),
197        x @ 2..=258 => Ok((x - 2) as u8),
198        _ => Err(Error::BadClock),
199    }?;
200
201    // SDIO_CK frequency = SDIOCLK / [CLKDIV + 2]
202    let clk_f = Hertz(ker_ck.0 / (clk_div as u32 + 2));
203    Ok((false, clk_div, clk_f))
204}
205
206#[cfg(sdio_v3)]
207type Transfer<'a> = crate::dma::Transfer<'a>;
208
209const DMA_TRANSFER_OPTIONS: crate::dma::TransferOptions = crate::dma::TransferOptions {
210    priority: crate::dma::Priority::VeryHigh,
211    circular: false,
212    half_transfer_ir: false,
213    complete_transfer_ir: true,
214    peripheral_increment: false,
215    memory_to_memory: false,
216};
217
218/// SDMMC configuration
219///
220/// Default values:
221/// data_transfer_timeout: 5_000_000
222#[non_exhaustive]
223pub struct Config {
224    /// The timeout to be set for data transfers, in card bus clock periods
225    pub data_transfer_timeout: u32,
226}
227
228impl Default for Config {
229    fn default() -> Self {
230        Self {
231            data_transfer_timeout: 5_000_000,
232        }
233    }
234}
235
236/// Sdmmc device
237pub struct Sdmmc<'d, T: Instance, Dma: SdioDma<T> = NoDma> {
238    _peri: Peri<'d, T>,
239    #[allow(unused)]
240    dma: Peri<'d, Dma>,
241
242    clk: Peri<'d, AnyPin>,
243    cmd: Peri<'d, AnyPin>,
244    d0: Peri<'d, AnyPin>,
245    d1: Option<Peri<'d, AnyPin>>,
246    d2: Option<Peri<'d, AnyPin>>,
247    d3: Option<Peri<'d, AnyPin>>,
248
249    config: Config,
250    /// Current clock to card
251    clock: Hertz,
252    /// Current signalling scheme to card
253    signalling: Signalling,
254    /// Card
255    card: Option<Card>,
256}
257
258#[cfg(sdio_v3)]
259impl<'d, T: Instance, Dma: SdioDma<T>> Sdmmc<'d, T, Dma> {
260    /// Create a new SDMMC driver, with 1 data lane.
261    pub fn new_1bit(
262        sdmmc: Peri<'d, T>,
263        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
264        dma: Peri<'d, Dma>,
265        clk: Peri<'d, impl CkPin<T, 0>>,
266        cmd: Peri<'d, impl CmdPin<T, 0>>,
267        d0: Peri<'d, impl D0Pin<T, 0>>,
268        config: Config,
269    ) -> Self {
270        critical_section::with(|_| {
271            clk.set_as_af_output(AFType::OutputPushPull, Speed::High);
272            cmd.set_as_af_output(AFType::OutputPushPull, Speed::High);
273            d0.set_as_af_output(AFType::OutputPushPull, Speed::High);
274        });
275
276        Self::new_inner(
277            sdmmc,
278            dma,
279            clk.into(),
280            cmd.into(),
281            d0.into(),
282            None,
283            None,
284            None,
285            config,
286        )
287    }
288
289    /// Create a new SDMMC driver, with 4 data lanes.
290    pub fn new_4bit(
291        sdmmc: Peri<'d, T>,
292        _irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
293        dma: Peri<'d, Dma>,
294        clk: Peri<'d, impl CkPin<T, 0>>,
295        cmd: Peri<'d, impl CmdPin<T, 0>>,
296        d0: Peri<'d, impl D0Pin<T, 0>>,
297        d1: Peri<'d, impl D1Pin<T, 0>>,
298        d2: Peri<'d, impl D2Pin<T, 0>>,
299        d3: Peri<'d, impl D3Pin<T, 0>>,
300        config: Config,
301    ) -> Self {
302        critical_section::with(|_| {
303            clk.set_as_af_output(AFType::OutputPushPull, Speed::High);
304            cmd.set_as_af_output(AFType::OutputPushPull, Speed::High);
305            d0.set_as_af_output(AFType::OutputPushPull, Speed::High);
306            d1.set_as_af_output(AFType::OutputPushPull, Speed::High);
307            d2.set_as_af_output(AFType::OutputPushPull, Speed::High);
308            d3.set_as_af_output(AFType::OutputPushPull, Speed::High);
309        });
310
311        Self::new_inner(
312            sdmmc,
313            dma,
314            clk.into(),
315            cmd.into(),
316            d0.into(),
317            Some(d1.into()),
318            Some(d2.into()),
319            Some(d3.into()),
320            config,
321        )
322    }
323}
324
325impl<'d, T: Instance, Dma: SdioDma<T> + 'd> Sdmmc<'d, T, Dma> {
326    fn new_inner(
327        sdmmc: Peri<'d, T>,
328        dma: Peri<'d, Dma>,
329        clk: Peri<'d, AnyPin>,
330        cmd: Peri<'d, AnyPin>,
331        d0: Peri<'d, AnyPin>,
332        d1: Option<Peri<'d, AnyPin>>,
333        d2: Option<Peri<'d, AnyPin>>,
334        d3: Option<Peri<'d, AnyPin>>,
335        config: Config,
336    ) -> Self {
337
338        T::enable_and_reset();
339
340        T::Interrupt::unpend();
341        unsafe { T::Interrupt::enable() };
342
343        let regs = T::regs();
344        regs.clkcr().write(|w| {
345            w.set_pwrsav(false);
346            w.set_negedge(false);
347
348            // Hardware flow control is broken on SDIOv1 and causes clock glitches, which result in CRC errors.
349            // See chip erratas for more details.
350            #[cfg(sdio_v3)]
351            w.set_hwfc_en(false);
352
353            #[cfg(sdio_v3)]
354            w.set_clken(true);
355        });
356
357        // Power off, writen 00: Clock to the card is stopped;
358        // D[7:0], CMD, and CK are driven high.
359        regs.power().modify(|w| w.set_pwrctrl(PowerCtrl::Off as u8));
360
361        Self {
362            _peri: sdmmc,
363            dma,
364
365            clk,
366            cmd,
367            d0,
368            d1,
369            d2,
370            d3,
371
372            config,
373            clock: SD_INIT_FREQ,
374            signalling: Default::default(),
375            card: None,
376        }
377    }
378
379    /// Data transfer is in progress
380    #[inline]
381    fn data_active() -> bool {
382        let regs = T::regs();
383
384        let status = regs.sta().read();
385        #[cfg(sdio_v3)]
386        return status.rxact() || status.txact();
387    }
388
389    /// Coammand transfer is in progress
390    #[inline]
391    fn cmd_active() -> bool {
392        let regs = T::regs();
393
394        let status = regs.sta().read();
395        #[cfg(sdio_v3)]
396        return status.cmdact();
397    }
398
399    /// Wait idle on CMDACT, RXACT and TXACT (v1) or DOSNACT and CPSMACT (v2)
400    #[inline]
401    fn wait_idle() {
402        while Self::data_active() || Self::cmd_active() {}
403    }
404
405    /// # Safety
406    ///
407    /// `buffer` must be valid for the whole transfer and word aligned
408    fn prepare_datapath_read<'a>(
409        &'a mut self,
410        buffer: &'a mut [u32],
411        length_bytes: u32,
412        block_size: u8,
413    ) -> Transfer<'a> {
414        assert!(block_size <= 14, "Block size up to 2^14 bytes");
415        let regs = T::regs();
416
417        // Command AND Data state machines must be idle
418        Self::wait_idle();
419        Self::clear_interrupt_flags();
420
421        regs.dtimer()
422            .write(|w| w.set_datatime(self.config.data_transfer_timeout));
423        regs.dlen().write(|w| w.set_datalength(length_bytes));
424
425        #[cfg(sdio_v3)]
426        let transfer = unsafe {
427            let request = self.dma.request();
428            Transfer::new_read(
429                self.dma.clone_unchecked(),
430                request,
431                regs.fifo().as_ptr() as *mut u32,
432                buffer,
433                DMA_TRANSFER_OPTIONS,
434            )
435        };
436
437        regs.dctrl().modify(|w| {
438            w.set_dblocksize(block_size);
439            w.set_dtdir(true);
440            #[cfg(sdio_v3)]
441            {
442                w.set_dmaen(true);
443                w.set_dten(true);
444            }
445        });
446
447        transfer
448    }
449
450    /// # Safety
451    ///
452    /// `buffer` must be valid for the whole transfer and word aligned
453    fn prepare_datapath_write<'a>(&'a mut self, buffer: &'a [u32], length_bytes: u32, block_size: u8) -> Transfer<'a> {
454        assert!(block_size <= 14, "Block size up to 2^14 bytes");
455        let regs = T::regs();
456
457        // Command AND Data state machines must be idle
458        Self::wait_idle();
459        Self::clear_interrupt_flags();
460
461        regs.dtimer()
462            .write(|w| w.set_datatime(self.config.data_transfer_timeout));
463        regs.dlen().write(|w| w.set_datalength(length_bytes));
464
465        #[cfg(sdio_v3)]
466        let transfer = unsafe {
467            let request = self.dma.request();
468            Transfer::new_write(
469                self.dma.clone_unchecked(),
470                request,
471                buffer,
472                regs.fifo().as_ptr() as *mut u32,
473                DMA_TRANSFER_OPTIONS,
474            )
475        };
476
477        regs.dctrl().modify(|w| {
478            w.set_dblocksize(block_size);
479            w.set_dtdir(false);
480            #[cfg(sdio_v3)]
481            {
482                w.set_dmaen(true);
483                w.set_dten(true);
484            }
485        });
486
487        transfer
488    }
489
490    /// Stops the DMA datapath
491    fn stop_datapath() {
492        let regs = T::regs();
493
494        #[cfg(sdio_v3)]
495        regs.dctrl().modify(|w| {
496            w.set_dmaen(false);
497            w.set_dten(false);
498        });
499    }
500
501    /// Sets the CLKDIV field in CLKCR. Updates clock field in self
502    fn clkcr_set_clkdiv(&mut self, freq: u32, width: BusWidth) -> Result<(), Error> {
503        let regs = T::regs();
504
505        let width_u32 = match width {
506            BusWidth::One => 1u32,
507            BusWidth::Four => 4u32,
508            BusWidth::Eight => 8u32,
509            _ => panic!("Invalid Bus Width"),
510        };
511
512        let ker_ck = T::frequency();
513        let (_bypass, clkdiv, new_clock) = clk_div(ker_ck, freq)?;
514
515        // Enforce AHB and SDMMC_CK clock relation. See RM0433 Rev 7
516        // Section 55.5.8
517        let sdmmc_bus_bandwidth = new_clock.0 * width_u32;
518        assert!(ker_ck.0 > 3 * sdmmc_bus_bandwidth / 32);
519        self.clock = new_clock;
520
521        // CPSMACT and DPSMACT must be 0 to set CLKDIV
522        Self::wait_idle();
523        regs.clkcr().modify(|w| {
524            w.set_clkdiv(clkdiv);
525            #[cfg(sdio_v3)]
526            w.set_bypass(_bypass);
527        });
528
529        Ok(())
530    }
531
532    /// Switch mode using CMD6.
533    ///
534    /// Attempt to set a new signalling mode. The selected
535    /// signalling mode is returned. Expects the current clock
536    /// frequency to be > 12.5MHz.
537    async fn switch_signalling_mode(&mut self, signalling: Signalling) -> Result<Signalling, Error> {
538        // NB PLSS v7_10 4.3.10.4: "the use of SET_BLK_LEN command is not
539        // necessary"
540
541        let set_function = 0x8000_0000
542            | match signalling {
543                // See PLSS v7_10 Table 4-11
544                Signalling::DDR50 => 0xFF_FF04,
545                Signalling::SDR104 => 0xFF_1F03,
546                Signalling::SDR50 => 0xFF_1F02,
547                Signalling::SDR25 => 0xFF_FF01,
548                Signalling::SDR12 => 0xFF_FF00,
549            };
550
551        let mut status = [0u32; 16];
552
553        // Arm `OnDrop` after the buffer, so it will be dropped first
554        let regs = T::regs();
555        let on_drop = OnDrop::new(|| Self::on_drop());
556
557        let transfer = self.prepare_datapath_read(&mut status, 64, 6);
558        InterruptHandler::<T>::data_interrupts(true);
559        Self::cmd(Cmd::cmd6(set_function), true)?; // CMD6
560
561        let res = poll_fn(|cx| {
562            T::state().register(cx.waker());
563            let status = regs.sta().read();
564
565            if status.dcrcfail() {
566                return Poll::Ready(Err(Error::Crc));
567            }
568            if status.dtimeout() {
569                return Poll::Ready(Err(Error::Timeout));
570            }
571            #[cfg(sdio_v3)]
572            if status.stbiterr() {
573                return Poll::Ready(Err(Error::StBitErr));
574            }
575            if status.dataend() {
576                return Poll::Ready(Ok(()));
577            }
578            Poll::Pending
579        })
580        .await;
581        Self::clear_interrupt_flags();
582
583        // Host is allowed to use the new functions at least 8
584        // clocks after the end of the switch command
585        // transaction. We know the current clock period is < 80ns,
586        // so a total delay of 640ns is required here
587        for _ in 0..300 {
588            qingke::riscv::asm::nop();
589        }
590
591        match res {
592            Ok(_) => {
593                on_drop.defuse();
594                Self::stop_datapath();
595                drop(transfer);
596
597                // Function Selection of Function Group 1
598                let selection = (u32::from_be(status[4]) >> 24) & 0xF;
599
600                match selection {
601                    0 => Ok(Signalling::SDR12),
602                    1 => Ok(Signalling::SDR25),
603                    2 => Ok(Signalling::SDR50),
604                    3 => Ok(Signalling::SDR104),
605                    4 => Ok(Signalling::DDR50),
606                    _ => Err(Error::UnsupportedCardType),
607                }
608            }
609            Err(e) => Err(e),
610        }
611    }
612
613    /// Query the card status (CMD13, returns R1)
614    fn read_status(&self, card: &Card) -> Result<CardStatus, Error> {
615        let regs = T::regs();
616        let rca = card.rca;
617
618        Self::cmd(Cmd::card_status(rca << 16), false)?; // CMD13
619
620        let r1 = regs.resp(0).read().cardstatus();
621        Ok(r1.into())
622    }
623
624    /// Reads the SD Status (ACMD13)
625    async fn read_sd_status(&mut self) -> Result<(), Error> {
626        let card = self.card.as_mut().ok_or(Error::NoCard)?;
627        let rca = card.rca;
628
629        Self::cmd(Cmd::set_block_length(64), false)?; // CMD16
630        Self::cmd(Cmd::app_cmd(rca << 16), false)?; // APP
631
632        let mut status = [0u32; 16];
633
634        // Arm `OnDrop` after the buffer, so it will be dropped first
635        let regs = T::regs();
636        let on_drop = OnDrop::new(|| Self::on_drop());
637
638        let transfer = self.prepare_datapath_read(&mut status, 64, 6);
639        InterruptHandler::<T>::data_interrupts(true);
640        Self::cmd(Cmd::card_status(0), true)?;
641
642        let res = poll_fn(|cx| {
643            T::state().register(cx.waker());
644            let status = regs.sta().read();
645
646            if status.dcrcfail() {
647                return Poll::Ready(Err(Error::Crc));
648            }
649            if status.dtimeout() {
650                return Poll::Ready(Err(Error::Timeout));
651            }
652            #[cfg(sdio_v3)]
653            if status.stbiterr() {
654                return Poll::Ready(Err(Error::StBitErr));
655            }
656            if status.dataend() {
657                return Poll::Ready(Ok(()));
658            }
659            Poll::Pending
660        })
661        .await;
662        Self::clear_interrupt_flags();
663
664        if res.is_ok() {
665            on_drop.defuse();
666            Self::stop_datapath();
667            drop(transfer);
668
669            for byte in status.iter_mut() {
670                *byte = u32::from_be(*byte);
671            }
672            self.card.as_mut().unwrap().status = status.into();
673        }
674        res
675    }
676
677    /// Select one card and place it into the _Tranfer State_
678    ///
679    /// If `None` is specifed for `card`, all cards are put back into
680    /// _Stand-by State_
681    fn select_card(&self, card: Option<&Card>) -> Result<(), Error> {
682        // Determine Relative Card Address (RCA) of given card
683        let rca = card.map(|c| c.rca << 16).unwrap_or(0);
684
685        let r = Self::cmd(Cmd::sel_desel_card(rca), false);
686        match (r, rca) {
687            (Err(Error::Timeout), 0) => Ok(()),
688            _ => r,
689        }
690    }
691
692    /// Clear flags in interrupt clear register
693    #[inline]
694    fn clear_interrupt_flags() {
695        let regs = T::regs();
696        regs.icr().write(|w| {
697            w.set_ccrcfailc(true);
698            w.set_dcrcfailc(true);
699            w.set_ctimeoutc(true);
700            w.set_dtimeoutc(true);
701            w.set_txunderrc(true);
702            w.set_rxoverrc(true);
703            w.set_cmdrendc(true);
704            w.set_cmdsentc(true);
705            w.set_dataendc(true);
706            w.set_dbckendc(true);
707            w.set_sdioitc(true);
708            #[cfg(sdio_v3)]
709            w.set_stbiterrc(true);
710        });
711    }
712
713    async fn get_scr(&mut self, card: &mut Card) -> Result<(), Error> {
714        // Read the the 64-bit SCR register
715        Self::cmd(Cmd::set_block_length(8), false)?; // CMD16
716        Self::cmd(Cmd::app_cmd(card.rca << 16), false)?;
717
718        let mut scr = [0u32; 2];
719
720        // Arm `OnDrop` after the buffer, so it will be dropped first
721        let regs = T::regs();
722        let on_drop = OnDrop::new(|| Self::on_drop());
723
724        let transfer = self.prepare_datapath_read(&mut scr[..], 8, 3);
725        InterruptHandler::<T>::data_interrupts(true);
726        Self::cmd(Cmd::cmd51(), true)?;
727
728        let res = poll_fn(|cx| {
729            T::state().register(cx.waker());
730            let status = regs.sta().read();
731
732            if status.dcrcfail() {
733                return Poll::Ready(Err(Error::Crc));
734            }
735            if status.dtimeout() {
736                return Poll::Ready(Err(Error::Timeout));
737            }
738            #[cfg(sdio_v3)]
739            if status.stbiterr() {
740                return Poll::Ready(Err(Error::StBitErr));
741            }
742            if status.dataend() {
743                return Poll::Ready(Ok(()));
744            }
745            Poll::Pending
746        })
747        .await;
748        Self::clear_interrupt_flags();
749
750        if res.is_ok() {
751            on_drop.defuse();
752            Self::stop_datapath();
753            drop(transfer);
754
755            unsafe {
756                let scr_bytes = &*(&scr as *const [u32; 2] as *const [u8; 8]);
757                card.scr = SCR(u64::from_be_bytes(*scr_bytes));
758            }
759        }
760        res
761    }
762
763    /// Send command to card
764    #[allow(unused_variables)]
765    fn cmd(cmd: Cmd, data: bool) -> Result<(), Error> {
766        let regs = T::regs();
767
768        Self::clear_interrupt_flags();
769        // CP state machine must be idle
770        while Self::cmd_active() {}
771
772        // Command arg
773        regs.arg().write(|w| w.set_cmdarg(cmd.arg));
774
775        // Command index and start CP State Machine
776        regs.cmd().write(|w| {
777            w.set_waitint(false);
778            w.set_waitresp(cmd.resp as u8);
779            w.set_cmdindex(cmd.cmd);
780            w.set_cpsmen(true);
781        });
782
783        let mut retries = 0x00010000;
784
785        let mut status;
786        if cmd.resp == Response::None {
787            // Wait for CMDSENT or a timeout
788            while {
789                status = regs.sta().read();
790                (!(status.ctimeout() || status.cmdsent())) && retries > 0
791            } {
792                retries -= 1;
793            }
794        } else {
795            // Wait for CMDREND or CCRCFAIL or a timeout
796            while {
797                status = regs.sta().read();
798                (!(status.ctimeout() || status.cmdrend() || status.ccrcfail())) && retries > 0
799            } {
800                retries -= 1;
801            }
802        }
803
804        if retries == 0 || status.ctimeout() {
805            return Err(Error::Timeout);
806        } else if status.ccrcfail() {
807            return Err(Error::Crc);
808        }
809        Ok(())
810    }
811
812    fn on_drop() {
813        let regs = T::regs();
814        if Self::data_active() {
815            Self::clear_interrupt_flags();
816            // Send abort
817            // CP state machine must be idle
818            while Self::cmd_active() {}
819
820            // Command arg
821            regs.arg().write(|w| w.set_cmdarg(0));
822
823            // Command index and start CP State Machine
824            regs.cmd().write(|w| {
825                w.set_waitint(false);
826                w.set_waitresp(Response::Short as u8);
827                w.set_cmdindex(12);
828                w.set_cpsmen(true);
829            });
830
831            // Wait for the abort
832            while Self::data_active() {}
833        }
834        InterruptHandler::<T>::data_interrupts(false);
835        Self::clear_interrupt_flags();
836        Self::stop_datapath();
837    }
838
839    /// Initializes card (if present) and sets the bus at the
840    /// specified frequency.
841    pub async fn init_card(&mut self, freq: Hertz) -> Result<(), Error> {
842        let regs = T::regs();
843        let ker_ck = T::frequency();
844
845        let bus_width = match self.d3.is_some() {
846            true => BusWidth::Four,
847            false => BusWidth::One,
848        };
849
850        // While the SD/SDIO card or eMMC is in identification mode,
851        // the SDMMC_CK frequency must be no more than 400 kHz.
852        let (_bypass, clkdiv, init_clock) = clk_div(ker_ck, SD_INIT_FREQ.0).unwrap();
853        self.clock = init_clock;
854
855        // CPSMACT and DPSMACT must be 0 to set WIDBUS
856        Self::wait_idle();
857
858        regs.clkcr().modify(|w| {
859            w.set_widbus(0);
860            w.set_clkdiv(clkdiv);
861            #[cfg(sdio_v3)]
862            w.set_bypass(_bypass);
863        });
864
865        regs.power().modify(|w| w.set_pwrctrl(PowerCtrl::On as u8));
866        Self::cmd(Cmd::idle(), false)?;
867
868        // Check if cards supports CMD8 (with pattern)
869        Self::cmd(Cmd::hs_send_ext_csd(0x1AA), false)?;
870        let r1 = regs.resp(0).read().cardstatus();
871
872        let mut card = if r1 == 0x1AA {
873            // Card echoed back the pattern. Must be at least v2
874            Card::default()
875        } else {
876            return Err(Error::UnsupportedCardVersion);
877        };
878
879        let ocr = loop {
880            // Signal that next command is a app command
881            Self::cmd(Cmd::app_cmd(0), false)?; // CMD55
882
883            let arg = CmdAppOper::VOLTAGE_WINDOW_SD as u32
884                | CmdAppOper::HIGH_CAPACITY as u32
885                | CmdAppOper::SD_SWITCH_1_8V_CAPACITY as u32;
886
887            // Initialize card
888            match Self::cmd(Cmd::app_op_cmd(arg), false) {
889                // ACMD41
890                Ok(_) => (),
891                Err(Error::Crc) => (),
892                Err(err) => return Err(err),
893            }
894            let ocr: OCR = regs.resp(0).read().cardstatus().into();
895            if !ocr.is_busy() {
896                // Power up done
897                break ocr;
898            }
899        };
900
901        if ocr.high_capacity() {
902            // Card is SDHC or SDXC or SDUC
903            card.card_type = CardCapacity::SDHC;
904        } else {
905            card.card_type = CardCapacity::SDSC;
906        }
907        card.ocr = ocr;
908
909        Self::cmd(Cmd::all_send_cid(), false)?; // CMD2
910        let cid0 = regs.resp(0).read().cardstatus() as u128;
911        let cid1 = regs.resp(1).read().cardstatus() as u128;
912        let cid2 = regs.resp(2).read().cardstatus() as u128;
913        let cid3 = regs.resp(3).read().cardstatus() as u128;
914        let cid = (cid0 << 96) | (cid1 << 64) | (cid2 << 32) | (cid3);
915        card.cid = cid.into();
916
917        Self::cmd(Cmd::send_rel_addr(), false)?;
918        card.rca = regs.resp(0).read().cardstatus() >> 16;
919
920        Self::cmd(Cmd::send_csd(card.rca << 16), false)?;
921        let csd0 = regs.resp(0).read().cardstatus() as u128;
922        let csd1 = regs.resp(1).read().cardstatus() as u128;
923        let csd2 = regs.resp(2).read().cardstatus() as u128;
924        let csd3 = regs.resp(3).read().cardstatus() as u128;
925        let csd = (csd0 << 96) | (csd1 << 64) | (csd2 << 32) | (csd3);
926        card.csd = csd.into();
927
928        self.select_card(Some(&card))?;
929
930        self.get_scr(&mut card).await?;
931
932        // Set bus width
933        let (width, acmd_arg) = match bus_width {
934            BusWidth::Eight => unimplemented!(),
935            BusWidth::Four if card.scr.bus_width_four() => (BusWidth::Four, 2),
936            _ => (BusWidth::One, 0),
937        };
938        Self::cmd(Cmd::app_cmd(card.rca << 16), false)?;
939        Self::cmd(Cmd::cmd6(acmd_arg), false)?;
940
941        // CPSMACT and DPSMACT must be 0 to set WIDBUS
942        Self::wait_idle();
943
944        regs.clkcr().modify(|w| {
945            w.set_widbus(match width {
946                BusWidth::One => 0,
947                BusWidth::Four => 1,
948                BusWidth::Eight => 2,
949                _ => panic!("Invalid Bus Width"),
950            })
951        });
952
953        // Set Clock
954        if freq.0 <= 25_000_000 {
955            // Final clock frequency
956            self.clkcr_set_clkdiv(freq.0, width)?;
957        } else {
958            // Switch to max clock for SDR12
959            self.clkcr_set_clkdiv(25_000_000, width)?;
960        }
961
962        self.card = Some(card);
963
964        // Read status
965        self.read_sd_status().await?;
966
967        if freq.0 > 25_000_000 {
968            // Switch to SDR25
969            self.signalling = self.switch_signalling_mode(Signalling::SDR25).await?;
970
971            if self.signalling == Signalling::SDR25 {
972                // Set final clock frequency
973                self.clkcr_set_clkdiv(freq.0, width)?;
974
975                if self.read_status(&card)?.state() != CurrentState::Transfer {
976                    return Err(Error::SignalingSwitchFailed);
977                }
978            }
979        }
980        // Read status after signalling change
981        self.read_sd_status().await?;
982
983        Ok(())
984    }
985
986    /// Read a data block.
987    #[inline]
988    pub async fn read_block(&mut self, block_idx: u32, buffer: &mut DataBlock) -> Result<(), Error> {
989        let card_capacity = self.card()?.card_type;
990
991        // NOTE(unsafe) DataBlock uses align 4
992        let buffer = unsafe { &mut *((&mut buffer.0) as *mut [u8; 512] as *mut [u32; 128]) };
993
994        // Always read 1 block of 512 bytes
995        // SDSC cards are byte addressed hence the blockaddress is in multiples of 512 bytes
996        let address = match card_capacity {
997            CardCapacity::SDSC => block_idx * 512,
998            _ => block_idx,
999        };
1000        Self::cmd(Cmd::set_block_length(512), false)?; // CMD16
1001
1002        let regs = T::regs();
1003        let on_drop = OnDrop::new(|| Self::on_drop());
1004
1005        let transfer = self.prepare_datapath_read(buffer, 512, 9);
1006        InterruptHandler::<T>::data_interrupts(true);
1007        Self::cmd(Cmd::read_single_block(address), true)?;
1008
1009        let res = poll_fn(|cx| {
1010            T::state().register(cx.waker());
1011            let status = regs.sta().read();
1012
1013            if status.dcrcfail() {
1014                return Poll::Ready(Err(Error::Crc));
1015            }
1016            if status.dtimeout() {
1017                return Poll::Ready(Err(Error::Timeout));
1018            }
1019            #[cfg(sdio_v3)]
1020            if status.stbiterr() {
1021                return Poll::Ready(Err(Error::StBitErr));
1022            }
1023            if status.dataend() {
1024                return Poll::Ready(Ok(()));
1025            }
1026            Poll::Pending
1027        })
1028        .await;
1029        Self::clear_interrupt_flags();
1030
1031        if res.is_ok() {
1032            on_drop.defuse();
1033            Self::stop_datapath();
1034            drop(transfer);
1035        }
1036        res
1037    }
1038
1039    /// Write a data block.
1040    pub async fn write_block(&mut self, block_idx: u32, buffer: &DataBlock) -> Result<(), Error> {
1041        let card = self.card.as_mut().ok_or(Error::NoCard)?;
1042
1043        // NOTE(unsafe) DataBlock uses align 4
1044        let buffer = unsafe { &*((&buffer.0) as *const [u8; 512] as *const [u32; 128]) };
1045
1046        // Always read 1 block of 512 bytes
1047        // SDSC cards are byte addressed hence the blockaddress is in multiples of 512 bytes
1048        let address = match card.card_type {
1049            CardCapacity::SDSC => block_idx * 512,
1050            _ => block_idx,
1051        };
1052        Self::cmd(Cmd::set_block_length(512), false)?; // CMD16
1053
1054        let regs = T::regs();
1055        let on_drop = OnDrop::new(|| Self::on_drop());
1056
1057        // sdio_v3 uses different cmd/dma order than v2, but only for writes
1058        #[cfg(sdio_v3)]
1059        Self::cmd(Cmd::write_single_block(address), true)?;
1060
1061        let transfer = self.prepare_datapath_write(buffer, 512, 9);
1062        InterruptHandler::<T>::data_interrupts(true);
1063
1064        let res = poll_fn(|cx| {
1065            T::state().register(cx.waker());
1066            let status = regs.sta().read();
1067
1068            if status.dcrcfail() {
1069                return Poll::Ready(Err(Error::Crc));
1070            }
1071            if status.dtimeout() {
1072                return Poll::Ready(Err(Error::Timeout));
1073            }
1074            #[cfg(sdio_v3)]
1075            if status.stbiterr() {
1076                return Poll::Ready(Err(Error::StBitErr));
1077            }
1078            if status.dataend() {
1079                return Poll::Ready(Ok(()));
1080            }
1081            Poll::Pending
1082        })
1083        .await;
1084        Self::clear_interrupt_flags();
1085
1086        match res {
1087            Ok(_) => {
1088                on_drop.defuse();
1089                Self::stop_datapath();
1090                drop(transfer);
1091
1092                // TODO: Make this configurable
1093                let mut timeout: u32 = 0x00FF_FFFF;
1094
1095                // Try to read card status (ACMD13)
1096                while timeout > 0 {
1097                    match self.read_sd_status().await {
1098                        Ok(_) => return Ok(()),
1099                        Err(Error::Timeout) => (), // Try again
1100                        Err(e) => return Err(e),
1101                    }
1102                    timeout -= 1;
1103                }
1104                Err(Error::SoftwareTimeout)
1105            }
1106            Err(e) => Err(e),
1107        }
1108    }
1109
1110    /// Get a reference to the initialized card
1111    ///
1112    /// # Errors
1113    ///
1114    /// Returns Error::NoCard if [`init_card`](#method.init_card)
1115    /// has not previously succeeded
1116    #[inline]
1117    pub fn card(&self) -> Result<&Card, Error> {
1118        self.card.as_ref().ok_or(Error::NoCard)
1119    }
1120
1121    /// Get the current SDMMC bus clock
1122    pub fn clock(&self) -> Hertz {
1123        self.clock
1124    }
1125}
1126
1127impl<'d, T: Instance, Dma: SdioDma<T> + 'd> Drop for Sdmmc<'d, T, Dma> {
1128    fn drop(&mut self) {
1129        T::Interrupt::disable();
1130        Self::on_drop();
1131
1132        critical_section::with(|_| {
1133            self.clk.set_as_disconnected();
1134            self.cmd.set_as_disconnected();
1135            self.d0.set_as_disconnected();
1136            if let Some(x) = &mut self.d1 {
1137                x.set_as_disconnected();
1138            }
1139            if let Some(x) = &mut self.d2 {
1140                x.set_as_disconnected();
1141            }
1142            if let Some(x) = &mut self.d3 {
1143                x.set_as_disconnected();
1144            }
1145        });
1146    }
1147}
1148
1149/// SD card Commands
1150impl Cmd {
1151    const fn new(cmd: u8, arg: u32, resp: Response) -> Cmd {
1152        Cmd { cmd, arg, resp }
1153    }
1154
1155    /// CMD0: Idle
1156    const fn idle() -> Cmd {
1157        Cmd::new(0, 0, Response::None)
1158    }
1159
1160    /// CMD2: Send CID
1161    const fn all_send_cid() -> Cmd {
1162        Cmd::new(2, 0, Response::Long)
1163    }
1164
1165    /// CMD3: Send Relative Address
1166    const fn send_rel_addr() -> Cmd {
1167        Cmd::new(3, 0, Response::Short)
1168    }
1169
1170    /// CMD6: Switch Function Command
1171    /// ACMD6: Bus Width
1172    const fn cmd6(arg: u32) -> Cmd {
1173        Cmd::new(6, arg, Response::Short)
1174    }
1175
1176    /// CMD7: Select one card and put it into the _Tranfer State_
1177    const fn sel_desel_card(rca: u32) -> Cmd {
1178        Cmd::new(7, rca, Response::Short)
1179    }
1180
1181    /// CMD8:
1182    const fn hs_send_ext_csd(arg: u32) -> Cmd {
1183        Cmd::new(8, arg, Response::Short)
1184    }
1185
1186    /// CMD9:
1187    const fn send_csd(rca: u32) -> Cmd {
1188        Cmd::new(9, rca, Response::Long)
1189    }
1190
1191    /// CMD12:
1192    //const fn stop_transmission() -> Cmd {
1193    //    Cmd::new(12, 0, Response::Short)
1194    //}
1195
1196    /// CMD13: Ask card to send status register
1197    /// ACMD13: SD Status
1198    const fn card_status(rca: u32) -> Cmd {
1199        Cmd::new(13, rca, Response::Short)
1200    }
1201
1202    /// CMD16:
1203    const fn set_block_length(blocklen: u32) -> Cmd {
1204        Cmd::new(16, blocklen, Response::Short)
1205    }
1206
1207    /// CMD17: Block Read
1208    const fn read_single_block(addr: u32) -> Cmd {
1209        Cmd::new(17, addr, Response::Short)
1210    }
1211
1212    /// CMD18: Multiple Block Read
1213    //const fn read_multiple_blocks(addr: u32) -> Cmd {
1214    //    Cmd::new(18, addr, Response::Short)
1215    //}
1216
1217    /// CMD24: Block Write
1218    const fn write_single_block(addr: u32) -> Cmd {
1219        Cmd::new(24, addr, Response::Short)
1220    }
1221
1222    const fn app_op_cmd(arg: u32) -> Cmd {
1223        Cmd::new(41, arg, Response::Short)
1224    }
1225
1226    const fn cmd51() -> Cmd {
1227        Cmd::new(51, 0, Response::Short)
1228    }
1229
1230    /// App Command. Indicates that next command will be a app command
1231    const fn app_cmd(rca: u32) -> Cmd {
1232        Cmd::new(55, rca, Response::Short)
1233    }
1234}
1235
1236//////////////////////////////////////////////////////
1237
1238trait SealedInstance {
1239    fn regs() -> RegBlock;
1240    fn state() -> &'static AtomicWaker;
1241}
1242
1243/// SDMMC instance trait.
1244#[allow(private_bounds)]
1245pub trait Instance: SealedInstance + RccPeripheral + PeripheralType + 'static {
1246    /// Interrupt for this instance.
1247    type Interrupt: interrupt::typelevel::Interrupt;
1248}
1249
1250pin_trait!(CkPin, Instance);
1251pin_trait!(CmdPin, Instance);
1252pin_trait!(D0Pin, Instance);
1253pin_trait!(D1Pin, Instance);
1254pin_trait!(D2Pin, Instance);
1255pin_trait!(D3Pin, Instance);
1256pin_trait!(D4Pin, Instance);
1257pin_trait!(D5Pin, Instance);
1258pin_trait!(D6Pin, Instance);
1259pin_trait!(D7Pin, Instance);
1260
1261#[cfg(sdio_v3)]
1262dma_trait!(SdioDma, Instance);
1263
1264foreach_peripheral!(
1265    (sdio, $inst:ident) => {
1266        impl SealedInstance for peripherals::$inst {
1267            fn regs() -> RegBlock {
1268                crate::pac::$inst
1269            }
1270
1271            fn state() -> &'static ::embassy_sync::waitqueue::AtomicWaker {
1272                static WAKER: ::embassy_sync::waitqueue::AtomicWaker = ::embassy_sync::waitqueue::AtomicWaker::new();
1273                &WAKER
1274            }
1275        }
1276
1277        impl Instance for peripherals::$inst {
1278            type Interrupt = crate::interrupt::typelevel::$inst;
1279        }
1280    };
1281);