sd.c 17 KB

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