1use embedded_hal_async::delay::DelayNs;
2use embedded_hal_async::spi::{Operation, SpiBus, SpiDevice};
3
4use crate::{BlockDevice, BLOCK_SIZE};
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10#[non_exhaustive]
11pub enum SpiError<E> {
12 Spi(E),
14 Timeout,
16 BadResponse(u8),
18 BadCrc,
20 UnsupportedCard,
22 OutOfRange,
24 WriteRejected(u8),
27}
28
29const READ_TOKEN_POLLS: u32 = 2_000;
31const READ_TOKEN_POLL_US: u32 = 50;
32
33const READ_RETRIES: usize = 2;
35
36#[cfg(feature = "write")]
38const WRITE_RETRIES: usize = 2;
39#[cfg(feature = "write")]
41const WRITE_FAST_POLLS: u32 = 64;
42#[cfg(feature = "write")]
43const WRITE_SLOW_POLLS: u32 = 500;
44
45const R1_WINDOW: usize = 8;
47const MIN_TOKEN_WINDOW: usize = 32;
50const START_TOKEN_WINDOW: usize = 256;
51const MAX_TOKEN_WINDOW: usize = 2_048;
52const SCRATCH: usize = R1_WINDOW + MAX_TOKEN_WINDOW + 1 + BLOCK_SIZE + 2;
53
54pub async fn send_init_clocks<B: SpiBus<u8>>(bus: &mut B) -> Result<(), B::Error> {
58 bus.write(&[0xff; 10]).await?;
59 bus.flush().await
60}
61
62pub struct SpiSdCard<SPI, D> {
79 spi: SPI,
80 delay: D,
81 high_capacity: bool,
82 blocks: u32,
83 check_crc: bool,
84 token_window: usize,
85 scratch: [u8; SCRATCH],
86}
87
88#[derive(Clone, Copy)]
89enum Reply {
90 R1,
91 R1WithFourBytes,
92}
93
94#[derive(Clone, Copy)]
95struct Response {
96 r1: u8,
97 extra: [u8; 4],
98}
99
100impl<SPI, D> SpiSdCard<SPI, D>
101where
102 SPI: SpiDevice<u8>,
103 D: DelayNs,
104{
105 pub async fn new(spi: SPI, delay: D) -> Result<Self, SpiError<SPI::Error>> {
108 Self::init(spi, delay).await.map_err(|(_, error)| error)
109 }
110
111 #[allow(clippy::type_complexity)]
114 pub async fn init(spi: SPI, delay: D) -> Result<Self, (SPI, SpiError<SPI::Error>)> {
115 let mut card = Self {
116 spi,
117 delay,
118 high_capacity: false,
119 blocks: 0,
120 check_crc: false,
121 token_window: START_TOKEN_WINDOW,
122 scratch: [0xff; SCRATCH],
123 };
124 match card.initialise().await {
125 Ok(()) => Ok(card),
126 Err(error) => Err((card.spi, error)),
127 }
128 }
129
130 async fn initialise(&mut self) -> Result<(), SpiError<SPI::Error>> {
131 self.delay.delay_ms(1).await;
132
133 let mut r1 = 0xff;
137 let mut timed_out = false;
138 for _ in 0..10 {
139 match self.command(0, 0, Reply::R1).await {
140 Ok(response) if response.r1 == 0x01 => {
141 r1 = 0x01;
142 break;
143 }
144 Ok(response) => {
145 r1 = response.r1;
146 timed_out = false;
147 }
148 Err(SpiError::Timeout) => {
149 r1 = 0xff;
150 timed_out = true;
151 }
152 Err(error) => return Err(error),
153 }
154 self.delay.delay_ms(1).await;
155 }
156 if r1 != 0x01 {
157 return Err(if timed_out {
158 SpiError::Timeout
159 } else {
160 SpiError::BadResponse(r1)
161 });
162 }
163
164 let interface = self.command(8, 0x1aa, Reply::R1WithFourBytes).await?;
165 let version_2 = interface.r1 & 0x04 == 0;
166 if version_2 && (interface.r1 != 0x01 || interface.extra != [0x00, 0x00, 0x01, 0xaa]) {
167 return Err(SpiError::BadResponse(interface.r1));
168 }
169
170 let host_capacity = if version_2 { 0x4000_0000 } else { 0 };
171 let mut ready = false;
172 for _ in 0..100 {
173 let app = self.command(55, 0, Reply::R1).await?;
174 if app.r1 > 0x01 {
175 return Err(SpiError::BadResponse(app.r1));
176 }
177 if self.command(41, host_capacity, Reply::R1).await?.r1 == 0x00 {
178 ready = true;
179 break;
180 }
181 self.delay.delay_ms(10).await;
182 }
183 if !ready {
184 return Err(SpiError::Timeout);
185 }
186
187 let ocr = self.command(58, 0, Reply::R1WithFourBytes).await?;
188 if ocr.r1 != 0x00 {
189 return Err(SpiError::BadResponse(ocr.r1));
190 }
191 self.high_capacity = ocr.extra[0] & 0x40 != 0;
192
193 if !self.high_capacity {
194 let length = self.command(16, BLOCK_SIZE as u32, Reply::R1).await?;
195 if length.r1 != 0x00 {
196 return Err(SpiError::BadResponse(length.r1));
197 }
198 }
199
200 self.check_crc = self.command(59, 1, Reply::R1).await?.r1 == 0x00;
201
202 let csd = self.read_csd().await?;
203 self.blocks = blocks_from_csd(&csd).ok_or(SpiError::UnsupportedCard)?;
204 Ok(())
205 }
206
207 pub fn into_spi(self) -> SPI {
209 self.spi
210 }
211
212 pub fn blocks(&self) -> u32 {
214 self.blocks
215 }
216
217 pub fn is_high_capacity(&self) -> bool {
219 self.high_capacity
220 }
221
222 pub fn spi_mut(&mut self) -> &mut SPI {
224 &mut self.spi
225 }
226
227 async fn read_block_inner(
228 &mut self,
229 block: u32,
230 buffer: &mut [u8; BLOCK_SIZE],
231 ) -> Result<(), SpiError<SPI::Error>> {
232 let address = if self.high_capacity {
233 block
234 } else {
235 block
236 .checked_mul(BLOCK_SIZE as u32)
237 .ok_or(SpiError::OutOfRange)?
238 };
239 self.read_with_data(17, address, buffer).await
240 }
241
242 #[cfg(feature = "write")]
246 async fn write_block_inner(
247 &mut self,
248 block: u32,
249 buffer: &[u8; BLOCK_SIZE],
250 ) -> Result<(), SpiError<SPI::Error>> {
251 if block >= self.blocks {
252 return Err(SpiError::OutOfRange);
253 }
254 let address = if self.high_capacity {
255 block
256 } else {
257 block
258 .checked_mul(BLOCK_SIZE as u32)
259 .ok_or(SpiError::OutOfRange)?
260 };
261 let mut result = self.write_block_once(address, buffer).await;
262 for _ in 0..WRITE_RETRIES {
263 if !matches!(result, Err(SpiError::BadCrc)) {
264 break;
265 }
266 result = self.write_block_once(address, buffer).await;
267 }
268 result
269 }
270
271 #[cfg(feature = "write")]
272 async fn write_block_once(
273 &mut self,
274 address: u32,
275 buffer: &[u8; BLOCK_SIZE],
276 ) -> Result<(), SpiError<SPI::Error>> {
277 self.wait_not_busy().await?;
281 let frame = command_frame(24, address);
282 let crc = crc16(buffer).to_be_bytes();
283 let mut r1_window = [0xffu8; R1_WINDOW];
287 let mut response = [0xffu8; 1];
288 self.spi
289 .transaction(&mut [
290 Operation::Write(&frame),
291 Operation::TransferInPlace(&mut r1_window),
292 Operation::Write(&[0xfe]),
293 Operation::Write(buffer),
294 Operation::Write(&crc),
295 Operation::TransferInPlace(&mut response),
296 ])
297 .await
298 .map_err(SpiError::Spi)?;
299
300 let r1 = r1_window
301 .iter()
302 .copied()
303 .find(|byte| *byte != 0xff)
304 .ok_or(SpiError::Timeout)?;
305 if r1 != 0x00 {
306 return Err(SpiError::BadResponse(r1));
307 }
308 if response[0] == 0xff {
310 return Err(SpiError::Timeout);
311 }
312 let status = match response[0] & 0x1f {
314 0x05 => Ok(()),
315 0x0b => Err(SpiError::BadCrc),
316 other => Err(SpiError::WriteRejected(other)),
317 };
318 self.wait_not_busy().await?;
321 status
322 }
323
324 #[cfg(feature = "write")]
326 async fn wait_not_busy(&mut self) -> Result<(), SpiError<SPI::Error>> {
327 for poll in 0..WRITE_FAST_POLLS + WRITE_SLOW_POLLS {
328 let mut byte = [0xffu8];
329 self.spi
330 .transaction(&mut [Operation::TransferInPlace(&mut byte)])
331 .await
332 .map_err(SpiError::Spi)?;
333 if byte[0] == 0xff {
334 return Ok(());
335 }
336 if poll < WRITE_FAST_POLLS {
337 self.delay.delay_us(READ_TOKEN_POLL_US).await;
338 } else {
339 self.delay.delay_ms(1).await;
340 }
341 }
342 Err(SpiError::Timeout)
343 }
344
345 async fn read_csd(&mut self) -> Result<[u8; 16], SpiError<SPI::Error>> {
346 let mut csd = [0u8; 16];
347 self.read_with_data(9, 0, &mut csd).await?;
348 Ok(csd)
349 }
350
351 async fn read_with_data(
356 &mut self,
357 index: u8,
358 argument: u32,
359 buffer: &mut [u8],
360 ) -> Result<(), SpiError<SPI::Error>> {
361 let mut result = self.read_with_data_once(index, argument, buffer).await;
362 for _ in 0..READ_RETRIES {
363 if !matches!(
364 result,
365 Err(SpiError::BadResponse(_) | SpiError::Timeout | SpiError::BadCrc)
366 ) {
367 break;
368 }
369 result = self.read_with_data_once(index, argument, buffer).await;
370 }
371 result
372 }
373
374 async fn read_with_data_once(
376 &mut self,
377 index: u8,
378 argument: u32,
379 buffer: &mut [u8],
380 ) -> Result<(), SpiError<SPI::Error>> {
381 let frame = command_frame(index, argument);
382 let window = self.token_window;
383 let length = R1_WINDOW + window + 1 + buffer.len() + 2;
384 let scratch = &mut self.scratch[..length];
385 scratch.fill(0xff);
386 self.spi
387 .transaction(&mut [
388 Operation::Write(&frame),
389 Operation::TransferInPlace(scratch),
390 ])
391 .await
392 .map_err(SpiError::Spi)?;
393
394 let r1_at = scratch[..R1_WINDOW]
395 .iter()
396 .position(|byte| *byte != 0xff)
397 .ok_or(SpiError::Timeout)?;
398 let r1 = scratch[r1_at];
399 if r1 != 0x00 {
400 return Err(SpiError::BadResponse(r1));
401 }
402
403 let first_idle = r1_at + 1;
406 let wanted = buffer.len() + 2;
407 let mut crc = [0xffu8; 2];
408 if let Some(gap) = scratch[first_idle..].iter().position(|byte| *byte != 0xff) {
409 let token_at = first_idle + gap;
410 let token = scratch[token_at];
411 let after = &scratch[token_at + 1..];
412 let have = after.len().min(wanted);
413 let data_have = have.min(buffer.len());
414 if token == 0xfe {
415 buffer[..data_have].copy_from_slice(&after[..data_have]);
416 crc[..have - data_have].copy_from_slice(&after[data_have..have]);
417 }
418 self.learn_gap(gap);
419 if token != 0xfe {
420 return Err(SpiError::BadResponse(token));
421 }
422 return if have == wanted {
423 self.check_data(buffer, u16::from_be_bytes(crc))
424 } else {
425 self.finish_block(buffer, data_have, crc, have - data_have)
426 .await
427 };
428 }
429
430 let mut waited = length - first_idle;
431 self.token_window = MAX_TOKEN_WINDOW;
432 let mut token = 0xff;
433 for _ in 0..READ_TOKEN_POLLS {
434 let mut byte = [0xff];
435 self.spi
436 .transaction(&mut [Operation::TransferInPlace(&mut byte)])
437 .await
438 .map_err(SpiError::Spi)?;
439 token = byte[0];
440 if token != 0xff {
441 break;
442 }
443 waited += 1;
444 self.delay.delay_us(READ_TOKEN_POLL_US).await;
445 }
446 if token != 0xfe {
447 return Err(SpiError::BadResponse(token));
448 }
449 self.learn_gap(waited);
450 self.finish_block(buffer, 0, crc, 0).await
451 }
452
453 async fn finish_block(
455 &mut self,
456 buffer: &mut [u8],
457 data_have: usize,
458 mut crc: [u8; 2],
459 crc_have: usize,
460 ) -> Result<(), SpiError<SPI::Error>> {
461 buffer[data_have..].fill(0xff);
462 self.spi
463 .transaction(&mut [
464 Operation::TransferInPlace(&mut buffer[data_have..]),
465 Operation::TransferInPlace(&mut crc[crc_have..]),
466 ])
467 .await
468 .map_err(SpiError::Spi)?;
469 self.check_data(buffer, u16::from_be_bytes(crc))
470 }
471
472 fn learn_gap(&mut self, gap: usize) {
473 self.token_window = (gap * 2 + MIN_TOKEN_WINDOW).clamp(MIN_TOKEN_WINDOW, MAX_TOKEN_WINDOW);
474 }
475
476 fn check_data(&self, buffer: &[u8], received: u16) -> Result<(), SpiError<SPI::Error>> {
477 if self.check_crc && crc16(buffer) != received {
478 return Err(SpiError::BadCrc);
479 }
480 Ok(())
481 }
482
483 async fn command(
486 &mut self,
487 index: u8,
488 argument: u32,
489 reply: Reply,
490 ) -> Result<Response, SpiError<SPI::Error>> {
491 let frame = command_frame(index, argument);
492
493 let mut bytes = [0xffu8; 12];
494 self.spi
495 .transaction(&mut [
496 Operation::Write(&frame),
497 Operation::TransferInPlace(&mut bytes),
498 ])
499 .await
500 .map_err(SpiError::Spi)?;
501 let position = bytes[..8]
502 .iter()
503 .position(|byte| *byte != 0xff)
504 .ok_or(SpiError::Timeout)?;
505 let mut extra = [0u8; 4];
506 if let Reply::R1WithFourBytes = reply {
507 extra.copy_from_slice(&bytes[position + 1..position + 5]);
508 }
509 Ok(Response {
510 r1: bytes[position],
511 extra,
512 })
513 }
514}
515
516impl<SPI, D> BlockDevice for SpiSdCard<SPI, D>
517where
518 SPI: SpiDevice<u8>,
519 D: DelayNs,
520{
521 type Error = SpiError<SPI::Error>;
522
523 async fn read_block(
524 &mut self,
525 block: u32,
526 buffer: &mut [u8; BLOCK_SIZE],
527 ) -> Result<(), Self::Error> {
528 self.read_block_inner(block, buffer).await
529 }
530
531 async fn num_blocks(&mut self) -> Result<u32, Self::Error> {
532 Ok(self.blocks)
533 }
534}
535
536#[cfg(feature = "write")]
537impl<SPI, D> crate::BlockWrite for SpiSdCard<SPI, D>
538where
539 SPI: SpiDevice<u8>,
540 D: DelayNs,
541{
542 async fn write_block(
543 &mut self,
544 block: u32,
545 buffer: &[u8; BLOCK_SIZE],
546 ) -> Result<(), Self::Error> {
547 self.write_block_inner(block, buffer).await
548 }
549}
550
551fn command_frame(index: u8, argument: u32) -> [u8; 6] {
552 let mut frame = [
553 0x40 | index,
554 (argument >> 24) as u8,
555 (argument >> 16) as u8,
556 (argument >> 8) as u8,
557 argument as u8,
558 0,
559 ];
560 frame[5] = crc7(&frame[..5]);
561 frame
562}
563
564fn blocks_from_csd(csd: &[u8; 16]) -> Option<u32> {
565 let structure = csd[0] >> 6;
566 let blocks = match structure {
567 0 => {
568 let read_bl_len = u32::from(csd[5] & 0x0f);
569 let c_size = (u64::from(csd[6] & 0x03) << 10)
570 | (u64::from(csd[7]) << 2)
571 | (u64::from(csd[8]) >> 6);
572 let c_size_mult = (u32::from(csd[9] & 0x03) << 1) | (u32::from(csd[10]) >> 7);
573 ((c_size + 1) << (c_size_mult + 2 + read_bl_len)) / BLOCK_SIZE as u64
574 }
575 1 => {
576 let c_size =
577 (u64::from(csd[7] & 0x3f) << 16) | (u64::from(csd[8]) << 8) | u64::from(csd[9]);
578 (c_size + 1) * 1024
579 }
580 _ => return None,
581 };
582 Some(u32::try_from(blocks).unwrap_or(u32::MAX).max(1))
583}
584
585pub fn crc7(data: &[u8]) -> u8 {
588 let mut crc = 0u8;
589 for &byte in data {
590 for bit in (0..8).rev() {
591 crc <<= 1;
592 if ((byte >> bit) & 1) ^ ((crc >> 7) & 1) != 0 {
593 crc ^= 0x09;
594 }
595 }
596 }
597 ((crc & 0x7f) << 1) | 1
598}
599
600pub fn crc16(data: &[u8]) -> u16 {
602 let mut crc = 0u16;
603 for &byte in data {
604 crc ^= u16::from(byte) << 8;
605 for _ in 0..8 {
606 crc = if crc & 0x8000 != 0 {
607 (crc << 1) ^ 0x1021
608 } else {
609 crc << 1
610 };
611 }
612 }
613 crc
614}
615
616#[cfg(test)]
617mod tests {
618 use super::{blocks_from_csd, crc16, crc7};
619
620 #[test]
621 fn a_version_1_csd_with_the_largest_fields_does_not_overflow() {
622 let mut csd = [0u8; 16];
623 csd[5] = 0x0b;
624 csd[6] = 0x03;
625 csd[7] = 0xff;
626 csd[8] = 0xc0;
627 csd[9] = 0x03;
628 csd[10] = 0x80;
629 assert_eq!(blocks_from_csd(&csd), Some(1 << 23));
630 }
631
632 #[test]
633 fn a_version_2_csd_at_the_maximum_c_size_saturates_instead_of_overflowing() {
634 let mut csd = [0u8; 16];
635 csd[0] = 0x40;
636 csd[7] = 0x3f;
637 csd[8] = 0xff;
638 csd[9] = 0xff;
639 assert_eq!(blocks_from_csd(&csd), Some(u32::MAX));
640 }
641
642 #[test]
643 fn an_unknown_csd_structure_is_unsupported() {
644 let mut csd = [0u8; 16];
645 csd[0] = 0x80;
646 assert_eq!(blocks_from_csd(&csd), None);
647 }
648
649 #[test]
650 fn crc7_matches_the_sd_command_frames() {
651 assert_eq!(crc7(&[0x40, 0x00, 0x00, 0x00, 0x00]), 0x95);
652 assert_eq!(crc7(&[0x48, 0x00, 0x00, 0x01, 0xaa]), 0x87);
653 }
654
655 #[test]
656 fn crc16_matches_the_sd_data_reference() {
657 assert_eq!(crc16(b"123456789"), 0x31c3);
659 }
660}