sdcard.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. /* sd2iec - SD/MMC to Commodore serial bus interface/controller
  2. Copyright (C) 2007-2010 Ingo Korb <ingo@akana.de>
  3. Inspiration and low-level SD/MMC access based on code from MMC2IEC
  4. by Lars Pontoppidan et al., see sdcard.c|h and config.h.
  5. FAT filesystem access based on code from ChaN and Jim Brain, see ff.c|h.
  6. This program is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; version 2 of the License only.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program; if not, write to the Free Software
  15. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. sdcard.c: SD/MMC access routines
  17. Extended, optimized and cleaned version of code from MMC2IEC,
  18. original copyright header follows:
  19. //
  20. // Title : SD/MMC Card driver
  21. // Author : Lars Pontoppidan, Aske Olsson, Pascal Dufour,
  22. // Date : Jan. 2006
  23. // Version : 0.42
  24. // Target MCU : Atmel AVR Series
  25. //
  26. // CREDITS:
  27. // This module is developed as part of a project at the technical univerisity of
  28. // Denmark, DTU.
  29. //
  30. // DESCRIPTION:
  31. // This SD card driver implements the fundamental communication with a SD card.
  32. // The driver is confirmed working on 8 MHz and 14.7456 MHz AtMega32 and has
  33. // been tested successfully with a large number of different SD and MMC cards.
  34. //
  35. // DISCLAIMER:
  36. // The author is in no way responsible for any problems or damage caused by
  37. // using this code. Use at your own risk.
  38. //
  39. // LICENSE:
  40. // This code is distributed under the GNU Public License
  41. // which can be found at http://www.gnu.org/licenses/gpl.txt
  42. //
  43. The exported functions in this file are weak-aliased to their corresponding
  44. versions defined in diskio.h so when this file is the only diskio provider
  45. compiled in they will be automatically used by the linker.
  46. */
  47. #include <arm/NXP/LPC17xx/LPC17xx.h>
  48. #include <arm/bits.h>
  49. #include "config.h"
  50. #include "crc.h"
  51. #include "diskio.h"
  52. #include "spi.h"
  53. #include "timer.h"
  54. #include "uart.h"
  55. #include "sdcard.h"
  56. // FIXME: Move, make configurable
  57. static void set_sd_led(uint8_t state) {
  58. BITBAND(LPC_GPIO2->FIODIR, 2) = state;
  59. }
  60. // FIXME: Move, add generic C or AVR ASM version
  61. static uint32_t swap_word(uint32_t input) {
  62. uint32_t result;
  63. asm("rev %[result], %[input]" : [result] "=r" (result) : [input] "r" (input));
  64. return result;
  65. }
  66. #ifdef CONFIG_TWINSD
  67. # define MAX_CARDS 2
  68. #else
  69. # define MAX_CARDS 1
  70. #endif
  71. // SD/MMC commands
  72. #define GO_IDLE_STATE 0
  73. #define SEND_OP_COND 1
  74. #define SWITCH_FUNC 6
  75. #define SEND_IF_COND 8
  76. #define SEND_CSD 9
  77. #define SEND_CID 10
  78. #define STOP_TRANSMISSION 12
  79. #define SEND_STATUS 13
  80. #define SET_BLOCKLEN 16
  81. #define READ_SINGLE_BLOCK 17
  82. #define READ_MULTIPLE_BLOCK 18
  83. #define WRITE_BLOCK 24
  84. #define WRITE_MULTIPLE_BLOCK 25
  85. #define PROGRAM_CSD 27
  86. #define SET_WRITE_PROT 28
  87. #define CLR_WRITE_PROT 29
  88. #define SEND_WRITE_PROT 30
  89. #define ERASE_WR_BLK_STAR_ADDR 32
  90. #define ERASE_WR_BLK_END_ADDR 33
  91. #define ERASE 38
  92. #define LOCK_UNLOCK 42
  93. #define APP_CMD 55
  94. #define GEN_CMD 56
  95. #define READ_OCR 58
  96. #define CRC_ON_OFF 59
  97. // SD ACMDs
  98. #define SD_STATUS 13
  99. #define SD_SEND_NUM_WR_BLOCKS 22
  100. #define SD_SET_WR_BLK_ERASE_COUNT 23
  101. #define SD_SEND_OP_COND 41
  102. #define SD_SET_CLR_CARD_DETECT 42
  103. #define SD_SEND_SCR 51
  104. // R1 status bits
  105. #define STATUS_IN_IDLE 1
  106. #define STATUS_ERASE_RESET 2
  107. #define STATUS_ILLEGAL_COMMAND 4
  108. #define STATUS_CRC_ERROR 8
  109. #define STATUS_ERASE_SEQ_ERROR 16
  110. #define STATUS_ADDRESS_ERROR 32
  111. #define STATUS_PARAMETER_ERROR 64
  112. /* Card types - cardtype == 0 is MMC */
  113. #define CARD_SD (1<<0)
  114. #define CARD_SDHC (1<<1)
  115. static uint8_t cardtype[MAX_CARDS];
  116. /**
  117. * getbits - read value from bit buffer
  118. * @buffer: pointer to the data buffer
  119. * @start : index of the first bit in the value
  120. * @bits : number of bits in the value
  121. *
  122. * This function returns a value from the memory region passed as
  123. * buffer, starting with bit "start" and "bits" bit long. The buffer
  124. * is assumed to be MSB first, passing 0 for start will read starting
  125. * from the highest-value bit of the first byte of the buffer.
  126. */
  127. static uint32_t getbits(void *buffer, uint16_t start, int8_t bits) {
  128. uint8_t *buf = buffer;
  129. uint32_t result = 0;
  130. if ((start % 8) != 0) {
  131. /* Unaligned start */
  132. result += buf[start / 8] & (0xff >> (start % 8));
  133. bits -= 8 - (start % 8);
  134. start += 8 - (start % 8);
  135. }
  136. while (bits >= 8) {
  137. result = (result << 8) + buf[start / 8];
  138. start += 8;
  139. bits -= 8;
  140. }
  141. if (bits > 0) {
  142. result = result << bits;
  143. result = result + (buf[start / 8] >> (8-bits));
  144. } else if (bits < 0) {
  145. /* Fraction of a single byte */
  146. result = result >> -bits;
  147. }
  148. return result;
  149. }
  150. /**
  151. * wait_for_response - waits for a response from the SD card
  152. * @expected: expected data byte (0 for anything != 0)
  153. *
  154. * This function waits until reading from the SD card returns the
  155. * byte in expected or until reading returns a non-zero byte if
  156. * expected is 0. Returns false if the expected response wasn't
  157. * received within 500ms or true if it was.
  158. */
  159. static uint8_t wait_for_response(uint8_t expected) {
  160. tick_t timeout = getticks() + HZ/2;
  161. while (time_before(getticks(), timeout)) {
  162. uint8_t byte = spi_rx_byte();
  163. if (expected == 0 && byte != 0)
  164. return 1;
  165. if (expected != 0 && byte == expected)
  166. return 1;
  167. }
  168. return 0;
  169. }
  170. static void deselectCard(uint8_t card) {
  171. // Send 8 clock cycles
  172. set_sd_led(0);
  173. spi_rx_byte();
  174. }
  175. /**
  176. * sendCommand - send a command to the SD card
  177. * @card : card number to be accessed
  178. * @command : command to be sent
  179. * @parameter: parameter to be sent
  180. * @deselect : Flags if the card should be deselected afterwards
  181. *
  182. * This function calculates the correct CRC7 for the command and
  183. * parameter and transmits all of it to the SD card. If requested
  184. * the card will be deselected afterwards.
  185. */
  186. static int sendCommand(const uint8_t card,
  187. const uint8_t command,
  188. const uint32_t parameter,
  189. const uint8_t deselect) {
  190. union {
  191. uint32_t l;
  192. uint8_t c[4];
  193. } long2char;
  194. uint8_t i,crc,errorcount;
  195. tick_t timeout;
  196. long2char.l = parameter;
  197. crc = crc7update(0 , 0x40+command);
  198. crc = crc7update(crc, long2char.c[3]);
  199. crc = crc7update(crc, long2char.c[2]);
  200. crc = crc7update(crc, long2char.c[1]);
  201. crc = crc7update(crc, long2char.c[0]);
  202. crc = (crc << 1) | 1;
  203. errorcount = 0;
  204. while (errorcount < CONFIG_SD_AUTO_RETRIES) {
  205. // Select card
  206. set_sd_led(1);
  207. #ifdef CONFIG_TWINSD
  208. if (card == 0 && command == GO_IDLE_STATE)
  209. /* Force both cards to SPI mode simultaneously */
  210. SPI_SS_LOW(1);
  211. #endif
  212. // Transfer command
  213. spi_tx_byte(0x40+command);
  214. uint32_t tmp = swap_word(parameter);
  215. spi_tx_block(&tmp, 4);
  216. spi_tx_byte(crc);
  217. // Wait for a valid response
  218. timeout = getticks() + HZ/2;
  219. do {
  220. i = spi_rx_byte();
  221. } while (i & 0x80 && time_before(getticks(), timeout));
  222. #ifdef CONFIG_TWINSD
  223. if (card == 0 && command == GO_IDLE_STATE)
  224. SPI_SS_HIGH(1);
  225. #endif
  226. // Check for CRC error
  227. // can't reliably retry unless deselect is allowed
  228. if (deselect && (i & STATUS_CRC_ERROR)) {
  229. uart_putc('x');
  230. deselectCard(card);
  231. errorcount++;
  232. continue;
  233. }
  234. if (deselect) deselectCard(card);
  235. break;
  236. }
  237. return i;
  238. }
  239. // Extended init sequence for SDHC support
  240. static uint8_t extendedInit(const uint8_t card) {
  241. uint8_t i;
  242. uint32_t answer;
  243. // Send CMD8: SEND_IF_COND
  244. // 0b000110101010 == 2.7-3.6V supply, check pattern 0xAA
  245. i = sendCommand(card, SEND_IF_COND, 0b000110101010, 0);
  246. if (i > 1) {
  247. // Card returned an error, ok (MMC or SD1.x) but not SDHC
  248. deselectCard(card);
  249. return 1;
  250. }
  251. // No error, continue SDHC initialization
  252. spi_rx_block(&answer, 4);
  253. answer = swap_word(answer);
  254. deselectCard(card);
  255. if (((answer >> 8) & 0x0f) != 0b0001) {
  256. // Card didn't accept our voltage specification
  257. return 0;
  258. }
  259. // Verify echo-back of check pattern
  260. if ((answer & 0xff) != 0b10101010) {
  261. // Check pattern mismatch, working but not SD2.0 compliant
  262. // The specs say we should not use the card, but let's try anyway.
  263. return 1;
  264. }
  265. return 1;
  266. }
  267. // SD common initialisation
  268. static void sdInit(const uint8_t card) {
  269. uint8_t i;
  270. uint16_t counter;
  271. printf("sdInit\n");
  272. counter = 0xffff;
  273. do {
  274. // Prepare for ACMD, send CMD55: APP_CMD
  275. i = sendCommand(card, APP_CMD, 0, 1);
  276. if (i > 1) {
  277. // Command not accepted, could be MMC
  278. return;
  279. }
  280. // Send ACMD41: SD_SEND_OP_COND
  281. // 1L<<30 == Host has High Capacity Support
  282. i = sendCommand(card, SD_SEND_OP_COND, 1L<<30, 1);
  283. // Repeat while card card accepts command but isn't ready
  284. } while (i == 1 && --counter > 0);
  285. // Ignore failures, there is at least one Sandisk MMC card
  286. // that accepts CMD55, but not ACMD41.
  287. if (i == 0)
  288. /* We know that a card is SD if ACMD41 was accepted. */
  289. cardtype[card] |= CARD_SD;
  290. }
  291. /* Detect changes of SD card 0 */
  292. #ifdef SD_CHANGE_VECT
  293. ISR(SD_CHANGE_VECT) {
  294. if (SDCARD_DETECT)
  295. disk_state = DISK_CHANGED;
  296. else
  297. disk_state = DISK_REMOVED;
  298. }
  299. #endif
  300. #ifdef CONFIG_TWINSD
  301. /* Detect changes of SD card 1 */
  302. ISR(SD2_CHANGE_VECT) {
  303. if (SD2_DETECT)
  304. disk_state = DISK_CHANGED;
  305. else
  306. disk_state = DISK_REMOVED;
  307. }
  308. #endif
  309. //
  310. // Public functions
  311. //
  312. void sd_init(void) {
  313. /*
  314. SDCARD_DETECT_SETUP();
  315. SDCARD_WP_SETUP();
  316. SD_CHANGE_SETUP();
  317. */
  318. #ifdef CONFIG_TWINSD
  319. /* Initialize the control lines for card 2 */
  320. SD2_SETUP();
  321. SD2_CHANGE_SETUP();
  322. #endif
  323. }
  324. void disk_init(void) __attribute__ ((weak, alias("sd_init")));
  325. DSTATUS sd_status(BYTE drv) {
  326. #ifdef CONFIG_TWINSD
  327. if (drv != 0) {
  328. if (SD2_DETECT) {
  329. if (SD2_PIN & SD2_WP) {
  330. return STA_PROTECT;
  331. } else {
  332. return RES_OK;
  333. }
  334. } else {
  335. return STA_NOINIT|STA_NODISK;
  336. }
  337. } else
  338. #endif
  339. if (SDCARD_DETECT)
  340. if (SDCARD_WP)
  341. return STA_PROTECT;
  342. else
  343. return RES_OK;
  344. else
  345. return STA_NOINIT|STA_NODISK;
  346. }
  347. DSTATUS disk_status(BYTE drv) __attribute__ ((weak, alias("sd_status")));
  348. /**
  349. * sd_initialize - initialize SD card
  350. * @drv : drive
  351. *
  352. * This function tries to initialize the selected SD card.
  353. */
  354. DSTATUS sd_initialize(BYTE drv) {
  355. uint8_t i;
  356. uint16_t counter;
  357. uint32_t answer;
  358. if (drv >= MAX_CARDS)
  359. return STA_NOINIT|STA_NODISK;
  360. /* Don't bother initializing a card that isn't there */
  361. if (sd_status(drv) & STA_NODISK)
  362. return sd_status(drv);
  363. /* JLB: Should be in sd_init, but some uIEC versions have
  364. * IEC lines tied to SPI, so I moved it here to resolve the
  365. * conflict.
  366. */
  367. spi_init(SPI_SPEED_SLOW);
  368. disk_state = DISK_ERROR;
  369. cardtype[drv] = 0;
  370. set_sd_led(0);
  371. // Send 80 clks
  372. for (counter=0; counter<1000; counter++) {
  373. spi_tx_byte(0xff);
  374. }
  375. // Reset card
  376. i = sendCommand(drv, GO_IDLE_STATE, 0, 1);
  377. if (i != 1) {
  378. return STA_NOINIT | STA_NODISK;
  379. }
  380. if (!extendedInit(drv)) {
  381. return STA_NOINIT | STA_NODISK;
  382. }
  383. sdInit(drv);
  384. counter = 0xffff;
  385. // According to the spec READ_OCR should work at this point
  386. // without retries. One of my Sandisk-cards thinks otherwise.
  387. do {
  388. // Send CMD58: READ_OCR
  389. i = sendCommand(drv, READ_OCR, 0, 0);
  390. if (i > 1)
  391. deselectCard(drv);
  392. } while (i > 1 && counter-- > 0);
  393. if (counter > 0) {
  394. spi_rx_block(&answer, 4);
  395. answer = swap_word(answer);
  396. // See if the card likes our supply voltage
  397. if (!(answer & SD_SUPPLY_VOLTAGE)) {
  398. // The code isn't set up to completely ignore the card,
  399. // but at least report it as nonworking
  400. deselectCard(drv);
  401. return STA_NOINIT | STA_NODISK;
  402. }
  403. // See what card we've got
  404. if (answer & 0x40000000) {
  405. cardtype[drv] |= CARD_SDHC;
  406. }
  407. }
  408. // Keep sending CMD1 (SEND_OP_COND) command until zero response
  409. counter = 0xffff;
  410. do {
  411. i = sendCommand(drv, SEND_OP_COND, 1L<<30, 1);
  412. counter--;
  413. } while (i != 0 && counter > 0);
  414. if (counter==0) {
  415. return STA_NOINIT | STA_NODISK;
  416. }
  417. #ifdef CONFIG_SD_DATACRC
  418. // Enable CRC checking
  419. // The SD spec says that the host "should" send CRC_ON_OFF before ACMD_SEND_OP_COND.
  420. // The MMC manual I have says that CRC_ON_OFF isn't allowed before SEND_OP_COND.
  421. // Let's just hope that all SD cards work with this order. =(
  422. i = sendCommand(drv, CRC_ON_OFF, 1, 1);
  423. if (i > 1) {
  424. return STA_NOINIT | STA_NODISK;
  425. }
  426. #endif
  427. // Send MMC CMD16(SET_BLOCKLEN) to 512 bytes
  428. i = sendCommand(drv, SET_BLOCKLEN, 512, 1);
  429. if (i != 0) {
  430. return STA_NOINIT | STA_NODISK;
  431. }
  432. // Thats it!
  433. spi_set_speed(SPI_SPEED_FAST);
  434. disk_state = DISK_OK;
  435. return sd_status(drv);
  436. }
  437. DSTATUS disk_initialize(BYTE drv) __attribute__ ((weak, alias("sd_initialize")));
  438. /**
  439. * sd_read - reads sectors from the SD card to buffer
  440. * @drv : drive
  441. * @buffer: pointer to the buffer
  442. * @sector: first sector to be read
  443. * @count : number of sectors to be read
  444. *
  445. * This function reads count sectors from the SD card starting
  446. * at sector to buffer. Returns RES_ERROR if an error occured or
  447. * RES_OK if successful. Up to SD_AUTO_RETRIES will be made if
  448. * the calculated data CRC does not match the one sent by the
  449. * card. If there were errors during the command transmission
  450. * disk_state will be set to DISK_ERROR and no retries are made.
  451. */
  452. DRESULT sd_read(BYTE drv, BYTE *buffer, DWORD sector, BYTE count) {
  453. uint8_t sec,res,errorcount;
  454. uint16_t crc,recvcrc;
  455. if (drv >= MAX_CARDS)
  456. return RES_PARERR;
  457. for (sec=0;sec<count;sec++) {
  458. errorcount = 0;
  459. while (errorcount < CONFIG_SD_AUTO_RETRIES) {
  460. if (cardtype[drv] & CARD_SDHC)
  461. res = sendCommand(drv, READ_SINGLE_BLOCK, sector+sec, 0);
  462. else
  463. res = sendCommand(drv, READ_SINGLE_BLOCK, (sector+sec) << 9, 0);
  464. if (res != 0) {
  465. set_sd_led(0);
  466. disk_state = DISK_ERROR;
  467. return RES_ERROR;
  468. }
  469. // Wait for data token
  470. if (!wait_for_response(0xFE)) {
  471. set_sd_led(0);
  472. disk_state = DISK_ERROR;
  473. return RES_ERROR;
  474. }
  475. // Get data
  476. crc = 0;
  477. #ifdef CONFIG_SD_BLOCKTRANSFER
  478. /* Transfer data first, calculate CRC afterwards */
  479. spi_rx_block(buffer, 512);
  480. recvcrc = spi_rx_byte() << 8 | spi_rx_byte();
  481. #ifdef CONFIG_SD_DATACRC
  482. crc = crc_xmodem_block(0, buffer, 512);
  483. #endif
  484. #else
  485. /* Interleave transfer/CRC calculation, AVR-specific */
  486. // Initiate data exchange over SPI
  487. SPDR = 0xff;
  488. uint8_t tmp;
  489. for (i=0; i<512; i++) {
  490. // Wait until data has been received
  491. loop_until_bit_is_set(SPSR, SPIF);
  492. tmp = SPDR;
  493. // Transmit the next byte while we store the current one
  494. SPDR = 0xff;
  495. *(buffer++) = tmp;
  496. #ifdef CONFIG_SD_DATACRC
  497. crc = _crc_xmodem_update(crc, tmp);
  498. #endif
  499. }
  500. // Wait until the first CRC byte is received
  501. loop_until_bit_is_set(SPSR, SPIF);
  502. // Check CRC
  503. recvcrc = (SPDR << 8) + spiTransferByte(0xff);
  504. #endif
  505. #ifdef CONFIG_SD_DATACRC
  506. if (recvcrc != crc) {
  507. uart_putc('X');
  508. deselectCard(drv);
  509. errorcount++;
  510. continue;
  511. }
  512. #endif
  513. break;
  514. }
  515. deselectCard(drv);
  516. if (errorcount >= CONFIG_SD_AUTO_RETRIES) return RES_ERROR;
  517. }
  518. return RES_OK;
  519. }
  520. DRESULT disk_read(BYTE drv, BYTE *buffer, DWORD sector, BYTE count) __attribute__ ((weak, alias("sd_read")));
  521. /**
  522. * sd_write - writes sectors from buffer to the SD card
  523. * @drv : drive
  524. * @buffer: pointer to the buffer
  525. * @sector: first sector to be written
  526. * @count : number of sectors to be written
  527. *
  528. * This function writes count sectors from buffer to the SD card
  529. * starting at sector. Returns RES_ERROR if an error occured,
  530. * RES_WPRT if the card is currently write-protected or RES_OK
  531. * if successful. Up to SD_AUTO_RETRIES will be made if the card
  532. * signals a CRC error. If there were errors during the command
  533. * transmission disk_state will be set to DISK_ERROR and no retries
  534. * are made.
  535. */
  536. DRESULT sd_write(BYTE drv, const BYTE *buffer, DWORD sector, BYTE count) {
  537. uint8_t res,sec,errorcount,status;
  538. uint16_t crc;
  539. if (drv >= MAX_CARDS)
  540. return RES_PARERR;
  541. #ifdef CONFIG_TWINSD
  542. if (drv != 0) {
  543. if (SD2_PIN & SD2_WP)
  544. return RES_WRPRT;
  545. } else
  546. #endif
  547. if (SDCARD_WP) return RES_WRPRT;
  548. for (sec=0;sec<count;sec++) {
  549. errorcount = 0;
  550. while (errorcount < CONFIG_SD_AUTO_RETRIES) {
  551. if (cardtype[drv] & CARD_SDHC)
  552. res = sendCommand(drv, WRITE_BLOCK, sector+sec, 0);
  553. else
  554. res = sendCommand(drv, WRITE_BLOCK, (sector+sec)<<9, 0);
  555. if (res != 0) {
  556. set_sd_led(0);
  557. disk_state = DISK_ERROR;
  558. return RES_ERROR;
  559. }
  560. // Send data token
  561. spi_tx_byte(0xfe);
  562. // Send data
  563. spi_tx_block(buffer, 512);
  564. #ifdef CONFIG_SD_DATACRC
  565. crc = crc_xmodem_block(0, buffer, 512);
  566. #else
  567. crc = 0;
  568. #endif
  569. // Send CRC
  570. spi_tx_byte(crc >> 8);
  571. spi_tx_byte(crc & 0xff);
  572. // Get and check status feedback
  573. status = spi_rx_byte();
  574. // Retry if neccessary
  575. if ((status & 0x0F) != 0x05) {
  576. uart_putc('X');
  577. deselectCard(drv);
  578. errorcount++;
  579. continue;
  580. }
  581. // Wait for write finish
  582. if (!wait_for_response(0)) {
  583. set_sd_led(0);
  584. disk_state = DISK_ERROR;
  585. return RES_ERROR;
  586. }
  587. break;
  588. }
  589. deselectCard(drv);
  590. if (errorcount >= CONFIG_SD_AUTO_RETRIES) {
  591. if (!(status & STATUS_CRC_ERROR))
  592. disk_state = DISK_ERROR;
  593. return RES_ERROR;
  594. }
  595. }
  596. return RES_OK;
  597. }
  598. DRESULT disk_write(BYTE drv, const BYTE *buffer, DWORD sector, BYTE count) __attribute__ ((weak, alias("sd_write")));
  599. DRESULT sd_getinfo(BYTE drv, BYTE page, void *buffer) {
  600. uint8_t buf[18];
  601. uint32_t capacity;
  602. if (drv >= MAX_CARDS)
  603. return RES_NOTRDY;
  604. if (sd_status(drv) & STA_NODISK)
  605. return RES_NOTRDY;
  606. if (page != 0)
  607. return RES_ERROR;
  608. /* Try to calculate the total number of sectors on the card */
  609. /* FIXME: Write a generic data read function and merge with sd_read */
  610. if (sendCommand(drv, SEND_CSD, 0, 0) != 0) {
  611. deselectCard(drv);
  612. return RES_ERROR;
  613. }
  614. /* Wait for data token */
  615. if (!wait_for_response(0xfe)) {
  616. deselectCard(drv);
  617. return RES_ERROR;
  618. }
  619. spi_rx_block(buf, 18);
  620. deselectCard(drv);
  621. if (cardtype[drv] & CARD_SDHC) {
  622. /* Special CSD for SDHC cards */
  623. capacity = (1 + getbits(buf,127-69,22)) * 1024;
  624. } else {
  625. /* Assume that MMC-CSD 1.0/1.1/1.2 and SD-CSD 1.1 are the same... */
  626. uint8_t exponent = 2 + getbits(buf, 127-49, 3);
  627. capacity = 1 + getbits(buf, 127-73, 12);
  628. exponent += getbits(buf, 127-83,4) - 9;
  629. while (exponent--) capacity *= 2;
  630. }
  631. diskinfo0_t *di = buffer;
  632. di->validbytes = sizeof(diskinfo0_t);
  633. di->disktype = DISK_TYPE_SD;
  634. di->sectorsize = 2;
  635. di->sectorcount = capacity;
  636. return RES_OK;
  637. }
  638. DRESULT disk_getinfo(BYTE drv, BYTE page, void *buffer) __attribute__ ((weak, alias("sd_getinfo")));