3 * Copyright (c) 2006-2009 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.
18 #include <avr/interrupt.h>
20 #include <cfg/debug.h>
23 * \addtogroup sd_raw MMC/SD/SDHC card raw access
25 * This module implements read and write access to MMC, SD
26 * and SDHC cards. It serves as a low-level driver for the
27 * higher level modules such as partition and file system
34 * MMC/SD/SDHC raw access implementation (license: GPLv2 or LGPLv2.1)
36 * \author Roland Riegel
40 * \addtogroup sd_raw_config MMC/SD configuration
41 * Preprocessor defines to configure the MMC/SD support.
48 /* commands available in SPI mode */
50 /* CMD0: response R1 */
51 #define CMD_GO_IDLE_STATE 0x00
52 /* CMD1: response R1 */
53 #define CMD_SEND_OP_COND 0x01
54 /* CMD8: response R7 */
55 #define CMD_SEND_IF_COND 0x08
56 /* CMD9: response R1 */
57 #define CMD_SEND_CSD 0x09
58 /* CMD10: response R1 */
59 #define CMD_SEND_CID 0x0a
60 /* CMD12: response R1 */
61 #define CMD_STOP_TRANSMISSION 0x0c
62 /* CMD13: response R2 */
63 #define CMD_SEND_STATUS 0x0d
64 /* CMD16: arg0[31:0]: block length, response R1 */
65 #define CMD_SET_BLOCKLEN 0x10
66 /* CMD17: arg0[31:0]: data address, response R1 */
67 #define CMD_READ_SINGLE_BLOCK 0x11
68 /* CMD18: arg0[31:0]: data address, response R1 */
69 #define CMD_READ_MULTIPLE_BLOCK 0x12
70 /* CMD24: arg0[31:0]: data address, response R1 */
71 #define CMD_WRITE_SINGLE_BLOCK 0x18
72 /* CMD25: arg0[31:0]: data address, response R1 */
73 #define CMD_WRITE_MULTIPLE_BLOCK 0x19
74 /* CMD27: response R1 */
75 #define CMD_PROGRAM_CSD 0x1b
76 /* CMD28: arg0[31:0]: data address, response R1b */
77 #define CMD_SET_WRITE_PROT 0x1c
78 /* CMD29: arg0[31:0]: data address, response R1b */
79 #define CMD_CLR_WRITE_PROT 0x1d
80 /* CMD30: arg0[31:0]: write protect data address, response R1 */
81 #define CMD_SEND_WRITE_PROT 0x1e
82 /* CMD32: arg0[31:0]: data address, response R1 */
83 #define CMD_TAG_SECTOR_START 0x20
84 /* CMD33: arg0[31:0]: data address, response R1 */
85 #define CMD_TAG_SECTOR_END 0x21
86 /* CMD34: arg0[31:0]: data address, response R1 */
87 #define CMD_UNTAG_SECTOR 0x22
88 /* CMD35: arg0[31:0]: data address, response R1 */
89 #define CMD_TAG_ERASE_GROUP_START 0x23
90 /* CMD36: arg0[31:0]: data address, response R1 */
91 #define CMD_TAG_ERASE_GROUP_END 0x24
92 /* CMD37: arg0[31:0]: data address, response R1 */
93 #define CMD_UNTAG_ERASE_GROUP 0x25
94 /* CMD38: arg0[31:0]: stuff bits, response R1b */
95 #define CMD_ERASE 0x26
96 /* ACMD41: arg0[31:0]: OCR contents, response R1 */
97 #define CMD_SD_SEND_OP_COND 0x29
98 /* CMD42: arg0[31:0]: stuff bits, response R1b */
99 #define CMD_LOCK_UNLOCK 0x2a
100 /* CMD55: arg0[31:0]: stuff bits, response R1 */
102 /* CMD58: arg0[31:0]: stuff bits, response R3 */
103 #define CMD_READ_OCR 0x3a
104 /* CMD59: arg0[31:1]: stuff bits, arg0[0:0]: crc option, response R1 */
105 #define CMD_CRC_ON_OFF 0x3b
107 /* command responses */
108 /* R1: size 1 byte */
109 #define R1_IDLE_STATE 0
110 #define R1_ERASE_RESET 1
111 #define R1_ILL_COMMAND 2
112 #define R1_COM_CRC_ERR 3
113 #define R1_ERASE_SEQ_ERR 4
114 #define R1_ADDR_ERR 5
115 #define R1_PARAM_ERR 6
116 /* R1b: equals R1, additional busy bytes */
117 /* R2: size 2 bytes */
118 #define R2_CARD_LOCKED 0
119 #define R2_WP_ERASE_SKIP 1
121 #define R2_CARD_ERR 3
122 #define R2_CARD_ECC_FAIL 4
123 #define R2_WP_VIOLATION 5
124 #define R2_INVAL_ERASE 6
125 #define R2_OUT_OF_RANGE 7
126 #define R2_CSD_OVERWRITE 7
127 #define R2_IDLE_STATE (R1_IDLE_STATE + 8)
128 #define R2_ERASE_RESET (R1_ERASE_RESET + 8)
129 #define R2_ILL_COMMAND (R1_ILL_COMMAND + 8)
130 #define R2_COM_CRC_ERR (R1_COM_CRC_ERR + 8)
131 #define R2_ERASE_SEQ_ERR (R1_ERASE_SEQ_ERR + 8)
132 #define R2_ADDR_ERR (R1_ADDR_ERR + 8)
133 #define R2_PARAM_ERR (R1_PARAM_ERR + 8)
134 /* R3: size 5 bytes */
135 #define R3_OCR_MASK (0xffffffffUL)
136 #define R3_IDLE_STATE (R1_IDLE_STATE + 32)
137 #define R3_ERASE_RESET (R1_ERASE_RESET + 32)
138 #define R3_ILL_COMMAND (R1_ILL_COMMAND + 32)
139 #define R3_COM_CRC_ERR (R1_COM_CRC_ERR + 32)
140 #define R3_ERASE_SEQ_ERR (R1_ERASE_SEQ_ERR + 32)
141 #define R3_ADDR_ERR (R1_ADDR_ERR + 32)
142 #define R3_PARAM_ERR (R1_PARAM_ERR + 32)
143 /* Data Response: size 1 byte */
144 #define DR_STATUS_MASK 0x0e
145 #define DR_STATUS_ACCEPTED 0x05
146 #define DR_STATUS_CRC_ERR 0x0a
147 #define DR_STATUS_WRITE_ERR 0x0c
149 /* status bits for card types */
150 #define SD_RAW_SPEC_1 0
151 #define SD_RAW_SPEC_2 1
152 #define SD_RAW_SPEC_SDHC 2
155 /* static data buffer for acceleration */
156 static uint8_t raw_block[512];
157 /* offset where the data within raw_block lies on the card */
158 static offset_t raw_block_address;
159 #if SD_RAW_WRITE_BUFFERING
160 /* flag to remember if raw_block was written to the card */
161 static uint8_t raw_block_written;
165 /* card type state */
166 static uint8_t sd_raw_card_type;
168 /* private helper functions */
169 static void sd_raw_send_byte(uint8_t b);
170 static uint8_t sd_raw_rec_byte(void);
171 static uint8_t sd_raw_send_command(uint8_t command, uint32_t arg);
177 * Initializes memory card communication.
179 * \returns 0 on failure, 1 on success.
181 uint8_t sd_raw_init()
183 /* enable inputs for reading card status */
184 configure_pin_available();
185 configure_pin_locked();
187 /* enable outputs for MOSI, SCK, SS, input for MISO */
188 configure_pin_mosi();
191 configure_pin_miso();
196 /* initialize SPI with lowest frequency; max. 400kHz during identification mode of card */
197 SPCR = (0 << SPIE) | /* SPI Interrupt Enable */
198 (1 << SPE) | /* SPI Enable */
199 (0 << DORD) | /* Data Order: MSB first */
200 (1 << MSTR) | /* Master mode */
201 (0 << CPOL) | /* Clock Polarity: SCK low when idle */
202 (0 << CPHA);// | /* Clock Phase: sample on rising SCK edge */
203 //(1 << SPR1) | /* Clock Frequency: f_OSC / 128 */
205 //SPSR &= ~(1 << SPI2X); /* No doubled clock frequency */
206 SPSR |= (1 << SPI2X);
208 /* initialization procedure */
209 sd_raw_card_type = 0;
211 if(!sd_raw_available())
214 /* card needs 74 cycles minimum to start up */
215 for(i2 = 0; i2 < 10; ++i2)
217 /* wait 8 clock cycles */
228 response = sd_raw_send_command(CMD_GO_IDLE_STATE, 0);
229 //uart_putw_hex(response);
231 if(response == (1 << R1_IDLE_STATE))
237 //uart_puts_p(PSTR("No Response to Idle\n"));
243 /* check for version of SD card specification */
244 response = sd_raw_send_command(CMD_SEND_IF_COND, 0x100 /* 2.7V - 3.6V */ | 0xaa /* test pattern */);
245 if((response & (1 << R1_ILL_COMMAND)) == 0)
249 if((sd_raw_rec_byte() & 0x01) == 0)
250 return 0; /* card operation voltage range doesn't match */
251 if(sd_raw_rec_byte() != 0xaa)
252 return 0; /* wrong test pattern */
254 /* card conforms to SD 2 card specification */
255 sd_raw_card_type |= (1 << SD_RAW_SPEC_2);
260 /* determine SD/MMC card type */
261 sd_raw_send_command(CMD_APP, 0);
262 response = sd_raw_send_command(CMD_SD_SEND_OP_COND, 0);
263 if((response & (1 << R1_ILL_COMMAND)) == 0)
265 /* card conforms to SD 1 card specification */
266 sd_raw_card_type |= (1 << SD_RAW_SPEC_1);
274 /* wait for card to get ready */
277 if(sd_raw_card_type & ((1 << SD_RAW_SPEC_1) | (1 << SD_RAW_SPEC_2)))
281 if(sd_raw_card_type & (1 << SD_RAW_SPEC_2))
284 sd_raw_send_command(CMD_APP, 0);
285 response = sd_raw_send_command(CMD_SD_SEND_OP_COND, arg);
289 response = sd_raw_send_command(CMD_SEND_OP_COND, 0);
292 if((response & (1 << R1_IDLE_STATE)) == 0)
298 //uart_puts_p(PSTR("No Response to Ready...\n"));
304 if(sd_raw_card_type & (1 << SD_RAW_SPEC_2))
306 if(sd_raw_send_command(CMD_READ_OCR, 0))
312 if(sd_raw_rec_byte() & 0x40)
313 sd_raw_card_type |= (1 << SD_RAW_SPEC_SDHC);
321 /* set block size to 512 bytes */
322 if(sd_raw_send_command(CMD_SET_BLOCKLEN, 512))
325 //uart_puts_p(PSTR("Failed at 'set block size'\n"));
332 /* switch to highest SPI frequency possible */
333 SPCR &= ~((1 << SPR1) | (1 << SPR0)); /* Clock Frequency: f_OSC / 4 */
334 SPSR |= (1 << SPI2X); /* Doubled Clock Frequency: f_OSC / 2 */
337 /* the first block is likely to be accessed first, so precache it here */
338 raw_block_address = (offset_t) -1;
339 #if SD_RAW_WRITE_BUFFERING
340 raw_block_written = 1;
342 if(!sd_raw_read(0, raw_block, sizeof(raw_block))){
343 //uart_puts_p(PSTR("Failed at Raw Save RAM\n"));
353 * Checks wether a memory card is located in the slot.
355 * \returns 1 if the card is available, 0 if it is not.
357 uint8_t sd_raw_available()
359 return get_pin_available() == 0x00;
364 * Checks wether the memory card is locked for write access.
366 * \returns 1 if the card is locked, 0 if it is not.
368 uint8_t sd_raw_locked()
370 return get_pin_locked() == 0x00;
375 * Sends a raw byte to the memory card.
377 * \param[in] b The byte to sent.
378 * \see sd_raw_rec_byte
380 void sd_raw_send_byte(uint8_t b)
383 /* wait for byte to be shifted out */
384 while(!(SPSR & (1 << SPIF)));
385 SPSR &= ~(1 << SPIF);
390 * Receives a raw byte from the memory card.
392 * \returns The byte which should be read.
393 * \see sd_raw_send_byte
395 uint8_t sd_raw_rec_byte(void)
397 /* send dummy data for receiving some */
399 while(!(SPSR & (1 << SPIF)));
400 SPSR &= ~(1 << SPIF);
407 * Send a command to the memory card which responses with a R1 response (and possibly others).
409 * \param[in] command The command to send.
410 * \param[in] arg The argument for command.
411 * \returns The command answer.
413 uint8_t sd_raw_send_command(uint8_t command, uint32_t arg)
417 /* wait some clock cycles */
420 /* send command via SPI */
421 sd_raw_send_byte(0x40 | command);
422 sd_raw_send_byte((arg >> 24) & 0xff);
423 sd_raw_send_byte((arg >> 16) & 0xff);
424 sd_raw_send_byte((arg >> 8) & 0xff);
425 sd_raw_send_byte((arg >> 0) & 0xff);
428 case CMD_GO_IDLE_STATE:
429 sd_raw_send_byte(0x95);
431 case CMD_SEND_IF_COND:
432 sd_raw_send_byte(0x87);
435 sd_raw_send_byte(0xff);
439 /* receive response */
440 for(i2 = 0; i2 < 10; ++i2)
442 response = sd_raw_rec_byte();
452 * Reads raw data from the card.
454 * \param[in] offset The offset from which to read.
455 * \param[out] buffer The buffer into which to write the data.
456 * \param[in] length The number of bytes to read.
457 * \returns 0 on failure, 1 on success.
458 * \see sd_raw_read_interval, sd_raw_write, sd_raw_write_interval
460 uint8_t sd_raw_read(offset_t offset, uint8_t* buffer, uintptr_t length)
462 offset_t block_address;
463 uint16_t block_offset;
464 uint16_t read_length;
467 /* determine byte count to read at once */
468 block_offset = offset & 0x01ff;
469 block_address = offset - block_offset;
470 read_length = 512 - block_offset; /* read up to block border */
471 if(read_length > length)
472 read_length = length;
475 /* check if the requested data is cached */
476 if(block_address != raw_block_address)
479 #if SD_RAW_WRITE_BUFFERING
487 /* send single block request */
489 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? block_address / 512 : block_address)))
491 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, block_address))
498 /* wait for data block (start byte 0xfe) */
499 while(sd_raw_rec_byte() != 0xfe);
502 /* read byte block */
503 uint16_t read_to = block_offset + read_length;
504 for(i2 = 0; i < 512; ++i)
506 uint8_t b = sd_raw_rec_byte();
507 if(i >= block_offset && i < read_to)
511 /* read byte block */
512 uint8_t* cache = raw_block;
513 for(i2 = 0; i2 < 512; ++i2)
514 *cache++ = sd_raw_rec_byte();
515 raw_block_address = block_address;
517 memcpy(buffer, raw_block + block_offset, read_length);
518 buffer += read_length;
528 /* let card some time to finish */
534 /* use cached data */
535 memcpy(buffer, raw_block + block_offset, read_length);
536 buffer += read_length;
540 length -= read_length;
541 offset += read_length;
549 * Continuously reads units of \c interval bytes and calls a callback function.
551 * This function starts reading at the specified offset. Every \c interval bytes,
552 * it calls the callback function with the associated data buffer.
554 * By returning zero, the callback may stop reading.
556 * \note Within the callback function, you can not start another read or
558 * \note This function only works if the following conditions are met:
559 * - (offset - (offset % 512)) % interval == 0
560 * - length % interval == 0
562 * \param[in] offset Offset from which to start reading.
563 * \param[in] buffer Pointer to a buffer which is at least interval bytes in size.
564 * \param[in] interval Number of bytes to read before calling the callback function.
565 * \param[in] length Number of bytes to read altogether.
566 * \param[in] callback The function to call every interval bytes.
567 * \param[in] p An opaque pointer directly passed to the callback function.
568 * \returns 0 on failure, 1 on success
569 * \see sd_raw_write_interval, sd_raw_read, sd_raw_write
571 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)
573 if(!buffer || interval == 0 || length < interval || !callback)
577 while(length >= interval)
579 /* as reading is now buffered, we directly
580 * hand over the request to sd_raw_read()
582 if(!sd_raw_read(offset, buffer, interval))
584 if(!callback(buffer, offset, p))
595 uint16_t block_offset;
596 uint16_t read_length;
598 uint8_t finished = 0;
601 /* determine byte count to read at once */
602 block_offset = offset & 0x01ff;
603 read_length = 512 - block_offset;
605 /* send single block request */
607 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? offset / 512 : offset - block_offset)))
609 if(sd_raw_send_command(CMD_READ_SINGLE_BLOCK, offset - block_offset))
616 /* wait for data block (start byte 0xfe) */
617 while(sd_raw_rec_byte() != 0xfe);
619 /* read up to the data of interest */
620 for(i2 = 0; i < block_offset; ++i)
623 /* read interval bytes of data and execute the callback */
626 if(read_length < interval || length < interval)
630 for(i2 = 0; i < interval; ++i)
631 *buffer_cur++ = sd_raw_rec_byte();
633 if(!callback(buffer, offset + (512 - read_length), p))
639 read_length -= interval;
642 } while(read_length > 0 && length > 0);
644 /* read rest of data block */
645 while(read_length-- > 0)
652 if(length < interval)
655 offset = offset - block_offset + 512;
662 /* let card some time to finish */
669 #if SD_RAW_WRITE_SUPPORT
672 * Writes raw data to the card.
674 * \note If write buffering is enabled, you might have to
675 * call sd_raw_sync() before disconnecting the card
676 * to ensure all remaining data has been written.
678 * \param[in] offset The offset where to start writing.
679 * \param[in] buffer The buffer containing the data to be written.
680 * \param[in] length The number of bytes to write.
681 * \returns 0 on failure, 1 on success.
682 * \see sd_raw_write_interval, sd_raw_read, sd_raw_read_interval
684 uint8_t sd_raw_write(offset_t offset, const uint8_t* buffer, uintptr_t length)
689 offset_t block_address;
690 uint16_t block_offset;
691 uint16_t write_length;
694 /* determine byte count to write at once */
695 block_offset = offset & 0x01ff;
696 block_address = offset - block_offset;
697 write_length = 512 - block_offset; /* write up to block border */
698 if(write_length > length)
699 write_length = length;
701 /* Merge the data to write with the content of the block.
702 * Use the cached block if available.
704 if(block_address != raw_block_address)
706 #if SD_RAW_WRITE_BUFFERING
710 if(block_offset || write_length < 512)
712 if(!sd_raw_read(block_address, raw_block, sizeof(raw_block)))
715 raw_block_address = block_address;
718 if(buffer != raw_block)
720 memcpy(raw_block + block_offset, buffer, write_length);
722 #if SD_RAW_WRITE_BUFFERING
723 raw_block_written = 0;
725 if(length == write_length)
733 /* send single block request */
735 if(sd_raw_send_command(CMD_WRITE_SINGLE_BLOCK, (sd_raw_card_type & (1 << SD_RAW_SPEC_SDHC) ? block_address / 512 : block_address)))
737 if(sd_raw_send_command(CMD_WRITE_SINGLE_BLOCK, block_address))
744 /* send start byte */
745 sd_raw_send_byte(0xfe);
747 /* write byte block */
748 uint8_t* cache = raw_block;
749 for(i2 = 0; i2 < 512; ++i2)
750 sd_raw_send_byte(*cache++);
752 /* write dummy crc16 */
753 sd_raw_send_byte(0xff);
754 sd_raw_send_byte(0xff);
756 /* wait while card is busy */
757 while(sd_raw_rec_byte() != 0xff);
763 buffer += write_length;
764 offset += write_length;
765 length -= write_length;
767 #if SD_RAW_WRITE_BUFFERING
768 raw_block_written = 1;
776 #if SD_RAW_WRITE_SUPPORT
779 * Writes a continuous data stream obtained from a callback function.
781 * This function starts writing at the specified offset. To obtain the
782 * next bytes to write, it calls the callback function. The callback fills the
783 * provided data buffer and returns the number of bytes it has put into the buffer.
785 * By returning zero, the callback may stop writing.
787 * \param[in] offset Offset where to start writing.
788 * \param[in] buffer Pointer to a buffer which is used for the callback function.
789 * \param[in] length Number of bytes to write in total. May be zero for endless writes.
790 * \param[in] callback The function used to obtain the bytes to write.
791 * \param[in] p An opaque pointer directly passed to the callback function.
792 * \returns 0 on failure, 1 on success
793 * \see sd_raw_read_interval, sd_raw_write, sd_raw_read
795 uint8_t sd_raw_write_interval(offset_t offset, uint8_t* buffer, uintptr_t length, sd_raw_write_interval_handler_t callback, void* p)
798 #error "SD_RAW_WRITE_SUPPORT is not supported together with SD_RAW_SAVE_RAM"
801 if(!buffer || !callback)
804 uint8_t endless = (length == 0);
805 while(endless || length > 0)
807 uint16_t bytes_to_write = callback(buffer, offset, p);
810 if(!endless && bytes_to_write > length)
813 /* as writing is always buffered, we directly
814 * hand over the request to sd_raw_write()
816 if(!sd_raw_write(offset, buffer, bytes_to_write))
819 offset += bytes_to_write;
820 length -= bytes_to_write;
827 #if SD_RAW_WRITE_SUPPORT
830 * Writes the write buffer's content to the card.
832 * \note When write buffering is enabled, you should
833 * call this function before disconnecting the
834 * card to ensure all remaining data has been
837 * \returns 0 on failure, 1 on success.
840 uint8_t sd_raw_sync()
842 #if SD_RAW_WRITE_BUFFERING
843 if(raw_block_written)
845 if(!sd_raw_write(raw_block_address, raw_block, sizeof(raw_block)))
847 raw_block_written = 1;
855 * Reads informational data from the card.
857 * This function reads and returns the card's registers
858 * containing manufacturing and status information.
860 * \note: The information retrieved by this function is
861 * not required in any way to operate on the card,
862 * but it might be nice to display some of the data
865 * \param[in] info A pointer to the structure into which to save the information.
866 * \returns 0 on failure, 1 on success.
868 uint8_t sd_raw_get_info(struct sd_raw_info* info)
870 if(!info || !sd_raw_available())
873 memset(info, 0, sizeof(*info));
877 /* read cid register */
878 if(sd_raw_send_command(CMD_SEND_CID, 0))
883 while(sd_raw_rec_byte() != 0xfe);
884 for(i2 = 0; i2 < 18; ++i2)
886 uint8_t b = sd_raw_rec_byte();
891 info->manufacturer = b;
895 info->oem[i2 - 1] = b;
902 info->product[i2 - 3] = b;
911 info->serial |= (uint32_t) b << ((12 - i2) * 8);
914 info->manufacturing_year = b << 4;
917 info->manufacturing_year |= b >> 4;
918 info->manufacturing_month = b & 0x0f;
923 /* read csd register */
924 uint8_t csd_read_bl_len = 0;
925 uint8_t csd_c_size_mult = 0;
927 uint16_t csd_c_size = 0;
929 uint32_t csd_c_size = 0;
931 if(sd_raw_send_command(CMD_SEND_CSD, 0))
936 while(sd_raw_rec_byte() != 0xfe);
937 for(i2 = 0; i2 < 18; ++i2)
939 uint8_t b = sd_raw_rec_byte();
946 info->flag_write_protect = 1;
948 info->flag_write_protect_temp = 1;
949 info->format = (b & 0x0c) >> 2;
954 if(sd_raw_card_type & (1 << SD_RAW_SPEC_2))
969 info->capacity = (offset_t) csd_c_size * 512 * 1024;
978 csd_read_bl_len = b & 0x0f;
981 csd_c_size = b & 0x03;
989 csd_c_size |= b >> 6;
993 csd_c_size_mult = b & 0x03;
994 csd_c_size_mult <<= 1;
997 csd_c_size_mult |= b >> 7;
999 info->capacity = (uint32_t) csd_c_size << (csd_c_size_mult + csd_read_bl_len + 2);