sdio-host2 0.1.0

no_std SD/SDIO/MMC host bus transaction traits and types
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
//! Physical SD/SDIO/MMC host-bus transaction traits.
//!
//! This crate intentionally models the shared CMD/DAT bus rather than a card,
//! block device, filesystem, or runtime queue. A host accepts one transaction
//! at a time: a command, an optional data phase, and a task-side poll path to
//! observe completion. Higher-level SD/MMC card protocols live in
//! `sdmmc-protocol`.

#![no_std]

extern crate alloc;

use alloc::boxed::Box;
use core::{
    fmt,
    num::{NonZeroU16, NonZeroU32},
};

use dma_api::{CompletedDma, DmaDirection, PreparedDma};

/// SD/SDIO/MMC command packet submitted on the CMD line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Command {
    pub index: u8,
    pub argument: u32,
    pub response: ResponseType,
}

impl Command {
    pub const fn new(index: u8, argument: u32, response: ResponseType) -> Self {
        Self {
            index,
            argument,
            response,
        }
    }

    pub const fn index(self) -> u8 {
        self.index
    }

    pub const fn argument(self) -> u32 {
        self.argument
    }

    pub const fn with_response(self, response: ResponseType) -> Self {
        Self { response, ..self }
    }

    /// Return a copy of this command with its response type overridden.
    ///
    /// Kept as a compatibility alias for existing SD/MMC protocol helpers.
    pub const fn with_resp_type(self, response: ResponseType) -> Self {
        self.with_response(response)
    }

    /// Compatibility alias for older SD/MMC command helpers.
    pub const fn cmd(self) -> u8 {
        self.index
    }

    /// Compatibility alias for older SD/MMC command helpers.
    pub const fn arg(self) -> u32 {
        self.argument
    }

    /// Direction of the data phase that follows this command when it is
    /// unambiguous from the command index alone.
    ///
    /// SDIO CMD53 carries its direction in the argument; CMD6 is also
    /// overloaded between ACMD6 and SWITCH_FUNC, so both return `None`.
    pub const fn data_direction(&self) -> Option<DataDirection> {
        match self.index {
            17 | 18 => Some(DataDirection::Read),
            24 | 25 => Some(DataDirection::Write),
            _ => None,
        }
    }

    /// Size in bytes of the data block when fixed by the command index.
    pub const fn data_block_size(&self) -> Option<u32> {
        match self.index {
            17 | 18 | 24 | 25 => Some(512),
            _ => None,
        }
    }

    /// Compute the SD SPI-mode CRC7 for this command packet.
    pub fn crc7(&self) -> u8 {
        let mut crc: u8 = 0;
        let token: u8 = 0x40 | (self.index & 0x3F);
        crc = crc7_update(crc, token);
        for byte in self.argument.to_be_bytes() {
            crc = crc7_update(crc, byte);
        }
        (crc << 1) | 1
    }

    /// Build the 6-byte SD SPI command packet.
    pub fn to_spi_bytes(&self) -> [u8; 6] {
        let crc = self.crc7();
        let token = 0x40 | (self.index & 0x3F);
        let arg = self.argument.to_be_bytes();
        [token, arg[0], arg[1], arg[2], arg[3], crc]
    }
}

fn crc7_update(crc: u8, byte: u8) -> u8 {
    let mut crc = crc;
    let mut data = byte;
    for _ in 0..8 {
        crc <<= 1;
        if (crc ^ data) & 0x80 != 0 {
            crc ^= 0x89;
        }
        data <<= 1;
    }
    crc
}

/// Command response shape expected from the card.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseType {
    None,
    R1,
    R1b,
    R2,
    R3,
    R4,
    R5,
    R6,
    R7,
}

/// Raw response words harvested by a host controller.
///
/// ABI:
///
/// - 48-bit responses store their response payload in `words[0]`.
/// - R2/CID/CSD responses store four 32-bit words in most-significant-word
///   first order.
/// - Each word is the big-endian value of the corresponding response bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawResponse {
    pub ty: ResponseType,
    pub words: [u32; 4],
}

impl RawResponse {
    pub const fn new(ty: ResponseType, words: [u32; 4]) -> Self {
        Self { ty, words }
    }

    pub const fn empty() -> Self {
        Self {
            ty: ResponseType::None,
            words: [0; 4],
        }
    }
}

/// Direction of a data phase on DAT lines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DataDirection {
    Read,
    Write,
}

/// Caller-owned data buffer tied to an in-flight transaction lifetime.
pub enum DataBuffer<'a> {
    Read(&'a mut [u8]),
    Write(&'a [u8]),
    Dma(PreparedDma),
}

impl DataBuffer<'_> {
    pub fn len(&self) -> usize {
        match self {
            Self::Read(buf) => buf.len(),
            Self::Write(buf) => buf.len(),
            Self::Dma(buffer) => buffer.len().get(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    pub fn matches_direction(&self, direction: DataDirection) -> bool {
        match self {
            Self::Read(_) => direction == DataDirection::Read,
            Self::Write(_) => direction == DataDirection::Write,
            Self::Dma(buffer) => matches!(
                (buffer.direction(), direction),
                (DmaDirection::FromDevice, DataDirection::Read)
                    | (DmaDirection::ToDevice, DataDirection::Write)
                    | (DmaDirection::Bidirectional, _)
            ),
        }
    }
}

pub type DataTransfer<'a> = DataBuffer<'a>;

/// Error returned while constructing an owned-DMA data phase.
pub struct DmaPhaseError {
    error: Error,
    buffer: Box<PreparedDma>,
}

impl DmaPhaseError {
    fn new(error: Error, buffer: PreparedDma) -> Self {
        Self {
            error,
            buffer: Box::new(buffer),
        }
    }

    pub const fn error(&self) -> Error {
        self.error
    }

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

    pub fn into_parts(self) -> (Error, PreparedDma) {
        (self.error, *self.buffer)
    }
}

impl fmt::Debug for DmaPhaseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DmaPhaseError")
            .field("error", &self.error)
            .finish_non_exhaustive()
    }
}

impl fmt::Display for DmaPhaseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.error.fmt(f)
    }
}

impl core::error::Error for DmaPhaseError {}

/// Optional data phase associated with a command.
pub struct DataPhase<'a> {
    pub direction: DataDirection,
    pub block_size: NonZeroU16,
    pub block_count: NonZeroU32,
    pub buffer: DataBuffer<'a>,
}

impl<'a> DataPhase<'a> {
    pub fn read(
        block_size: NonZeroU16,
        block_count: NonZeroU32,
        buffer: &'a mut [u8],
    ) -> Result<Self, Error> {
        let phase = Self {
            direction: DataDirection::Read,
            block_size,
            block_count,
            buffer: DataBuffer::Read(buffer),
        };
        phase.validate()?;
        Ok(phase)
    }

    pub fn write(
        block_size: NonZeroU16,
        block_count: NonZeroU32,
        buffer: &'a [u8],
    ) -> Result<Self, Error> {
        let phase = Self {
            direction: DataDirection::Write,
            block_size,
            block_count,
            buffer: DataBuffer::Write(buffer),
        };
        phase.validate()?;
        Ok(phase)
    }

    pub fn dma(
        direction: DataDirection,
        block_size: NonZeroU16,
        block_count: NonZeroU32,
        buffer: PreparedDma,
    ) -> Result<Self, DmaPhaseError> {
        let phase = Self {
            direction,
            block_size,
            block_count,
            buffer: DataBuffer::Dma(buffer),
        };
        match phase.validate() {
            Ok(()) => Ok(phase),
            Err(err) => {
                let DataBuffer::Dma(buffer) = phase.buffer else {
                    unreachable!("DataPhase::dma always stores a DMA buffer")
                };
                Err(DmaPhaseError::new(err, buffer))
            }
        }
    }

    pub fn validate(&self) -> Result<(), Error> {
        let expected = usize::from(self.block_size.get())
            .checked_mul(
                usize::try_from(self.block_count.get()).map_err(|_| Error::InvalidArgument)?,
            )
            .ok_or(Error::InvalidArgument)?;
        if self.buffer.len() != expected {
            return Err(Error::InvalidArgument);
        }
        if !self.buffer.matches_direction(self.direction) {
            return Err(Error::InvalidArgument);
        }
        Ok(())
    }
}

/// One physical bus transaction: a command and an optional data phase.
pub struct Transaction<'a> {
    pub command: Command,
    pub data: Option<DataPhase<'a>>,
}

impl<'a> Transaction<'a> {
    pub const fn command(command: Command) -> Self {
        Self {
            command,
            data: None,
        }
    }

    pub const fn with_data(command: Command, data: DataPhase<'a>) -> Self {
        Self {
            command,
            data: Some(data),
        }
    }
}

/// Submit failure for an owned transaction.
///
/// When `transaction` is present, the caller may recover and retry the DMA
/// backing. When it is absent, the host had to consume/quiesce the transaction
/// while handling the error; no hardware access remains active on return.
pub struct SubmitTransactionError<'a> {
    pub error: Error,
    transaction: Option<Box<Transaction<'a>>>,
}

impl<'a> SubmitTransactionError<'a> {
    pub fn new(error: Error, transaction: Transaction<'a>) -> Self {
        Self {
            error,
            transaction: Some(Box::new(transaction)),
        }
    }

    pub const fn consumed(error: Error) -> Self {
        Self {
            error,
            transaction: None,
        }
    }

    pub fn into_transaction(self) -> Option<Transaction<'a>> {
        self.transaction.map(|transaction| *transaction)
    }
}

/// Result of advancing a submitted request once.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RequestPoll<T> {
    Pending,
    Ready(Result<T, Error>),
}

/// Error returned when a request is polled through the wrong handle or after
/// its terminal state.
///
/// Unlike [`RequestPoll::Ready`], this is not a transfer terminal state for
/// the request payload. Implementations must not report a terminal
/// [`RequestPoll::Ready`] error until the controller is no longer accessing
/// the transaction buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PollRequestError {
    WrongOwner,
    WrongKind,
    AlreadyCompleted,
    StaleGeneration,
    /// Recovery could not be reported through the requested handle.
    ///
    /// Safe host implementations must still quiesce the hardware before any
    /// request object that borrows caller memory can be dropped. This variant
    /// is diagnostic only; it must not mean DMA is still active.
    RecoveryFailed,
}

/// SD/SDIO/MMC bus width.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BusWidth {
    Bit1,
    Bit4,
    Bit8,
}

/// Named card clock modes used by SD/MMC protocol state machines.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClockSpeed {
    Identification,
    Default,
    HighSpeed,
    Sdr12,
    Sdr25,
    Sdr50,
    Sdr104,
    Ddr50,
    Hs200,
}

/// Concrete clock frequency request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct ClockHz(pub u32);

/// Bus signaling voltage.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SignalVoltage {
    V330,
    V180,
    V120,
}

/// Non-data bus operation that may itself need asynchronous completion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BusOp {
    ResetAll,
    ResetCommandLine,
    ResetDataLine,
    PowerOn,
    PowerOff,
    SetClock(ClockSpeed),
    SetClockHz(ClockHz),
    SetBusWidth(BusWidth),
    SetSignalVoltage(SignalVoltage),
    ExecuteTuning {
        command: Command,
        block_size: NonZeroU16,
    },
}

/// Host/bus-layer error.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    Busy,
    Timeout,
    Crc,
    NoCard,
    Unsupported,
    InvalidArgument,
    Misaligned,
    Bus,
    Controller,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::Busy => "host bus is busy",
            Self::Timeout => "host bus timeout",
            Self::Crc => "host bus CRC error",
            Self::NoCard => "no card present",
            Self::Unsupported => "operation is not supported",
            Self::InvalidArgument => "invalid host bus argument",
            Self::Misaligned => "misaligned host bus buffer",
            Self::Bus => "host bus error",
            Self::Controller => "host controller error",
        };
        f.write_str(s)
    }
}

impl core::error::Error for Error {}

impl fmt::Display for PollRequestError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::WrongOwner => "request belongs to a different host",
            Self::WrongKind => "request was polled through the wrong operation kind",
            Self::AlreadyCompleted => "request has already completed",
            Self::StaleGeneration => "request generation is no longer active",
            Self::RecoveryFailed => "request recovery failed",
        };
        f.write_str(s)
    }
}

impl core::error::Error for PollRequestError {}

/// Physical SD/SDIO/MMC host bus.
///
/// The base contract is single active transaction: a host may reject a submit
/// with [`Error::Busy`] while another transaction or bus operation is active.
pub trait SdioHost {
    type TransactionRequest<'a>
    where
        Self: 'a;
    type BusRequest;

    /// Submit one CMD/DAT transaction.
    ///
    /// # Safety
    ///
    /// Callers must poll the returned request until [`RequestPoll::Ready`] or
    /// call [`Self::abort_transaction`] before dropping it. Until one of those
    /// terminal paths runs, the host may still access the associated data
    /// buffer through DMA or FIFO PIO.
    unsafe fn submit_transaction<'a>(
        &mut self,
        transaction: Transaction<'a>,
    ) -> Result<Self::TransactionRequest<'a>, Error>
    where
        Self: 'a;

    /// Submit one CMD/DAT transaction while preserving transaction ownership
    /// on submit-side failure when the host has not started hardware access.
    ///
    /// The default path is kept for legacy hosts. Native DMA users should
    /// override it so submit failure can return the original transaction.
    ///
    /// # Safety
    ///
    /// Same lifetime contract as [`Self::submit_transaction`].
    unsafe fn submit_transaction_owned<'a>(
        &mut self,
        transaction: Transaction<'a>,
    ) -> Result<Self::TransactionRequest<'a>, SubmitTransactionError<'a>>
    where
        Self: 'a,
    {
        match unsafe { self.submit_transaction(transaction) } {
            Ok(request) => Ok(request),
            Err(error) => Err(SubmitTransactionError::consumed(error)),
        }
    }

    fn poll_transaction<'a>(
        &mut self,
        request: &mut Self::TransactionRequest<'a>,
    ) -> Result<RequestPoll<RawResponse>, PollRequestError>
    where
        Self: 'a;

    /// Abort a transaction.
    ///
    /// This is part of the safe lifetime contract for borrowed transaction
    /// buffers. Implementations may return an error to report that the
    /// controller had to be reset or poisoned, but before returning they must
    /// have stopped command/data engines and any DMA bus-master access that
    /// could still touch the request buffer.
    fn abort_transaction<'a>(
        &mut self,
        request: &mut Self::TransactionRequest<'a>,
    ) -> Result<(), Error>
    where
        Self: 'a;

    fn take_completed_dma<'a>(
        &mut self,
        _request: &mut Self::TransactionRequest<'a>,
    ) -> Option<CompletedDma>
    where
        Self: 'a,
    {
        None
    }

    /// Submit one non-data bus operation.
    ///
    /// # Safety
    ///
    /// The returned request must be polled until [`RequestPoll::Ready`] or
    /// passed to [`Self::abort_bus_op`] before being dropped.
    unsafe fn submit_bus_op(&mut self, op: BusOp) -> Result<Self::BusRequest, Error>;

    fn poll_bus_op(
        &mut self,
        request: &mut Self::BusRequest,
    ) -> Result<RequestPoll<()>, PollRequestError>;

    /// Abort a bus operation.
    ///
    /// Like [`Self::abort_transaction`], returning from this method means the
    /// controller is no longer executing the operation even when the return
    /// value carries a diagnostic error.
    fn abort_bus_op(&mut self, request: &mut Self::BusRequest) -> Result<(), Error>;

    fn now_ms(&self) -> Option<u64> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct MockHost {
        busy: bool,
    }

    #[derive(Debug)]
    struct MockTransactionRequest {
        response: RawResponse,
        pending_once: bool,
        done: bool,
    }

    #[derive(Debug)]
    struct MockBusRequest {
        pending_once: bool,
        done: bool,
    }

    impl SdioHost for MockHost {
        type TransactionRequest<'a>
            = MockTransactionRequest
        where
            Self: 'a;
        type BusRequest = MockBusRequest;

        unsafe fn submit_transaction<'a>(
            &mut self,
            transaction: Transaction<'a>,
        ) -> Result<Self::TransactionRequest<'a>, Error>
        where
            Self: 'a,
        {
            if self.busy {
                return Err(Error::Busy);
            }
            self.busy = true;
            Ok(MockTransactionRequest {
                response: RawResponse::new(transaction.command.response, [0x1234, 0, 0, 0]),
                pending_once: true,
                done: false,
            })
        }

        fn poll_transaction<'a>(
            &mut self,
            request: &mut Self::TransactionRequest<'a>,
        ) -> Result<RequestPoll<RawResponse>, PollRequestError>
        where
            Self: 'a,
        {
            if request.done {
                return Err(PollRequestError::AlreadyCompleted);
            }
            if request.pending_once {
                request.pending_once = false;
                return Ok(RequestPoll::Pending);
            }
            self.busy = false;
            request.done = true;
            Ok(RequestPoll::Ready(Ok(request.response)))
        }

        fn abort_transaction<'a>(
            &mut self,
            request: &mut Self::TransactionRequest<'a>,
        ) -> Result<(), Error>
        where
            Self: 'a,
        {
            request.done = true;
            self.busy = false;
            Ok(())
        }

        unsafe fn submit_bus_op(&mut self, _op: BusOp) -> Result<Self::BusRequest, Error> {
            if self.busy {
                return Err(Error::Busy);
            }
            self.busy = true;
            Ok(MockBusRequest {
                pending_once: false,
                done: false,
            })
        }

        fn poll_bus_op(
            &mut self,
            request: &mut Self::BusRequest,
        ) -> Result<RequestPoll<()>, PollRequestError> {
            if request.done {
                return Err(PollRequestError::AlreadyCompleted);
            }
            if request.pending_once {
                request.pending_once = false;
                return Ok(RequestPoll::Pending);
            }
            self.busy = false;
            request.done = true;
            Ok(RequestPoll::Ready(Ok(())))
        }

        fn abort_bus_op(&mut self, request: &mut Self::BusRequest) -> Result<(), Error> {
            request.done = true;
            self.busy = false;
            Ok(())
        }
    }

    #[test]
    fn data_phase_validates_buffer_shape() {
        let mut read = [0u8; 1024];
        let block = NonZeroU16::new(512).unwrap();
        let phase = DataPhase::read(block, NonZeroU32::new(2).unwrap(), &mut read).unwrap();
        assert_eq!(phase.direction, DataDirection::Read);
        assert_eq!(phase.buffer.len(), 1024);
    }

    #[test]
    fn host_reports_busy_for_second_active_transaction() {
        let mut host = MockHost { busy: false };
        let cmd = Command::new(17, 0, ResponseType::R1);
        let mut request = unsafe { host.submit_transaction(Transaction::command(cmd)) }.unwrap();
        assert_eq!(
            unsafe { host.submit_transaction(Transaction::command(cmd)) }.unwrap_err(),
            Error::Busy
        );
        assert_eq!(
            host.poll_transaction(&mut request),
            Ok(RequestPoll::Pending)
        );
        assert!(matches!(
            host.poll_transaction(&mut request),
            Ok(RequestPoll::Ready(Ok(_)))
        ));
        assert_eq!(
            host.poll_transaction(&mut request),
            Err(PollRequestError::AlreadyCompleted)
        );
        assert!(unsafe { host.submit_transaction(Transaction::command(cmd)) }.is_ok());
    }

    #[test]
    fn bus_op_uses_same_single_active_contract() {
        let mut host = MockHost { busy: false };
        let _request = unsafe { host.submit_bus_op(BusOp::SetClock(ClockSpeed::Default)) }.unwrap();
        assert_eq!(
            unsafe { host.submit_bus_op(BusOp::SetBusWidth(BusWidth::Bit4)) }.unwrap_err(),
            Error::Busy
        );
    }

    #[test]
    fn abort_releases_single_active_contract() {
        let mut host = MockHost { busy: false };
        let cmd = Command::new(17, 0, ResponseType::R1);
        let mut request = unsafe { host.submit_transaction(Transaction::command(cmd)) }.unwrap();

        host.abort_transaction(&mut request).unwrap();

        assert!(unsafe { host.submit_transaction(Transaction::command(cmd)) }.is_ok());
        assert_eq!(
            host.poll_transaction(&mut request),
            Err(PollRequestError::AlreadyCompleted)
        );
    }
}