Contiki-Inga 3.x
sdcard.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2013, Institute of Operating Systems and Computer Networks (TU Braunschweig).
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  * notice, this list of conditions and the following disclaimer in the
12  * documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the Institute nor the names of its contributors
14  * may be used to endorse or promote products derived from this software
15  * without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /**
31  * \addtogroup inga_device_driver
32  * @{
33  *
34  * \addtogroup sdcard_interface
35  * @{
36  */
37 
38 /**
39  * \file
40  * SD Card interface implementation
41  * \author
42  * Original source: Ulrich Radig
43  * << modified by >>
44  * Ulf Kulau <kulau@ibr.cs.tu-bs.de>
45  * Christoph Peltz <peltz@ibr.cs.tu-bs.de>
46  * Enrico Joerns <e.joerns@tu-bs.de>
47  */
48 
49 #include "sdcard.h"
50 #include "dev/watchdog.h"
51 #include <util/delay.h>
52 
53 #define DEBUG 0
54 
55 #if DEBUG
56 #include <stdio.h>
57 #define PRINTD(...) printf(__VA_ARGS__)
58 #else
59 #define PRINTD(...)
60 #endif
61 // DEBUG > 1 is verbose
62 #if DEBUG > 1
63 #define PRINTF(...) printf(__VA_ARGS__)
64 #else
65 #define PRINTF(...)
66 #endif
67 
68 #define SD_DATA_HIGH 0xFF
69 
70 /** CMD0 -- GO_IDLE_STATE */
71 #define SDCARD_CMD0 0
72 /** CMD1 -- SEND_OP_COND */
73 #define SDCARD_CMD1 1
74 /** CMD8 -- SEND_IF_COND (deprecated?)*/
75 #define SDCARD_CMD8 8
76 
77 /** CMD9 -- SEND_CSD */
78 #define SDCARD_CMD9 9
79 /** CMD10 -- SEND_CID */
80 #define SDCARD_CMD10 10
81 /** CMD13 -- SEND_STATUS */
82 #define SDCARD_CMD13 13
83 
84 /** CMD16 -- SET_BLOCKLEN */
85 #define SDCARD_CMD16 16
86 // -- Read commands
87 /** CMD17 -- READ_SINGLE_BLOCK */
88 #define SDCARD_CMD17 17
89 /** CMD18 -- READ_MULTIPLE_BLOCK */
90 #define SDCARD_CMD18 18
91 // -- Write commands
92 /** CMD24 -- WRITE_BLOCK */
93 #define SDCARD_CMD24 24
94 /** CMD25 -- WRITE_MULTIPLE_BLOCK */
95 #define SDCARD_CMD25 25
96 // --
97 /** CMD27 -- PROGRAM_CSD */
98 #define SDCARD_CMD27 27
99 // -- Erase commands
100 /** CMD32 -- ERASE_WR_BLK_START_ADDR */
101 #define SDCARD_CMD32 32
102 /** CMD33 -- ERASE_WR_BLK_END_ADDR */
103 #define SDCARD_CMD33 33
104 /** CMD38 -- ERASE */
105 #define SDCARD_CMD38 38
106 // --
107 /** CMD58 -- READ_OCR */
108 #define SDCARD_CMD58 58
109 /** CMD59 -- CRC_ON_OFF */
110 #define SDCARD_CMD59 59
111 
112 /** CMD55 -- APP_CMD */
113 #define SDCARD_CMD55 55
114 
115 #define IS_ACMD 0x80
116 /** ACMD23 -- SET_WR_BLK_ERASE_COUNT */
117 #define SDCARD_ACMD23 (IS_ACMD | 23)
118 /** ACMD41 -- SD_SEND_OP_COND */
119 #define SDCARD_ACMD41 (IS_ACMD | 41)
120 
121 /* Response types */
122 #define SDCARD_RESP1 0x01
123 #define SDCARD_RESP2 0x02
124 #define SDCARD_RESP3 0x03
125 #define SDCARD_RESP7 0x07
126 
127 /* Response R1 bits */
128 #define SD_R1_IN_IDLE_STATE 0x01
129 #define SD_R1_ERASE_RESET 0x02
130 #define SD_R1_ILLEGAL_CMD 0x04
131 #define SD_R1_COM_CRC_ERR 0x08
132 #define SD_R1_ERASE_SEQ_ERR 0x10
133 #define SD_R1_ADDR_ERR 0x20
134 #define SD_R1_PARAM_ERR 0x40
135 
136 /* Response R2 bits */
137 #define R2_OUT_OF_RANGE 0x80
138 #define R2_ERASE_PARAM 0x40
139 #define R2_WP_VIOLATION 0x20
140 #define R2_EEC_FAILED 0x10
141 #define R2_CC_ERROR 0x08
142 #define R2_ERROR 0x04
143 #define R2_ERASE_SKIP 0x02
144 #define R2_CARD_LOCKED 0x01
145 
146 /* OCR register bits */
147 #define OCR_H_CCS 0x40
148 #define OCR_H_POWER_UP 0x80
149 
150 /* Data response tokens (sent by card) */
151 #define DATA_RESP_ACCEPTED 0x05
152 #define DATA_RESP_CRC_REJECT 0x0B
153 #define DATA_RESP_WRITE_ERROR 0x0D
154 
155 /* Single-Block Read, Single-Block Write and Multiple-Block Read
156  * (sent both by host and by card) */
157 #define START_BLOCK_TOKEN 0xFE
158 /* Multiple Block Write Operation (sent by host) */
159 #define MULTI_START_BLOCK_TOKEN 0xFC
160 #define STOP_TRAN_TOKEN 0xFD
161 
162 /* Data error token (sent by card) */
163 #define DATA_ERROR 0x01
164 #define DATA_CC_ERROR 0x02
165 #define DATA_CARD_ECC_FAILED 0x04
166 #define DATA_OUT_OF_RANGE 0x08
167 
168 /* Configures the number of ms to busy wait
169  * Note: Standard says, maximum busy for write must be <250ms.
170  * Only in context of multi-block write stop
171  * also 500ms are allowed. */
172 #define BUSY_WAIT_MS 300
173 
174 #define N_CX_MAX 8
175 #define N_CR_MAX 8
176 
177 /**
178  * \brief The number of bytes in one block on the SD-Card.
179  */
180 static uint16_t sdcard_block_size = 512;
181 
182 /**
183  * \brief Number of blocks on the SD-Card.
184  */
185 static uint32_t sdcard_card_block_count = 0;
186 
187 /**
188  * \brief Indicates if the inserted card is a SDSC card (!=0) or not (==0).
189  */
190 static uint8_t sdcard_sdsc_card = 1;
191 
192 /**
193  * \brief Indicates if the cards CRC mode is on (1) or off (0). Default is off.
194  */
195 static uint8_t sdcard_crc_enable = 0;
196 
197 static void get_csd_info(uint8_t *csd);
198 /**
199  * Waits for the busy signal to become high.
200  * \retval 0 successfull
201  */
202 static uint8_t sdcard_busy_wait();
203 
204 /* Debugging functions */
205 #if DEBUG
206 static void
207 print_r1_resp(uint8_t cmd, uint8_t rsp) {
208  /* everything might be ok */
209  if (rsp == 0x00) {
210  PRINTF("\nCMD%d: ", cmd & ~IS_ACMD);
211  PRINTF("\n\tOk");
212  return;
213  /* idle is not really critical */
214  } else if (rsp == SD_R1_IN_IDLE_STATE) {
215  PRINTF("\nCMD%d: ", cmd & ~IS_ACMD);
216  PRINTF("\n\tIdle");
217  return;
218  /* let us see what kind of error(s) we have */
219  } else {
220  PRINTD("\nCMD%d: ", cmd & ~IS_ACMD);
221  if (rsp & SD_R1_IN_IDLE_STATE) {
222  PRINTD("\n\tIdle");
223  }
224  if (rsp & SD_R1_ERASE_RESET) {
225  PRINTD("\n\tErase Reset");
226  }
227  if (rsp & SD_R1_ILLEGAL_CMD) {
228  PRINTD("\n\tIllegal Cmd");
229  }
230  if (rsp & SD_R1_COM_CRC_ERR) {
231  PRINTD("\n\tCom CRC Err");
232  }
233  if (rsp & SD_R1_ERASE_SEQ_ERR) {
234  PRINTD("\n\tErase Seq Err");
235  }
236  if (rsp & SD_R1_ADDR_ERR) {
237  PRINTD("\n\tAddr Err");
238  }
239  if (rsp & SD_R1_PARAM_ERR) {
240  PRINTD("\n\tParam Err");
241  }
242  }
243 }
244 /*----------------------------------------------------------------------------*/
245 static void
246 dbg_resp_r1(uint8_t cmd, uint8_t rsp) {
247  print_r1_resp(cmd, rsp);
248 }
249 /*----------------------------------------------------------------------------*/
250 static void
251 dbg_resp_r2(uint8_t cmd, uint8_t* rsp) {
252  print_r1_resp(cmd, rsp[0]);
253  if(rsp[1] & R2_OUT_OF_RANGE) {
254  PRINTD("\nOut of Range");
255  }
256  if(rsp[1] & R2_ERASE_PARAM) {
257  PRINTD("\nErase param");
258  }
259  if(rsp[1] & R2_WP_VIOLATION) {
260  PRINTD("\nWP violation");
261  }
262  if(rsp[1] & R2_EEC_FAILED) {
263  PRINTD("\nEEC failed");
264  }
265  if(rsp[1] & R2_CC_ERROR) {
266  PRINTD("\nCC error");
267  }
268  if(rsp[1] & R2_ERROR) {
269  PRINTD("\nError");
270  }
271  if(rsp[1] & R2_ERASE_SKIP) {
272  PRINTD("\nErase skip");
273  }
274  if(rsp[1] & R2_CARD_LOCKED) {
275  PRINTD("\nCard locked");
276  }
277 }
278 /*----------------------------------------------------------------------------*/
279 static void
280 dbg_resp_r3(uint8_t cmd, uint8_t* rsp) {
281  print_r1_resp(cmd, rsp[0]);
282  PRINTF("\nOCR: 0x%04x", rsp[1]);
283 }
284 /*----------------------------------------------------------------------------*/
285 static void
286 dbg_resp_r7(uint8_t cmd, uint8_t* rsp) {
287  print_r1_resp(cmd, rsp[0]);
288  PRINTF("\nR7_DATA: 0x%04x", rsp[1]);
289 }
290 /*----------------------------------------------------------------------------*/
291 static void
292 dbg_data_err(uint8_t ret) {
293  if ((ret & 0xF0) == 0) { // error bit mask
294  if(ret & DATA_ERROR) {
295  PRINTD("\nError");
296  }
297  if(ret & DATA_CC_ERROR) {
298  PRINTD("\nCC Error");
299  }
300  if(ret & DATA_CARD_ECC_FAILED) {
301  PRINTD("\nEEC Failed");
302  }
303  if(ret & DATA_OUT_OF_RANGE) {
304  PRINTD("\nOut of range");
305  }
306  }
307 }
308 /*----------------------------------------------------------------------------*/
309 #else
310 /* dummy fuctions */
311 #define dbg_resp_r1(a, b)
312 #define dbg_resp_r2(a, b)
313 #define dbg_resp_r3(a, b)
314 #define dbg_resp_r7(a, b)
315 #define dbg_data_err(ret)
316 #endif
317 /*----------------------------------------------------------------------------*/
318 uint64_t
320 {
321  return ((uint64_t) sdcard_card_block_count) * sdcard_block_size;
322 }
323 /*----------------------------------------------------------------------------*/
324 uint32_t
326 {
327  return (sdcard_card_block_count / sdcard_block_size) * sdcard_get_block_size();
328 }
329 /*----------------------------------------------------------------------------*/
330 uint16_t
332 {
333  return 512;
334 }
335 /*----------------------------------------------------------------------------*/
336 uint8_t
338 {
339  return sdcard_sdsc_card;
340 }
341 /*----------------------------------------------------------------------------*/
342 uint8_t
343 sdcard_set_CRC(uint8_t enable)
344 {
345  uint8_t ret;
346  uint32_t arg = enable ? 1L : 0L;
347 
349 
350  if ((ret = sdcard_write_cmd(SDCARD_CMD59, &arg, NULL)) != 0x00) {
351  PRINTD("\nsdcard_set_CRC(): ret = %u", ret);
352  return SDCARD_CMD_ERROR;
353  }
354 
355  sdcard_crc_enable = enable;
357 
358  return SDCARD_SUCCESS;
359 }
360 /*----------------------------------------------------------------------------*/
361 uint8_t
362 sdcard_read_csd(uint8_t *buffer)
363 {
364  uint8_t ret, i = 0;
365 
367 
368  if ((ret = sdcard_write_cmd(SDCARD_CMD9, NULL, NULL)) != 0x00) {
369  return SDCARD_CMD_ERROR;
370  }
371 
372  /* wait for the 0xFE start byte */
373  i = 0;
374  while ((ret = mspi_transceive(MSPI_DUMMY_BYTE)) == SD_DATA_HIGH) {
375  i++;
376  if (i > N_CX_MAX) {
377  PRINTD("\nsdcard_read_csd(): No data token");
378  return SDCARD_DATA_TIMEOUT;
379  }
380  }
381 
382  /* Check for start block token */
383  if (ret != START_BLOCK_TOKEN) {
384  dbg_data_err(ret);
385  return SDCARD_DATA_ERROR;
386  }
387 
388  /* Read 16 bit CSD content */
389  for (i = 0; i < 16; i++) {
390  *buffer++ = mspi_transceive(MSPI_DUMMY_BYTE);
391  }
392 
393  /* CRC-Byte: don't care */
394  mspi_transceive(MSPI_DUMMY_BYTE);
395  mspi_transceive(MSPI_DUMMY_BYTE);
396 
397  /*release chip select and disable sdcard spi*/
399 
400  return SDCARD_SUCCESS;
401 }
402 /*----------------------------------------------------------------------------*/
403 /**
404  * Parse the given csd and extract the needed information out of it.
405  *
406  * \param *csd A Buffer in which the contents of the csd are saved (get them with sdcard_read_csd()).
407  */
408 static void
409 get_csd_info(uint8_t *csd)
410 {
411  uint8_t csd_version = 0;
412  uint8_t READ_BL_LEN = 0;
413  uint32_t C_SIZE = 0;
414  uint16_t C_SIZE_MULT = 0;
415  uint32_t mult = 0;
416  uint8_t SECTOR_SIZE = 0;
417  uint32_t capacity = 0;
418  // TODO: Check CCC?
419 
420  /* First, determine CSD version and layout */
421  csd_version = csd[0] >> 6;
422 
423  /* CSD Version 1.0 */
424  if (csd_version == 0) {
425  /* 80:83 (4 Bit) */
426  READ_BL_LEN = csd[5] & 0x0F;
427  /* 73:62 (12 Bit) [xxxxxxDD:DDDDDDDD:DDxxxxxx] */
428  C_SIZE = (((uint16_t) (csd[6] & 0x03)) << 10) | (((uint16_t) csd[7]) << 2) | (csd[8] >> 6);
429  /* 49:47 (3 Bit) */
430  C_SIZE_MULT = ((csd[9] & 0x03) << 1) | (csd[10] >> 7);
431  /* 45:39 (7 Bit) */
432  SECTOR_SIZE = ((csd[11] >> 7) | ((csd[10] & 0x3F) << 1)) + 1;
433 
434  mult = (1 << (C_SIZE_MULT + 2));
435  sdcard_card_block_count = (C_SIZE + 1) * mult;
436  sdcard_block_size = 1 << READ_BL_LEN;
437  capacity = sdcard_card_block_count * sdcard_block_size / 1024 / 1024;
438 
439  /* CSD Version 2.0 (SDHC/SDXC) */
440  } else if (csd_version == 1) {
441  /* 80:83, should be fixed to 512 Bytes */
442  READ_BL_LEN = csd[5] & 0x0F;
443  /* 69:48 (22 Bit) */
444  C_SIZE = csd[9] + (((uint32_t) csd[8]) << 8) + (((uint32_t) csd[7] & 0x3f) << 16);
445  /* 45:39 (7 Bit) */
446  SECTOR_SIZE = ((csd[11] >> 7) | ((csd[10] & 0x3F) << 1)) + 1;
447 
448  sdcard_card_block_count = (C_SIZE + 1) * 1024;
449  sdcard_block_size = 512;
450  capacity = C_SIZE * 512 / 1024;
451  } else {
452  PRINTD("\nInvalid CSD version");
453  return;
454  }
455 
456  PRINTF("\nget_csd_info(): CSD Version = %u", csd_version);
457  PRINTF("\nget_csd_info(): READ_BL_LEN = %u", READ_BL_LEN);
458  PRINTF("\nget_csd_info(): C_SIZE = %lu", C_SIZE);
459  PRINTF("\nget_csd_info(): Capacity = %lu MB", capacity);
460  PRINTF("\nget_csd_info(): C_SIZE_MULT = %u", C_SIZE_MULT);
461  PRINTF("\nget_csd_info(): mult = %lu", mult);
462  PRINTF("\nget_csd_info(): sdcard_card_block_count = %lu", sdcard_card_block_count);
463  PRINTF("\nget_csd_info(): sdcard_block_size = %u", sdcard_block_size);
464  PRINTF("\nget_csd_info(): SECTOR_SIZE = %u", SECTOR_SIZE);
465 }
466 /*----------------------------------------------------------------------------*/
467 /**
468  * \brief This function calculates the CRC7 for SD Card commands.
469  *
470  * \param *cmd The array containing the command with every byte except
471  * the CRC byte correctly set. The CRC part will be written into the
472  * cmd array (at the correct position).
473  */
474 void
475 sdcard_cmd_crc(uint8_t *cmd)
476 {
477  uint32_t stream = (((uint32_t) cmd[0]) << 24) +
478  (((uint32_t) cmd[1]) << 16) +
479  (((uint32_t) cmd[2]) << 8) +
480  ((uint32_t) cmd[3]);
481  uint8_t i = 0;
482  uint32_t gen = ((uint32_t) 0x89) << 24;
483 
484  for (i = 0; i < 40; i++) {
485  if (stream & (((uint32_t) 0x80) << 24)) {
486  stream ^= gen;
487  }
488 
489  stream = stream << 1;
490  if (i == 7) {
491  stream += cmd[4];
492  }
493  }
494 
495  cmd[5] = (stream >> 24) + 1;
496 }
497 /*----------------------------------------------------------------------------*/
498 uint16_t
499 sdcard_data_crc(uint8_t *data)
500 {
501  uint32_t stream = (((uint32_t) data[0]) << 24) +
502  (((uint32_t) data[1]) << 16) +
503  (((uint32_t) data[2]) << 8) +
504  ((uint32_t) data[3]);
505  uint16_t i = 0;
506  uint32_t gen = ((uint32_t) 0x11021) << 15;
507 
508  /* 4096 Bits = 512 Bytes a 8 Bits */
509  for (i = 0; i < 4096; i++) {
510  if (stream & (((uint32_t) 0x80) << 24)) {
511  stream ^= gen;
512  }
513 
514  stream = stream << 1;
515  if (((i + 1) % 8) == 0 && i < 4064) {
516  stream += data[((i + 1) / 8) + 3];
517  }
518  }
519 
520  return (stream >> 16);
521 }
522 /*----------------------------------------------------------------------------*/
523 uint8_t
525 {
526  uint16_t i;
527  uint8_t ret = 0;
528  sdcard_sdsc_card = 1;
529 
530  uint32_t cmd_arg = 0;
531  /*Response Array for the R3 and R7 responses*/
532  uint8_t resp[5] = {0x00, 0x00, 0x00, 0x00, 0x00};
533  /* Memory for the contents of the csd */
534  uint8_t csd[16];
535 
536  /* READY TO INITIALIZE micro SD / SD card */
538 
539  /*init mspi in mode0, at chip select pin 2 and max baud rate */
541 
542  /* set SPI mode by chip select (only necessary when mspi manager is active) */
544 
545  /* send initialization sequence (>74 clock cycles) */
546  for (i = 0; i < 16; i++) {
547  mspi_transceive(MSPI_DUMMY_BYTE);
548  }
549 
550  /* CMD0 with CS asserted enables SPI mode.
551  * Note: Card may hold line low until fully initialized */
552  i = 0;
553  while ((ret = sdcard_write_cmd(SDCARD_CMD0, NULL, NULL)) != SD_R1_IN_IDLE_STATE) {
554  i++;
555  if (i > 200) {
557  PRINTD("\nsdcard_init(): cmd0 timeout -> %d", ret);
558  return SDCARD_CMD_TIMEOUT;
559  }
560  }
561 
562  /* CMD8: Test if the card supports CSD Version 2.
563  * Shall be issued before ACMD41. */
564  i = 0;
565  /* CMD8 payload [ 01 = voltage supplied (2.7-3.6V), 0xAA = any check-pattern ] */
566  cmd_arg = 0x000001AAUL;
567  resp[0] = SDCARD_RESP7;
568  while ((ret = sdcard_write_cmd(SDCARD_CMD8, &cmd_arg, resp)) != SD_R1_IN_IDLE_STATE) {
569  if ((ret & SD_R1_ILLEGAL_CMD) && ret != 0xFF) {
570  PRINTF("\nsdcard_init(): cmd8 not supported -> Ver1.X or no SD Memory Card");
571  break;
572  }
573  i++;
574  if (i > 200) {
576  PRINTD("\nsdcard_init(): cmd8 timeout -> %d", ret);
577  return SDCARD_CMD_TIMEOUT;
578  }
579  }
580  /* Check response payload in case of accepted response */
581  if (ret == SD_R1_IN_IDLE_STATE) {
582  // check voltage
583  if (resp[3] != ((uint8_t) (cmd_arg >> 8) & 0x0F)) {
584  printf("\nsdcard_init(): Voltage not accepted");
585  return SDCARD_REJECTED;
586  }
587  // check echo-back pattern
588  if (resp[4] != ((uint8_t) (cmd_arg & 0xFF))) {
589  printf("\nsdcard_init(): Echo-back pattern wrong, sent %02x, rec: %02x",
590  (uint8_t) (cmd_arg & 0xFF), resp[4]);
591  return SDCARD_CMD_ERROR;
592  }
593  }
594 
595  /* Illegal command -> Ver 1.X SD Memory Card or Not SD Memory Card*/
596  if (ret & SD_R1_ILLEGAL_CMD) {
597 
598  /* CMD1: init CSD Version 1 and MMC cards*/
599  i = 0;
600  while ((ret = sdcard_write_cmd(SDCARD_CMD1, NULL, NULL)) != 0) {
601  i++;
602  if (i > 5500) {
603  PRINTD("\nsdcard_init(): cmd1 timeout reached, last return value was %d", ret);
605  return SDCARD_CMD_TIMEOUT;
606  }
607  }
608 
609  /* CMD16: Sets the block length, needed for CSD Version 1 cards */
610  i = 0;
611  /* CMD15 payload (block length = 512) */
612  cmd_arg = 0x00000200UL;
613  while ((ret = sdcard_write_cmd(SDCARD_CMD16, &cmd_arg, NULL)) != 0x00) {
614  i++;
615  if (i > 500) {
616  PRINTF("\nsdcard_init(): cmd16 timeout reached, last return value was %d", ret);
618  return SDCARD_CMD_TIMEOUT;
619  }
620  }
621 
622  /* Ver2.00 or later SD Memory Card */
623  } else {
624 
625  i = 0;
626  /* ACMD41 payload [HCS bit set] */
627  cmd_arg = 0x40000000UL;
628  while (sdcard_write_cmd(SDCARD_ACMD41, &cmd_arg, NULL) != 0) {
629  i++;
630  _delay_ms(2);
631 
632  if (i > 200) {
633  PRINTD("\nsdcard_init(): acmd41 timeout reached, last return value was %u", ret);
635  return SDCARD_CMD_TIMEOUT;
636  }
637  }
638 
639  /* CMD58: Gets the OCR-Register to check if card is SDSC or not */
640  i = 0;
641  resp[0] = SDCARD_RESP3;
642  while ((ret = sdcard_write_cmd(SDCARD_CMD58, NULL, resp)) != 0x0) {
643  i++;
644  if (i > 900) {
645  PRINTD("\nsdcard_init(): cmd58 timeout reached, last return value was %d", ret);
647  return SDCARD_CMD_TIMEOUT;
648  }
649  }
650 
651  /* Check if power up finished */
652  if (resp[1] & OCR_H_POWER_UP) {
653  PRINTF("\nsdcard_init(): acmd41: Card power up okay!");
654  /* Check if SDSC or SDHC/SDXC */
655  if (resp[1] & OCR_H_CCS) {
656  sdcard_sdsc_card = 0;
657  PRINTF("\nsdcard_init(): acmd41: Card is SDHC/SDXC");
658  } else {
659  PRINTF("\nsdcard_init(): acmd41: Card is SDSC");
660  }
661 
662  }
663  }
664 
665  /* Read card-specific data (CSD) register */
666  i = 0;
667  while (sdcard_read_csd(csd) != SDCARD_SUCCESS) {
668  i++;
669  if (i > 100) {
671  PRINTD("\nsdcard_init(): CSD read error");
672  return SDCARD_CSD_ERROR;
673  }
674  }
675  get_csd_info(csd);
676 
678 
679  return SDCARD_SUCCESS;
680 }
681 /*----------------------------------------------------------------------------*/
682 uint8_t
683 sdcard_erase_blocks(uint32_t startaddr, uint32_t endaddr)
684 {
685  uint16_t ret;
686 
687  /* calculate the start address: block_addr = addr * 512
688  * this is only needed if the card is a SDSC card and uses
689  * byte addressing (Block size of 512 is set in sdcard_init()).
690  * SDHC and SDXC card use block-addressing with a block size of
691  * 512 Bytes.
692  */
693  if (sdcard_sdsc_card) {
694  startaddr = startaddr << 9;
695  endaddr = endaddr << 9;
696  }
697 
699 
700  /* send CMD32 with address information. */
701  if ((ret = sdcard_write_cmd(SDCARD_CMD32, &startaddr, NULL)) != 0x00) {
703  PRINTD("\nCMD32 failed");
704  return ret;
705  }
706 
707  /* send CMD33 with address information. */
708  if ((ret = sdcard_write_cmd(SDCARD_CMD33, &endaddr, NULL)) != 0x00) {
710  PRINTD("\nCMD33 failed");
711  return ret;
712  }
713 
714  /* send CMD38 with address information. */
715  if ((ret = sdcard_write_cmd(SDCARD_CMD38, NULL, NULL)) != 0x00) {
717  PRINTD("\nCMD38 failed");
718  return ret;
719  }
720 
721  /* release chip select and disable sdcard spi */
723 
724  return SDCARD_SUCCESS;
725 }
726 /*----------------------------------------------------------------------------*/
727 uint8_t
728 sdcard_read_block(uint32_t addr, uint8_t *buffer)
729 {
730  uint16_t i;
731  uint8_t ret;
732 
733  /* calculate the start address: block_addr = addr * 512
734  * this is only needed if the card is a SDSC card and uses
735  * byte addressing (Block size of 512 is set in sdcard_init()).
736  * SDHC and SDXC card use block-addressing with a block size of
737  * 512 Bytes.
738  */
739  if (sdcard_sdsc_card) {
740  addr = addr << 9;
741  }
742 
744 
745  if (sdcard_busy_wait() == SDCARD_BUSY_TIMEOUT) {
746  return SDCARD_BUSY_TIMEOUT;
747  }
748 
749  /* send CMD17 with address information. */
750  if ((i = sdcard_write_cmd(SDCARD_CMD17, &addr, NULL)) != 0x00) {
751  PRINTD("\nsdcard_read_block(): CMD17 failure! (%u)", i);
752  return SDCARD_CMD_ERROR;
753  }
754 
755  /* wait for the 0xFE start byte */
756  i = 0;
757  while ((ret = mspi_transceive(MSPI_DUMMY_BYTE)) == SD_DATA_HIGH) {
758  if (i >= 200) {
759  PRINTD("\nsdcard_read_block(): No Start Byte recieved, last was %d", ret);
760  return SDCARD_DATA_TIMEOUT;
761  }
762  }
763  /* exit on error response */
764  if (ret != START_BLOCK_TOKEN) {
765 #if DEBUG
766  dbg_data_err(ret);
767 #endif // debug
768  return SDCARD_DATA_ERROR;
769  }
770 
771  /* transfer block */
772  for (i = 0; i < 512; i++) {
773  buffer[i] = mspi_transceive(MSPI_DUMMY_BYTE);
774  }
775 
776  /* Read CRC-Byte: don't care */
777  mspi_transceive(MSPI_DUMMY_BYTE);
778  mspi_transceive(MSPI_DUMMY_BYTE);
779 
780  /* release chip select and disable sdcard spi */
782 
783  return SDCARD_SUCCESS;
784 }
785 /*----------------------------------------------------------------------------*/
786 /* @TODO: currently not used in any way */
787 uint16_t
788 sdcard_get_status(void)
789 {
790  uint8_t resp[5] = {SDCARD_RESP2, 0x00, 0x00, 0x00, 0x00};
791 
792  if (sdcard_busy_wait() == SDCARD_BUSY_TIMEOUT) {
793  return SDCARD_BUSY_TIMEOUT;
794  }
795 
796  if (sdcard_write_cmd(SDCARD_CMD13, NULL, resp) != 0x00) {
797  printf("\nFailed to read status");
798  return 0;
799  }
800 
801  return ((uint16_t) resp[1] << 8) + ((uint16_t) resp[0]);
802 }
803 /*----------------------------------------------------------------------------*/
804 uint8_t
805 sdcard_write_block(uint32_t addr, uint8_t *buffer)
806 {
807  uint16_t i;
808 
809  /* calculate the start address: byte_addr = block_addr * 512.
810  * this is only needed if the card is a SDSC card and uses
811  * byte addressing (Block size of 512 is set in sdcard_init()).
812  * SDHC and SDXC card use block-addressing with a fixed block size
813  * of 512 Bytes.
814  */
815  if (sdcard_sdsc_card) {
816  addr = addr << 9;
817  }
818 
820 
821  if (sdcard_busy_wait() == SDCARD_BUSY_TIMEOUT) {
822  return SDCARD_BUSY_TIMEOUT;
823  }
824 
825  /* send CMD24 with address information. */
826  if (sdcard_write_cmd(SDCARD_CMD24, &addr, NULL) != 0x00) {
828  return SDCARD_CMD_ERROR;
829  }
830 
831  /* send start byte 0xFE to the sdcard card to symbolize the beginning
832  * of one data block (512byte) */
833  mspi_transceive(START_BLOCK_TOKEN);
834 
835  /* send 1 block (512byte) to the sdcard card */
836  for (i = 0; i < 512; i++) {
837  mspi_transceive(buffer[i]);
838  }
839 
840  /* write dummy 16 bit CRC checksum */
841  /** @todo: handle crc enabled? */
842  mspi_transceive(MSPI_DUMMY_BYTE);
843  mspi_transceive(MSPI_DUMMY_BYTE);
844 
845  /* failure check: Data Response XXX0RRR1 */
846  i = mspi_transceive(MSPI_DUMMY_BYTE) & 0x1F;
847  /* after the response the card requires additional 8 clock cycles. */
848  mspi_transceive(MSPI_DUMMY_BYTE);
849 
850  /* release chip select and disable sdcard spi
851  * note: busy waiting is not required here
852  * becaus it is already done before writing/reading
853  */
855 
856  /* Data Response XXX00101 = OK */
857  if (i != DATA_RESP_ACCEPTED) {
858 #if DEBUG
859  if (i == DATA_RESP_CRC_REJECT) {
860  PRINTD("\nWrite response: CRC error");
861  } else if (i == DATA_RESP_WRITE_ERROR) {
862  PRINTD("\nData Resp: Write error");
863  } else {
864  PRINTD("\nData Resp %02x unknown", i);
865  }
866 #endif
867  return SDCARD_DATA_ERROR;
868  }
869 
870  return SDCARD_SUCCESS;
871 }
872 /*----------------------------------------------------------------------------*/
873 uint8_t
874 sdcard_write_multi_block_start(uint32_t addr, uint32_t num_blocks)
875 {
876 
877  /* calculate the start address: byte_addr = block_addr * 512.
878  * this is only needed if the card is a SDSC card and uses
879  * byte addressing (Block size of 512 is set in sdcard_init()).
880  * SDHC and SDXC card use block-addressing with a fixed block size
881  * of 512 Bytes.
882  */
883  if (sdcard_sdsc_card) {
884  addr = addr << 9;
885  }
886 
888 
889  if (sdcard_busy_wait() == SDCARD_BUSY_TIMEOUT) {
890  return SDCARD_BUSY_TIMEOUT;
891  }
892 
893  if (num_blocks != 0) {
894  /* Announce number of blocks to write to card for pre-erase
895  * Note. */
896  PRINTF("\nPre-erasing %ld blocks", num_blocks);
897  sdcard_write_cmd(SDCARD_ACMD23, &num_blocks, NULL);
898  }
899 
900  /* send CMD25 with address information. */
901  if (sdcard_write_cmd(SDCARD_CMD25, &addr, NULL) != 0x00) {
903  return SDCARD_CMD_ERROR;
904  }
905 
906  return SDCARD_SUCCESS;
907 }
908 /*----------------------------------------------------------------------------*/
909 uint8_t
911 {
912  uint16_t i;
913 
915 
916  if (sdcard_busy_wait() == SDCARD_BUSY_TIMEOUT) {
917  return SDCARD_BUSY_TIMEOUT;
918  }
919 
920  /* send start byte 0xFC to the sdcard card to symbolize the beginning
921  * of one data block (512byte) */
922  mspi_transceive(MULTI_START_BLOCK_TOKEN);
923 
924  /* send 1 block (512byte) to the sdcard card */
925  for (i = 0; i < 512; i++) {
926  mspi_transceive(buffer[i]);
927  }
928 
929  /* write dummy 16 bit CRC checksum */
930  /** @todo: handle crc enabled? */
931  mspi_transceive(MSPI_DUMMY_BYTE);
932  mspi_transceive(MSPI_DUMMY_BYTE);
933 
934  /* failure check: Data Response XXX0RRR1 */
935  i = mspi_transceive(MSPI_DUMMY_BYTE) & 0x1F;
936  /* after the response the card requires additional 8 clock cycles. */
937  mspi_transceive(MSPI_DUMMY_BYTE);
938 
939  /* release chip select and disable sdcard spi */
941 
942  /* Data Response XXX00101 = OK */
943  if (i != DATA_RESP_ACCEPTED) {
944 #if DEBUG
945  if (i == DATA_RESP_CRC_REJECT) {
946  PRINTD("\nWrite response: CRC error");
947  } else if (i == DATA_RESP_WRITE_ERROR) {
948  PRINTD("\nData Resp: Write error");
949  } else {
950  PRINTD("\nData Resp %02x unknown", i);
951  }
952 #endif
953  return SDCARD_DATA_ERROR;
954  }
955 
956  return SDCARD_SUCCESS;
957 }
958 /*----------------------------------------------------------------------------*/
959 uint8_t
961 {
963 
964  if (sdcard_busy_wait() == SDCARD_BUSY_TIMEOUT) {
965  return SDCARD_BUSY_TIMEOUT;
966  }
967 
968  mspi_transceive(STOP_TRAN_TOKEN);
969  /* after the response the card requires additional 8 clock cycles. */
970  mspi_transceive(MSPI_DUMMY_BYTE);
971 
972  /* release chip select and disable sdcard spi */
974 
975  return SDCARD_SUCCESS;
976 }
977 /*----------------------------------------------------------------------------*/
978 static uint8_t
979 sdcard_busy_wait()
980 {
981  /* Wait until the card is not busy anymore!
982  * Note: It is always checked twice because
983  * busy signal becomes high only when clocked before */
984  uint16_t i = 0;
985  while ((mspi_transceive(MSPI_DUMMY_BYTE) != SD_DATA_HIGH)
986  && (mspi_transceive(MSPI_DUMMY_BYTE) != SD_DATA_HIGH)) {
987  _delay_ms(1);
988  i++;
989  if (i >= BUSY_WAIT_MS) {
990  PRINTD("\nsdcard_busy_wait(): Busy wait timeout");
991  return SDCARD_BUSY_TIMEOUT;
992  }
993  }
994 
995  return SDCARD_SUCCESS;
996 }
997 /*----------------------------------------------------------------------------*/
998 // returns 0xFF as error code, else R1 part if available
999 uint8_t
1000 sdcard_write_cmd(uint8_t cmd, uint32_t *arg, uint8_t *resp)
1001 {
1002  uint16_t i;
1003  uint8_t data;
1004  uint8_t idx = 0;
1005  uint8_t resp_type = 0x01;
1006  static uint8_t cmd_seq[6] = {0x40, 0x00, 0x00, 0x00, 0x00, 0xFF};
1007 
1008  uint8_t ret;
1009  /* pre-send CMD55 for ACMD */
1010  if (cmd & IS_ACMD) {
1011  /* Abort if response has error bit set */
1012  if (((ret = sdcard_write_cmd(SDCARD_CMD55, NULL, NULL)) & 0xFE) != 0x00) {
1013  return 0xFF;
1014  }
1015  }
1016 
1017  /* Give card chance to raise busy signal while we perform some calculations */
1018  mspi_transceive(MSPI_DUMMY_BYTE);
1019 
1020  /* (remove potential ACMD-marker, add host bit to complete command */
1021  cmd_seq[0] = (cmd & ~IS_ACMD) | 0x40;
1022 
1023  if (resp != NULL) {
1024  resp_type = resp[0];
1025  }
1026  /* If no argument given, send 0's */
1027  if (arg == NULL) {
1028  cmd_seq[1] = 0x00;
1029  cmd_seq[2] = 0x00;
1030  cmd_seq[3] = 0x00;
1031  cmd_seq[4] = 0x00;
1032  /* else create cmd bytes according to the (address) argument */
1033  } else {
1034  cmd_seq[1] = ((*arg & 0xFF000000) >> 24);
1035  cmd_seq[2] = ((*arg & 0x00FF0000) >> 16);
1036  cmd_seq[3] = ((*arg & 0x0000FF00) >> 8);
1037  cmd_seq[4] = ((*arg & 0x000000FF));
1038  }
1039 
1040  /* CMD0 is the only command that always requires a valid CRC */
1041  if (cmd == SDCARD_CMD0) {
1042  cmd_seq[5] = 0x95;
1043  /* Calc CRC if enabled */
1044  } else if ((sdcard_crc_enable) || (cmd == SDCARD_CMD8)) {
1045  sdcard_cmd_crc(cmd_seq);
1046  /* Else set fixed value (last bit must be '1') */
1047  } else {
1048  cmd_seq[5] = 0xFF;
1049  }
1050 
1051  /* Send the 48 command bits */
1052  for (i = 0; i < 6; i++) {
1053  mspi_transceive(*(cmd_seq + i));
1054  }
1055 
1056  /* wait for the answer of the sd card */
1057  i = 0;
1058  do {
1059  i++;
1060  /*0x01 for acknowledge*/
1061  data = mspi_transceive(MSPI_DUMMY_BYTE);
1063 
1064  /* If we still wait for the Rx response,
1065  * we do not accept 0xFF */
1066  if ((data == 0xFF) && (idx == 0)) {
1067  continue;
1068  }
1069 
1070  /* For R1 with NULL arg (no return buffer) */
1071  if (resp == NULL) {
1072  dbg_resp_r1(cmd, data);
1073  break;
1074  }
1075 
1076  switch (resp_type) {
1077 
1078  case SDCARD_RESP1:
1079  resp[0] = data;
1080  dbg_resp_r1(cmd, data);
1081  i = 501;
1082  break;
1083 
1084  case SDCARD_RESP2:
1085  resp[idx] = data;
1086  idx++;
1087  if ((idx >= 2) || (resp[0] & 0xFE) != 0) {
1088  dbg_resp_r2(cmd, resp);
1089  data = resp[0];
1090  i = 501;
1091  }
1092  break;
1093 
1094  case SDCARD_RESP3:
1095  case SDCARD_RESP7:
1096  resp[idx] = data;
1097  idx++;
1098  if ((idx >= 5) || (resp[0] & 0xFE) != 0) {
1099  if (resp_type == SDCARD_RESP3) {
1100  dbg_resp_r3(cmd, resp);
1101  } else {
1102  dbg_resp_r7(cmd, resp);
1103  }
1104  data = resp[0];
1105  i = 501;
1106  }
1107  break;
1108  }
1109  } while (i < 100); // should not be more than N_CR_MAX + 5
1110 
1111  /* Loop left at 500 indicates timeout error */
1112  if (i == 500) {
1113  PRINTD("\nResponse timeout");
1114  data = 0xFF;
1115  }
1116 
1117  return data;
1118 }
1119 /*----------------------------------------------------------------------------*/