sd.c 17 KB

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