-
Notifications
You must be signed in to change notification settings - Fork 732
/
mod.rs
1554 lines (1333 loc) · 45.6 KB
/
mod.rs
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Secure Digital / MultiMedia Card (SDMMC)
#![macro_use]
use core::default::Default;
use core::future::poll_fn;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use core::task::Poll;
use embassy_hal_internal::drop::OnDrop;
use embassy_hal_internal::{into_ref, PeripheralRef};
use embassy_sync::waitqueue::AtomicWaker;
use sdio_host::{BusWidth, CardCapacity, CardStatus, CurrentState, SDStatus, CID, CSD, OCR, SCR};
use crate::dma::NoDma;
#[cfg(gpio_v2)]
use crate::gpio::Pull;
use crate::gpio::{AfType, AnyPin, OutputType, SealedPin, Speed};
use crate::interrupt::typelevel::Interrupt;
use crate::pac::sdmmc::Sdmmc as RegBlock;
use crate::rcc::{self, RccPeripheral};
use crate::time::Hertz;
use crate::{interrupt, peripherals, Peripheral};
/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}
impl<T: Instance> InterruptHandler<T> {
fn data_interrupts(enable: bool) {
let regs = T::regs();
regs.maskr().write(|w| {
w.set_dcrcfailie(enable);
w.set_dtimeoutie(enable);
w.set_dataendie(enable);
#[cfg(sdmmc_v1)]
w.set_stbiterre(enable);
#[cfg(sdmmc_v2)]
w.set_dabortie(enable);
});
}
}
impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
Self::data_interrupts(false);
T::state().wake();
}
}
/// Frequency used for SD Card initialization. Must be no higher than 400 kHz.
const SD_INIT_FREQ: Hertz = Hertz(400_000);
/// The signalling scheme used on the SDMMC bus
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Signalling {
SDR12,
SDR25,
SDR50,
SDR104,
DDR50,
}
impl Default for Signalling {
fn default() -> Self {
Signalling::SDR12
}
}
/// Aligned data block for SDMMC transfers.
///
/// This is a 512-byte array, aligned to 4 bytes to satisfy DMA requirements.
#[repr(align(4))]
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct DataBlock(pub [u8; 512]);
impl Deref for DataBlock {
type Target = [u8; 512];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for DataBlock {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// Command Block buffer for SDMMC command transfers.
///
/// This is a 16-word array, exposed so that DMA commpatible memory can be used if required.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct CmdBlock(pub [u32; 16]);
impl CmdBlock {
/// Creates a new instance of CmdBlock
pub const fn new() -> Self {
Self([0u32; 16])
}
}
impl Deref for CmdBlock {
type Target = [u32; 16];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for CmdBlock {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
/// Errors
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
/// Timeout reported by the hardware
Timeout,
/// Timeout reported by the software driver.
SoftwareTimeout,
/// Unsupported card version.
UnsupportedCardVersion,
/// Unsupported card type.
UnsupportedCardType,
/// CRC error.
Crc,
/// No card inserted.
NoCard,
/// Bad clock supplied to the SDMMC peripheral.
BadClock,
/// Signaling switch failed.
SignalingSwitchFailed,
/// ST bit error.
#[cfg(sdmmc_v1)]
StBitErr,
}
/// A SD command
struct Cmd {
cmd: u8,
arg: u32,
resp: Response,
}
#[derive(Clone, Copy, Debug, Default)]
/// SD Card
pub struct Card {
/// The type of this card
pub card_type: CardCapacity,
/// Operation Conditions Register
pub ocr: OCR,
/// Relative Card Address
pub rca: u32,
/// Card ID
pub cid: CID,
/// Card Specific Data
pub csd: CSD,
/// SD CARD Configuration Register
pub scr: SCR,
/// SD Status
pub status: SDStatus,
}
impl Card {
/// Size in bytes
pub fn size(&self) -> u64 {
// SDHC / SDXC / SDUC
u64::from(self.csd.block_count()) * 512
}
}
#[repr(u8)]
enum PowerCtrl {
Off = 0b00,
On = 0b11,
}
#[repr(u32)]
#[allow(dead_code)]
#[allow(non_camel_case_types)]
enum CmdAppOper {
VOLTAGE_WINDOW_SD = 0x8010_0000,
HIGH_CAPACITY = 0x4000_0000,
SDMMC_STD_CAPACITY = 0x0000_0000,
SDMMC_CHECK_PATTERN = 0x0000_01AA,
SD_SWITCH_1_8V_CAPACITY = 0x0100_0000,
}
#[derive(Eq, PartialEq, Copy, Clone)]
enum Response {
None = 0,
Short = 1,
Long = 3,
}
/// Calculate clock divisor. Returns a SDMMC_CK less than or equal to
/// `sdmmc_ck` in Hertz.
///
/// Returns `(bypass, clk_div, clk_f)`, where `bypass` enables clock divisor bypass (only sdmmc_v1),
/// `clk_div` is the divisor register value and `clk_f` is the resulting new clock frequency.
#[cfg(sdmmc_v1)]
fn clk_div(ker_ck: Hertz, sdmmc_ck: u32) -> Result<(bool, u8, Hertz), Error> {
// sdmmc_v1 maximum clock is 50 MHz
if sdmmc_ck > 50_000_000 {
return Err(Error::BadClock);
}
// bypass divisor
if ker_ck.0 <= sdmmc_ck {
return Ok((true, 0, ker_ck));
}
// `ker_ck / sdmmc_ck` rounded up
let clk_div = match (ker_ck.0 + sdmmc_ck - 1) / sdmmc_ck {
0 | 1 => Ok(0),
x @ 2..=258 => Ok((x - 2) as u8),
_ => Err(Error::BadClock),
}?;
// SDIO_CK frequency = SDIOCLK / [CLKDIV + 2]
let clk_f = Hertz(ker_ck.0 / (clk_div as u32 + 2));
Ok((false, clk_div, clk_f))
}
/// Calculate clock divisor. Returns a SDMMC_CK less than or equal to
/// `sdmmc_ck` in Hertz.
///
/// Returns `(bypass, clk_div, clk_f)`, where `bypass` enables clock divisor bypass (only sdmmc_v1),
/// `clk_div` is the divisor register value and `clk_f` is the resulting new clock frequency.
#[cfg(sdmmc_v2)]
fn clk_div(ker_ck: Hertz, sdmmc_ck: u32) -> Result<(bool, u16, Hertz), Error> {
// `ker_ck / sdmmc_ck` rounded up
match (ker_ck.0 + sdmmc_ck - 1) / sdmmc_ck {
0 | 1 => Ok((false, 0, ker_ck)),
x @ 2..=2046 => {
// SDMMC_CK frequency = SDMMCCLK / [CLKDIV * 2]
let clk_div = ((x + 1) / 2) as u16;
let clk = Hertz(ker_ck.0 / (clk_div as u32 * 2));
Ok((false, clk_div, clk))
}
_ => Err(Error::BadClock),
}
}
#[cfg(sdmmc_v1)]
type Transfer<'a> = crate::dma::Transfer<'a>;
#[cfg(sdmmc_v2)]
struct Transfer<'a> {
_dummy: PhantomData<&'a ()>,
}
#[cfg(all(sdmmc_v1, dma))]
const DMA_TRANSFER_OPTIONS: crate::dma::TransferOptions = crate::dma::TransferOptions {
pburst: crate::dma::Burst::Incr4,
mburst: crate::dma::Burst::Incr4,
flow_ctrl: crate::dma::FlowControl::Peripheral,
fifo_threshold: Some(crate::dma::FifoThreshold::Full),
priority: crate::dma::Priority::VeryHigh,
circular: false,
half_transfer_ir: false,
complete_transfer_ir: true,
};
#[cfg(all(sdmmc_v1, not(dma)))]
const DMA_TRANSFER_OPTIONS: crate::dma::TransferOptions = crate::dma::TransferOptions {
priority: crate::dma::Priority::VeryHigh,
circular: false,
half_transfer_ir: false,
complete_transfer_ir: true,
};
/// SDMMC configuration
///
/// Default values:
/// data_transfer_timeout: 5_000_000
#[non_exhaustive]
pub struct Config {
/// The timeout to be set for data transfers, in card bus clock periods
pub data_transfer_timeout: u32,
}
impl Default for Config {
fn default() -> Self {
Self {
data_transfer_timeout: 5_000_000,
}
}
}
/// Sdmmc device
pub struct Sdmmc<'d, T: Instance, Dma: SdmmcDma<T> = NoDma> {
_peri: PeripheralRef<'d, T>,
#[allow(unused)]
dma: PeripheralRef<'d, Dma>,
clk: PeripheralRef<'d, AnyPin>,
cmd: PeripheralRef<'d, AnyPin>,
d0: PeripheralRef<'d, AnyPin>,
d1: Option<PeripheralRef<'d, AnyPin>>,
d2: Option<PeripheralRef<'d, AnyPin>>,
d3: Option<PeripheralRef<'d, AnyPin>>,
config: Config,
/// Current clock to card
clock: Hertz,
/// Current signalling scheme to card
signalling: Signalling,
/// Card
card: Option<Card>,
/// An optional buffer to be used for commands
/// This should be used if there are special memory location requirements for dma
cmd_block: Option<&'d mut CmdBlock>,
}
const CLK_AF: AfType = AfType::output(OutputType::PushPull, Speed::VeryHigh);
#[cfg(gpio_v1)]
const CMD_AF: AfType = AfType::output(OutputType::PushPull, Speed::VeryHigh);
#[cfg(gpio_v2)]
const CMD_AF: AfType = AfType::output_pull(OutputType::PushPull, Speed::VeryHigh, Pull::Up);
const DATA_AF: AfType = CMD_AF;
#[cfg(sdmmc_v1)]
impl<'d, T: Instance, Dma: SdmmcDma<T>> Sdmmc<'d, T, Dma> {
/// Create a new SDMMC driver, with 1 data lane.
pub fn new_1bit(
sdmmc: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
dma: impl Peripheral<P = Dma> + 'd,
clk: impl Peripheral<P = impl CkPin<T>> + 'd,
cmd: impl Peripheral<P = impl CmdPin<T>> + 'd,
d0: impl Peripheral<P = impl D0Pin<T>> + 'd,
config: Config,
) -> Self {
into_ref!(clk, cmd, d0);
critical_section::with(|_| {
clk.set_as_af(clk.af_num(), CLK_AF);
cmd.set_as_af(cmd.af_num(), CMD_AF);
d0.set_as_af(d0.af_num(), DATA_AF);
});
Self::new_inner(
sdmmc,
dma,
clk.map_into(),
cmd.map_into(),
d0.map_into(),
None,
None,
None,
config,
)
}
/// Create a new SDMMC driver, with 4 data lanes.
pub fn new_4bit(
sdmmc: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
dma: impl Peripheral<P = Dma> + 'd,
clk: impl Peripheral<P = impl CkPin<T>> + 'd,
cmd: impl Peripheral<P = impl CmdPin<T>> + 'd,
d0: impl Peripheral<P = impl D0Pin<T>> + 'd,
d1: impl Peripheral<P = impl D1Pin<T>> + 'd,
d2: impl Peripheral<P = impl D2Pin<T>> + 'd,
d3: impl Peripheral<P = impl D3Pin<T>> + 'd,
config: Config,
) -> Self {
into_ref!(clk, cmd, d0, d1, d2, d3);
critical_section::with(|_| {
clk.set_as_af(clk.af_num(), CLK_AF);
cmd.set_as_af(cmd.af_num(), CMD_AF);
d0.set_as_af(d0.af_num(), DATA_AF);
d1.set_as_af(d1.af_num(), DATA_AF);
d2.set_as_af(d2.af_num(), DATA_AF);
d3.set_as_af(d3.af_num(), DATA_AF);
});
Self::new_inner(
sdmmc,
dma,
clk.map_into(),
cmd.map_into(),
d0.map_into(),
Some(d1.map_into()),
Some(d2.map_into()),
Some(d3.map_into()),
config,
)
}
}
#[cfg(sdmmc_v2)]
impl<'d, T: Instance> Sdmmc<'d, T, NoDma> {
/// Create a new SDMMC driver, with 1 data lane.
pub fn new_1bit(
sdmmc: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
clk: impl Peripheral<P = impl CkPin<T>> + 'd,
cmd: impl Peripheral<P = impl CmdPin<T>> + 'd,
d0: impl Peripheral<P = impl D0Pin<T>> + 'd,
config: Config,
) -> Self {
into_ref!(clk, cmd, d0);
critical_section::with(|_| {
clk.set_as_af(clk.af_num(), CLK_AF);
cmd.set_as_af(cmd.af_num(), CMD_AF);
d0.set_as_af(d0.af_num(), DATA_AF);
});
Self::new_inner(
sdmmc,
NoDma.into_ref(),
clk.map_into(),
cmd.map_into(),
d0.map_into(),
None,
None,
None,
config,
)
}
/// Create a new SDMMC driver, with 4 data lanes.
pub fn new_4bit(
sdmmc: impl Peripheral<P = T> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
clk: impl Peripheral<P = impl CkPin<T>> + 'd,
cmd: impl Peripheral<P = impl CmdPin<T>> + 'd,
d0: impl Peripheral<P = impl D0Pin<T>> + 'd,
d1: impl Peripheral<P = impl D1Pin<T>> + 'd,
d2: impl Peripheral<P = impl D2Pin<T>> + 'd,
d3: impl Peripheral<P = impl D3Pin<T>> + 'd,
config: Config,
) -> Self {
into_ref!(clk, cmd, d0, d1, d2, d3);
critical_section::with(|_| {
clk.set_as_af(clk.af_num(), CLK_AF);
cmd.set_as_af(cmd.af_num(), CMD_AF);
d0.set_as_af(d0.af_num(), DATA_AF);
d1.set_as_af(d1.af_num(), DATA_AF);
d2.set_as_af(d2.af_num(), DATA_AF);
d3.set_as_af(d3.af_num(), DATA_AF);
});
Self::new_inner(
sdmmc,
NoDma.into_ref(),
clk.map_into(),
cmd.map_into(),
d0.map_into(),
Some(d1.map_into()),
Some(d2.map_into()),
Some(d3.map_into()),
config,
)
}
}
impl<'d, T: Instance, Dma: SdmmcDma<T> + 'd> Sdmmc<'d, T, Dma> {
fn new_inner(
sdmmc: impl Peripheral<P = T> + 'd,
dma: impl Peripheral<P = Dma> + 'd,
clk: PeripheralRef<'d, AnyPin>,
cmd: PeripheralRef<'d, AnyPin>,
d0: PeripheralRef<'d, AnyPin>,
d1: Option<PeripheralRef<'d, AnyPin>>,
d2: Option<PeripheralRef<'d, AnyPin>>,
d3: Option<PeripheralRef<'d, AnyPin>>,
config: Config,
) -> Self {
into_ref!(sdmmc, dma);
rcc::enable_and_reset::<T>();
T::Interrupt::unpend();
unsafe { T::Interrupt::enable() };
let regs = T::regs();
regs.clkcr().write(|w| {
w.set_pwrsav(false);
w.set_negedge(false);
// Hardware flow control is broken on SDIOv1 and causes clock glitches, which result in CRC errors.
// See chip erratas for more details.
#[cfg(sdmmc_v1)]
w.set_hwfc_en(false);
#[cfg(sdmmc_v2)]
w.set_hwfc_en(true);
#[cfg(sdmmc_v1)]
w.set_clken(true);
});
// Power off, writen 00: Clock to the card is stopped;
// D[7:0], CMD, and CK are driven high.
regs.power().modify(|w| w.set_pwrctrl(PowerCtrl::Off as u8));
Self {
_peri: sdmmc,
dma,
clk,
cmd,
d0,
d1,
d2,
d3,
config,
clock: SD_INIT_FREQ,
signalling: Default::default(),
card: None,
cmd_block: None,
}
}
/// Data transfer is in progress
#[inline]
fn data_active() -> bool {
let regs = T::regs();
let status = regs.star().read();
#[cfg(sdmmc_v1)]
return status.rxact() || status.txact();
#[cfg(sdmmc_v2)]
return status.dpsmact();
}
/// Coammand transfer is in progress
#[inline]
fn cmd_active() -> bool {
let regs = T::regs();
let status = regs.star().read();
#[cfg(sdmmc_v1)]
return status.cmdact();
#[cfg(sdmmc_v2)]
return status.cpsmact();
}
/// Wait idle on CMDACT, RXACT and TXACT (v1) or DOSNACT and CPSMACT (v2)
#[inline]
fn wait_idle() {
while Self::data_active() || Self::cmd_active() {}
}
/// # Safety
///
/// `buffer` must be valid for the whole transfer and word aligned
#[allow(unused_variables)]
fn prepare_datapath_read<'a>(
config: &Config,
dma: &'a mut PeripheralRef<'d, Dma>,
buffer: &'a mut [u32],
length_bytes: u32,
block_size: u8,
) -> Transfer<'a> {
assert!(block_size <= 14, "Block size up to 2^14 bytes");
let regs = T::regs();
// Command AND Data state machines must be idle
Self::wait_idle();
Self::clear_interrupt_flags();
regs.dtimer().write(|w| w.set_datatime(config.data_transfer_timeout));
regs.dlenr().write(|w| w.set_datalength(length_bytes));
#[cfg(sdmmc_v1)]
let transfer = unsafe {
let request = dma.request();
Transfer::new_read(
dma,
request,
regs.fifor().as_ptr() as *mut u32,
buffer,
DMA_TRANSFER_OPTIONS,
)
};
#[cfg(sdmmc_v2)]
let transfer = {
regs.idmabase0r().write(|w| w.set_idmabase0(buffer.as_mut_ptr() as u32));
regs.idmactrlr().modify(|w| w.set_idmaen(true));
Transfer {
_dummy: core::marker::PhantomData,
}
};
regs.dctrl().modify(|w| {
w.set_dblocksize(block_size);
w.set_dtdir(true);
#[cfg(sdmmc_v1)]
{
w.set_dmaen(true);
w.set_dten(true);
}
});
transfer
}
/// # Safety
///
/// `buffer` must be valid for the whole transfer and word aligned
fn prepare_datapath_write<'a>(&'a mut self, buffer: &'a [u32], length_bytes: u32, block_size: u8) -> Transfer<'a> {
assert!(block_size <= 14, "Block size up to 2^14 bytes");
let regs = T::regs();
// Command AND Data state machines must be idle
Self::wait_idle();
Self::clear_interrupt_flags();
regs.dtimer()
.write(|w| w.set_datatime(self.config.data_transfer_timeout));
regs.dlenr().write(|w| w.set_datalength(length_bytes));
#[cfg(sdmmc_v1)]
let transfer = unsafe {
let request = self.dma.request();
Transfer::new_write(
&mut self.dma,
request,
buffer,
regs.fifor().as_ptr() as *mut u32,
DMA_TRANSFER_OPTIONS,
)
};
#[cfg(sdmmc_v2)]
let transfer = {
regs.idmabase0r().write(|w| w.set_idmabase0(buffer.as_ptr() as u32));
regs.idmactrlr().modify(|w| w.set_idmaen(true));
Transfer {
_dummy: core::marker::PhantomData,
}
};
regs.dctrl().modify(|w| {
w.set_dblocksize(block_size);
w.set_dtdir(false);
#[cfg(sdmmc_v1)]
{
w.set_dmaen(true);
w.set_dten(true);
}
});
transfer
}
/// Stops the DMA datapath
fn stop_datapath() {
let regs = T::regs();
#[cfg(sdmmc_v1)]
regs.dctrl().modify(|w| {
w.set_dmaen(false);
w.set_dten(false);
});
#[cfg(sdmmc_v2)]
regs.idmactrlr().modify(|w| w.set_idmaen(false));
}
/// Sets the CLKDIV field in CLKCR. Updates clock field in self
fn clkcr_set_clkdiv(&mut self, freq: u32, width: BusWidth) -> Result<(), Error> {
let regs = T::regs();
let width_u32 = match width {
BusWidth::One => 1u32,
BusWidth::Four => 4u32,
BusWidth::Eight => 8u32,
_ => panic!("Invalid Bus Width"),
};
let ker_ck = T::frequency();
let (_bypass, clkdiv, new_clock) = clk_div(ker_ck, freq)?;
// Enforce AHB and SDMMC_CK clock relation. See RM0433 Rev 7
// Section 55.5.8
let sdmmc_bus_bandwidth = new_clock.0 * width_u32;
assert!(ker_ck.0 > 3 * sdmmc_bus_bandwidth / 32);
self.clock = new_clock;
// CPSMACT and DPSMACT must be 0 to set CLKDIV
Self::wait_idle();
regs.clkcr().modify(|w| {
w.set_clkdiv(clkdiv);
#[cfg(sdmmc_v1)]
w.set_bypass(_bypass);
});
Ok(())
}
/// Switch mode using CMD6.
///
/// Attempt to set a new signalling mode. The selected
/// signalling mode is returned. Expects the current clock
/// frequency to be > 12.5MHz.
async fn switch_signalling_mode(&mut self, signalling: Signalling) -> Result<Signalling, Error> {
// NB PLSS v7_10 4.3.10.4: "the use of SET_BLK_LEN command is not
// necessary"
let set_function = 0x8000_0000
| match signalling {
// See PLSS v7_10 Table 4-11
Signalling::DDR50 => 0xFF_FF04,
Signalling::SDR104 => 0xFF_1F03,
Signalling::SDR50 => 0xFF_1F02,
Signalling::SDR25 => 0xFF_FF01,
Signalling::SDR12 => 0xFF_FF00,
};
let status = match self.cmd_block.as_deref_mut() {
Some(x) => x,
None => &mut CmdBlock::new(),
};
// Arm `OnDrop` after the buffer, so it will be dropped first
let regs = T::regs();
let on_drop = OnDrop::new(|| Self::on_drop());
let transfer = Self::prepare_datapath_read(&self.config, &mut self.dma, status.as_mut(), 64, 6);
InterruptHandler::<T>::data_interrupts(true);
Self::cmd(Cmd::cmd6(set_function), true)?; // CMD6
let res = poll_fn(|cx| {
T::state().register(cx.waker());
let status = regs.star().read();
if status.dcrcfail() {
return Poll::Ready(Err(Error::Crc));
}
if status.dtimeout() {
return Poll::Ready(Err(Error::Timeout));
}
#[cfg(sdmmc_v1)]
if status.stbiterr() {
return Poll::Ready(Err(Error::StBitErr));
}
if status.dataend() {
return Poll::Ready(Ok(()));
}
Poll::Pending
})
.await;
Self::clear_interrupt_flags();
// Host is allowed to use the new functions at least 8
// clocks after the end of the switch command
// transaction. We know the current clock period is < 80ns,
// so a total delay of 640ns is required here
for _ in 0..300 {
cortex_m::asm::nop();
}
match res {
Ok(_) => {
on_drop.defuse();
Self::stop_datapath();
drop(transfer);
// Function Selection of Function Group 1
let selection = (u32::from_be(status[4]) >> 24) & 0xF;
match selection {
0 => Ok(Signalling::SDR12),
1 => Ok(Signalling::SDR25),
2 => Ok(Signalling::SDR50),
3 => Ok(Signalling::SDR104),
4 => Ok(Signalling::DDR50),
_ => Err(Error::UnsupportedCardType),
}
}
Err(e) => Err(e),
}
}
/// Query the card status (CMD13, returns R1)
fn read_status(&self, card: &Card) -> Result<CardStatus, Error> {
let regs = T::regs();
let rca = card.rca;
Self::cmd(Cmd::card_status(rca << 16), false)?; // CMD13
let r1 = regs.respr(0).read().cardstatus();
Ok(r1.into())
}
/// Reads the SD Status (ACMD13)
async fn read_sd_status(&mut self) -> Result<(), Error> {
let card = self.card.as_mut().ok_or(Error::NoCard)?;
let rca = card.rca;
let cmd_block = match self.cmd_block.as_deref_mut() {
Some(x) => x,
None => &mut CmdBlock::new(),
};
Self::cmd(Cmd::set_block_length(64), false)?; // CMD16
Self::cmd(Cmd::app_cmd(rca << 16), false)?; // APP
let status = cmd_block;
// Arm `OnDrop` after the buffer, so it will be dropped first
let regs = T::regs();
let on_drop = OnDrop::new(|| Self::on_drop());
let transfer = Self::prepare_datapath_read(&self.config, &mut self.dma, status.as_mut(), 64, 6);
InterruptHandler::<T>::data_interrupts(true);
Self::cmd(Cmd::card_status(0), true)?;
let res = poll_fn(|cx| {
T::state().register(cx.waker());
let status = regs.star().read();
if status.dcrcfail() {
return Poll::Ready(Err(Error::Crc));
}
if status.dtimeout() {
return Poll::Ready(Err(Error::Timeout));
}
#[cfg(sdmmc_v1)]
if status.stbiterr() {
return Poll::Ready(Err(Error::StBitErr));
}
if status.dataend() {
return Poll::Ready(Ok(()));
}
Poll::Pending
})
.await;
Self::clear_interrupt_flags();
if res.is_ok() {
on_drop.defuse();
Self::stop_datapath();
drop(transfer);
for byte in status.iter_mut() {
*byte = u32::from_be(*byte);
}
self.card.as_mut().unwrap().status = status.0.into();
}
res
}
/// Select one card and place it into the _Tranfer State_
///
/// If `None` is specifed for `card`, all cards are put back into
/// _Stand-by State_
fn select_card(&self, card: Option<&Card>) -> Result<(), Error> {
// Determine Relative Card Address (RCA) of given card
let rca = card.map(|c| c.rca << 16).unwrap_or(0);
let r = Self::cmd(Cmd::sel_desel_card(rca), false);
match (r, rca) {
(Err(Error::Timeout), 0) => Ok(()),
_ => r,
}
}
/// Clear flags in interrupt clear register
#[inline]
fn clear_interrupt_flags() {
let regs = T::regs();
regs.icr().write(|w| {
w.set_ccrcfailc(true);
w.set_dcrcfailc(true);
w.set_ctimeoutc(true);
w.set_dtimeoutc(true);
w.set_txunderrc(true);
w.set_rxoverrc(true);
w.set_cmdrendc(true);
w.set_cmdsentc(true);
w.set_dataendc(true);
w.set_dbckendc(true);
w.set_sdioitc(true);
#[cfg(sdmmc_v1)]
w.set_stbiterrc(true);
#[cfg(sdmmc_v2)]
{
w.set_dholdc(true);
w.set_dabortc(true);
w.set_busyd0endc(true);
w.set_ackfailc(true);
w.set_acktimeoutc(true);
w.set_vswendc(true);
w.set_ckstopc(true);
w.set_idmatec(true);
w.set_idmabtcc(true);
}
});
}
async fn get_scr(&mut self, card: &mut Card) -> Result<(), Error> {
// Read the the 64-bit SCR register
Self::cmd(Cmd::set_block_length(8), false)?; // CMD16
Self::cmd(Cmd::app_cmd(card.rca << 16), false)?;
let cmd_block = match self.cmd_block.as_deref_mut() {
Some(x) => x,
None => &mut CmdBlock::new(),
};
let scr = &mut cmd_block.0[..2];
// Arm `OnDrop` after the buffer, so it will be dropped first
let regs = T::regs();
let on_drop = OnDrop::new(|| Self::on_drop());
let transfer = Self::prepare_datapath_read(&self.config, &mut self.dma, scr, 8, 3);
InterruptHandler::<T>::data_interrupts(true);
Self::cmd(Cmd::cmd51(), true)?;
let res = poll_fn(|cx| {
T::state().register(cx.waker());
let status = regs.star().read();
if status.dcrcfail() {
return Poll::Ready(Err(Error::Crc));
}
if status.dtimeout() {
return Poll::Ready(Err(Error::Timeout));
}
#[cfg(sdmmc_v1)]
if status.stbiterr() {
return Poll::Ready(Err(Error::StBitErr));
}
if status.dataend() {
return Poll::Ready(Ok(()));
}
Poll::Pending
})
.await;
Self::clear_interrupt_flags();
if res.is_ok() {
on_drop.defuse();
Self::stop_datapath();
drop(transfer);
unsafe {
let scr_bytes = &*(&scr as *const _ as *const [u8; 8]);
card.scr = SCR(u64::from_be_bytes(*scr_bytes));
}
}
res
}
/// Send command to card
#[allow(unused_variables)]
fn cmd(cmd: Cmd, data: bool) -> Result<(), Error> {
let regs = T::regs();
Self::clear_interrupt_flags();
// CP state machine must be idle
while Self::cmd_active() {}
// Command arg
regs.argr().write(|w| w.set_cmdarg(cmd.arg));
// Command index and start CP State Machine
regs.cmdr().write(|w| {
w.set_waitint(false);
w.set_waitresp(cmd.resp as u8);
w.set_cmdindex(cmd.cmd);
w.set_cpsmen(true);
#[cfg(sdmmc_v2)]
{
// Special mode in CP State Machine
// CMD12: Stop Transmission
let cpsm_stop_transmission = cmd.cmd == 12;
w.set_cmdstop(cpsm_stop_transmission);
w.set_cmdtrans(data);
}
});
let mut status;
if cmd.resp == Response::None {
// Wait for CMDSENT or a timeout
while {
status = regs.star().read();
!(status.ctimeout() || status.cmdsent())