sdmmc-protocol 0.4.1

no_std SD/MMC protocol building blocks for embedded systems
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! Compatibility adapter between `sdio-host2` and the protocol `SdioHost` trait.

#[cfg(feature = "rdif")]
use alloc::boxed::Box;
use alloc::sync::Arc;
use core::{
    cell::UnsafeCell,
    num::{NonZeroU16, NonZeroU32},
    sync::atomic::{AtomicBool, Ordering},
};

use dma_api::CompletedDma;
#[cfg(feature = "rdif")]
use dma_api::PreparedDma;
use log::{debug, warn};

use super::{
    card::SdioSdmmc,
    host::{
        BusWidth, ClockSpeed, HostEvent, SdioBusOp, SdioHost, SdioIrqHandle, SdioIrqHost,
        SignalVoltage,
    },
};
use crate::{
    block::{CommandResponsePoll, DataCommandPoll, OperationPoll},
    cmd::Command,
    error::{Error, ErrorContext, Phase},
    response::ResponseType,
};

#[cfg(feature = "rdif")]
pub(crate) struct DmaSubmitError {
    pub error: Error,
    buffer: Box<PreparedDma>,
}

#[cfg(feature = "rdif")]
impl DmaSubmitError {
    fn new(error: Error, buffer: PreparedDma) -> Self {
        Self {
            error,
            buffer: Box::new(buffer),
        }
    }

    pub(crate) fn into_buffer(self) -> PreparedDma {
        *self.buffer
    }
}

pub struct SdioHost2Adapter<H: SdioHost2Irq + 'static> {
    core: Host2Shared<H>,
    command_request: Option<H::TransactionRequest<'static>>,
}

/// IRQ-capable extension used by [`SdioHost2Adapter`].
///
/// `sdio-host2` intentionally does not define IRQ abstractions. This protocol
/// crate only needs a way to forward host-specific completion IRQ handles when
/// a physical host is wrapped for the legacy `SdioHost` card state machine.
pub trait SdioHost2Irq: sdio_host2::SdioHost {
    type Event: HostEvent + Default;
    type IrqHandle: SdioIrqHandle<Event = Self::Event>;

    fn completion_irq_enabled(&self) -> bool {
        false
    }

    fn enable_completion_irq(&mut self) -> Result<(), Error> {
        Ok(())
    }

    fn disable_completion_irq(&mut self) -> Result<(), Error> {
        Ok(())
    }

    fn irq_handle(&mut self) -> Self::IrqHandle;
}

impl<T> SdioHost2Irq for T
where
    T: sdio_host2::SdioHost + SdioIrqHost,
{
    type Event = <T as SdioHost>::Event;
    type IrqHandle = <T as SdioIrqHost>::IrqHandle;

    fn completion_irq_enabled(&self) -> bool {
        SdioHost::completion_irq_enabled(self)
    }

    fn enable_completion_irq(&mut self) -> Result<(), Error> {
        SdioHost::enable_completion_irq(self)
    }

    fn disable_completion_irq(&mut self) -> Result<(), Error> {
        SdioHost::disable_completion_irq(self)
    }

    fn irq_handle(&mut self) -> Self::IrqHandle {
        SdioIrqHost::irq_handle(self)
    }
}

struct Host2Shared<H> {
    inner: Arc<Host2SharedInner<H>>,
}

struct Host2SharedInner<H> {
    host: UnsafeCell<H>,
    borrowed: AtomicBool,
}

// SAFETY: Access to `host` is serialized by `borrowed`; the wrapper never
// hands out references that outlive a `with_*` call.
unsafe impl<H: Send> Send for Host2SharedInner<H> {}
// SAFETY: See the `Send` impl.
unsafe impl<H: Send> Sync for Host2SharedInner<H> {}

impl<H> Clone for Host2Shared<H> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

impl<H> Host2Shared<H> {
    fn new(host: H) -> Self {
        Self {
            inner: Arc::new(Host2SharedInner {
                host: UnsafeCell::new(host),
                borrowed: AtomicBool::new(false),
            }),
        }
    }

    fn with_ref<R>(&self, f: impl FnOnce(&H) -> R) -> R {
        self.borrow(|host| f(host))
    }

    fn with_mut<R>(&self, f: impl FnOnce(&mut H) -> R) -> R {
        self.borrow(|host| f(host))
    }

    fn borrow<R>(&self, f: impl FnOnce(&mut H) -> R) -> R {
        if self
            .inner
            .borrowed
            .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
            .is_err()
        {
            panic!("sdio-host2 adapter host borrowed concurrently");
        }
        struct BorrowGuard<'a>(&'a AtomicBool);
        impl Drop for BorrowGuard<'_> {
            fn drop(&mut self) {
                self.0.store(false, Ordering::Release);
            }
        }
        let _guard = BorrowGuard(&self.inner.borrowed);
        // SAFETY: the atomic guard above serializes access to the host.
        f(unsafe { &mut *self.inner.host.get() })
    }
}

impl<H: SdioHost2Irq + 'static> SdioHost2Adapter<H> {
    pub fn new(host: H) -> Self {
        Self {
            core: Host2Shared::new(host),
            command_request: None,
        }
    }

    pub fn with_host<R>(&self, f: impl FnOnce(&H) -> R) -> R {
        self.core.with_ref(f)
    }

    pub fn with_host_mut<R>(&self, f: impl FnOnce(&mut H) -> R) -> R {
        self.core.with_mut(f)
    }

    fn drain_bus_op(&mut self, request: &mut SdioHost2BusRequest<H>) -> Result<(), Error> {
        for _ in 0..SDIO_HOST2_COMPAT_POLL_LIMIT {
            match self.poll_bus_op(request)? {
                OperationPoll::Pending => core::hint::spin_loop(),
                OperationPoll::Complete(()) => return Ok(()),
            }
        }
        request.abort()?;
        Err(Error::Timeout(ErrorContext::new(Phase::Init)))
    }
}

pub(super) const SDIO_HOST2_COMPAT_POLL_LIMIT: u32 = 1_000_000;

// SAFETY: The physical host is only accessed through `Host2Shared`, which
// serializes mutable borrows. `command_request` is only touched through
// `&mut self` and is aborted in `Drop`.
unsafe impl<H> Send for SdioHost2Adapter<H>
where
    H: SdioHost2Irq + Send + 'static,
    H::TransactionRequest<'static>: Send,
{
}

// SAFETY: Shared references only expose `with_host`, mediated by
// `Host2Shared`. Request mutation and IRQ endpoint extraction still require
// `&mut self`.
unsafe impl<H> Sync for SdioHost2Adapter<H>
where
    H: SdioHost2Irq + Send + 'static,
    H::TransactionRequest<'static>: Send,
{
}

impl<H: SdioHost2Irq + 'static> Drop for SdioHost2Adapter<H> {
    fn drop(&mut self) {
        let Some(mut request) = self.command_request.take() else {
            return;
        };
        let result = self
            .core
            .with_mut(|host| host.abort_transaction(&mut request))
            .map_err(host2_error);
        if let Err(err) = result {
            warn!(
                "sdio-host2 adapter: abort pending command on drop reported recovery error: \
                 {err:?}"
            );
        }
    }
}

pub struct SdioHost2DataRequest<'a, H: SdioHost2Irq + 'static> {
    core: Host2Shared<H>,
    inner: Option<H::TransactionRequest<'a>>,
    completed_dma: Option<CompletedDma>,
}

impl<H: SdioHost2Irq + 'static> SdioHost2DataRequest<'_, H> {
    pub(crate) fn abort(&mut self) -> Result<(), Error> {
        let Some(mut request) = self.inner.take() else {
            return Ok(());
        };
        let (result, completed_dma) = self.core.with_mut(|host| {
            let result = host.abort_transaction(&mut request).map_err(host2_error);
            let completed_dma = host.take_completed_dma(&mut request);
            (result, completed_dma)
        });
        self.completed_dma = completed_dma;
        result
    }

    #[cfg(feature = "rdif")]
    pub(crate) fn take_completed_dma(&mut self) -> Option<CompletedDma> {
        self.completed_dma.take()
    }
}

impl<H: SdioHost2Irq + 'static> Drop for SdioHost2DataRequest<'_, H> {
    fn drop(&mut self) {
        if let Err(err) = self.abort() {
            warn!(
                "sdio-host2 adapter: abort pending data request on drop reported recovery error: \
                 {err:?}"
            );
        }
    }
}

pub struct SdioHost2BusRequest<H: SdioHost2Irq + 'static> {
    core: Host2Shared<H>,
    inner: Option<H::BusRequest>,
    op: sdio_host2::BusOp,
}

impl<H: SdioHost2Irq + 'static> SdioHost2BusRequest<H> {
    fn abort(&mut self) -> Result<(), Error> {
        let Some(mut request) = self.inner.take() else {
            return Ok(());
        };
        self.core
            .with_mut(|host| host.abort_bus_op(&mut request))
            .map_err(host2_error)
    }
}

impl<H: SdioHost2Irq + 'static> Drop for SdioHost2BusRequest<H> {
    fn drop(&mut self) {
        if let Err(err) = self.abort() {
            warn!(
                "sdio-host2 adapter: abort pending bus op on drop reported recovery error: {err:?}"
            );
        }
    }
}

impl<H: SdioHost2Irq + 'static> SdioHost for SdioHost2Adapter<H> {
    type Event = H::Event;
    type DataRequest<'a>
        = SdioHost2DataRequest<'a, H>
    where
        Self: 'a;
    type BusRequest = SdioHost2BusRequest<H>;

    fn submit_command(&mut self, cmd: &Command) -> Result<(), Error> {
        if self.command_request.is_some() {
            return Err(Error::Busy);
        }
        debug!(
            "sdio-host2 adapter: submit command CMD{} arg={:#010x} resp={:?}",
            cmd.index, cmd.argument, cmd.response
        );
        let request = self
            .core
            .with_mut(|host| unsafe {
                host.submit_transaction(sdio_host2::Transaction::command(*cmd))
            })
            .map_err(host2_error)?;
        self.command_request = Some(request);
        Ok(())
    }

    fn poll_command_response(&mut self) -> Result<CommandResponsePoll, Error> {
        let mut request = self.command_request.take().ok_or(Error::InvalidArgument)?;
        match self
            .core
            .with_mut(|host| host.poll_transaction(&mut request))
        {
            Ok(sdio_host2::RequestPoll::Pending) => {
                self.command_request = Some(request);
                Ok(CommandResponsePoll::Pending)
            }
            Ok(sdio_host2::RequestPoll::Ready(Ok(raw))) => {
                crate::response::response_from_raw(raw).map(CommandResponsePoll::Complete)
            }
            Ok(sdio_host2::RequestPoll::Ready(Err(err))) => {
                warn!("sdio-host2 adapter: command completed with error {:?}", err);
                Err(host2_error(err))
            }
            Err(err) => {
                warn!("sdio-host2 adapter: command poll failed with {:?}", err);
                self.command_request = Some(request);
                Err(host2_poll_error(err))
            }
        }
    }

    fn submit_read_data<'a>(
        &mut self,
        cmd: &Command,
        buf: &'a mut [u8],
        block_size: u32,
        block_count: u32,
    ) -> Result<Self::DataRequest<'a>, Error> {
        let data = sdio_host2::DataPhase::read(
            nonzero_block_size(block_size)?,
            nonzero_block_count(block_count)?,
            buf,
        )
        .map_err(host2_error)?;
        let request = self
            .core
            .with_mut(|host| unsafe {
                host.submit_transaction(sdio_host2::Transaction::with_data(*cmd, data))
            })
            .map_err(host2_error)?;
        Ok(SdioHost2DataRequest {
            core: self.core.clone(),
            inner: Some(request),
            completed_dma: None,
        })
    }

    fn submit_write_data<'a>(
        &mut self,
        cmd: &Command,
        buf: &'a [u8],
        block_size: u32,
        block_count: u32,
    ) -> Result<Self::DataRequest<'a>, Error> {
        let data = sdio_host2::DataPhase::write(
            nonzero_block_size(block_size)?,
            nonzero_block_count(block_count)?,
            buf,
        )
        .map_err(host2_error)?;
        let request = self
            .core
            .with_mut(|host| unsafe {
                host.submit_transaction(sdio_host2::Transaction::with_data(*cmd, data))
            })
            .map_err(host2_error)?;
        Ok(SdioHost2DataRequest {
            core: self.core.clone(),
            inner: Some(request),
            completed_dma: None,
        })
    }

    fn poll_data_request<'a>(
        &mut self,
        request: &mut Self::DataRequest<'a>,
    ) -> Result<DataCommandPoll, Error> {
        let inner = request.inner.as_mut().ok_or(Error::InvalidArgument)?;
        match request.core.with_mut(|host| host.poll_transaction(inner)) {
            Ok(sdio_host2::RequestPoll::Pending) => Ok(DataCommandPoll::Pending),
            Ok(sdio_host2::RequestPoll::Ready(Ok(raw))) => {
                request.completed_dma = request
                    .inner
                    .as_mut()
                    .and_then(|inner| request.core.with_mut(|host| host.take_completed_dma(inner)));
                request.inner = None;
                crate::response::response_from_raw(raw).map(DataCommandPoll::Complete)
            }
            Ok(sdio_host2::RequestPoll::Ready(Err(err))) => {
                request.completed_dma = request
                    .inner
                    .as_mut()
                    .and_then(|inner| request.core.with_mut(|host| host.take_completed_dma(inner)));
                request.inner = None;
                Err(host2_error(err))
            }
            Err(err) => Err(host2_poll_error(err)),
        }
    }

    fn set_bus_width(&mut self, width: BusWidth) -> Result<(), Error> {
        let mut request = self.submit_bus_op(SdioBusOp::SetBusWidth(width))?;
        self.drain_bus_op(&mut request)
    }

    fn set_clock(&mut self, speed: ClockSpeed) -> Result<(), Error> {
        let mut request = self.submit_bus_op(SdioBusOp::SetClock(speed))?;
        self.drain_bus_op(&mut request)
    }

    fn switch_voltage(&mut self, voltage: SignalVoltage) -> Result<(), Error> {
        let mut request = self.submit_bus_op(SdioBusOp::SwitchVoltage(voltage))?;
        self.drain_bus_op(&mut request)
    }

    fn execute_tuning(&mut self, cmd_index: u8, block_size: NonZeroU16) -> Result<(), Error> {
        let mut request = self.submit_bus_op(SdioBusOp::ExecuteTuning {
            cmd_index,
            block_size,
        })?;
        self.drain_bus_op(&mut request)
    }

    fn submit_bus_op(&mut self, op: SdioBusOp) -> Result<Self::BusRequest, Error> {
        let host_op = match op {
            SdioBusOp::ResetAll => sdio_host2::BusOp::ResetAll,
            SdioBusOp::PowerOn => sdio_host2::BusOp::PowerOn,
            SdioBusOp::PowerOff => sdio_host2::BusOp::PowerOff,
            SdioBusOp::SetBusWidth(width) => sdio_host2::BusOp::SetBusWidth(width),
            SdioBusOp::SetClock(speed) => sdio_host2::BusOp::SetClock(speed),
            SdioBusOp::SwitchVoltage(voltage) => sdio_host2::BusOp::SetSignalVoltage(voltage),
            SdioBusOp::ExecuteTuning {
                cmd_index,
                block_size,
            } => {
                let command = Command::new(cmd_index, 0, ResponseType::R1);
                sdio_host2::BusOp::ExecuteTuning {
                    command,
                    block_size,
                }
            }
        };
        let inner = self
            .core
            .with_mut(|host| unsafe { host.submit_bus_op(host_op) })
            .map_err(host2_error)?;
        Ok(SdioHost2BusRequest {
            core: self.core.clone(),
            inner: Some(inner),
            op: host_op,
        })
    }

    fn poll_bus_op(&mut self, request: &mut Self::BusRequest) -> Result<OperationPoll<()>, Error> {
        let inner = request.inner.as_mut().ok_or(Error::InvalidArgument)?;
        match request.core.with_mut(|host| host.poll_bus_op(inner)) {
            Ok(sdio_host2::RequestPoll::Pending) => Ok(OperationPoll::Pending),
            Ok(sdio_host2::RequestPoll::Ready(Ok(()))) => {
                request.inner = None;
                Ok(OperationPoll::Complete(()))
            }
            Ok(sdio_host2::RequestPoll::Ready(Err(err))) => {
                warn!(
                    "sdio-host2 adapter: bus op {:?} completed with error {:?}",
                    request.op, err
                );
                request.inner = None;
                Err(host2_error(err))
            }
            Err(err) => {
                warn!(
                    "sdio-host2 adapter: bus op {:?} poll failed with {:?}",
                    request.op, err
                );
                Err(host2_poll_error(err))
            }
        }
    }

    fn enable_completion_irq(&mut self) -> Result<(), Error> {
        self.core.with_mut(|host| host.enable_completion_irq())
    }

    fn disable_completion_irq(&mut self) -> Result<(), Error> {
        self.core.with_mut(|host| host.disable_completion_irq())
    }

    fn completion_irq_enabled(&self) -> bool {
        self.core.with_ref(|host| host.completion_irq_enabled())
    }

    fn now_ms(&self) -> Option<u64> {
        self.core.with_ref(|host| host.now_ms())
    }
}

impl<H: SdioHost2Irq + 'static> SdioIrqHost for SdioHost2Adapter<H> {
    type IrqHandle = H::IrqHandle;

    fn irq_handle(&mut self) -> Self::IrqHandle {
        self.core.with_mut(|host| host.irq_handle())
    }
}

#[cfg(feature = "rdif")]
impl<H: SdioHost2Irq + 'static> SdioHost2Adapter<H> {
    pub(crate) fn submit_dma_data(
        &mut self,
        cmd: &Command,
        direction: sdio_host2::DataDirection,
        buffer: PreparedDma,
        block_size: u32,
        block_count: u32,
    ) -> Result<SdioHost2DataRequest<'static, H>, DmaSubmitError> {
        let block_size = match nonzero_block_size(block_size) {
            Ok(block_size) => block_size,
            Err(err) => return Err(DmaSubmitError::new(err, buffer)),
        };
        let block_count = match nonzero_block_count(block_count) {
            Ok(block_count) => block_count,
            Err(err) => return Err(DmaSubmitError::new(err, buffer)),
        };
        let data = sdio_host2::DataPhase::dma(direction, block_size, block_count, buffer).map_err(
            |err| {
                let (error, buffer) = err.into_parts();
                DmaSubmitError::new(host2_error(error), buffer)
            },
        )?;
        let transaction = sdio_host2::Transaction::with_data(*cmd, data);
        let request = self
            .core
            .with_mut(|host| unsafe { host.submit_transaction_owned(transaction) });
        match request {
            Ok(request) => Ok(SdioHost2DataRequest {
                core: self.core.clone(),
                inner: Some(request),
                completed_dma: None,
            }),
            Err(err) => {
                let error = host2_error(err.error);
                let Some(transaction) = err.into_transaction() else {
                    panic!("sdio-host2 DMA submit consumed owned transaction on failure");
                };
                let Some(buffer) = recover_dma_buffer(transaction) else {
                    panic!("sdio-host2 DMA submit failure did not return DMA buffer");
                };
                Err(DmaSubmitError::new(error, buffer))
            }
        }
    }
}

#[cfg(feature = "rdif")]
fn recover_dma_buffer(transaction: sdio_host2::Transaction<'_>) -> Option<PreparedDma> {
    match transaction.data?.buffer {
        sdio_host2::DataBuffer::Dma(buffer) => Some(buffer),
        sdio_host2::DataBuffer::Read(_) | sdio_host2::DataBuffer::Write(_) => None,
    }
}

impl<H: SdioHost2Irq + 'static> SdioSdmmc<SdioHost2Adapter<H>> {
    pub fn new_host2(host: H) -> Self {
        Self::new(SdioHost2Adapter::new(host))
    }
}

fn nonzero_block_size(block_size: u32) -> Result<NonZeroU16, Error> {
    u16::try_from(block_size)
        .ok()
        .and_then(NonZeroU16::new)
        .ok_or(Error::InvalidArgument)
}

fn nonzero_block_count(block_count: u32) -> Result<NonZeroU32, Error> {
    NonZeroU32::new(block_count).ok_or(Error::InvalidArgument)
}

fn host2_error(err: sdio_host2::Error) -> Error {
    match err {
        sdio_host2::Error::Busy => Error::Busy,
        sdio_host2::Error::Timeout => Error::Timeout(ErrorContext::default()),
        sdio_host2::Error::Crc => Error::Crc(ErrorContext::default()),
        sdio_host2::Error::NoCard => Error::NoCard,
        sdio_host2::Error::Unsupported => Error::UnsupportedCommand,
        sdio_host2::Error::InvalidArgument => Error::InvalidArgument,
        sdio_host2::Error::Misaligned => Error::Misaligned,
        sdio_host2::Error::Bus => Error::BusError(ErrorContext::default()),
        sdio_host2::Error::Controller => Error::BusError(ErrorContext::default()),
        _ => Error::BusError(ErrorContext::default()),
    }
}

fn host2_poll_error(err: sdio_host2::PollRequestError) -> Error {
    match err {
        sdio_host2::PollRequestError::AlreadyCompleted => Error::InvalidArgument,
        sdio_host2::PollRequestError::WrongOwner
        | sdio_host2::PollRequestError::WrongKind
        | sdio_host2::PollRequestError::StaleGeneration
        | sdio_host2::PollRequestError::RecoveryFailed => Error::BusError(ErrorContext::default()),
        _ => Error::BusError(ErrorContext::default()),
    }
}