3 * Copyright (c) 2006-2012 by Roland Riegel <feedback@roland-riegel.de>
5 * This file is free software; you can redistribute it and/or modify
6 * it under the terms of either the GNU General Public License version 2
7 * or the GNU Lesser General Public License version 2.1, both as
8 * published by the Free Software Foundation.
12 #include <avr/pgmspace.h>
19 * \addtogroup sd_raw MMC/SD/SDHC card raw access
21 * This module implements read and write access to MMC, SD
22 * and SDHC cards. It serves as a low-level driver for the
23 * higher level modules such as partition and file system
30 * MMC/SD/SDHC raw access implementation (license: GPLv2 or LGPLv2.1)
32 * \author Roland Riegel
36 * \addtogroup sd_raw_config MMC/SD configuration
37 * Preprocessor defines to configure the MMC/SD support.
44 /* commands available in SPI mode */
46 /* CMD0: response R1 */
47 #define CMD_GO_IDLE_STATE 0x00
48 /* CMD1: response R1 */
49 #define CMD_SEND_OP_COND 0x01
50 /* CMD8: response R7 */
51 #define CMD_SEND_IF_COND 0x08
52 /* CMD9: response R1 */
53 #define CMD_SEND_CSD 0x09
54 /* CMD10: response R1 */
55 #define CMD_SEND_CID 0x0a
56 /* CMD12: response R1 */
57 #define CMD_STOP_TRANSMISSION 0x0c
58 /* CMD13: response R2 */
59 #define CMD_SEND_STATUS 0x0d
60 /* CMD16: arg0[31:0]: block length, response R1 */
61 #define CMD_SET_BLOCKLEN 0x10
62 /* CMD17: arg0[31:0]: data address, response R1 */
63 #define CMD_READ_SINGLE_BLOCK 0x11
64 /* CMD18: arg0[31:0]: data address, response R1 */
65 #define CMD_READ_MULTIPLE_BLOCK 0x12
66 /* CMD24: arg0[31:0]: data address, response R1 */
67 #define CMD_WRITE_SINGLE_BLOCK 0x18
68 /* CMD25: arg0[31:0]: data address, response R1 */
69 #define CMD_WRITE_MULTIPLE_BLOCK 0x19
70 /* CMD27: response R1 */
71 #define CMD_PROGRAM_CSD 0x1b
72 /* CMD28: arg0[31:0]: data address, response R1b */
73 #define CMD_SET_WRITE_PROT 0x1c
74 /* CMD29: arg0[31:0]: data address, response R1b */
75 #define CMD_CLR_WRITE_PROT 0x1d
76 /* CMD30: arg0[31:0]: write protect data address, response R1 */
77 #define CMD_SEND_WRITE_PROT 0x1e
78 /* CMD32: arg0[31:0]: data address, response R1 */
79 #define CMD_TAG_SECTOR_START 0x20
80 /* CMD33: arg0[31:0]: data address, response R1 */
81 #define CMD_TAG_SECTOR_END 0x21
82 /* CMD34: arg0[31:0]: data address, response R1 */
83 #define CMD_UNTAG_SECTOR 0x22
84 /* CMD35: arg0[31:0]: data address, response R1 */
85 #define CMD_TAG_ERASE_GROUP_START 0x23
86 /* CMD36: arg0[31:0]: data address, response R1 */
87 #define CMD_TAG_ERASE_GROUP_END 0x24
88 /* CMD37: arg0[31:0]: data address, response R1 */
89 #define CMD_UNTAG_ERASE_GROUP 0x25
90 /* CMD38: arg0[31:0]: stuff bits, response R1b */
91 #define CMD_ERASE 0x26
92 /* ACMD41: arg0[31:0]: OCR contents, response R1 */
93 #define CMD_SD_SEND_OP_COND 0x29
94 /* CMD42: arg0[31:0]: stuff bits, response R1b */
95 #define CMD_LOCK_UNLOCK 0x2a
96 /* CMD55: arg0[31:0]: stuff bits, response R1 */
98 /* CMD58: arg0[31:0]: stuff bits, response R3 */
99 #define CMD_READ_OCR 0x3a
100 /* CMD59: arg0[31:1]: stuff bits, arg0[0:0]: crc option, response R1 */
101 #define CMD_CRC_ON_OFF 0x3b
103 /* command responses */
104 /* R1: size 1 byte */
105 #define R1_IDLE_STATE 0
106 #define R1_ERASE_RESET 1
107 #define R1_ILL_COMMAND 2
108 #define R1_COM_CRC_ERR 3
109 #define R1_ERASE_SEQ_ERR 4
110 #define R1_ADDR_ERR 5
111 #define R1_PARAM_ERR 6
112 /* R1b: equals R1, additional busy bytes */
113 /* R2: size 2 bytes */
114 #define R2_CARD_LOCKED 0
115 #define R2_WP_ERASE_SKIP 1
117 #define R2_CARD_ERR 3
118 #define R2_CARD_ECC_FAIL 4
119 #define R2_WP_VIOLATION 5
120 #define R2_INVAL_ERASE 6
121 #define R2_OUT_OF_RANGE 7
122 #define R2_CSD_OVERWRITE 7
123 #define R2_IDLE_STATE (R1_IDLE_STATE + 8)
124 #define R2_ERASE_RESET (R1_ERASE_RESET + 8)
125 #define R2_ILL_COMMAND (R1_ILL_COMMAND + 8)
126 #define R2_COM_CRC_ERR (R1_COM_CRC_ERR + 8)
127 #define R2_ERASE_SEQ_ERR (R1_ERASE_SEQ_ERR + 8)
128 #define R2_ADDR_ERR (R1_ADDR_ERR + 8)
129 #define R2_PARAM_ERR (R1_PARAM_ERR + 8)
130 /* R3: size 5 bytes */
131 #define R3_OCR_MASK (0xffffffffUL)
132 #define R3_IDLE_STATE (R1_IDLE_STATE + 32)
133 #define R3_ERASE_RESET (R1_ERASE_RESET + 32)
134 #define R3_ILL_COMMAND (R1_ILL_COMMAND + 32)
135 #define R3_COM_CRC_ERR (R1_COM_CRC_ERR + 32)
136 #define R3_ERASE_SEQ_ERR (R1_ERASE_SEQ_ERR + 32)
137 #define R3_ADDR_ERR (R1_ADDR_ERR + 32)
138 #define R3_PARAM_ERR (R1_PARAM_ERR + 32)
139 /* Data Response: size 1 byte */
140 #define DR_STATUS_MASK 0x0e
141 #define DR_STATUS_ACCEPTED 0x05
142 #define DR_STATUS_CRC_ERR 0x0a
143 #define DR_STATUS_WRITE_ERR 0x0c
145 /* status bits for card types */
146 #define SD_RAW_SPEC_1 0
147 #define SD_RAW_SPEC_2 1
148 #define SD_RAW_SPEC_SDHC 2
151 /* static data buffer for acceleration */
152 static uint8_t raw_block[512];
153 /* offset where the data within raw_block lies on the card */
154 static offset_t raw_block_address;
155 #if SD_RAW_WRITE_BUFFERING
156 /* flag to remember if raw_block was written to the card */
157 static uint8_t raw_block_written;
161 /* card type state */
162 static uint8_t sd_raw_card_type;
164 /* private helper functions */
165 static void sd_raw_send_byte(uint8_t b);
166 static uint8_t sd_raw_rec_byte(void);
167 static uint8_t sd_raw_send_command(uint8_t command, uint32_t arg);
171 * Initializes memory card communication.
173 * \returns 0 on failure, 1 on success.
175 uint8_t sd_raw_init(void)
177 /* enable inputs for reading card status */
178 configure_pin_available();
179 configure_pin_locked();
181 /* enable outputs for MOSI, SCK, SS, input for MISO */
182 configure_pin_mosi();
185 configure_pin_miso();
189 /* initialize SPI with lowest frequency; max. 400kHz during identification mode of card */
190 SPCR = (0 << SPIE) | /* SPI Interrupt Enable */
191 (1 << SPE) | /* SPI Enable */
192 (0 << DORD) | /* Data Order: MSB first */
193 (1 << MSTR) | /* Master mode */
194 (0 << CPOL) | /* Clock Polarity: SCK low when idle */
195 (0 << CPHA) | /* Clock Phase: sample on rising SCK edge */
196 (1 << SPR1) | /* Clock Frequency: f_OSC / 128 */
198 SPSR &= ~(1 << SPI2X); /* No doubled clock frequency */
200 /* initialization procedure */
201 sd_raw_card_type = 0;
203 if(!sd_raw_available())
206 /* card needs 74 cycles minimum to start up */
207 for(uint8_t i = 0; i < 10; ++i)
209 /* wait 8 clock cycles */
218 for(uint16_t i = 0; ; ++i)
220 response = sd_raw_send_command(CMD_GO_IDLE_STATE, 0);
221 if(response == (1 << R1_IDLE_STATE))
232 /* check for version of SD card specification */
233 response = sd_raw_send_command(CMD_SEND_IF_COND, 0x100 /* 2.7V - 3.6V */ | 0xaa /* test pattern */);
234 if((response & (1 << R1_ILL_COMMAND)) == 0)
238 if((sd_raw_rec_byte() & 0x01) == 0)
239 return 0; /* card operation voltage range doesn't match */
240 if(sd_raw_rec_byte() != 0xaa)
241 return 0; /* wrong test pattern */
243 /* card conforms to SD 2 card specification */
244 sd_raw_card_type |= (1 << SD_RAW_SPEC_2);
249 /* determine SD/MMC card type */
250 sd_raw_send_command(CMD_APP, 0);
251 response = sd_raw_send_command(CMD_SD_SEND_OP_COND, 0);
252 if((response & (1 << R1_ILL_COMMAND)) == 0)
254 /* card conforms to SD 1 card specification */
255 sd_raw_card_type |= (1 << SD_RAW_SPEC_1);
263 /* wait for card to get ready */
264 for(uint16_t i = 0; ; ++i)
266 if(sd_raw_card_type & ((1 << SD_RAW_SPEC_1) | (1 << SD_RAW_SPEC_2)))
270 if(sd_raw_card_type & (1 << SD_RAW_SPEC_2))
273 sd_raw_send_command(CMD_APP, 0);
274 response = sd_raw_send_command(CMD_SD_SEND_OP_COND, arg);
278 response = sd_raw_send_command(CMD_SEND_OP_COND, 0);
281 if((response & (1 << R1_IDLE_STATE)) == 0)
292 if(sd_raw_card_type & (1 << SD_RAW_SPEC_2))
294 if(sd_raw_send_command(CMD_READ_OCR, 0))
300 if(sd_raw_rec_byte() & 0x40)
301 sd_raw_card_type |= (1 << SD_RAW_SPEC_SDHC);
309 /* set block size to 512 bytes */
310 if(sd_raw_send_command(CMD_SET_BLOCKLEN, 512))
319 /* switch to highest SPI frequency possible */
320 SPCR &= ~((1 << SPR1) | (1 << SPR0)); /* Clock Frequency: f_OSC / 4 */
321 SPSR |= (1 << SPI2X); /* Doubled Clock Frequency: f_OSC / 2 */
324 /* the first block is likely to be accessed first, so precache it here */
325 raw_block_address = (offset_t) -1;
326 #if SD_RAW_WRITE_BUFFERING
327 raw_block_written = 1;
329 if(!sd_raw_read(0, raw_block, sizeof(raw_block)))
338 * Checks wether a memory card is located in the slot.
340 * \returns 1 if the card is available, 0 if it is not.
342 uint8_t sd_raw_available()
344 return get_pin_available() == 0x00;
349 * Checks wether the memory card is locked for write access.
351 * \returns 1 if the card is locked, 0 if it is not.
353 uint8_t sd_raw_locked()
355 return get_pin_locked() == 0x00;
360 * Sends a raw byte to the memory card.
362 * \param[in] b The byte to sent.
363 * \see sd_raw_rec_byte
365 void sd_raw_send_byte(uint8_t b)
368 /* wait for byte to be shifted out */
369 while(!(SPSR & (1 << SPIF)));
370 SPSR &= ~(1 << SPIF);
375 * Receives a raw byte from the memory card.
377 * \returns The byte which should be read.
378 * \see sd_raw_send_byte
380 uint8_t sd_raw_rec_byte()
382 /* send dummy data for receiving some */
384 while(!(SPSR & (1 << SPIF)));
385 SPSR &= ~(1 << SPIF);
392 * Send a command to the memory card which responses with a R1 response (and possibly others).
394 * \param[in] command The command to send.
395 * \param[in] arg The argument for command.
396 * \returns The command answer.
398 uint8_t sd_raw_send_command(uint8_t command, uint32_t arg)
402 /* wait some clock cycles */
405 /* send command via SPI */
406 sd_raw_send_byte(0x40 | command);
407 sd_raw_send_byte((arg >> 24) & 0xff);
408 sd_raw_send_byte((arg >> 16) & 0xff);
409 sd_raw_send_byte((arg >> 8) & 0xff);
410 sd_raw_send_byte((arg >> 0) & 0xff);
413 case CMD_GO_IDLE_STATE:
414 sd_raw_send_byte(0x95);
416 case CMD_SEND_IF_COND:
417 sd_raw_send_byte(0x87);
420 sd_raw_send_byte(0xff);
424 /* receive response */
425 for(uint8_t i = 0; i < 10; ++i)
427 response = sd_raw_rec_byte();
437 * Reads raw data from the card.
439 * \param[in] offset The offset from which to read.
440 * \param[out] buffer The buffer into which to write the data.
441 * \param[in] length The number of bytes to read.
442 * \returns 0 on failure, 1 on success.
443 * \see sd_raw_read_interval, sd_raw_write, sd_raw_write_interval
445 uint8_t sd_raw_read(offset_t offset, uint8_t* buffer, uintptr_t length)
447 offset_t block_address;
448 uint16_t block_offset;
449 uint16_t read_length;
452 /* determine byte count to read at once */
453 block_offset = offset & 0x01ff;
454 block_address = offset - block_offset;
455 read_length = 512 - block_offset; /* read up to block border */
456 if(read_length > length)
457 read_length = length;
460 /* check if the requested data is cached */
461 if(block_address != raw_block_address)
464 #if SD_RAW_WRITE_BUFFERING
472 /* send single block request */
474 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? block_address / 512 : block_address)))
476 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, block_address))
483 /* wait for data block (start byte 0xfe) */
484 while(sd_raw_rec_byte() != 0xfe);
487 /* read byte block */
488 uint16_t read_to = block_offset + read_length;
489 for(uint16_t i = 0; i < 512; ++i)
491 uint8_t b = sd_raw_rec_byte();
492 if(i >= block_offset && i < read_to)
496 /* read byte block */
497 uint8_t* cache = raw_block;
498 for(uint16_t i = 0; i < 512; ++i)
499 *cache++ = sd_raw_rec_byte();
500 raw_block_address = block_address;
502 memcpy(buffer, raw_block + block_offset, read_length);
503 buffer += read_length;
513 /* let card some time to finish */
519 /* use cached data */
520 memcpy(buffer, raw_block + block_offset, read_length);
521 buffer += read_length;
525 length -= read_length;
526 offset += read_length;
534 * Continuously reads units of \c interval bytes and calls a callback function.
536 * This function starts reading at the specified offset. Every \c interval bytes,
537 * it calls the callback function with the associated data buffer.
539 * By returning zero, the callback may stop reading.
541 * \note Within the callback function, you can not start another read or
543 * \note This function only works if the following conditions are met:
544 * - (offset - (offset % 512)) % interval == 0
545 * - length % interval == 0
547 * \param[in] offset Offset from which to start reading.
548 * \param[in] buffer Pointer to a buffer which is at least interval bytes in size.
549 * \param[in] interval Number of bytes to read before calling the callback function.
550 * \param[in] length Number of bytes to read altogether.
551 * \param[in] callback The function to call every interval bytes.
552 * \param[in] p An opaque pointer directly passed to the callback function.
553 * \returns 0 on failure, 1 on success
554 * \see sd_raw_write_interval, sd_raw_read, sd_raw_write
556 uint8_t sd_raw_read_interval(offset_t offset, uint8_t* buffer, uintptr_t interval, uintptr_t length, sd_raw_read_interval_handler_t callback, void* p)
558 if(!buffer || interval == 0 || length < interval || !callback)
562 while(length >= interval)
564 /* as reading is now buffered, we directly
565 * hand over the request to sd_raw_read()
567 if(!sd_raw_read(offset, buffer, interval))
569 if(!callback(buffer, offset, p))
580 uint16_t block_offset;
581 uint16_t read_length;
583 uint8_t finished = 0;
586 /* determine byte count to read at once */
587 block_offset = offset & 0x01ff;
588 read_length = 512 - block_offset;
590 /* send single block request */
592 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? offset / 512 : offset - block_offset)))
594 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, offset - block_offset))
601 /* wait for data block (start byte 0xfe) */
602 while(sd_raw_rec_byte() != 0xfe);
604 /* read up to the data of interest */
605 for(uint16_t i = 0; i < block_offset; ++i)
608 /* read interval bytes of data and execute the callback */
611 if(read_length < interval || length < interval)
615 for(uint16_t i = 0; i < interval; ++i)
616 *buffer_cur++ = sd_raw_rec_byte();
618 if(!callback(buffer, offset + (512 - read_length), p))
624 read_length -= interval;
627 } while(read_length > 0 && length > 0);
629 /* read rest of data block */
630 while(read_length-- > 0)
637 if(length < interval)
640 offset = offset - block_offset + 512;
647 /* let card some time to finish */
654 #if DOXYGEN || SD_RAW_WRITE_SUPPORT
657 * Writes raw data to the card.
659 * \note If write buffering is enabled, you might have to
660 * call sd_raw_sync() before disconnecting the card
661 * to ensure all remaining data has been written.
663 * \param[in] offset The offset where to start writing.
664 * \param[in] buffer The buffer containing the data to be written.
665 * \param[in] length The number of bytes to write.
666 * \returns 0 on failure, 1 on success.
667 * \see sd_raw_write_interval, sd_raw_read, sd_raw_read_interval
669 uint8_t sd_raw_write(offset_t offset, const uint8_t* buffer, uintptr_t length)
674 offset_t block_address;
675 uint16_t block_offset;
676 uint16_t write_length;
679 /* determine byte count to write at once */
680 block_offset = offset & 0x01ff;
681 block_address = offset - block_offset;
682 write_length = 512 - block_offset; /* write up to block border */
683 if(write_length > length)
684 write_length = length;
686 /* Merge the data to write with the content of the block.
687 * Use the cached block if available.
689 if(block_address != raw_block_address)
691 #if SD_RAW_WRITE_BUFFERING
696 if(block_offset || write_length < 512)
698 if(!sd_raw_read(block_address, raw_block, sizeof(raw_block)))
701 raw_block_address = block_address;
704 if(buffer != raw_block)
706 memcpy(raw_block + block_offset, buffer, write_length);
708 #if SD_RAW_WRITE_BUFFERING
709 raw_block_written = 0;
711 if(length == write_length)
719 /* send single block request */
721 if(sd_raw_send_command(CMD_WRITE_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? block_address / 512 : block_address)))
723 if(sd_raw_send_command(CMD_WRITE_SINGLE_BLOCK, block_address))
730 /* send start byte */
731 sd_raw_send_byte(0xfe);
733 /* write byte block */
734 uint8_t* cache = raw_block;
735 for(uint16_t i = 0; i < 512; ++i)
736 sd_raw_send_byte(*cache++);
738 /* write dummy crc16 */
739 sd_raw_send_byte(0xff);
740 sd_raw_send_byte(0xff);
742 /* wait while card is busy */
743 while(sd_raw_rec_byte() != 0xff);
749 buffer += write_length;
750 offset += write_length;
751 length -= write_length;
753 #if SD_RAW_WRITE_BUFFERING
754 raw_block_written = 1;
762 #if DOXYGEN || SD_RAW_WRITE_SUPPORT
765 * Writes a continuous data stream obtained from a callback function.
767 * This function starts writing at the specified offset. To obtain the
768 * next bytes to write, it calls the callback function. The callback fills the
769 * provided data buffer and returns the number of bytes it has put into the buffer.
771 * By returning zero, the callback may stop writing.
773 * \param[in] offset Offset where to start writing.
774 * \param[in] buffer Pointer to a buffer which is used for the callback function.
775 * \param[in] length Number of bytes to write in total. May be zero for endless writes.
776 * \param[in] callback The function used to obtain the bytes to write.
777 * \param[in] p An opaque pointer directly passed to the callback function.
778 * \returns 0 on failure, 1 on success
779 * \see sd_raw_read_interval, sd_raw_write, sd_raw_read
781 uint8_t sd_raw_write_interval(offset_t offset, uint8_t* buffer, uintptr_t length, sd_raw_write_interval_handler_t callback, void* p)
784 #error "SD_RAW_WRITE_SUPPORT is not supported together with SD_RAW_SAVE_RAM"
787 if(!buffer || !callback)
790 uint8_t endless = (length == 0);
791 while(endless || length > 0)
793 uint16_t bytes_to_write = callback(buffer, offset, p);
796 if(!endless && bytes_to_write > length)
799 /* as writing is always buffered, we directly
800 * hand over the request to sd_raw_write()
802 if(!sd_raw_write(offset, buffer, bytes_to_write))
805 offset += bytes_to_write;
806 length -= bytes_to_write;
813 #if DOXYGEN || SD_RAW_WRITE_SUPPORT
816 * Writes the write buffer's content to the card.
818 * \note When write buffering is enabled, you should
819 * call this function before disconnecting the
820 * card to ensure all remaining data has been
823 * \returns 0 on failure, 1 on success.
826 uint8_t sd_raw_sync()
828 #if SD_RAW_WRITE_BUFFERING
829 if(raw_block_written)
831 if(!sd_raw_write(raw_block_address, raw_block, sizeof(raw_block)))
833 raw_block_written = 1;
841 * Reads informational data from the card.
843 * This function reads and returns the card's registers
844 * containing manufacturing and status information.
846 * \note: The information retrieved by this function is
847 * not required in any way to operate on the card,
848 * but it might be nice to display some of the data
851 * \param[in] info A pointer to the structure into which to save the information.
852 * \returns 0 on failure, 1 on success.
854 uint8_t sd_raw_get_info(struct sd_raw_info* info)
856 if(!info || !sd_raw_available())
859 memset(info, 0, sizeof(*info));
863 /* read cid register */
864 if(sd_raw_send_command(CMD_SEND_CID, 0))
869 while(sd_raw_rec_byte() != 0xfe);
870 for(uint8_t i = 0; i < 18; ++i)
872 uint8_t b = sd_raw_rec_byte();
877 info->manufacturer = b;
881 info->oem[i - 1] = b;
888 info->product[i - 3] = b;
897 info->serial |= (uint32_t) b << ((12 - i) * 8);
900 info->manufacturing_year = b << 4;
903 info->manufacturing_year |= b >> 4;
904 info->manufacturing_month = b & 0x0f;
909 /* read csd register */
910 uint8_t csd_read_bl_len = 0;
911 uint8_t csd_c_size_mult = 0;
913 uint16_t csd_c_size = 0;
915 uint32_t csd_c_size = 0;
917 uint8_t csd_structure = 0;
918 if(sd_raw_send_command(CMD_SEND_CSD, 0))
923 while(sd_raw_rec_byte() != 0xfe);
924 for(uint8_t i = 0; i < 18; ++i)
926 uint8_t b = sd_raw_rec_byte();
930 csd_structure = b >> 6;
938 info->flag_write_protect = 1;
940 info->flag_write_protect_temp = 1;
941 info->format = (b & 0x0c) >> 2;
946 if(csd_structure == 0x01)
961 info->capacity = (offset_t) csd_c_size * 512 * 1024;
964 else if(csd_structure == 0x00)
970 csd_read_bl_len = b & 0x0f;
973 csd_c_size = b & 0x03;
981 csd_c_size |= b >> 6;
985 csd_c_size_mult = b & 0x03;
986 csd_c_size_mult <<= 1;
989 csd_c_size_mult |= b >> 7;
991 info->capacity = (uint32_t) csd_c_size << (csd_c_size_mult + csd_read_bl_len + 2);