sdcard.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. /* sd2iec - SD/MMC to Commodore serial bus interface/controller
  2. Copyright (C) 2007-2009 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 <avr/io.h>
  48. #include <avr/interrupt.h>
  49. #include <avr/pgmspace.h>
  50. #include <util/crc16.h>
  51. #include <util/delay.h>
  52. #include "config.h"
  53. #include "avrcompat.h"
  54. #include "crc7.h"
  55. #include "diskio.h"
  56. #include "spi.h"
  57. #include "uart.h"
  58. #include "sdcard.h"
  59. #include "fpga_spi.h"
  60. #ifndef TRUE
  61. #define TRUE -1
  62. #endif
  63. #ifndef FALSE
  64. #define FALSE 0
  65. #endif
  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. static uint8_t sdResponse(uint8_t expected)
  151. {
  152. unsigned short count = 0x0FFF;
  153. while ((spiTransferByte(0xFF) != expected) && count )
  154. count--;
  155. // If count didn't run out, return success
  156. return (count != 0);
  157. }
  158. static uint8_t sdWaitWriteFinish(void)
  159. {
  160. uint32_t count = 0x1FFFF; // wait for quite some time
  161. while ((spiTransferByte(0xFF) == 0) && count )
  162. count--;
  163. // If count didn't run out, return success
  164. return (count != 0);
  165. }
  166. static void deselectCard(uint8_t card) {
  167. // Send 8 clock cycles
  168. SPI_SS_HIGH(card);
  169. spiTransferByte(0xff);
  170. }
  171. /**
  172. * sendCommand - send a command to the SD card
  173. * @card : card number to be accessed
  174. * @command : command to be sent
  175. * @parameter: parameter to be sent
  176. * @deselect : Flags if the card should be deselected afterwards
  177. *
  178. * This function calculates the correct CRC7 for the command and
  179. * parameter and transmits all of it to the SD card. If requested
  180. * the card will be deselected afterwards.
  181. */
  182. static int sendCommand(const uint8_t card,
  183. const uint8_t command,
  184. const uint32_t parameter,
  185. const uint8_t deselect) {
  186. union {
  187. uint32_t l;
  188. uint8_t c[4];
  189. } long2char;
  190. uint8_t i,crc=0,errorcount;
  191. uint16_t counter;
  192. long2char.l = parameter;
  193. crc = crc7update(0 , 0x40+command);
  194. crc = crc7update(crc, long2char.c[3]);
  195. crc = crc7update(crc, long2char.c[2]);
  196. crc = crc7update(crc, long2char.c[1]);
  197. crc = crc7update(crc, long2char.c[0]);
  198. crc = (crc << 1) | 1;
  199. errorcount = 0;
  200. while (errorcount < CONFIG_SD_AUTO_RETRIES) {
  201. // Select card
  202. SPI_SS_LOW(card);
  203. #ifdef CONFIG_TWINSD
  204. if (card == 0 && command == GO_IDLE_STATE)
  205. /* Force both cards to SPI mode simultaneously */
  206. SPI_SS_LOW(1);
  207. #endif
  208. // Transfer command
  209. spiTransferByte(0x40+command);
  210. spiTransferLong(parameter);
  211. spiTransferByte(crc);
  212. // Wait for a valid response
  213. counter = 0;
  214. do {
  215. i = spiTransferByte(0xff);
  216. counter++;
  217. } while (i & 0x80 && counter < 0x1000);
  218. #ifdef CONFIG_TWINSD
  219. if (card == 0 && command == GO_IDLE_STATE)
  220. SPI_SS_HIGH(1);
  221. #endif
  222. // Check for CRC error
  223. // can't reliably retry unless deselect is allowed
  224. if (deselect && (i & STATUS_CRC_ERROR)) {
  225. uart_putc('x');
  226. deselectCard(card);
  227. errorcount++;
  228. continue;
  229. }
  230. if (deselect) deselectCard(card);
  231. break;
  232. }
  233. return i;
  234. }
  235. // Extended init sequence for SDHC support
  236. static uint8_t extendedInit(const uint8_t card) {
  237. uint8_t i;
  238. uint32_t answer;
  239. // Send CMD8: SEND_IF_COND
  240. // 0b000110101010 == 2.7-3.6V supply, check pattern 0xAA
  241. i = sendCommand(card, SEND_IF_COND, 0b000110101010, 0);
  242. if (i > 1) {
  243. // Card returned an error, ok (MMC oder SD1.x) but not SDHC
  244. deselectCard(card);
  245. return TRUE;
  246. }
  247. // No error, continue SDHC initialization
  248. answer = spiTransferLong(0);
  249. deselectCard(card);
  250. if (((answer >> 8) & 0x0f) != 0b0001) {
  251. // Card didn't accept our voltage specification
  252. return FALSE;
  253. }
  254. // Verify echo-back of check pattern
  255. if ((answer & 0xff) != 0b10101010) {
  256. // Check pattern mismatch, working but not SD2.0 compliant
  257. // The specs say we should not use the card, but let's try anyway.
  258. return TRUE;
  259. }
  260. return TRUE;
  261. }
  262. // SD common initialisation
  263. static void sdInit(const uint8_t card) {
  264. uint8_t i;
  265. uint16_t counter;
  266. SD_SPI_OFFLOAD = 0;
  267. counter = 0xffff;
  268. do {
  269. // Prepare for ACMD, send CMD55: APP_CMD
  270. i = sendCommand(card, APP_CMD, 0, 1);
  271. if (i > 1)
  272. // Command not accepted, could be MMC
  273. return;
  274. // Send ACMD41: SD_SEND_OP_COND
  275. // 1L<<30 == Host has High Capacity Support
  276. i = sendCommand(card, SD_SEND_OP_COND, 1L<<30, 1);
  277. // Repeat while card card accepts command but isn't ready
  278. } while (i == 1 && --counter > 0);
  279. // Ignore failures, there is at least one Sandisk MMC card
  280. // that accepts CMD55, but not ACMD41.
  281. if (i == 0)
  282. /* We know that a card is SD if ACMD41 was accepted. */
  283. cardtype[card] |= CARD_SD;
  284. }
  285. /* Detect changes of SD card 0 */
  286. #ifdef SD_CHANGE_VECT
  287. ISR(SD_CHANGE_VECT) {
  288. if (SDCARD_DETECT)
  289. disk_state = DISK_CHANGED;
  290. else
  291. disk_state = DISK_REMOVED;
  292. }
  293. #endif
  294. #ifdef CONFIG_TWINSD
  295. /* Detect changes of SD card 1 */
  296. ISR(SD2_CHANGE_VECT) {
  297. if (SD2_DETECT)
  298. disk_state = DISK_CHANGED;
  299. else
  300. disk_state = DISK_REMOVED;
  301. }
  302. #endif
  303. //
  304. // Public functions
  305. //
  306. void sd_init(void) {
  307. SDCARD_DETECT_SETUP();
  308. SDCARD_WP_SETUP();
  309. SD_CHANGE_SETUP();
  310. #ifdef CONFIG_TWINSD
  311. /* Initialize the control lines for card 2 */
  312. SD2_SETUP();
  313. SD2_CHANGE_SETUP();
  314. #endif
  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. // uart_putc('0');
  333. if (SDCARD_WP) {
  334. // uart_putc('1');
  335. return STA_PROTECT;
  336. } else {
  337. // uart_putc('2');
  338. return RES_OK;
  339. }
  340. } else {
  341. // uart_putc('3');
  342. return STA_NOINIT|STA_NODISK;
  343. }
  344. }
  345. DSTATUS disk_status(BYTE drv) __attribute__ ((weak, alias("sd_status")));
  346. /**
  347. * sd_initialize - initialize SD card
  348. * @drv : drive
  349. *
  350. * This function tries to initialize the selected SD card.
  351. */
  352. DSTATUS sd_initialize(BYTE drv) {
  353. uint8_t i;
  354. uint16_t counter;
  355. uint32_t answer;
  356. if (drv >= MAX_CARDS)
  357. return STA_NOINIT|STA_NODISK;
  358. /* Don't bother initializing a card that isn't there */
  359. // uart_putc('#');
  360. if (sd_status(drv) & STA_NODISK)
  361. return sd_status(drv);
  362. /* JLB: Should be in sd_init, but some uIEC versions have
  363. * IEC lines tied to SPI, so I moved it here to resolve the
  364. * conflict.
  365. */
  366. spiInit();
  367. disk_state = DISK_ERROR;
  368. cardtype[drv] = 0;
  369. SPI_SS_HIGH(drv);
  370. // Send 80 clks
  371. for (i=0; i<10; i++) {
  372. spiTransferByte(0xFF);
  373. }
  374. // Reset card
  375. i = sendCommand(drv, GO_IDLE_STATE, 0, 1);
  376. if (i != 1) {
  377. return STA_NOINIT | STA_NODISK;
  378. }
  379. if (!extendedInit(drv))
  380. return STA_NOINIT | STA_NODISK;
  381. sdInit(drv);
  382. counter = 0xffff;
  383. // According to the spec READ_OCR should work at this point
  384. // without retries. One of my Sandisk-cards thinks otherwise.
  385. do {
  386. // Send CMD58: READ_OCR
  387. i = sendCommand(drv, READ_OCR, 0, 0);
  388. if (i > 1)
  389. deselectCard(drv);
  390. } while (i > 1 && counter-- > 0);
  391. if (counter > 0) {
  392. answer = spiTransferLong(0);
  393. // See if the card likes our supply voltage
  394. if (!(answer & SD_SUPPLY_VOLTAGE)) {
  395. // The code isn't set up to completely ignore the card,
  396. // but at least report it as nonworking
  397. deselectCard(drv);
  398. return STA_NOINIT | STA_NODISK;
  399. }
  400. // See what card we've got
  401. if (answer & 0x40000000) {
  402. cardtype[drv] |= CARD_SDHC;
  403. }
  404. }
  405. // Keep sending CMD1 (SEND_OP_COND) command until zero response
  406. counter = 0xffff;
  407. do {
  408. i = sendCommand(drv, SEND_OP_COND, 1L<<30, 1);
  409. counter--;
  410. } while (i != 0 && counter > 0);
  411. if (counter==0) {
  412. return STA_NOINIT | STA_NODISK;
  413. }
  414. #ifdef CONFIG_SD_DATACRC
  415. // Enable CRC checking
  416. // The SD spec says that the host "should" send CRC_ON_OFF before ACMD_SEND_OP_COND.
  417. // The MMC manual I have says that CRC_ON_OFF isn't allowed before SEND_OP_COND.
  418. // Let's just hope that all SD cards work with this order. =(
  419. i = sendCommand(drv, CRC_ON_OFF, 1, 1);
  420. if (i > 1) {
  421. return STA_NOINIT | STA_NODISK;
  422. }
  423. #endif
  424. // Send MMC CMD16(SET_BLOCKLEN) to 512 bytes
  425. i = sendCommand(drv, SET_BLOCKLEN, 512, 1);
  426. if (i != 0) {
  427. return STA_NOINIT | STA_NODISK;
  428. }
  429. // Thats it!
  430. disk_state = DISK_OK;
  431. return sd_status(drv);
  432. }
  433. DSTATUS disk_initialize(BYTE drv) __attribute__ ((weak, alias("sd_initialize")));
  434. /**
  435. * sd_read - reads sectors from the SD card to buffer
  436. * @drv : drive
  437. * @buffer: pointer to the buffer
  438. * @sector: first sector to be read
  439. * @count : number of sectors to be read
  440. *
  441. * This function reads count sectors from the SD card starting
  442. * at sector to buffer. Returns RES_ERROR if an error occured or
  443. * RES_OK if successful. Up to SD_AUTO_RETRIES will be made if
  444. * the calculated data CRC does not match the one sent by the
  445. * card. If there were errors during the command transmission
  446. * disk_state will be set to DISK_ERROR and no retries are made.
  447. */
  448. DRESULT sd_read(BYTE drv, BYTE *buffer, DWORD sector, BYTE count) {
  449. uint8_t sec,res,tmp,errorcount;
  450. uint16_t crc,recvcrc;
  451. if (drv >= MAX_CARDS)
  452. return RES_PARERR;
  453. for (sec=0;sec<count;sec++) {
  454. errorcount = 0;
  455. while (errorcount < CONFIG_SD_AUTO_RETRIES) {
  456. if (cardtype[drv] & CARD_SDHC)
  457. res = sendCommand(drv, READ_SINGLE_BLOCK, sector+sec, 0);
  458. else
  459. res = sendCommand(drv, READ_SINGLE_BLOCK, (sector+sec) << 9, 0);
  460. if (res != 0) {
  461. uart_putc('?');
  462. dprintf("SD error: %02x\n", res);
  463. SPI_SS_HIGH(drv);
  464. disk_state = DISK_ERROR;
  465. return RES_ERROR;
  466. }
  467. // Wait for data token
  468. if (!sdResponse(0xFE)) {
  469. uart_putc('-');
  470. SPI_SS_HIGH(drv);
  471. disk_state = DISK_ERROR;
  472. return RES_ERROR;
  473. }
  474. uint16_t i;
  475. #ifdef CONFIG_SD_DATACRC
  476. BYTE *oldbuffer = buffer;
  477. #endif
  478. // Get data
  479. crc = 0;
  480. if(SD_SPI_OFFLOAD) {
  481. // uart_putc('O');
  482. PORTB |= _BV(PB2);
  483. DDRB |= _BV(PB2);
  484. _delay_us(1);
  485. PORTB &= ~_BV(PB2);
  486. DDRB &= ~_BV(PB7); // tristate SCK
  487. PORTB |= _BV(PB2);
  488. DDRB &= ~_BV(PB2);
  489. _delay_us(1);
  490. while(!(PINB & _BV(PB2)));
  491. DDRB |= _BV(PB7);
  492. DDRB |= _BV(PB2);
  493. // _delay_us(1);
  494. deselectCard(drv);
  495. SD_SPI_OFFLOAD = 0;
  496. return RES_OK;
  497. SPDR = 0xff;
  498. } else {
  499. // Initiate data exchange over SPI
  500. SPDR = 0xff;
  501. for (i=0; i<512; i++) {
  502. // Wait until data has been received
  503. loop_until_bit_is_set(SPSR, SPIF);
  504. tmp = SPDR;
  505. // Transmit the next byte while we store the current one
  506. SPDR = 0xff;
  507. *(buffer++) = tmp;
  508. #ifdef CONFIG_SD_DATACRC
  509. crc = _crc_xmodem_update(crc, tmp);
  510. #endif
  511. }
  512. }
  513. // Wait until the first CRC byte is received
  514. loop_until_bit_is_set(SPSR, SPIF);
  515. // Check CRC
  516. recvcrc = (SPDR << 8) + spiTransferByte(0xff);
  517. #ifdef CONFIG_SD_DATACRC
  518. if (recvcrc != crc) {
  519. uart_putc('X');
  520. deselectCard(drv);
  521. errorcount++;
  522. buffer = oldbuffer;
  523. continue;
  524. }
  525. #endif
  526. break;
  527. }
  528. deselectCard(drv);
  529. if (errorcount >= CONFIG_SD_AUTO_RETRIES) return RES_ERROR;
  530. }
  531. return RES_OK;
  532. }
  533. DRESULT disk_read(BYTE drv, BYTE *buffer, DWORD sector, BYTE count) __attribute__ ((weak, alias("sd_read")));
  534. /**
  535. * sd_write - writes sectors from buffer to the SD card
  536. * @drv : drive
  537. * @buffer: pointer to the buffer
  538. * @sector: first sector to be written
  539. * @count : number of sectors to be written
  540. *
  541. * This function writes count sectors from buffer to the SD card
  542. * starting at sector. Returns RES_ERROR if an error occured,
  543. * RES_WPRT if the card is currently write-protected or RES_OK
  544. * if successful. Up to SD_AUTO_RETRIES will be made if the card
  545. * signals a CRC error. If there were errors during the command
  546. * transmission disk_state will be set to DISK_ERROR and no retries
  547. * are made.
  548. */
  549. DRESULT sd_write(BYTE drv, const BYTE *buffer, DWORD sector, BYTE count) {
  550. uint8_t res,sec,errorcount,status;
  551. uint16_t crc;
  552. if (drv >= MAX_CARDS)
  553. return RES_PARERR;
  554. #ifdef CONFIG_TWINSD
  555. if (drv != 0) {
  556. if (SD2_PIN & SD2_WP)
  557. return RES_WRPRT;
  558. } else
  559. #endif
  560. if (SDCARD_WP) return RES_WRPRT;
  561. for (sec=0;sec<count;sec++) {
  562. errorcount = 0;
  563. while (errorcount < CONFIG_SD_AUTO_RETRIES) {
  564. if (cardtype[drv] & CARD_SDHC)
  565. res = sendCommand(drv, WRITE_BLOCK, sector+sec, 0);
  566. else
  567. res = sendCommand(drv, WRITE_BLOCK, (sector+sec)<<9, 0);
  568. if (res != 0) {
  569. uart_putc('C');
  570. SPI_SS_HIGH(drv);
  571. disk_state = DISK_ERROR;
  572. return RES_ERROR;
  573. }
  574. // Send data token
  575. spiTransferByte(0xFE);
  576. uint16_t i;
  577. const BYTE *oldbuffer = buffer;
  578. // Send data
  579. crc = 0;
  580. for (i=0; i<512; i++) {
  581. #ifdef CONFIG_SD_DATACRC
  582. crc = _crc_xmodem_update(crc, *buffer);
  583. #endif
  584. spiTransferByte(*(buffer++));
  585. }
  586. // Send CRC
  587. spiTransferByte(crc >> 8);
  588. spiTransferByte(crc & 0xff);
  589. // Get and check status feedback
  590. status = spiTransferByte(0xFF);
  591. // Retry if neccessary
  592. if ((status & 0x0F) != 0x05) {
  593. uart_putc('X');
  594. deselectCard(drv);
  595. errorcount++;
  596. buffer = oldbuffer;
  597. continue;
  598. }
  599. // Wait for write finish
  600. if (!sdWaitWriteFinish()) {
  601. uart_putc('W');
  602. SPI_SS_HIGH(drv);
  603. disk_state = DISK_ERROR;
  604. return RES_ERROR;
  605. }
  606. break;
  607. }
  608. deselectCard(drv);
  609. if (errorcount >= CONFIG_SD_AUTO_RETRIES) {
  610. if (!(status & STATUS_CRC_ERROR))
  611. disk_state = DISK_ERROR;
  612. return RES_ERROR;
  613. }
  614. }
  615. return RES_OK;
  616. }
  617. DRESULT disk_write(BYTE drv, const BYTE *buffer, DWORD sector, BYTE count) __attribute__ ((weak, alias("sd_write")));
  618. DRESULT sd_getinfo(BYTE drv, BYTE page, void *buffer) {
  619. uint8_t i;
  620. uint8_t buf[18];
  621. uint32_t capacity;
  622. if (drv >= MAX_CARDS)
  623. return RES_NOTRDY;
  624. if (sd_status(drv) & STA_NODISK)
  625. return RES_NOTRDY;
  626. if (page != 0)
  627. return RES_ERROR;
  628. /* Try to calculate the total number of sectors on the card */
  629. /* FIXME: Write a generic data read function and merge with sd_read */
  630. if (sendCommand(drv, SEND_CSD, 0, 0) != 0) {
  631. deselectCard(drv);
  632. return RES_ERROR;
  633. }
  634. /* Wait for data token */
  635. if (!sdResponse(0xfe)) {
  636. deselectCard(drv);
  637. return RES_ERROR;
  638. }
  639. for (i=0;i<18;i++) {
  640. buf[i] = spiTransferByte(0xff);
  641. }
  642. deselectCard(drv);
  643. if (cardtype[drv] & CARD_SDHC) {
  644. /* Special CSD for SDHC cards */
  645. capacity = (1 + getbits(buf,127-69,22)) * 1024;
  646. } else {
  647. /* Assume that MMC-CSD 1.0/1.1/1.2 and SD-CSD 1.1 are the same... */
  648. uint8_t exponent = 2 + getbits(buf, 127-49, 3);
  649. capacity = 1 + getbits(buf, 127-73, 12);
  650. exponent += getbits(buf, 127-83,4) - 9;
  651. while (exponent--) capacity *= 2;
  652. }
  653. diskinfo0_t *di = buffer;
  654. di->validbytes = sizeof(diskinfo0_t);
  655. di->disktype = DISK_TYPE_SD;
  656. di->sectorsize = 2;
  657. di->sectorcount = capacity;
  658. return RES_OK;
  659. }
  660. DRESULT disk_getinfo(BYTE drv, BYTE page, void *buffer) __attribute__ ((weak, alias("sd_getinfo")));