2
0

sdcard.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /* ----------------------------------------------------------------------- *
  2. *
  3. * Copyright 2010-2021 H. Peter Anvin - All Rights Reserved
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
  8. * Boston MA 02110-1301, USA; either version 2 of the License, or
  9. * (at your option) any later version; incorporated herein by reference.
  10. *
  11. * ----------------------------------------------------------------------- */
  12. /*
  13. * sdcard.c
  14. *
  15. * SD card block driver
  16. *
  17. * Note: the handling of read operations is tricky, because they pick up
  18. * the results from the *previous* transaction. Therefore there are some
  19. * serious subtleties, especially with which byte position in the shift
  20. * register the result ends up in and what the size flag should be set to.
  21. */
  22. #include <stdbool.h>
  23. #include <stddef.h>
  24. #include <string.h>
  25. #include "fw.h"
  26. #include "io.h"
  27. #include "sdcard.h"
  28. #include "systime.h"
  29. #include "console.h"
  30. #include "ff.h"
  31. #include "diskio.h"
  32. #ifndef DEBUG
  33. # define DEBUG 0
  34. #endif
  35. #if DEBUG
  36. # define dbg_printf con_printf
  37. # define dbg_puts con_puts
  38. # define dbg_putc con_putc
  39. #else
  40. # define dbg_printf(f,...) ((void)0)
  41. # define dbg_puts(x) ((void)0)
  42. # define dbg_putc(x) ((void)0)
  43. #endif
  44. #define SECTOR_SHIFT 9
  45. #define SECTOR_SIZE (1UL << SECTOR_SHIFT)
  46. /* Command codes, including the leading 01 sequence */
  47. enum sdcard_cmd {
  48. CMD_GO_IDLE_STATE = 0x40, /* a.k.a. reset */
  49. CMD_SEND_OP_COND = 0x41,
  50. CMD_SWITCH_FUNC = 0x46,
  51. CMD_SEND_IF_COND = 0x48,
  52. CMD_SEND_CSD = 0x49,
  53. CMD_SEND_CID = 0x4a,
  54. CMD_STOP_TRANSMISSION = 0x4c,
  55. CMD_SEND_STATUS = 0x4d,
  56. CMD_SET_BLOCKLEN = 0x50,
  57. CMD_READ_SINGLE_BLOCK = 0x51,
  58. CMD_READ_MULTIPLE_BLOCK = 0x52,
  59. CMD_WRITE_BLOCK = 0x58,
  60. CMD_WRITE_MULTIPLE_BLOCK = 0x59,
  61. CMD_PROGRAM_CSD = 0x5b,
  62. CMD_SET_WRITE_PROT = 0x5c,
  63. CMD_CLR_WRITE_PROT = 0x5d,
  64. CMD_SEND_WRITE_PROT = 0x5e,
  65. CMD_ERASE_WR_BLK_START_ADDR = 0x60,
  66. CMD_ERASE_WR_BLK_END_ADDR = 0x61,
  67. CMD_ERASE = 0x66,
  68. CMD_LOCK_UNLOCK = 0x6a,
  69. CMD_APP_CMD = 0x77, /* == ACMD prefix */
  70. CMD_GEN_CMD = 0x78,
  71. CMD_READ_OCR = 0x7a,
  72. CMD_CRC_ON_OFF = 0x7b
  73. };
  74. enum sdcard_acmd {
  75. ACMD_SD_STATUS = 0x4d,
  76. ACMD_SEND_NUM_WR_BLOCKS = 0x56,
  77. ACMD_SET_WR_BLK_ERASE_COUNT = 0x57,
  78. ACMD_SD_SEND_OP_COND = 0x69,
  79. ACMD_SET_CLR_CARD_DETECT = 0x6a,
  80. ACMD_SEND_SCR = 0x73
  81. };
  82. struct sdcard_csd {
  83. uint32_t raw[4];
  84. };
  85. struct sdcard_cid {
  86. uint32_t raw[4];
  87. };
  88. struct sdcard_info {
  89. DSTATUS status;
  90. int8_t card_type;
  91. unsigned long lbasize;
  92. uint32_t if_cond;
  93. uint32_t ocr;
  94. struct sdcard_csd csd;
  95. struct sdcard_cid cid;
  96. };
  97. struct sdcard_info sdc = {
  98. .status = STA_NOINIT
  99. };
  100. /* < 0 if it should be left on, 0 for off, > 0 for off after timeout */
  101. static volatile int8_t sdcard_led;
  102. /*
  103. * Called by the timer interrupt
  104. */
  105. void sdcard_timer_tick(void)
  106. {
  107. #if 0
  108. if (sdcard_led > 0) {
  109. if (--sdcard_led == 0)
  110. *IO_SYS_LED &= ~0x01;
  111. }
  112. #endif
  113. }
  114. /*
  115. * Enable LED
  116. */
  117. static void sdcard_led_on(void)
  118. {
  119. #if 0
  120. sdcard_led = -1;
  121. *IO_SYS_LED |= 0x01;
  122. #endif
  123. }
  124. /*
  125. * Disable LED after timeout
  126. */
  127. static void sdcard_led_off(void)
  128. {
  129. sdcard_led = 4; /* 4 ticks @ 64 Hz = 62.5 ms */
  130. }
  131. static int sdcard_send_cmd(uint8_t opcode, uint32_t argument)
  132. {
  133. int status = -1;
  134. int i;
  135. if (!opcode)
  136. return 0; /* No command */
  137. dbg_printf("sdcard: CMD%02u arg %08x:", opcode ^ 0x40, argument);
  138. sd_writeb(opcode, SD_GO8|SD_CLEARCRC);
  139. sd_writel(argument, SD_BE|SD_GO32);
  140. /* GO16 so we discard the shifted-in byte from during the CRC7 */
  141. sd_writeb(sd_crc7_wr(), SD_GO16);
  142. /* The spec says a reply within 8 cycles, cut it some slack */
  143. for (i = 16; i; i--) {
  144. status = sd_readb(SD_GO8);
  145. dbg_printf(" %02x", status);
  146. if ((int8_t)status >= 0) /* Bit 7 = 0 for a valid reply */
  147. break;
  148. }
  149. dbg_putc('\n');
  150. return status;
  151. }
  152. static int sdcard_send_acmd(uint8_t opcode, uint32_t argument)
  153. {
  154. int rv;
  155. /* CMD55 = application command follows */
  156. rv = sdcard_send_cmd(CMD_APP_CMD, 0);
  157. if (rv & 0x04) /* Unknown command (very old card)? */
  158. return rv;
  159. return sdcard_send_cmd(opcode, argument);
  160. }
  161. /*
  162. * Read a data block of length len, with a timeout of (timeout)
  163. * byte-times. Note that the minimum length is 4 by spec;
  164. * this function may fail if this is not the case.
  165. *
  166. * The input buffer is allowed to be unaligned.
  167. */
  168. static int sdcard_read_block(void *buf, int len, int timeout,
  169. uint8_t xcmd, uint32_t xarg)
  170. {
  171. uint8_t tok;
  172. uint16_t zcrc;
  173. xptr_t p;
  174. int i;
  175. int badtimeout = 8;
  176. p.b = buf;
  177. /*
  178. * Are we supposed to send a command in parallel?
  179. * This is unsafe for small blocks, but we only need to do this
  180. * for full sectors (used to send STOP_TRANSMISSION).
  181. */
  182. if (xcmd)
  183. len -= 6; /* Handle the last 6 bytes specially */
  184. /*
  185. * Wait for data token
  186. */
  187. dbg_puts("sdcard: read token:");
  188. for (;;) {
  189. tok = sd_readb(SD_GO8|SD_CLEARCRC);
  190. dbg_printf(" %02x", tok);
  191. if (tok == 0xfe)
  192. break;
  193. if (tok < 0xfe && !--badtimeout) {
  194. dbg_printf("\nsdcard: read_block: bad token: %02x\n", tok);
  195. return -1; /* Bad token */
  196. }
  197. if (!--timeout) {
  198. dbg_printf("\nsdcard: read_block: reply timeout\n");
  199. return -1; /* Timeout */
  200. }
  201. }
  202. dbg_putc('\n');
  203. /*
  204. * At this point the first byte after the token is latched into
  205. * the input shift register. After dealing with alignment,
  206. * use dummy reads to shift in the rest of the first longword.
  207. */
  208. /* Shift in bytes if needed for alignment */
  209. if (p.a & 1) {
  210. *p.b++ = sd_readb(SD_GO8);
  211. len--;
  212. }
  213. sd_readb(SD_GO8); /* Now total of 2 bytes latched */
  214. if (p.a & 2) {
  215. *p.w++ = sd_readh(SD_GO16);
  216. len -= 2;
  217. }
  218. if (len >= 6) {
  219. sd_readh(SD_GO16); /* Now total of 4 bytes latched */
  220. while (len >= 6) {
  221. *p.l++ = sd_readl(SD_GO32);
  222. len -= 4;
  223. }
  224. *p.w++ = sd_readh(2); /* Consume the two least recent bytes */
  225. len -= 2;
  226. }
  227. /*
  228. * At this point, we are aligned to a 2-byte boundary with 2 bytes
  229. * in the input shift register; we need to maintain those two bytes
  230. * for the CRC.
  231. */
  232. while (len--)
  233. *p.b++ = sd_readb(SD_GO8 | 1);
  234. /*
  235. * If we're sending a command in parallel, then we have to
  236. * read in the last 6 bytes in parallel with transmitting the
  237. * command out. Because pb may be misaligned at this point,
  238. * do the latch reads/writes to memory as byte I/O.
  239. * We still have 2 bytes of data latched, and should end
  240. * with the same (for the CRC).
  241. *
  242. * To keep the logic anything remotely consistent, passively stuff
  243. * the new command into the transmit register before triggering
  244. * active read operations.
  245. *
  246. * Note that the destination buffer may be unaligned here.
  247. */
  248. if (xcmd) {
  249. sd_writeb(xcmd, SD_CLEARCRC);
  250. *p.b++ = sd_readb(SD_GO8 | 1);
  251. sd_writel(xarg, SD_BE);
  252. *p.b++ = sd_readb(SD_GO8 | 1);
  253. *p.b++ = sd_readb(SD_GO8 | 1);
  254. *p.b++ = sd_readb(SD_GO8 | 1);
  255. *p.b++ = sd_readb(SD_GO8 | 1);
  256. sd_writeb(sd_crc7_wr(), 0);
  257. *p.b++ = sd_readb(SD_GO8 | 1);
  258. }
  259. /*
  260. * Now the CRC is latched in the shift register, and the CRC
  261. * in the CRC generator should be zero.
  262. */
  263. zcrc = sd_crc16_rd();
  264. if (zcrc != 0x0000) {
  265. con_printf("sdcard_read_block: CRC error (zcrc = %04x)\n", zcrc);
  266. return -1;
  267. }
  268. /*
  269. * Shift in the first
  270. * byte after the CRC for the next round.
  271. */
  272. sd_readb(SD_GO8);
  273. return 0;
  274. }
  275. /*
  276. * Read a number of sectors; returns the number of sectors read.
  277. * The input buffer may be unaligned.
  278. */
  279. int sdcard_read_sectors(void *buf, uint32_t lba, int count)
  280. {
  281. int rv;
  282. int okcount = 0;
  283. static const uint16_t stop_transmission[3] =
  284. { (0x40|CMD_STOP_TRANSMISSION) << 8, 0x0000, 0x0061 };
  285. uint8_t resp;
  286. uint8_t *p = buf;
  287. if (!count)
  288. return 0;
  289. sdcard_led_on();
  290. con_printf("sdcard: reading %d sector%s at %u to %p\n",
  291. count, (count != 1) ? "s" : "", lba, buf);
  292. if (sdc.card_type == 1)
  293. lba <<= SECTOR_SHIFT; /* Convert to a byte address */
  294. rv = sdcard_send_cmd(CMD_READ_MULTIPLE_BLOCK, lba);
  295. if (rv & ~1) {
  296. con_printf("sdcard: read_multiple error %02x\n", rv);
  297. goto out;
  298. }
  299. while (count--) {
  300. rv = sdcard_read_block(p, SECTOR_SIZE, 200000,
  301. count ? 0 : CMD_STOP_TRANSMISSION, 0);
  302. if (rv)
  303. goto out;
  304. okcount++;
  305. p += SECTOR_SIZE;
  306. }
  307. /* The first byte after the stop command is undefined */
  308. sd_readb(SD_GO8);
  309. /* Wait for the response to the STOP TRANSMISSION command */
  310. do {
  311. resp = sd_readb(SD_GO8);
  312. } while ((int8_t)resp < 0);
  313. if (resp) {
  314. con_printf("sdcard: read_sectors: terminate command error %02x\n",
  315. resp);
  316. }
  317. out:
  318. sdcard_led_off();
  319. return okcount;
  320. }
  321. DRESULT disk_read(BYTE drive, BYTE *buffer,
  322. LBA_t sectornumber, UINT sectorcount)
  323. {
  324. int rv;
  325. (void)drive;
  326. rv = sdcard_read_sectors(buffer, sectornumber, sectorcount);
  327. return (rv == (int)sectorcount) ? RES_OK : RES_ERROR;
  328. }
  329. /*
  330. * Read CSD/CID
  331. */
  332. static int sdcard_read_reg(uint8_t opcode, void *buf, const char *name)
  333. {
  334. int rv;
  335. uint32_t *bp = buf;
  336. unsigned int i;
  337. memset(buf, 0, 16);
  338. con_printf("sdcard: %s:", name);
  339. rv = sdcard_send_cmd(opcode, 0);
  340. if (rv & ~1)
  341. goto err;
  342. rv = sdcard_read_block(buf, 16, 2000, 0, 0);
  343. if (rv)
  344. goto err;
  345. for (i = 0; i < 4; i++) {
  346. bp[i] = __builtin_bswap32(bp[i]);
  347. con_printf(" %08x", bp[i]);
  348. }
  349. con_putc('\n');
  350. return 0;
  351. err:
  352. con_printf(" failed, err %02x\n", rv);
  353. return rv;
  354. }
  355. static int sdcard_read_csd(void)
  356. {
  357. return sdcard_read_reg(CMD_SEND_CSD, &sdc.csd, "CSD");
  358. }
  359. static int sdcard_read_cid(void)
  360. {
  361. return sdcard_read_reg(CMD_SEND_CID, &sdc.cid, "CID");
  362. }
  363. /*
  364. * Write a number of sectors; returns the number of sectors written.
  365. * The buffer may be unaligned.
  366. */
  367. int sdcard_write_sectors(const void *buf, uint32_t lba, int count)
  368. {
  369. int rv;
  370. int okcount = 0;
  371. uint16_t crc;
  372. uint8_t resp;
  373. xcptr_t p;
  374. if (!count)
  375. return 0;
  376. p.b = buf;
  377. sdcard_led_on();
  378. con_printf("sdcard: writing %d sectors at %u from %p\n", count, lba, buf);
  379. if (sdc.card_type == 1)
  380. lba <<= SECTOR_SHIFT; /* Convert to a byte address */
  381. rv = sdcard_send_cmd(CMD_WRITE_MULTIPLE_BLOCK, lba);
  382. if (rv) {
  383. con_printf("sdcard: write_multiple error %02x\n", rv);
  384. goto out;
  385. }
  386. while (count--) {
  387. unsigned int podd = p.a & 3;
  388. size_t endloop = (p.a + SECTOR_SIZE) & ~3;
  389. /* Start block token */
  390. sd_writeb(0xfc, SD_GO8);
  391. /* Clear the CRC generator; dummy cycle */
  392. sd_writeb(~0, SD_CLEARCRC);
  393. if (podd & 1)
  394. sd_writeb(*p.b++, SD_GO8);
  395. if (podd & 2)
  396. sd_writeh(*p.w++, SD_GO16);
  397. while (p.a < endloop)
  398. sd_writel(*p.l++, SD_GO32);
  399. podd = -podd;
  400. if (podd & 2)
  401. sd_writeh(*p.w++, SD_GO16);
  402. if (podd & 1)
  403. sd_writeb(*p.b++, SD_GO8);
  404. sd_writeh(sd_crc16_wr(), SD_GO16);
  405. /* Wait for data response token */
  406. do {
  407. resp = sd_readb(SD_GO8);
  408. } while ((resp & 0x11) != 0x01);
  409. resp &= ~0xe0;
  410. if (resp != 0x05) {
  411. /*
  412. * Things are confusing here... the spec says
  413. * that on error we are supposed to issue a
  414. * STOP_TRANSMISSION command, which isn't the normal
  415. * thing to do for a write... figure this out later.
  416. */
  417. break; /* Error */
  418. }
  419. /* Wait until the card is ready for the next block */
  420. do {
  421. resp = sd_readb(SD_GO8);
  422. } while (resp == 0x00);
  423. okcount++;
  424. }
  425. /* Send stop transmission token */
  426. sd_writeb(0xfd, SD_GO8);
  427. /* Wait for the card to go busy, then unbusy */
  428. do {
  429. resp = sd_readb(SD_GO8);
  430. } while (resp != 0x00);
  431. do {
  432. resp = sd_readb(SD_GO8);
  433. } while (resp == 0x00);
  434. out:
  435. sdcard_led_off();
  436. return okcount;
  437. }
  438. DRESULT disk_write(BYTE drive, const BYTE *buffer, LBA_t sectornumber,
  439. UINT sectorcount)
  440. {
  441. int rv;
  442. if (drive != 0)
  443. return STA_NOINIT;
  444. rv = sdcard_write_sectors(buffer, sectornumber, sectorcount);
  445. return (rv == (int)sectorcount) ? RES_OK : RES_ERROR;
  446. }
  447. DRESULT disk_ioctl(BYTE drive, BYTE command, void *buffer)
  448. {
  449. if (drive != 0)
  450. return STA_NOINIT;
  451. switch (command) {
  452. case CTRL_SYNC:
  453. return RES_OK;
  454. case GET_SECTOR_SIZE:
  455. *(WORD *)buffer = 512;
  456. return RES_OK;
  457. case GET_SECTOR_COUNT:
  458. *(DWORD *)buffer = sdc.lbasize;
  459. return RES_OK;
  460. case GET_BLOCK_SIZE:
  461. *(DWORD *)buffer = 1; /* XXX */
  462. return RES_OK;
  463. default:
  464. return RES_PARERR;
  465. }
  466. }
  467. DWORD get_fattime(void)
  468. {
  469. return SYSCLOCK_DATETIME; /* Already in FAT format */
  470. }
  471. static unsigned long sdcard_compute_size(struct sdcard_info *sdi)
  472. {
  473. unsigned int c_size;
  474. unsigned int c_size_mult;
  475. unsigned int read_bl_len;
  476. unsigned long lbasize;
  477. sdi->card_type = (sdi->csd.raw[0] >> 30)+1;
  478. switch (sdi->card_type) {
  479. case 1: /* Classic SD/MMC card */
  480. c_size = ((sdi->csd.raw[2] & 0x3ff) << 2) +
  481. (sdi->csd.raw[3] >> 30);
  482. c_size_mult = (sdi->csd.raw[2] >> 15) & 7;
  483. read_bl_len = (sdi->csd.raw[1] >> 16) & 0xf;
  484. lbasize = (c_size + 1) << (c_size_mult + read_bl_len + 2 - 9);
  485. break;
  486. case 2: /* SDHC/SDXC/eMMC card */
  487. c_size = ((sdi->csd.raw[1] & 0x3f) << 16) +
  488. (sdi->csd.raw[2] >> 16);
  489. lbasize = c_size << 10;
  490. break;
  491. default:
  492. sdi->card_type = 0;
  493. return 0;
  494. }
  495. return sdi->lbasize = lbasize;
  496. }
  497. static const char *sdcard_type_name(uint8_t type)
  498. {
  499. static const char * const names[] = {
  500. "unknown",
  501. "SD/MMC",
  502. "SDHC/SDXC/eMMC"
  503. };
  504. if (type >= sizeof names/sizeof names[0])
  505. type = 0;
  506. return names[type];
  507. }
  508. static void sdcard_try_high_speed(void)
  509. {
  510. int rv;
  511. uint8_t tran_speed;
  512. return;
  513. if (!(sdc.csd.raw[1] & (1 << 30)))
  514. return; /* Cmd group 10 = CMD6 not supported */
  515. /* Try to switch to high speed mode */
  516. rv = sdcard_send_cmd(CMD_SWITCH_FUNC, 0x80fffff1);
  517. if (rv & ~1) {
  518. dbg_printf("sdcard: CMD6 returned %02x\n", rv);
  519. return;
  520. }
  521. if (1) {
  522. /*
  523. * Despite the spec, this doesn't seem to actually happen
  524. * in SPI mode?
  525. */
  526. uint8_t swdata[64]; /* Response from CMD6 */
  527. int i;
  528. for (i = 0; i < 64; i++)
  529. swdata[i] = sd_readb(SD_GO8);
  530. if ((swdata[47] & 0x0f) != 1) {
  531. dbg_printf("sdcard: CMD6 reported %X for high speed request\n",
  532. swdata[47] & 0x0f);
  533. return; /* Failed to switch to high speed mode */
  534. }
  535. }
  536. /*
  537. * Success, we should have switched mode.
  538. * This should be refleded in the TRAN_SPEED field in the CSD.
  539. */
  540. sd_readl(SD_GO32); /* Issue at least 8 clocks; go for 32 */
  541. /* Re-read the CSD */
  542. sdcard_read_csd();
  543. /* TRAN_SPEED should have changed now */
  544. tran_speed = (uint8_t)sdc.csd.raw[0];
  545. if ((tran_speed & 7) < 2 ||
  546. ((tran_speed & 7) == 2 && (tran_speed >> 3) < 0xb)) {
  547. dbg_printf("sdcard: speed switch failed, tran_speed %02x\n",
  548. tran_speed);
  549. return; /* High speed not available */
  550. }
  551. sd_set_mode(SD_50MHZ, true);
  552. con_printf("sdcard: switched to high speed\n");
  553. }
  554. DSTATUS disk_initialize(BYTE drive)
  555. {
  556. uint16_t status;
  557. uint32_t try_sdhc;
  558. bool is_sd;
  559. int i, j, rv;
  560. if (drive != 0)
  561. return STA_NOINIT;
  562. /* So we can wait for the ready condition */
  563. SDCARD_CTL_IRQEN = SDCARD_IRQ_READY;
  564. memset(&sdc, 0, sizeof sdc);
  565. #if 0
  566. status = /* Check card detect if present */
  567. if (!(status & 0x04)) {
  568. con_printf("No memory card installed\n");
  569. return sdc.status = STA_NOINIT|STA_NODISK;
  570. }
  571. #endif
  572. sdcard_led_on();
  573. /* Allow 4 retries in case the card is in a funky state */
  574. i = 4;
  575. while (1) {
  576. /*
  577. * Generate 256 clock cycles in slow mode, with CS# high.
  578. */
  579. sd_set_mode(SD_SLOW, false);
  580. for (j = 0; j < 8; j++)
  581. sd_writel(~0, SD_GO32);
  582. /* Assert CS# and send reset command */
  583. sd_set_mode(SD_SLOW, true);
  584. sd_writeb(~0, SD_GO8); /* Dummy byte after CS# assert */
  585. rv = sdcard_send_cmd(CMD_GO_IDLE_STATE, 0);
  586. if (rv == 0x01)
  587. break; /* Success! */
  588. if (!--i) {
  589. con_printf("sdcard: reset failed, assuming no card present\n", rv);
  590. sdcard_led_off();
  591. return sdc.status = STA_NOINIT | STA_NODISK;
  592. }
  593. }
  594. /* Switch to 20 MHz */
  595. sd_set_mode(SD_20MHZ, true);
  596. /* Enable command CRC checking (ignore result) */
  597. sdcard_send_cmd(CMD_CRC_ON_OFF, 0x0001);
  598. /* Probe for extended features */
  599. /*
  600. * Bit 7:0 = check pattern
  601. * Bit 11:8 = supply voltage (3.3 V)
  602. */
  603. rv = sdcard_send_cmd(CMD_SEND_IF_COND, 0x01aa);
  604. if ((rv & 0x04) == 0) {
  605. /* CMD8 supported */
  606. if (rv & ~0x03) {
  607. dbg_printf("sdcard; CMD8 error %02x\n", rv);
  608. sdcard_led_off();
  609. return sdc.status = STA_NOINIT;
  610. }
  611. /* Shift in additional data bytes */
  612. sd_readb(SD_GO8);
  613. sd_readh(SD_GO16);
  614. sdc.if_cond = sd_readl(SD_GO16|SD_BE);
  615. dbg_printf("sdcard: CMD8 returned 0x%08x\n", sdc.if_cond);
  616. if ((sdc.if_cond & 0x1ff) != 0x1aa) {
  617. con_printf("sdcard: CMD8 reports unusable card (0x%x)\n",
  618. sdc.if_cond);
  619. sdcard_led_off();
  620. return sdc.status = STA_NOINIT;
  621. }
  622. try_sdhc = 1 << 30;
  623. } else {
  624. try_sdhc = 0;
  625. }
  626. /* Initialize card */
  627. do {
  628. rv = sdcard_send_acmd(ACMD_SD_SEND_OP_COND, try_sdhc);
  629. if (rv & 0x04)
  630. break;
  631. if (rv & ~0x01) {
  632. con_printf("sdcard: ACMD41 error %02x\n", rv);
  633. sdcard_led_off();
  634. return sdc.status = STA_NOINIT;
  635. }
  636. } while (rv);
  637. if (!rv) {
  638. /* ACMD41 successful; this is an SD card: can switch to 25 MHz */
  639. is_sd = true;
  640. sd_set_mode(SD_25MHZ, true);
  641. rv = sdcard_send_cmd(CMD_READ_OCR, try_sdhc);
  642. if (rv) {
  643. con_printf("sdcard: CMD58 error %02x\n", rv);
  644. sdcard_led_off();
  645. return sdc.status = STA_NOINIT;
  646. }
  647. /* Shift in additional data bytes */
  648. sd_readb(SD_GO8);
  649. sd_readh(SD_GO16);
  650. sdc.ocr = sd_readl(SD_GO16|SD_BE);
  651. } else {
  652. /* ACMD41 unsupported, try CMD1 */
  653. is_sd = false;
  654. do {
  655. rv = sdcard_send_cmd(CMD_SEND_OP_COND, 0);
  656. if (rv & ~0x01) {
  657. con_printf("sdcard: CMD1 error %02x\n", rv);
  658. sdcard_led_off();
  659. return sdc.status = STA_NOINIT;
  660. }
  661. } while (rv);
  662. }
  663. /*
  664. * Set block length -- some cards power up to a larger block size
  665. * than 512 bytes even though that violates the spec.
  666. */
  667. rv = sdcard_send_cmd(CMD_SET_BLOCKLEN, 512);
  668. if (rv) {
  669. con_printf("sdcard: CMD16 error %02x\n", rv);
  670. sdcard_led_off();
  671. return sdc.status = STA_NOINIT;
  672. }
  673. /*
  674. * Read the CSD to figure out what command sets are available...
  675. */
  676. sdcard_read_csd(); /* Read CSD */
  677. /*
  678. * Try to switch to 50 MHz (optional)
  679. */
  680. if (is_sd)
  681. sdcard_try_high_speed();
  682. /*
  683. * Read the CID
  684. */
  685. sdcard_read_cid();
  686. sdcard_compute_size(&sdc);
  687. con_printf("sdcard: %s card found, capacity %u sectors\n",
  688. sdcard_type_name(sdc.card_type), sdc.lbasize);
  689. sdc.status = 0;
  690. sdcard_led_off();
  691. return sdc.status;
  692. }
  693. DSTATUS disk_status(BYTE drive)
  694. {
  695. if (drive != 0)
  696. return STA_NOINIT;
  697. return sdc.status;
  698. }
  699. static FATFS sd_fs;
  700. int disk_init(void)
  701. {
  702. FRESULT rv;
  703. char label[128];
  704. uint32_t volid, freeclust;
  705. FATFS *fs;
  706. rv = f_mount(&sd_fs, "", 1);
  707. if (rv != FR_OK) {
  708. con_printf("sdcard: no volume found\n");
  709. return -1;
  710. }
  711. label[0] = '\0';
  712. volid = 0;
  713. f_getlabel("", label, &volid);
  714. con_printf("sdcard: volume found, label \"%s\", volid %08x\n", label, volid);
  715. freeclust = 0;
  716. f_getfree("", &freeclust, &fs);
  717. con_printf("sdcard: %u/%u clusters free, clusters = %u bytes\n",
  718. freeclust, fs->n_fatent - 2, fs->csize << 9);
  719. return 0;
  720. }