sdcard.c 19 KB

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