4 * This file is part of BeRTOS.
6 * Bertos is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
20 * As a special exception, you may use this file as part of a free software
21 * library without restriction. Specifically, if other files instantiate
22 * templates or use macros or inline functions from this file, or you compile
23 * this file and link it with other files to produce an executable, this
24 * file does not by itself cause the resulting executable to be covered by
25 * the GNU General Public License. This exception does not however
26 * invalidate any other reasons why the executable file might be covered by
27 * the GNU General Public License.
29 * Copyright 2007 Develer S.r.l. (http://www.develer.com/)
32 * \brief Function library for secure digital memory.
34 * \author Francesco Sacchi <batt@develer.com>
41 #include <io/kblock.h>
42 #include <drv/timer.h>
46 #include "cfg/cfg_sd.h"
48 #define LOG_LEVEL SD_LOG_LEVEL
49 #define LOG_FORMAT SD_LOG_FORMAT
51 #include <cpu/power.h>
53 #include <string.h> /* memset */
57 * read directly from the card.
59 typedef struct CardCSD
61 uint16_t block_len; ///< Length of a block
62 uint32_t block_num; ///< Number of block on the card
63 uint16_t capacity; ///< Card capacity in MB
66 #define SD_IN_IDLE 0x01
67 #define SD_STARTTOKEN 0xFE
69 #define TIMEOUT_NAC 16384
70 #define SD_DEFAULT_BLOCKLEN 512
72 #define SD_BUSY_TIMEOUT ms_to_ticks(200)
74 static bool sd_select(Sd *sd, bool state)
82 ticks_t start = timer_clock();
85 if (kfile_getc(fd) == 0xff)
90 while (timer_clock() - start < SD_BUSY_TIMEOUT);
93 LOG_ERR("sd_select timeout\n");
105 static int16_t sd_waitR1(Sd *sd)
109 for (int i = 0; i < TIMEOUT_NAC; i++)
111 datain = kfile_getc(sd->ch);
113 return (int16_t)datain;
115 LOG_ERR("Timeout waiting R1\n");
119 static int16_t sd_sendCommand(Sd *sd, uint8_t cmd, uint32_t param, uint8_t crc)
122 /* The 7th bit of command must be a 1 */
123 kfile_putc(cmd | 0x40, fd);
126 kfile_putc((param >> 24) & 0xFF, fd);
127 kfile_putc((param >> 16) & 0xFF, fd);
128 kfile_putc((param >> 8) & 0xFF, fd);
129 kfile_putc((param) & 0xFF, fd);
133 return sd_waitR1(sd);
136 static bool sd_getBlock(Sd *sd, void *buf, size_t len)
143 for (int i = 0; i < TIMEOUT_NAC; i++)
145 token = kfile_getc(fd);
148 if (token == SD_STARTTOKEN)
150 if (kfile_read(fd, buf, len) == len)
152 if (kfile_read(fd, &crc, sizeof(crc)) == sizeof(crc))
153 /* check CRC here if needed */
156 LOG_ERR("get_block error getting crc\n");
159 LOG_ERR("get_block len error: %d\n", (int)len);
162 LOG_ERR("get_block token error: %02X\n", token);
168 LOG_ERR("get_block timeout waiting token\n");
172 #define SD_SELECT(sd) \
175 if (!sd_select((sd), true)) \
177 LOG_ERR("%s failed, card busy\n", __func__); \
183 #define SD_SETBLOCKLEN 0x50
185 static int16_t sd_setBlockLen(Sd *sd, uint32_t newlen)
189 sd->r1 = sd_sendCommand(sd, SD_SETBLOCKLEN, newlen, 0);
191 sd_select(sd, false);
195 #define SD_SEND_CSD 0x49
197 static int16_t sd_getCSD(Sd *sd, CardCSD *csd)
201 int16_t r1 = sd_sendCommand(sd, SD_SEND_CSD, 0, 0);
205 LOG_ERR("send_csd failed: %04X\n", sd->r1);
206 sd_select(sd, false);
211 bool res = sd_getBlock(sd, buf, sizeof(buf));
212 sd_select(sd, false);
216 #if LOG_LEVEL >= LOG_LVL_INFO
218 for (int i = 0; i < 16; i++)
219 kprintf("%02X ", buf[i]);
223 uint16_t mult = (1L << ((((buf[9] & 0x03) << 1) | ((buf[10] & 0x80) >> 7)) + 2));
224 uint16_t c_size = (((uint16_t)(buf[6] & 0x03)) << 10) | (((uint16_t)buf[7]) << 2) |
225 (((uint16_t)(buf[8] & 0xC0)) >> 6);
227 csd->block_len = (1L << (buf[5] & 0x0F));
228 csd->block_num = (c_size + 1) * mult;
229 csd->capacity = (csd->block_len * csd->block_num) >> 20; // in MB
231 LOG_INFO("block_len %d bytes, block_num %ld, total capacity %dMB\n", csd->block_len, csd->block_num, csd->capacity);
239 #define SD_READ_SINGLEBLOCK 0x51
241 static size_t sd_readDirect(struct KBlock *b, block_idx_t idx, void *buf, size_t offset, size_t size)
244 LOG_INFO("reading from block %ld, offset %d, size %d\n", idx, offset, size);
246 if (sd->tranfer_len != size)
248 if ((sd->r1 = sd_setBlockLen(sd, size)))
250 LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
253 sd->tranfer_len = size;
258 sd->r1 = sd_sendCommand(sd, SD_READ_SINGLEBLOCK, idx * SD_DEFAULT_BLOCKLEN + offset, 0);
262 LOG_ERR("read single block failed: %04X\n", sd->r1);
263 sd_select(sd, false);
267 bool res = sd_getBlock(sd, buf, size);
268 sd_select(sd, false);
271 LOG_ERR("read single block failed reading data\n");
278 #define SD_WRITE_SINGLEBLOCK 0x58
279 #define SD_DATA_ACCEPTED 0x05
281 static size_t sd_writeDirect(KBlock *b, block_idx_t idx, const void *buf, size_t offset, size_t size)
286 ASSERT(size == SD_DEFAULT_BLOCKLEN);
288 LOG_INFO("writing block %ld\n", idx);
289 if (sd->tranfer_len != SD_DEFAULT_BLOCKLEN)
291 if ((sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN)))
293 LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
296 sd->tranfer_len = SD_DEFAULT_BLOCKLEN;
301 sd->r1 = sd_sendCommand(sd, SD_WRITE_SINGLEBLOCK, idx * SD_DEFAULT_BLOCKLEN, 0);
305 LOG_ERR("write single block failed: %04X\n", sd->r1);
306 sd_select(sd, false);
310 kfile_putc(SD_STARTTOKEN, fd);
311 kfile_write(fd, buf, SD_DEFAULT_BLOCKLEN);
316 uint8_t dataresp = kfile_getc(fd);
317 sd_select(sd, false);
319 if ((dataresp & 0x1f) != SD_DATA_ACCEPTED)
321 LOG_ERR("write block %ld failed: %02X\n", idx, dataresp);
325 return SD_DEFAULT_BLOCKLEN;
328 void sd_writeTest(Sd *sd)
330 uint8_t buf[SD_DEFAULT_BLOCKLEN];
331 memset(buf, 0, sizeof(buf));
333 for (block_idx_t i = 0; i < sd->b.blk_cnt; i++)
335 LOG_INFO("writing block %ld: %s\n", i, (sd_writeDirect(&sd->b, i, buf, 0, SD_DEFAULT_BLOCKLEN) == SD_DEFAULT_BLOCKLEN) ? "OK" : "FAIL");
342 uint8_t buf[SD_DEFAULT_BLOCKLEN];
344 if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
348 for (int i = 0; i < SD_DEFAULT_BLOCKLEN; i++)
350 kprintf("%02X ", buf[i]);
356 if (sd_writeDirect(&sd->b, 0, buf, 0, SD_DEFAULT_BLOCKLEN) != SD_DEFAULT_BLOCKLEN)
359 memset(buf, 0, sizeof(buf));
360 if (sd_readDirect(&sd->b, 0, buf, 0, sd->b.blk_size) != sd->b.blk_size)
364 for (block_idx_t i = 0; i < sd->b.blk_size; i++)
366 kprintf("%02X ", buf[i]);
375 static int sd_error(KBlock *b)
381 static void sd_clearerr(KBlock *b)
387 static const KBlockVTable sd_unbuffered_vt =
389 .readDirect = sd_readDirect,
390 .writeDirect = sd_writeDirect,
393 .clearerr = sd_clearerr,
396 static const KBlockVTable sd_buffered_vt =
398 .readDirect = sd_readDirect,
399 .writeDirect = sd_writeDirect,
401 .readBuf = kblock_swReadBuf,
402 .writeBuf = kblock_swWriteBuf,
403 .load = kblock_swLoad,
404 .store = kblock_swStore,
407 .clearerr = sd_clearerr,
410 #define SD_GO_IDLE_STATE 0x40
411 #define SD_GO_IDLE_STATE_CRC 0x95
412 #define SD_SEND_OP_COND 0x41
413 #define SD_SEND_OP_COND_CRC 0xF9
415 #define SD_START_DELAY 10
416 #define SD_INIT_TIMEOUT ms_to_ticks(2000)
417 #define SD_IDLE_RETRIES 4
419 static bool sd_blockInit(Sd *sd, KFile *ch)
423 memset(sd, 0, sizeof(*sd));
424 DB(sd->b.priv.type = KBT_SD);
430 /* Wait a few moments for supply voltage to stabilize */
431 timer_delay(SD_START_DELAY);
433 /* Give 80 clk pulses to wake up the card */
434 for (int i = 0; i < 10; i++)
435 kfile_putc(0xff, ch);
438 for (int i = 0; i < SD_IDLE_RETRIES; i++)
441 sd->r1 = sd_sendCommand(sd, SD_GO_IDLE_STATE, 0, SD_GO_IDLE_STATE_CRC);
442 sd_select(sd, false);
444 if (sd->r1 == SD_IN_IDLE)
448 if (sd->r1 != SD_IN_IDLE)
450 LOG_ERR("go_idle_state failed: %04X\n", sd->r1);
454 ticks_t start = timer_clock();
456 /* Wait for card to start */
460 sd->r1 = sd_sendCommand(sd, SD_SEND_OP_COND, 0, SD_SEND_OP_COND_CRC);
461 sd_select(sd, false);
464 while (sd->r1 != 0 && timer_clock() - start < SD_INIT_TIMEOUT);
468 LOG_ERR("send_op_cond failed: %04X\n", sd->r1);
472 sd->r1 = sd_setBlockLen(sd, SD_DEFAULT_BLOCKLEN);
473 sd->tranfer_len = SD_DEFAULT_BLOCKLEN;
477 LOG_ERR("setBlockLen failed: %04X\n", sd->r1);
481 /* Avoid warning for uninitialized csd use (gcc bug?) */
484 sd->r1 = sd_getCSD(sd, &csd);
488 LOG_ERR("getCSD failed: %04X\n", sd->r1);
492 sd->b.blk_size = SD_DEFAULT_BLOCKLEN;
493 sd->b.blk_cnt = csd.block_num * (csd.block_len / SD_DEFAULT_BLOCKLEN);
494 LOG_INFO("blk_size %d, blk_cnt %ld\n", sd->b.blk_size, sd->b.blk_cnt);
496 #if CONFIG_SD_AUTOASSIGN_FAT
497 disk_assignDrive(&sd->b, 0);
505 #include <drv/hsmci_sam3.h>
507 /* SD commands type argument response */
509 /* This is basically the same command as for MMC with some quirks. */
510 #define SD_SEND_RELATIVE_ADDR 3 /* bcr R6 */
511 #define SD_SEND_IF_COND 8 /* bcr [11:0] See below R7 */
512 #define SD_SWITCH_VOLTAGE 11 /* ac R1 */
515 #define SD_SWITCH 6 /* adtc [31:0] See below R1 */
518 #define SD_ERASE_WR_BLK_START 32 /* ac [31:0] data addr R1 */
519 #define SD_ERASE_WR_BLK_END 33 /* ac [31:0] data addr R1 */
521 /* Application commands */
522 #define SD_APP_SET_BUS_WIDTH 6 /* ac [1:0] bus width R1 */
523 #define SD_APP_SD_STATUS 13 /* adtc R1 */
524 #define SD_APP_SEND_NUM_WR_BLKS 22 /* adtc R1 */
525 #define SD_APP_OP_COND 41 /* bcr [31:0] OCR R3 */
526 #define SD_APP_SEND_SCR 51 /* adtc R1 */
528 /* OCR bit definitions */
529 #define SD_OCR_S18R (1 << 24) /* 1.8V switching request */
530 #define SD_ROCR_S18A SD_OCR_S18R /* 1.8V switching accepted by card */
531 #define SD_OCR_XPC (1 << 28) /* SDXC power control */
534 * SD_SWITCH argument format:
536 * [31] Check (0) or switch (1)
537 * [30:24] Reserved (0)
538 * [23:20] Function group 6
539 * [19:16] Function group 5
540 * [15:12] Function group 4
541 * [11:8] Function group 3
542 * [7:4] Function group 2
543 * [3:0] Function group 1
547 * SD_SEND_IF_COND argument format:
549 * [31:12] Reserved (0)
550 * [11:8] Host Voltage Supply Flags
551 * [7:0] Check Pattern (0xAA)
555 * SCR field definitions
558 #define SCR_SPEC_VER_0 0 /* Implements system specification 1.0 - 1.01 */
559 #define SCR_SPEC_VER_1 1 /* Implements system specification 1.10 */
560 #define SCR_SPEC_VER_2 2 /* Implements system specification 2.00-3.0X */
562 #define UNSTUFF_BITS(resp, start, size) \
564 const uint32_t __size = size; \
565 const uint32_t __mask = (__size < 32 ? 1 << __size : 0) - 1; \
566 const uint32_t __off = 3 - ((start) / 32); \
567 const uint32_t __shft = (start) & 31; \
570 __res = resp[__off] >> __shft; \
571 if (__size + __shft > 32) \
572 __res |= resp[__off-1] << ((32 - __shft) % 32); \
577 #define BCD_TO_INT_32BIT(bcd) ((uint32_t )((bcd) & 0xf) * 1 + \
578 (((bcd) >> 4) & 0xf) * 10 + \
579 (((bcd) >> 8) & 0xf) * 100 + \
580 (((bcd) >> 12) & 0xf) * 1000 + \
581 (((bcd) >> 16) & 0xf) * 10000 + \
582 (((bcd) >> 20) & 0xf) * 100000 + \
583 (((bcd) >> 24) & 0xf) * 1000000 + \
584 (((bcd) >> 28) & 0xf) * 10000000) \
587 int sd_decode_csd(SDcsd *csd, uint32_t *resp, size_t len)
593 csd->structure = UNSTUFF_BITS(resp, 126, 2);
594 csd->ccc = UNSTUFF_BITS(resp, 84, 12);
596 if (csd->structure == 0)
598 kprintf("csize %ld\n", UNSTUFF_BITS(resp, 62, 12));
599 kprintf("csize_mul %ld\n", UNSTUFF_BITS(resp, 47, 3));
600 kprintf("bit read %ld %ld\n", csd->read_blk_bits = UNSTUFF_BITS(resp, 80, 4), csd->read_blk_bits);
602 // (C_size + 1) x 2^(C_SIZE_MUL+2)
603 csd->blk_num = (1 + UNSTUFF_BITS(resp, 62, 12)) << (UNSTUFF_BITS(resp, 47, 3) + 2);
605 csd->read_blk_bits = UNSTUFF_BITS(resp, 80, 4);
606 csd->write_blk_bits = UNSTUFF_BITS(resp, 22, 4);
608 csd->blk_len = 1 << csd->read_blk_bits;
609 csd->capacity = csd->blk_num * csd->blk_len;
611 csd->read_partial = UNSTUFF_BITS(resp, 79, 1);
612 csd->read_misalign = UNSTUFF_BITS(resp, 77, 1);
614 csd->write_misalign = UNSTUFF_BITS(resp, 78, 1);
615 csd->write_partial = UNSTUFF_BITS(resp, 21, 1);
617 if (UNSTUFF_BITS(resp, 46, 1))
621 else if(csd->write_blk_bits >= 9)
623 csd->erase_size = UNSTUFF_BITS(resp, 39, 7) + 1;
624 csd->erase_size <<= csd->write_blk_bits - 9;
629 else if (csd->structure == 1)
631 kprintf("csize %ld\n", UNSTUFF_BITS(resp, 48, 22));
632 csd->capacity = (1 + UNSTUFF_BITS(resp, 48, 22)) << 10;
634 csd->write_blk_bits = 9;
635 csd->write_partial = 0;
636 csd->write_misalign = 0;
638 csd->read_blk_bits = 9;
639 csd->read_partial = 0;
640 csd->read_misalign = 0;
643 // the block size if fixed to 512kb
644 csd->blk_len = (1 << csd->write_blk_bits) << 10;
650 kprintf("Unrecognised CSD structure version %d\n", csd->structure);
658 void sd_dump_csd(SDcsd *csd)
662 kprintf("VERSION: %d.0\n", csd->structure ? 2 : 1);
663 kprintf("CARD COMMAND CLASS: %d\n", csd->ccc);
664 kprintf("WRITE BLK LEN BITS: %ld\n", csd->write_blk_bits);
665 kprintf("READ BLK LEN BITS: %ld\n", csd->read_blk_bits);
666 kprintf("ERASE SIZE: %ld\n", csd->erase_size);
667 kprintf("BLK NUM: %ld\n", csd->blk_num);
668 kprintf("BLK LEN: %ld\n", csd->blk_len);
669 kprintf("CAPACITY %ld\n", csd->capacity);
670 kprintf("FLAG Write: WP %d, W MISALIGN %d\n", csd->write_partial, csd->write_misalign);
671 kprintf("FLAG Read: RP %d, R MISALIGN %d\n", csd->read_partial, csd->read_misalign);
676 void sd_decode_cid(SDcid *cid, uint32_t *resp, size_t len)
682 cid->manfid = UNSTUFF_BITS(resp, 120, 8);
683 cid->oemid = UNSTUFF_BITS(resp, 104, 16);
684 cid->prod_name[0] = UNSTUFF_BITS(resp, 96, 8);
685 cid->prod_name[1] = UNSTUFF_BITS(resp, 88, 8);
686 cid->prod_name[2] = UNSTUFF_BITS(resp, 80, 8);
687 cid->prod_name[3] = UNSTUFF_BITS(resp, 72, 8);
688 cid->prod_name[4] = UNSTUFF_BITS(resp, 64, 8);
689 cid->m_rev = UNSTUFF_BITS(resp, 60, 4);
690 cid->l_rev = UNSTUFF_BITS(resp, 56, 4);
691 cid->serial = (uint32_t)UNSTUFF_BITS(resp, 24, 32);
692 cid->year_off = UNSTUFF_BITS(resp, 8, 12);
695 void sd_dump_cid(SDcid *cid)
699 kprintf("MANFID: %d\n", cid->manfid);
700 kprintf("OEMID: %d\n", cid->oemid);
701 kprintf("SERIAL: %ld\n", cid->serial);
702 kprintf("PROD_NAME: %s\n", cid->prod_name);
703 kprintf("REV: %d.%d\n", cid->m_rev, cid->l_rev);
704 kprintf("OFF,Y,M: %lx, %ld\n", cid->year_off, BCD_TO_INT_32BIT(cid->year_off));
707 void sd_send_init(void)
709 if (hsmci_sendCmd(0, 0, HSMCI_CMDR_SPCMD_INIT | HSMCI_CMDR_RSPTYP_NORESP))
710 kprintf("INIT Errore %lx\n", HSMCI_SR);
714 void sd_go_idle(void)
716 if (hsmci_sendCmd(0, 0, HSMCI_CMDR_RSPTYP_NORESP))
717 kprintf("0 Errore %lx\n", HSMCI_SR);
720 int sd_send_if_cond(void)
722 if (hsmci_sendCmd(8, CMD8_V_RANGE_27V_36V, HSMCI_CMDR_RSPTYP_48_BIT))
724 kprintf("8 Errore %lx\n", HSMCI_SR);
729 uint32_t r = HSMCI_RSPR;
730 if ((r & 0xFFF) == CMD8_V_RANGE_27V_36V)
732 kprintf("8 ok: %lx\n", r);
735 kprintf("8 ko: %lx\n", r);
740 int sd_send_app_op_cond(void)
742 if (hsmci_sendCmd(55, 0, HSMCI_CMDR_RSPTYP_48_BIT))
744 kprintf("55 Errore %lx\n", HSMCI_SR);
749 kprintf("55 Risposta %lx\n", HSMCI_RSPR);
752 // if (hsmci_sendCmd(41, SD_HOST_VOLTAGE_RANGE, HSMCI_CMDR_RSPTYP_48_BIT))
753 if (hsmci_sendCmd(41, SD_HOST_VOLTAGE_RANGE | SD_OCR_CCS, HSMCI_CMDR_RSPTYP_48_BIT))// se cmd 8 va ok.
755 kprintf("41 Errore %lx\n", HSMCI_SR);
760 uint32_t status = HSMCI_RSPR;
761 kprintf("41 reply[%0lx]\n", status);
762 if (status & SD_OCR_BUSY)
764 kprintf("sd power up! Hight Capability [%ld]\n", status & SD_OCR_CCS);
768 kputs("sd not ready.\n");
774 int sd_get_cid(uint32_t *resp, size_t len)
776 if (hsmci_sendCmd(2, 0, HSMCI_CMDR_RSPTYP_136_BIT))
778 kprintf("2 Errore %lx\n", HSMCI_SR);
782 hsmci_readResp(resp, len);
787 int sd_get_csd(uint32_t *resp, size_t len)
789 if (hsmci_sendCmd(9, 0, HSMCI_CMDR_RSPTYP_136_BIT))
791 kprintf("9 Errore %lx\n", HSMCI_SR);
795 hsmci_readResp(resp, len);
800 int sd_app_status(uint32_t *resp, size_t len)
802 if (hsmci_sendCmd(13, 0, HSMCI_CMDR_RSPTYP_48_BIT))
804 kprintf("13 Errore %lx\n", HSMCI_SR);
808 hsmci_readResp(resp, len);
813 int sd_send_relative_addr(uint32_t *resp, size_t len)
816 if (hsmci_sendCmd(3, 0, HSMCI_CMDR_RSPTYP_48_BIT))
818 kprintf("3 Errore %lx\n", HSMCI_SR);
822 hsmci_readResp(resp, len);
827 void sd_decode_addr(SDAddr *addr, uint32_t *resp, size_t len)
833 kprintf("%0lx\n", resp[0] >> 16);
834 addr->rca = UNSTUFF_BITS(resp, 16, 16);
835 addr->status = UNSTUFF_BITS(resp, 0, 16);
838 void sd_dump_addr(SDAddr *addr)
841 kprintf("RCA: %0lx\n", addr->rca);
842 kprintf("STATUS: %0lx\n", addr->status);
848 bool sd_initUnbuf(Sd *sd, KFile *ch)
850 if (sd_blockInit(sd, ch))
852 sd->b.priv.vt = &sd_unbuffered_vt;
859 static uint8_t sd_buf[SD_DEFAULT_BLOCKLEN];
861 bool sd_initBuf(Sd *sd, KFile *ch)
863 if (sd_blockInit(sd, ch))
865 sd->b.priv.buf = sd_buf;
866 sd->b.priv.flags |= KB_BUFFERED | KB_PARTIAL_WRITE;
867 sd->b.priv.vt = &sd_buffered_vt;
868 sd->b.priv.vt->load(&sd->b, 0);