sdcard.c 19 KB

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