sd.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #include <rtthread.h>
  2. #include <dfs_fs.h>
  3. #include "spi.h"
  4. #include "sd.h"
  5. /* 512 bytes for each sector */
  6. #define SD_SECTOR_SIZE 512
  7. /* token for write operation */
  8. #define TOKEN_SINGLE_BLOCK 0xFE
  9. #define TOKEN_MULTI_BLOCK 0xFC
  10. #define TOKEN_STOP_TRAN 0xFD
  11. /* Local variables */
  12. static uint8_t CardType;
  13. static SDCFG SDCfg;
  14. static struct rt_device sdcard_device;
  15. static struct dfs_partition part;
  16. /* Local Function Prototypes */
  17. static bool LPC17xx_SD_Init (void);
  18. static uint8_t LPC17xx_SD_SendCmd (uint8_t cmd, uint32_t arg);
  19. static bool LPC17xx_SD_ReadSector (uint32_t sector, uint8_t *buff, uint32_t count);
  20. static bool LPC17xx_SD_ReadDataBlock ( uint8_t *buff, uint32_t cnt);
  21. static bool LPC17xx_SD_WriteSector (uint32_t sector, const uint8_t *buff, uint32_t count);
  22. static bool LPC17xx_SD_WirteDataBlock (const uint8_t *buff, uint8_t token);
  23. static bool LPC17xx_SD_ReadCfg (SDCFG *cfg);
  24. static bool LPC17xx_SD_WaitForReady (void);
  25. /* wait until the card is not busy */
  26. static bool LPC17xx_SD_WaitForReady (void)
  27. {
  28. uint8_t res;
  29. /* timeout should be large enough to make sure the write operaion can be completed. */
  30. uint32_t timeout = 400000;
  31. LPC17xx_SPI_SendByte(0xFF);
  32. do {
  33. res = LPC17xx_SPI_RecvByte();
  34. } while ((res != 0xFF) && timeout--);
  35. return (res == 0xFF ? true : false);
  36. }
  37. /* Initialize SD/MMC card. */
  38. static bool LPC17xx_SD_Init (void)
  39. {
  40. uint32_t i, timeout;
  41. uint8_t cmd, ct, ocr[4];
  42. bool ret = false;
  43. /* Initialize SPI interface and enable Flash Card SPI mode. */
  44. LPC17xx_SPI_Init ();
  45. /* At least 74 clock cycles are required prior to starting bus communication */
  46. for (i = 0; i < 80; i++) { /* 80 dummy clocks */
  47. LPC17xx_SPI_SendByte (0xFF);
  48. }
  49. ct = CT_NONE;
  50. if (LPC17xx_SD_SendCmd (GO_IDLE_STATE, 0) == 0x1)
  51. {
  52. timeout = 50000;
  53. if (LPC17xx_SD_SendCmd(CMD8, 0x1AA) == 1) { /* SDHC */
  54. /* Get trailing return value of R7 resp */
  55. for (i = 0; i < 4; i++) ocr[i] = LPC17xx_SPI_RecvByte();
  56. if (ocr[2] == 0x01 && ocr[3] == 0xAA) { /* The card can work at vdd range of 2.7-3.6V */
  57. /* Wait for leaving idle state (ACMD41 with HCS bit) */
  58. while (timeout-- && LPC17xx_SD_SendCmd(SD_SEND_OP_COND, 1UL << 30));
  59. /* Check CCS bit in the OCR */
  60. if (timeout && LPC17xx_SD_SendCmd(READ_OCR, 0) == 0) {
  61. for (i = 0; i < 4; i++) ocr[i] = LPC17xx_SPI_RecvByte();
  62. ct = (ocr[0] & 0x40) ? CT_SD2 | CT_BLOCK : CT_SD2;
  63. }
  64. } else { /* SDSC or MMC */
  65. if (LPC17xx_SD_SendCmd(SD_SEND_OP_COND, 0) <= 1) {
  66. ct = CT_SD1; cmd = SD_SEND_OP_COND; /* SDSC */
  67. } else {
  68. ct = CT_MMC; cmd = SEND_OP_COND; /* MMC */
  69. }
  70. /* Wait for leaving idle state */
  71. while (timeout-- && LPC17xx_SD_SendCmd(cmd, 0));
  72. /* Set R/W block length to 512 */
  73. if (!timeout || LPC17xx_SD_SendCmd(SET_BLOCKLEN, SD_SECTOR_SIZE) != 0)
  74. ct = CT_NONE;
  75. }
  76. }
  77. else { /* SDSC or MMC */
  78. if (LPC17xx_SD_SendCmd(SD_SEND_OP_COND, 0) <= 1) {
  79. ct = CT_SD1; cmd = SD_SEND_OP_COND; /* SDSC */
  80. } else {
  81. ct = CT_MMC; cmd = SEND_OP_COND; /* MMC */
  82. }
  83. /* Wait for leaving idle state */
  84. while (timeout-- && LPC17xx_SD_SendCmd(cmd, 0));
  85. /* Set R/W block length to 512 */
  86. if (!timeout || LPC17xx_SD_SendCmd(SET_BLOCKLEN, SD_SECTOR_SIZE) != 0)
  87. ct = CT_NONE;
  88. }
  89. }
  90. CardType = ct;
  91. LPC17xx_SPI_Release();
  92. if (ct) { /* Initialization succeeded */
  93. ret = true;
  94. if ( ct == CT_MMC ) {
  95. LPC17xx_SPI_SetSpeed(SPI_SPEED_20MHz);
  96. } else {
  97. LPC17xx_SPI_SetSpeed(SPI_SPEED_20MHz);
  98. }
  99. } else { /* Initialization failed */
  100. LPC17xx_SPI_Select ();
  101. LPC17xx_SD_WaitForReady ();
  102. LPC17xx_SPI_DeInit();
  103. }
  104. return ret;
  105. }
  106. /*****************************************************************************
  107. Send a Command to Flash card and get a Response
  108. cmd: cmd index
  109. arg: argument for the cmd
  110. return the received response of the commond
  111. *****************************************************************************/
  112. static uint8_t LPC17xx_SD_SendCmd (uint8_t cmd, uint32_t arg)
  113. {
  114. uint32_t r1, n;
  115. if (cmd & 0x80) { /* ACMD<n> is the command sequence of CMD55-CMD<n> */
  116. cmd &= 0x7F;
  117. r1 = LPC17xx_SD_SendCmd(APP_CMD, 0); /* CMD55 */
  118. if (r1 > 1) return r1; /* cmd send failed */
  119. }
  120. /* Select the card and wait for ready */
  121. LPC17xx_SPI_DeSelect();
  122. LPC17xx_SPI_Select();
  123. if (LPC17xx_SD_WaitForReady() == false ) return 0xFF;
  124. LPC17xx_SPI_SendByte (0xFF); /* prepare 8 clocks */
  125. LPC17xx_SPI_SendByte (cmd);
  126. LPC17xx_SPI_SendByte (arg >> 24);
  127. LPC17xx_SPI_SendByte (arg >> 16);
  128. LPC17xx_SPI_SendByte (arg >> 8);
  129. LPC17xx_SPI_SendByte (arg);
  130. /* Checksum, should only be valid for the first command.CMD0 */
  131. n = 0x01; /* Dummy CRC + Stop */
  132. if (cmd == GO_IDLE_STATE) n = 0x95; /* Valid CRC for CMD0(0) */
  133. if (cmd == CMD8) n = 0x87; /* Valid CRC for CMD8(0x1AA) */
  134. LPC17xx_SPI_SendByte(n);
  135. if (cmd == STOP_TRAN) LPC17xx_SPI_RecvByte (); /* Skip a stuff byte when stop reading */
  136. n = 10; /* Wait for a valid response in timeout of 10 attempts */
  137. do {
  138. r1 = LPC17xx_SPI_RecvByte ();
  139. } while ((r1 & 0x80) && --n);
  140. return (r1); /* Return with the response value */
  141. }
  142. /*****************************************************************************
  143. Read "count" Sector(s) starting from sector index "sector",
  144. buff <- [sector, sector+1, ... sector+count-1]
  145. if success, return true, otherwise return false
  146. *****************************************************************************/
  147. static bool LPC17xx_SD_ReadSector (uint32_t sector, uint8_t *buff, uint32_t count)
  148. {
  149. /* Convert to byte address if needed */
  150. if (!(CardType & CT_BLOCK)) sector *= SD_SECTOR_SIZE;
  151. if (count == 1) { /* Single block read */
  152. if ((LPC17xx_SD_SendCmd(READ_BLOCK, sector) == 0)
  153. && LPC17xx_SD_ReadDataBlock(buff, SD_SECTOR_SIZE))
  154. count = 0;
  155. } else { /* Multiple block read */
  156. if (LPC17xx_SD_SendCmd(READ_MULT_BLOCK, sector) == 0) {
  157. do {
  158. if (!LPC17xx_SD_ReadDataBlock(buff, SD_SECTOR_SIZE)) break;
  159. buff += SD_SECTOR_SIZE;
  160. } while (--count);
  161. LPC17xx_SD_SendCmd(STOP_TRAN, 0); /* STOP_TRANSMISSION */
  162. }
  163. }
  164. LPC17xx_SPI_Release();
  165. return count ? false : true;
  166. }
  167. /*****************************************************************************
  168. read specified number of data to specified buffer.
  169. buff: Data buffer to store received data
  170. cnt: Byte count (must be multiple of 4, normally 512)
  171. *****************************************************************************/
  172. static bool LPC17xx_SD_ReadDataBlock ( uint8_t *buff, uint32_t cnt)
  173. {
  174. uint8_t token;
  175. uint32_t timeout;
  176. timeout = 20000;
  177. do { /* Wait for data packet in timeout of 100ms */
  178. token = LPC17xx_SPI_RecvByte();
  179. } while ((token == 0xFF) && timeout--);
  180. if(token != 0xFE) return false; /* If not valid data token, return with error */
  181. #if USE_FIFO
  182. LPC17xx_SPI_RecvBlock_FIFO (buff, cnt);
  183. #else
  184. do { /* Receive the data block into buffer */
  185. *buff++ = LPC17xx_SPI_RecvByte ();
  186. *buff++ = LPC17xx_SPI_RecvByte ();
  187. *buff++ = LPC17xx_SPI_RecvByte ();
  188. *buff++ = LPC17xx_SPI_RecvByte ();
  189. } while (cnt -= 4);
  190. #endif /* USE_FIFO */
  191. LPC17xx_SPI_RecvByte (); /* Discard CRC */
  192. LPC17xx_SPI_RecvByte ();
  193. return true; /* Return with success */
  194. }
  195. /*****************************************************************************
  196. Write "count" Sector(s) starting from sector index "sector",
  197. buff -> [sector, sector+1, ... sector+count-1]
  198. if success, return true, otherwise return false
  199. *****************************************************************************/
  200. static bool LPC17xx_SD_WriteSector (uint32_t sector, const uint8_t *buff, uint32_t count)
  201. {
  202. if (!(CardType & CT_BLOCK)) sector *= 512; /* Convert to byte address if needed */
  203. if (count == 1) { /* Single block write */
  204. if ((LPC17xx_SD_SendCmd(WRITE_BLOCK, sector) == 0)
  205. && LPC17xx_SD_WirteDataBlock(buff, TOKEN_SINGLE_BLOCK))
  206. count = 0;
  207. } else { /* Multiple block write */
  208. if (CardType & CT_SDC) LPC17xx_SD_SendCmd(SET_WR_BLK_ERASE_COUNT, count);
  209. if (LPC17xx_SD_SendCmd(WRITE_MULT_BLOCK, sector) == 0) {
  210. do {
  211. if (!LPC17xx_SD_WirteDataBlock(buff, TOKEN_MULTI_BLOCK)) break;
  212. buff += 512;
  213. } while (--count);
  214. #if 1
  215. if (!LPC17xx_SD_WirteDataBlock(0, TOKEN_STOP_TRAN)) /* STOP_TRAN token */
  216. count = 1;
  217. #else
  218. LPC17xx_SPI_SendByte(TOKEN_STOP_TRAN);
  219. #endif
  220. }
  221. }
  222. LPC17xx_SPI_Release();
  223. return count ? false : true;
  224. }
  225. /*****************************************************************************
  226. Write 512 bytes
  227. buffer: 512 byte data block to be transmitted
  228. token: 0xFE -> single block
  229. 0xFC -> multi block
  230. 0xFD -> Stop
  231. *****************************************************************************/
  232. static bool LPC17xx_SD_WirteDataBlock (const uint8_t *buff, uint8_t token)
  233. {
  234. uint8_t resp, i;
  235. i = i; // avoid warning
  236. LPC17xx_SPI_SendByte (token); /* send data token first*/
  237. if (token != TOKEN_STOP_TRAN) {
  238. #if USE_FIFO
  239. LPC17xx_SPI_SendBlock_FIFO (buff);
  240. #else
  241. /* Send data. */
  242. for (i = 512/4; i ; i--) {
  243. LPC17xx_SPI_SendByte (*buff++);
  244. LPC17xx_SPI_SendByte (*buff++);
  245. LPC17xx_SPI_SendByte (*buff++);
  246. LPC17xx_SPI_SendByte (*buff++);
  247. }
  248. #endif /* USE_FIFO */
  249. LPC17xx_SPI_SendByte(0xFF); /* 16-bit CRC (Dummy) */
  250. LPC17xx_SPI_SendByte(0xFF);
  251. resp = LPC17xx_SPI_RecvByte(); /* Receive data response */
  252. if ((resp & 0x1F) != 0x05) /* If not accepted, return with error */
  253. return false;
  254. if ( LPC17xx_SD_WaitForReady() == false) /* Wait while Flash Card is busy. */
  255. return false;
  256. }
  257. return true;
  258. }
  259. /* Read MMC/SD Card device configuration. */
  260. static bool LPC17xx_SD_ReadCfg (SDCFG *cfg)
  261. {
  262. uint8_t i;
  263. uint16_t csize;
  264. uint8_t n, csd[16];
  265. bool retv = false;
  266. /* Read the OCR - Operations Condition Register. */
  267. if (LPC17xx_SD_SendCmd (READ_OCR, 0) != 0x00) goto x;
  268. for (i = 0; i < 4; i++) cfg->ocr[i] = LPC17xx_SPI_RecvByte ();
  269. /* Read the CID - Card Identification. */
  270. if ((LPC17xx_SD_SendCmd (SEND_CID, 0) != 0x00) ||
  271. (LPC17xx_SD_ReadDataBlock (cfg->cid, 16) == false))
  272. goto x;
  273. /* Read the CSD - Card Specific Data. */
  274. if ((LPC17xx_SD_SendCmd (SEND_CSD, 0) != 0x00) ||
  275. (LPC17xx_SD_ReadDataBlock (cfg->csd, 16) == false))
  276. goto x;
  277. cfg -> sectorsize = SD_SECTOR_SIZE;
  278. /* Get number of sectors on the disk (DWORD) */
  279. if ((cfg->csd[0] >> 6) == 1) { /* SDC ver 2.00 */
  280. csize = cfg->csd[9] + ((uint16_t)cfg->csd[8] << 8) + 1;
  281. cfg -> sectorcnt = (uint32_t)csize << 10;
  282. } else { /* SDC ver 1.XX or MMC*/
  283. n = (cfg->csd[5] & 15) + ((cfg->csd[10] & 128) >> 7) + ((cfg->csd[9] & 3) << 1) + 2; // 19
  284. csize = (cfg->csd[8] >> 6) + ((uint16_t)cfg->csd[7] << 2) + ((uint16_t)(cfg->csd[6] & 3) << 10) + 1; // 3752
  285. cfg -> sectorcnt = (uint32_t)csize << (n - 9); // 3842048
  286. }
  287. cfg->size = cfg -> sectorcnt * cfg -> sectorsize; // 512*3842048=1967128576Byte (1.83GB)
  288. /* Get erase block size in unit of sector (DWORD) */
  289. if (CardType & CT_SD2) { /* SDC ver 2.00 */
  290. if (LPC17xx_SD_SendCmd(SD_STATUS /*ACMD13*/, 0) == 0) { /* Read SD status */
  291. LPC17xx_SPI_RecvByte();
  292. if (LPC17xx_SD_ReadDataBlock(csd, 16)) { /* Read partial block */
  293. for (n = 64 - 16; n; n--) LPC17xx_SPI_RecvByte(); /* Purge trailing data */
  294. cfg->blocksize = 16UL << (csd[10] >> 4);
  295. retv = true;
  296. }
  297. }
  298. } else { /* SDC ver 1.XX or MMC */
  299. if ((LPC17xx_SD_SendCmd(SEND_CSD, 0) == 0) && LPC17xx_SD_ReadDataBlock(csd, 16)) { /* Read CSD */
  300. if (CardType & CT_SD1) { /* SDC ver 1.XX */
  301. cfg->blocksize = (((csd[10] & 63) << 1) + ((uint16_t)(csd[11] & 128) >> 7) + 1) << ((csd[13] >> 6) - 1);
  302. } else { /* MMC */
  303. // cfg->blocksize = ((uint16_t)((buf[10] & 124) >> 2) + 1) * (((buf[11] & 3) << 3) + ((buf[11] & 224) >> 5) + 1);
  304. cfg->blocksize = ((uint16_t)((cfg->csd[10] & 124) >> 2) + 1) * (((cfg->csd[10] & 3) << 3) + ((cfg->csd[11] & 224) >> 5) + 1);
  305. }
  306. retv = true;
  307. }
  308. }
  309. x: LPC17xx_SPI_Release();
  310. return (retv);
  311. }
  312. static rt_err_t rt_sdcard_init(rt_device_t dev)
  313. {
  314. return RT_EOK;
  315. }
  316. static rt_err_t rt_sdcard_open(rt_device_t dev, rt_uint16_t oflag)
  317. {
  318. return RT_EOK;
  319. }
  320. static rt_err_t rt_sdcard_close(rt_device_t dev)
  321. {
  322. return RT_EOK;
  323. }
  324. static rt_size_t rt_sdcard_read(rt_device_t dev, rt_off_t pos, void* buffer, rt_size_t size)
  325. {
  326. bool status;
  327. status = LPC17xx_SD_ReadSector(part.offset + pos, buffer, size);
  328. if (status == true) return size;
  329. rt_kprintf("read failed: %d, pos 0x%08x, size %d\n", status, pos, size);
  330. return 0;
  331. }
  332. static rt_size_t rt_sdcard_write (rt_device_t dev, rt_off_t pos, const void* buffer, rt_size_t size)
  333. {
  334. bool status;
  335. status = LPC17xx_SD_WriteSector(part.offset + pos, buffer, size);
  336. if (status == true) return size;
  337. rt_kprintf("write failed: %d, pos 0x%08x, size %d\n", status, pos, size);
  338. return 0;
  339. }
  340. static rt_err_t rt_sdcard_control(rt_device_t dev, rt_uint8_t cmd, void *args)
  341. {
  342. return RT_EOK;
  343. }
  344. void rt_hw_sdcard_init()
  345. {
  346. if (LPC17xx_SD_Init() && LPC17xx_SD_ReadCfg(&SDCfg))
  347. {
  348. bool status;
  349. rt_uint8_t *sector;
  350. /* get the first sector to read partition table */
  351. sector = (rt_uint8_t*) rt_malloc (512);
  352. if (sector == RT_NULL)
  353. {
  354. rt_kprintf("allocate partition sector buffer failed\n");
  355. return;
  356. }
  357. status = LPC17xx_SD_ReadSector(0, sector, 1);
  358. if (status == true)
  359. {
  360. /* get the first partition */
  361. if (dfs_filesystem_get_partition(&part, sector, 0) != 0)
  362. {
  363. /* there is no partition */
  364. part.offset = 0;
  365. part.size = 0;
  366. }
  367. }
  368. else
  369. {
  370. /* there is no partition table */
  371. part.offset = 0;
  372. part.size = 0;
  373. }
  374. /* release sector buffer */
  375. rt_free(sector);
  376. /* register sdcard device */
  377. sdcard_device.type = RT_Device_Class_Block;
  378. sdcard_device.init = rt_sdcard_init;
  379. sdcard_device.open = rt_sdcard_open;
  380. sdcard_device.close = rt_sdcard_close;
  381. sdcard_device.read = rt_sdcard_read;
  382. sdcard_device.write = rt_sdcard_write;
  383. sdcard_device.control = rt_sdcard_control;
  384. /* no private */
  385. sdcard_device.private = &SDCfg;
  386. rt_device_register(&sdcard_device, "sd0",
  387. RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_REMOVABLE | RT_DEVICE_FLAG_STANDALONE);
  388. return;
  389. }
  390. rt_kprintf("sdcard init failed\n");
  391. }