sdio.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. /**
  2. * ZuluSCSI™ - Copyright (c) 2022 Rabbit Hole Computing™
  3. *
  4. * ZuluSCSI™ firmware is licensed under the GPL version 3 or any later version. 
  5. *
  6. * https://www.gnu.org/licenses/gpl-3.0.html
  7. * ----
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version. 
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  16. * GNU General Public License for more details. 
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program.  If not, see <https://www.gnu.org/licenses/>.
  20. **/
  21. // Implementation of SDIO communication for RP2040
  22. //
  23. // The RP2040 official work-in-progress code at
  24. // https://github.com/raspberrypi/pico-extras/tree/master/src/rp2_common/pico_sd_card
  25. // may be useful reference, but this is independent implementation.
  26. //
  27. // For official SDIO specifications, refer to:
  28. // https://www.sdcard.org/downloads/pls/
  29. // "SDIO Physical Layer Simplified Specification Version 8.00"
  30. #include "sdio.h"
  31. #include <hardware/pio.h>
  32. #include <hardware/dma.h>
  33. #include <hardware/gpio.h>
  34. #include <ZuluSCSI_platform.h>
  35. #include <ZuluSCSI_log.h>
  36. // \todo find a better way
  37. #include <hardware/structs/scb.h>
  38. #if defined(ZULUSCSI_PICO_2) || defined(ZULUSCSI_BS2)
  39. #include "sdio_Pico_2.pio.h"
  40. #else
  41. #include "sdio_RP2350.pio.h"
  42. #endif
  43. #define SDIO_PIO pio1
  44. #define SDIO_CMD_SM 0
  45. #define SDIO_DATA_SM 1
  46. #define SDIO_DMA_CH 4
  47. #define SDIO_DMA_CHB 5
  48. // Maximum number of 512 byte blocks to transfer in one request
  49. #define SDIO_MAX_BLOCKS 256
  50. enum sdio_transfer_state_t { SDIO_IDLE, SDIO_RX, SDIO_TX, SDIO_TX_WAIT_IDLE};
  51. static struct {
  52. uint32_t pio_cmd_clk_offset;
  53. uint32_t pio_data_rx_offset;
  54. pio_sm_config pio_cfg_data_rx;
  55. uint32_t pio_data_tx_offset;
  56. pio_sm_config pio_cfg_data_tx;
  57. sdio_transfer_state_t transfer_state;
  58. uint32_t transfer_start_time;
  59. uint32_t *data_buf;
  60. uint32_t blocks_done; // Number of blocks transferred so far
  61. uint32_t total_blocks; // Total number of blocks to transfer
  62. uint32_t blocks_checksumed; // Number of blocks that have had CRC calculated
  63. uint32_t checksum_errors; // Number of checksum errors detected
  64. // Variables for block writes
  65. uint64_t next_wr_block_checksum;
  66. uint32_t end_token_buf[3]; // CRC and end token for write block
  67. sdio_status_t wr_status;
  68. uint32_t card_response;
  69. // Variables for block reads
  70. // This is used to perform DMA into data buffers and checksum buffers separately.
  71. struct {
  72. void * write_addr;
  73. uint32_t transfer_count;
  74. } dma_blocks[SDIO_MAX_BLOCKS * 2];
  75. struct {
  76. uint32_t top;
  77. uint32_t bottom;
  78. } received_checksums[SDIO_MAX_BLOCKS];
  79. } g_sdio;
  80. void rp2040_sdio_dma_irq();
  81. /*******************************************************
  82. * Checksum algorithms
  83. *******************************************************/
  84. // Table lookup for calculating CRC-7 checksum that is used in SDIO command packets.
  85. // Usage:
  86. // uint8_t crc = 0;
  87. // crc = crc7_table[crc ^ byte];
  88. // .. repeat for every byte ..
  89. static const uint8_t crc7_table[256] = {
  90. 0x00, 0x12, 0x24, 0x36, 0x48, 0x5a, 0x6c, 0x7e, 0x90, 0x82, 0xb4, 0xa6, 0xd8, 0xca, 0xfc, 0xee,
  91. 0x32, 0x20, 0x16, 0x04, 0x7a, 0x68, 0x5e, 0x4c, 0xa2, 0xb0, 0x86, 0x94, 0xea, 0xf8, 0xce, 0xdc,
  92. 0x64, 0x76, 0x40, 0x52, 0x2c, 0x3e, 0x08, 0x1a, 0xf4, 0xe6, 0xd0, 0xc2, 0xbc, 0xae, 0x98, 0x8a,
  93. 0x56, 0x44, 0x72, 0x60, 0x1e, 0x0c, 0x3a, 0x28, 0xc6, 0xd4, 0xe2, 0xf0, 0x8e, 0x9c, 0xaa, 0xb8,
  94. 0xc8, 0xda, 0xec, 0xfe, 0x80, 0x92, 0xa4, 0xb6, 0x58, 0x4a, 0x7c, 0x6e, 0x10, 0x02, 0x34, 0x26,
  95. 0xfa, 0xe8, 0xde, 0xcc, 0xb2, 0xa0, 0x96, 0x84, 0x6a, 0x78, 0x4e, 0x5c, 0x22, 0x30, 0x06, 0x14,
  96. 0xac, 0xbe, 0x88, 0x9a, 0xe4, 0xf6, 0xc0, 0xd2, 0x3c, 0x2e, 0x18, 0x0a, 0x74, 0x66, 0x50, 0x42,
  97. 0x9e, 0x8c, 0xba, 0xa8, 0xd6, 0xc4, 0xf2, 0xe0, 0x0e, 0x1c, 0x2a, 0x38, 0x46, 0x54, 0x62, 0x70,
  98. 0x82, 0x90, 0xa6, 0xb4, 0xca, 0xd8, 0xee, 0xfc, 0x12, 0x00, 0x36, 0x24, 0x5a, 0x48, 0x7e, 0x6c,
  99. 0xb0, 0xa2, 0x94, 0x86, 0xf8, 0xea, 0xdc, 0xce, 0x20, 0x32, 0x04, 0x16, 0x68, 0x7a, 0x4c, 0x5e,
  100. 0xe6, 0xf4, 0xc2, 0xd0, 0xae, 0xbc, 0x8a, 0x98, 0x76, 0x64, 0x52, 0x40, 0x3e, 0x2c, 0x1a, 0x08,
  101. 0xd4, 0xc6, 0xf0, 0xe2, 0x9c, 0x8e, 0xb8, 0xaa, 0x44, 0x56, 0x60, 0x72, 0x0c, 0x1e, 0x28, 0x3a,
  102. 0x4a, 0x58, 0x6e, 0x7c, 0x02, 0x10, 0x26, 0x34, 0xda, 0xc8, 0xfe, 0xec, 0x92, 0x80, 0xb6, 0xa4,
  103. 0x78, 0x6a, 0x5c, 0x4e, 0x30, 0x22, 0x14, 0x06, 0xe8, 0xfa, 0xcc, 0xde, 0xa0, 0xb2, 0x84, 0x96,
  104. 0x2e, 0x3c, 0x0a, 0x18, 0x66, 0x74, 0x42, 0x50, 0xbe, 0xac, 0x9a, 0x88, 0xf6, 0xe4, 0xd2, 0xc0,
  105. 0x1c, 0x0e, 0x38, 0x2a, 0x54, 0x46, 0x70, 0x62, 0x8c, 0x9e, 0xa8, 0xba, 0xc4, 0xd6, 0xe0, 0xf2
  106. };
  107. // Calculate the CRC16 checksum for parallel 4 bit lines separately.
  108. // When the SDIO bus operates in 4-bit mode, the CRC16 algorithm
  109. // is applied to each line separately and generates total of
  110. // 4 x 16 = 64 bits of checksum.
  111. __attribute__((optimize("O3")))
  112. uint64_t sdio_crc16_4bit_checksum(uint32_t *data, uint32_t num_words)
  113. {
  114. uint64_t crc = 0;
  115. uint32_t *end = data + num_words;
  116. while (data < end)
  117. {
  118. for (int unroll = 0; unroll < 4; unroll++)
  119. {
  120. // Each 32-bit word contains 8 bits per line.
  121. // Reverse the bytes because SDIO protocol is big-endian.
  122. uint32_t data_in = __builtin_bswap32(*data++);
  123. // Shift out 8 bits for each line
  124. uint32_t data_out = crc >> 32;
  125. crc <<= 32;
  126. // XOR outgoing data to itself with 4 bit delay
  127. data_out ^= (data_out >> 16);
  128. // XOR incoming data to outgoing data with 4 bit delay
  129. data_out ^= (data_in >> 16);
  130. // XOR outgoing and incoming data to accumulator at each tap
  131. uint64_t xorred = data_out ^ data_in;
  132. crc ^= xorred;
  133. crc ^= xorred << (5 * 4);
  134. crc ^= xorred << (12 * 4);
  135. }
  136. }
  137. return crc;
  138. }
  139. /*******************************************************
  140. * Status Register Receiver
  141. *******************************************************/
  142. sdio_status_t receive_status_register(uint8_t* sds) {
  143. rp2040_sdio_rx_start(sds, 1, 64);
  144. // Wait for the DMA operation to complete, or fail if it took too long
  145. waitagain:
  146. while (dma_channel_is_busy(SDIO_DMA_CHB) || dma_channel_is_busy(SDIO_DMA_CH))
  147. {
  148. if ((uint32_t)(millis() - g_sdio.transfer_start_time) > 2)
  149. {
  150. // Reset the state machine program
  151. dma_channel_abort(SDIO_DMA_CHB);
  152. pio_sm_set_enabled(SDIO_PIO, SDIO_CMD_SM, false);
  153. pio_sm_clear_fifos(SDIO_PIO, SDIO_CMD_SM);
  154. return SDIO_ERR_RESPONSE_TIMEOUT;
  155. }
  156. }
  157. // Assert that both DMA channels are complete
  158. if(dma_channel_is_busy(SDIO_DMA_CHB) || dma_channel_is_busy(SDIO_DMA_CH)) {
  159. // Wait failure, go back.
  160. goto waitagain;
  161. }
  162. pio_sm_set_enabled(SDIO_PIO, SDIO_DATA_SM, false);
  163. g_sdio.transfer_state = SDIO_IDLE;
  164. return SDIO_OK;
  165. }
  166. /*******************************************************
  167. * Basic SDIO command execution
  168. *******************************************************/
  169. static void sdio_send_command(uint8_t command, uint32_t arg, uint8_t response_bits)
  170. {
  171. // dbgmsg("SDIO Command: ", (int)command, " arg ", arg);
  172. // Format the arguments in the way expected by the PIO code.
  173. uint32_t word0 =
  174. (47 << 24) | // Number of bits in command minus one
  175. ( 1 << 22) | // Transfer direction from host to card
  176. (command << 16) | // Command byte
  177. (((arg >> 24) & 0xFF) << 8) | // MSB byte of argument
  178. (((arg >> 16) & 0xFF) << 0);
  179. uint32_t word1 =
  180. (((arg >> 8) & 0xFF) << 24) |
  181. (((arg >> 0) & 0xFF) << 16) | // LSB byte of argument
  182. ( 1 << 8); // End bit
  183. // Set number of bits in response minus one, or leave at 0 if no response expected
  184. if (response_bits)
  185. {
  186. word1 |= ((response_bits - 1) << 0);
  187. }
  188. // Calculate checksum in the order that the bytes will be transmitted (big-endian)
  189. uint8_t crc = 0;
  190. crc = crc7_table[crc ^ ((word0 >> 16) & 0xFF)];
  191. crc = crc7_table[crc ^ ((word0 >> 8) & 0xFF)];
  192. crc = crc7_table[crc ^ ((word0 >> 0) & 0xFF)];
  193. crc = crc7_table[crc ^ ((word1 >> 24) & 0xFF)];
  194. crc = crc7_table[crc ^ ((word1 >> 16) & 0xFF)];
  195. word1 |= crc << 8;
  196. // Transmit command
  197. pio_sm_clear_fifos(SDIO_PIO, SDIO_CMD_SM);
  198. pio_sm_put(SDIO_PIO, SDIO_CMD_SM, word0);
  199. pio_sm_put(SDIO_PIO, SDIO_CMD_SM, word1);
  200. }
  201. sdio_status_t rp2040_sdio_command_R1(uint8_t command, uint32_t arg, uint32_t *response)
  202. {
  203. sdio_send_command(command, arg, response ? 48 : 0);
  204. // Wait for response
  205. uint32_t start = millis();
  206. uint32_t wait_words = response ? 2 : 1;
  207. while (pio_sm_get_rx_fifo_level(SDIO_PIO, SDIO_CMD_SM) < wait_words)
  208. {
  209. if ((uint32_t)(millis() - start) > 2)
  210. {
  211. if (command != 8) // Don't log for missing SD card
  212. {
  213. dbgmsg("Timeout waiting for response in rp2040_sdio_command_R1(", (int)command, "), ",
  214. "PIO PC: ", (int)pio_sm_get_pc(SDIO_PIO, SDIO_CMD_SM) - (int)g_sdio.pio_cmd_clk_offset,
  215. " RXF: ", (int)pio_sm_get_rx_fifo_level(SDIO_PIO, SDIO_CMD_SM),
  216. " TXF: ", (int)pio_sm_get_tx_fifo_level(SDIO_PIO, SDIO_CMD_SM));
  217. }
  218. // Reset the state machine program
  219. pio_sm_clear_fifos(SDIO_PIO, SDIO_CMD_SM);
  220. pio_sm_exec(SDIO_PIO, SDIO_CMD_SM, pio_encode_jmp(g_sdio.pio_cmd_clk_offset));
  221. return SDIO_ERR_RESPONSE_TIMEOUT;
  222. }
  223. }
  224. if (response)
  225. {
  226. // Read out response packet
  227. uint32_t resp0 = pio_sm_get(SDIO_PIO, SDIO_CMD_SM);
  228. uint32_t resp1 = pio_sm_get(SDIO_PIO, SDIO_CMD_SM);
  229. // dbgmsg("SDIO R1 response: ", resp0, " ", resp1);
  230. // Calculate response checksum
  231. uint8_t crc = 0;
  232. crc = crc7_table[crc ^ ((resp0 >> 24) & 0xFF)];
  233. crc = crc7_table[crc ^ ((resp0 >> 16) & 0xFF)];
  234. crc = crc7_table[crc ^ ((resp0 >> 8) & 0xFF)];
  235. crc = crc7_table[crc ^ ((resp0 >> 0) & 0xFF)];
  236. crc = crc7_table[crc ^ ((resp1 >> 8) & 0xFF)];
  237. uint8_t actual_crc = ((resp1 >> 0) & 0xFE);
  238. if (crc != actual_crc)
  239. {
  240. dbgmsg("rp2040_sdio_command_R1(", (int)command, "): CRC error, calculated ", crc, " packet has ", actual_crc);
  241. return SDIO_ERR_RESPONSE_CRC;
  242. }
  243. uint8_t response_cmd = ((resp0 >> 24) & 0xFF);
  244. if (response_cmd != command && command != 41)
  245. {
  246. dbgmsg("rp2040_sdio_command_R1(", (int)command, "): received reply for ", (int)response_cmd);
  247. return SDIO_ERR_RESPONSE_CODE;
  248. }
  249. *response = ((resp0 & 0xFFFFFF) << 8) | ((resp1 >> 8) & 0xFF);
  250. }
  251. else
  252. {
  253. // Read out dummy marker
  254. pio_sm_get(SDIO_PIO, SDIO_CMD_SM);
  255. }
  256. return SDIO_OK;
  257. }
  258. sdio_status_t rp2040_sdio_command_R2(uint8_t command, uint32_t arg, uint8_t response[16])
  259. {
  260. // The response is too long to fit in the PIO FIFO, so use DMA to receive it.
  261. pio_sm_clear_fifos(SDIO_PIO, SDIO_CMD_SM);
  262. uint32_t response_buf[5];
  263. dma_channel_config dmacfg = dma_channel_get_default_config(SDIO_DMA_CH);
  264. channel_config_set_transfer_data_size(&dmacfg, DMA_SIZE_32);
  265. channel_config_set_read_increment(&dmacfg, false);
  266. channel_config_set_write_increment(&dmacfg, true);
  267. channel_config_set_dreq(&dmacfg, pio_get_dreq(SDIO_PIO, SDIO_CMD_SM, false));
  268. dma_channel_configure(SDIO_DMA_CH, &dmacfg, &response_buf, &SDIO_PIO->rxf[SDIO_CMD_SM], 5, true);
  269. sdio_send_command(command, arg, 136);
  270. uint32_t start = millis();
  271. while (dma_channel_is_busy(SDIO_DMA_CH))
  272. {
  273. if ((uint32_t)(millis() - start) > 2)
  274. {
  275. dbgmsg("Timeout waiting for response in rp2040_sdio_command_R2(", (int)command, "), ",
  276. "PIO PC: ", (int)pio_sm_get_pc(SDIO_PIO, SDIO_CMD_SM) - (int)g_sdio.pio_cmd_clk_offset,
  277. " RXF: ", (int)pio_sm_get_rx_fifo_level(SDIO_PIO, SDIO_CMD_SM),
  278. " TXF: ", (int)pio_sm_get_tx_fifo_level(SDIO_PIO, SDIO_CMD_SM));
  279. // Reset the state machine program
  280. dma_channel_abort(SDIO_DMA_CH);
  281. pio_sm_clear_fifos(SDIO_PIO, SDIO_CMD_SM);
  282. pio_sm_exec(SDIO_PIO, SDIO_CMD_SM, pio_encode_jmp(g_sdio.pio_cmd_clk_offset));
  283. return SDIO_ERR_RESPONSE_TIMEOUT;
  284. }
  285. }
  286. dma_channel_abort(SDIO_DMA_CH);
  287. // Copy the response payload to output buffer
  288. response[0] = ((response_buf[0] >> 16) & 0xFF);
  289. response[1] = ((response_buf[0] >> 8) & 0xFF);
  290. response[2] = ((response_buf[0] >> 0) & 0xFF);
  291. response[3] = ((response_buf[1] >> 24) & 0xFF);
  292. response[4] = ((response_buf[1] >> 16) & 0xFF);
  293. response[5] = ((response_buf[1] >> 8) & 0xFF);
  294. response[6] = ((response_buf[1] >> 0) & 0xFF);
  295. response[7] = ((response_buf[2] >> 24) & 0xFF);
  296. response[8] = ((response_buf[2] >> 16) & 0xFF);
  297. response[9] = ((response_buf[2] >> 8) & 0xFF);
  298. response[10] = ((response_buf[2] >> 0) & 0xFF);
  299. response[11] = ((response_buf[3] >> 24) & 0xFF);
  300. response[12] = ((response_buf[3] >> 16) & 0xFF);
  301. response[13] = ((response_buf[3] >> 8) & 0xFF);
  302. response[14] = ((response_buf[3] >> 0) & 0xFF);
  303. response[15] = ((response_buf[4] >> 0) & 0xFF);
  304. // Calculate checksum of the payload
  305. uint8_t crc = 0;
  306. for (int i = 0; i < 15; i++)
  307. {
  308. crc = crc7_table[crc ^ response[i]];
  309. }
  310. uint8_t actual_crc = response[15] & 0xFE;
  311. if (crc != actual_crc)
  312. {
  313. dbgmsg("rp2040_sdio_command_R2(", (int)command, "): CRC error, calculated ", crc, " packet has ", actual_crc);
  314. return SDIO_ERR_RESPONSE_CRC;
  315. }
  316. uint8_t response_cmd = ((response_buf[0] >> 24) & 0xFF);
  317. if (response_cmd != 0x3F)
  318. {
  319. dbgmsg("rp2040_sdio_command_R2(", (int)command, "): Expected reply code 0x3F");
  320. return SDIO_ERR_RESPONSE_CODE;
  321. }
  322. return SDIO_OK;
  323. }
  324. sdio_status_t rp2040_sdio_command_R3(uint8_t command, uint32_t arg, uint32_t *response)
  325. {
  326. sdio_send_command(command, arg, 48);
  327. // Wait for response
  328. uint32_t start = millis();
  329. while (pio_sm_get_rx_fifo_level(SDIO_PIO, SDIO_CMD_SM) < 2)
  330. {
  331. if ((uint32_t)(millis() - start) > 2)
  332. {
  333. dbgmsg("Timeout waiting for response in rp2040_sdio_command_R3(", (int)command, "), ",
  334. "PIO PC: ", (int)pio_sm_get_pc(SDIO_PIO, SDIO_CMD_SM) - (int)g_sdio.pio_cmd_clk_offset,
  335. " RXF: ", (int)pio_sm_get_rx_fifo_level(SDIO_PIO, SDIO_CMD_SM),
  336. " TXF: ", (int)pio_sm_get_tx_fifo_level(SDIO_PIO, SDIO_CMD_SM));
  337. // Reset the state machine program
  338. pio_sm_clear_fifos(SDIO_PIO, SDIO_CMD_SM);
  339. pio_sm_exec(SDIO_PIO, SDIO_CMD_SM, pio_encode_jmp(g_sdio.pio_cmd_clk_offset));
  340. return SDIO_ERR_RESPONSE_TIMEOUT;
  341. }
  342. }
  343. // Read out response packet
  344. uint32_t resp0 = pio_sm_get(SDIO_PIO, SDIO_CMD_SM);
  345. uint32_t resp1 = pio_sm_get(SDIO_PIO, SDIO_CMD_SM);
  346. *response = ((resp0 & 0xFFFFFF) << 8) | ((resp1 >> 8) & 0xFF);
  347. // dbgmsg("SDIO R3 response: ", resp0, " ", resp1);
  348. return SDIO_OK;
  349. }
  350. /*******************************************************
  351. * Data reception from SD card
  352. *******************************************************/
  353. sdio_status_t rp2040_sdio_rx_start(uint8_t *buffer, uint32_t num_blocks, uint32_t block_size)
  354. {
  355. // Buffer must be aligned
  356. assert(((uint32_t)buffer & 3) == 0 && num_blocks <= SDIO_MAX_BLOCKS);
  357. g_sdio.transfer_state = SDIO_RX;
  358. g_sdio.transfer_start_time = millis();
  359. g_sdio.data_buf = (uint32_t*)buffer;
  360. g_sdio.blocks_done = 0;
  361. g_sdio.total_blocks = num_blocks;
  362. g_sdio.blocks_checksumed = 0;
  363. g_sdio.checksum_errors = 0;
  364. // Create DMA block descriptors to store each block of block_size bytes of data to buffer
  365. // and then 8 bytes to g_sdio.received_checksums.
  366. for (int i = 0; i < num_blocks; i++)
  367. {
  368. g_sdio.dma_blocks[i * 2].write_addr = buffer + i * block_size;
  369. g_sdio.dma_blocks[i * 2].transfer_count = block_size / sizeof(uint32_t);
  370. g_sdio.dma_blocks[i * 2 + 1].write_addr = &g_sdio.received_checksums[i];
  371. g_sdio.dma_blocks[i * 2 + 1].transfer_count = 2;
  372. }
  373. g_sdio.dma_blocks[num_blocks * 2].write_addr = 0;
  374. g_sdio.dma_blocks[num_blocks * 2].transfer_count = 0;
  375. // Configure first DMA channel for reading from the PIO RX fifo
  376. dma_channel_config dmacfg = dma_channel_get_default_config(SDIO_DMA_CH);
  377. channel_config_set_transfer_data_size(&dmacfg, DMA_SIZE_32);
  378. channel_config_set_read_increment(&dmacfg, false);
  379. channel_config_set_write_increment(&dmacfg, true);
  380. channel_config_set_dreq(&dmacfg, pio_get_dreq(SDIO_PIO, SDIO_DATA_SM, false));
  381. channel_config_set_bswap(&dmacfg, true);
  382. channel_config_set_chain_to(&dmacfg, SDIO_DMA_CHB);
  383. dma_channel_configure(SDIO_DMA_CH, &dmacfg, 0, &SDIO_PIO->rxf[SDIO_DATA_SM], 0, false);
  384. // Configure second DMA channel for reconfiguring the first one
  385. dmacfg = dma_channel_get_default_config(SDIO_DMA_CHB);
  386. channel_config_set_transfer_data_size(&dmacfg, DMA_SIZE_32);
  387. channel_config_set_read_increment(&dmacfg, true);
  388. channel_config_set_write_increment(&dmacfg, true);
  389. channel_config_set_ring(&dmacfg, true, 3);
  390. dma_channel_configure(SDIO_DMA_CHB, &dmacfg, &dma_hw->ch[SDIO_DMA_CH].al1_write_addr,
  391. g_sdio.dma_blocks, 2, false);
  392. // Initialize PIO state machine
  393. pio_sm_init(SDIO_PIO, SDIO_DATA_SM, g_sdio.pio_data_rx_offset, &g_sdio.pio_cfg_data_rx);
  394. pio_sm_set_consecutive_pindirs(SDIO_PIO, SDIO_DATA_SM, SDIO_D0, 4, false);
  395. // Write number of nibbles to receive to Y register
  396. pio_sm_put(SDIO_PIO, SDIO_DATA_SM, block_size * 2 + 16 - 1);
  397. pio_sm_exec(SDIO_PIO, SDIO_DATA_SM, pio_encode_out(pio_y, 32));
  398. // Enable RX FIFO join because we don't need the TX FIFO during transfer.
  399. // This gives more leeway for the DMA block switching
  400. SDIO_PIO->sm[SDIO_DATA_SM].shiftctrl |= PIO_SM0_SHIFTCTRL_FJOIN_RX_BITS;
  401. // Start PIO and DMA
  402. dma_channel_start(SDIO_DMA_CHB);
  403. pio_sm_set_enabled(SDIO_PIO, SDIO_DATA_SM, true);
  404. return SDIO_OK;
  405. }
  406. // Check checksums for received blocks
  407. static void sdio_verify_rx_checksums(uint32_t maxcount)
  408. {
  409. while (g_sdio.blocks_checksumed < g_sdio.blocks_done && maxcount-- > 0)
  410. {
  411. // Calculate checksum from received data
  412. int blockidx = g_sdio.blocks_checksumed++;
  413. uint64_t checksum = sdio_crc16_4bit_checksum(g_sdio.data_buf + blockidx * SDIO_WORDS_PER_BLOCK,
  414. SDIO_WORDS_PER_BLOCK);
  415. // Convert received checksum to little-endian format
  416. uint32_t top = __builtin_bswap32(g_sdio.received_checksums[blockidx].top);
  417. uint32_t bottom = __builtin_bswap32(g_sdio.received_checksums[blockidx].bottom);
  418. uint64_t expected = ((uint64_t)top << 32) | bottom;
  419. if (checksum != expected)
  420. {
  421. g_sdio.checksum_errors++;
  422. if (g_sdio.checksum_errors == 1)
  423. {
  424. logmsg("SDIO checksum error in reception: block ", blockidx,
  425. " calculated ", checksum, " expected ", expected);
  426. }
  427. }
  428. }
  429. }
  430. sdio_status_t rp2040_sdio_rx_poll(uint32_t *bytes_complete)
  431. {
  432. // Was everything done when the previous rx_poll() finished?
  433. if (g_sdio.blocks_done >= g_sdio.total_blocks)
  434. {
  435. g_sdio.transfer_state = SDIO_IDLE;
  436. }
  437. else
  438. {
  439. // Use the idle time to calculate checksums
  440. sdio_verify_rx_checksums(4);
  441. // Check how many DMA control blocks have been consumed
  442. uint32_t dma_ctrl_block_count = (dma_hw->ch[SDIO_DMA_CHB].read_addr - (uint32_t)&g_sdio.dma_blocks);
  443. dma_ctrl_block_count /= sizeof(g_sdio.dma_blocks[0]);
  444. // Compute how many complete 512 byte SDIO blocks have been transferred
  445. // When transfer ends, dma_ctrl_block_count == g_sdio.total_blocks * 2 + 1
  446. g_sdio.blocks_done = (dma_ctrl_block_count - 1) / 2;
  447. // NOTE: When all blocks are done, rx_poll() still returns SDIO_BUSY once.
  448. // This provides a chance to start the SCSI transfer before the last checksums
  449. // are computed. Any checksum failures can be indicated in SCSI status after
  450. // the data transfer has finished.
  451. }
  452. if (bytes_complete)
  453. {
  454. *bytes_complete = g_sdio.blocks_done * SDIO_BLOCK_SIZE;
  455. }
  456. if (g_sdio.transfer_state == SDIO_IDLE)
  457. {
  458. // Verify all remaining checksums.
  459. sdio_verify_rx_checksums(g_sdio.total_blocks);
  460. if (g_sdio.checksum_errors == 0)
  461. return SDIO_OK;
  462. else
  463. return SDIO_ERR_DATA_CRC;
  464. }
  465. else if ((uint32_t)(millis() - g_sdio.transfer_start_time) > 1000)
  466. {
  467. dbgmsg("rp2040_sdio_rx_poll() timeout, "
  468. "PIO PC: ", (int)pio_sm_get_pc(SDIO_PIO, SDIO_DATA_SM) - (int)g_sdio.pio_data_rx_offset,
  469. " RXF: ", (int)pio_sm_get_rx_fifo_level(SDIO_PIO, SDIO_DATA_SM),
  470. " TXF: ", (int)pio_sm_get_tx_fifo_level(SDIO_PIO, SDIO_DATA_SM),
  471. " DMA CNT: ", dma_hw->ch[SDIO_DMA_CH].al2_transfer_count);
  472. rp2040_sdio_stop();
  473. return SDIO_ERR_DATA_TIMEOUT;
  474. }
  475. return SDIO_BUSY;
  476. }
  477. /*******************************************************
  478. * Data transmission to SD card
  479. *******************************************************/
  480. static void sdio_start_next_block_tx()
  481. {
  482. // Initialize PIO
  483. pio_sm_init(SDIO_PIO, SDIO_DATA_SM, g_sdio.pio_data_tx_offset, &g_sdio.pio_cfg_data_tx);
  484. // Configure DMA to send the data block payload (512 bytes)
  485. dma_channel_config dmacfg = dma_channel_get_default_config(SDIO_DMA_CH);
  486. channel_config_set_transfer_data_size(&dmacfg, DMA_SIZE_32);
  487. channel_config_set_read_increment(&dmacfg, true);
  488. channel_config_set_write_increment(&dmacfg, false);
  489. channel_config_set_dreq(&dmacfg, pio_get_dreq(SDIO_PIO, SDIO_DATA_SM, true));
  490. channel_config_set_bswap(&dmacfg, true);
  491. channel_config_set_chain_to(&dmacfg, SDIO_DMA_CHB);
  492. dma_channel_configure(SDIO_DMA_CH, &dmacfg,
  493. &SDIO_PIO->txf[SDIO_DATA_SM], g_sdio.data_buf + g_sdio.blocks_done * SDIO_WORDS_PER_BLOCK,
  494. SDIO_WORDS_PER_BLOCK, false);
  495. // Prepare second DMA channel to send the CRC and block end marker
  496. uint64_t crc = g_sdio.next_wr_block_checksum;
  497. g_sdio.end_token_buf[0] = (uint32_t)(crc >> 32);
  498. g_sdio.end_token_buf[1] = (uint32_t)(crc >> 0);
  499. g_sdio.end_token_buf[2] = 0xFFFFFFFF;
  500. channel_config_set_bswap(&dmacfg, false);
  501. dma_channel_configure(SDIO_DMA_CHB, &dmacfg,
  502. &SDIO_PIO->txf[SDIO_DATA_SM], g_sdio.end_token_buf, 3, false);
  503. // Enable IRQ to trigger when block is done
  504. dma_hw->ints1 = 1 << SDIO_DMA_CHB;
  505. dma_set_irq1_channel_mask_enabled(1 << SDIO_DMA_CHB, 1);
  506. // Initialize register X with nibble count and register Y with response bit count
  507. pio_sm_put(SDIO_PIO, SDIO_DATA_SM, 1048);
  508. pio_sm_exec(SDIO_PIO, SDIO_DATA_SM, pio_encode_out(pio_x, 32));
  509. pio_sm_put(SDIO_PIO, SDIO_DATA_SM, 31);
  510. pio_sm_exec(SDIO_PIO, SDIO_DATA_SM, pio_encode_out(pio_y, 32));
  511. // Initialize pins to output and high
  512. pio_sm_exec(SDIO_PIO, SDIO_DATA_SM, pio_encode_set(pio_pins, 15));
  513. pio_sm_exec(SDIO_PIO, SDIO_DATA_SM, pio_encode_set(pio_pindirs, 15));
  514. // Write start token and start the DMA transfer.
  515. pio_sm_put(SDIO_PIO, SDIO_DATA_SM, 0xFFFFFFF0);
  516. dma_channel_start(SDIO_DMA_CH);
  517. // Start state machine
  518. pio_sm_set_enabled(SDIO_PIO, SDIO_DATA_SM, true);
  519. }
  520. static void sdio_compute_next_tx_checksum()
  521. {
  522. assert (g_sdio.blocks_done < g_sdio.total_blocks && g_sdio.blocks_checksumed < g_sdio.total_blocks);
  523. int blockidx = g_sdio.blocks_checksumed++;
  524. g_sdio.next_wr_block_checksum = sdio_crc16_4bit_checksum(g_sdio.data_buf + blockidx * SDIO_WORDS_PER_BLOCK,
  525. SDIO_WORDS_PER_BLOCK);
  526. }
  527. // Start transferring data from memory to SD card
  528. sdio_status_t rp2040_sdio_tx_start(const uint8_t *buffer, uint32_t num_blocks)
  529. {
  530. // Buffer must be aligned
  531. assert(((uint32_t)buffer & 3) == 0 && num_blocks <= SDIO_MAX_BLOCKS);
  532. g_sdio.transfer_state = SDIO_TX;
  533. g_sdio.transfer_start_time = millis();
  534. g_sdio.data_buf = (uint32_t*)buffer;
  535. g_sdio.blocks_done = 0;
  536. g_sdio.total_blocks = num_blocks;
  537. g_sdio.blocks_checksumed = 0;
  538. g_sdio.checksum_errors = 0;
  539. // Compute first block checksum
  540. sdio_compute_next_tx_checksum();
  541. // Start first DMA transfer and PIO
  542. sdio_start_next_block_tx();
  543. if (g_sdio.blocks_checksumed < g_sdio.total_blocks)
  544. {
  545. // Precompute second block checksum
  546. sdio_compute_next_tx_checksum();
  547. }
  548. return SDIO_OK;
  549. }
  550. sdio_status_t check_sdio_write_response(uint32_t card_response)
  551. {
  552. // Shift card response until top bit is 0 (the start bit)
  553. // The format of response is poorly documented in SDIO spec but refer to e.g.
  554. // http://my-cool-projects.blogspot.com/2013/02/the-mysterious-sd-card-crc-status.html
  555. uint32_t resp = card_response;
  556. if (!(~resp & 0xFFFF0000)) resp <<= 16;
  557. if (!(~resp & 0xFF000000)) resp <<= 8;
  558. if (!(~resp & 0xF0000000)) resp <<= 4;
  559. if (!(~resp & 0xC0000000)) resp <<= 2;
  560. if (!(~resp & 0x80000000)) resp <<= 1;
  561. uint32_t wr_status = (resp >> 28) & 7;
  562. if (wr_status == 2)
  563. {
  564. return SDIO_OK;
  565. }
  566. else if (wr_status == 5)
  567. {
  568. logmsg("SDIO card reports write CRC error, status ", card_response);
  569. return SDIO_ERR_WRITE_CRC;
  570. }
  571. else if (wr_status == 6)
  572. {
  573. logmsg("SDIO card reports write failure, status ", card_response);
  574. return SDIO_ERR_WRITE_FAIL;
  575. }
  576. else
  577. {
  578. logmsg("SDIO card reports unknown write status ", card_response);
  579. return SDIO_ERR_WRITE_FAIL;
  580. }
  581. }
  582. // When a block finishes, this IRQ handler starts the next one
  583. static void rp2040_sdio_tx_irq()
  584. {
  585. dma_hw->ints1 = 1 << SDIO_DMA_CHB;
  586. if (g_sdio.transfer_state == SDIO_TX)
  587. {
  588. if (!dma_channel_is_busy(SDIO_DMA_CH) && !dma_channel_is_busy(SDIO_DMA_CHB))
  589. {
  590. // Main data transfer is finished now.
  591. // When card is ready, PIO will put card response on RX fifo
  592. g_sdio.transfer_state = SDIO_TX_WAIT_IDLE;
  593. if (!pio_sm_is_rx_fifo_empty(SDIO_PIO, SDIO_DATA_SM))
  594. {
  595. // Card is already idle
  596. g_sdio.card_response = pio_sm_get(SDIO_PIO, SDIO_DATA_SM);
  597. }
  598. else
  599. {
  600. // Use DMA to wait for the response
  601. dma_channel_config dmacfg = dma_channel_get_default_config(SDIO_DMA_CHB);
  602. channel_config_set_transfer_data_size(&dmacfg, DMA_SIZE_32);
  603. channel_config_set_read_increment(&dmacfg, false);
  604. channel_config_set_write_increment(&dmacfg, false);
  605. channel_config_set_dreq(&dmacfg, pio_get_dreq(SDIO_PIO, SDIO_DATA_SM, false));
  606. dma_channel_configure(SDIO_DMA_CHB, &dmacfg,
  607. &g_sdio.card_response, &SDIO_PIO->rxf[SDIO_DATA_SM], 1, true);
  608. }
  609. }
  610. }
  611. if (g_sdio.transfer_state == SDIO_TX_WAIT_IDLE)
  612. {
  613. if (!dma_channel_is_busy(SDIO_DMA_CHB))
  614. {
  615. g_sdio.wr_status = check_sdio_write_response(g_sdio.card_response);
  616. if (g_sdio.wr_status != SDIO_OK)
  617. {
  618. rp2040_sdio_stop();
  619. return;
  620. }
  621. g_sdio.blocks_done++;
  622. if (g_sdio.blocks_done < g_sdio.total_blocks)
  623. {
  624. sdio_start_next_block_tx();
  625. g_sdio.transfer_state = SDIO_TX;
  626. if (g_sdio.blocks_checksumed < g_sdio.total_blocks)
  627. {
  628. // Precompute the CRC for next block so that it is ready when
  629. // we want to send it.
  630. sdio_compute_next_tx_checksum();
  631. }
  632. }
  633. else
  634. {
  635. rp2040_sdio_stop();
  636. }
  637. }
  638. }
  639. }
  640. // Check if transmission is complete
  641. sdio_status_t rp2040_sdio_tx_poll(uint32_t *bytes_complete)
  642. {
  643. // if (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk)
  644. // #define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */
  645. if (scb_hw->icsr & (0x1FFUL))
  646. {
  647. // Verify that IRQ handler gets called even if we are in hardfault handler
  648. rp2040_sdio_tx_irq();
  649. }
  650. if (bytes_complete)
  651. {
  652. *bytes_complete = g_sdio.blocks_done * SDIO_BLOCK_SIZE;
  653. }
  654. if (g_sdio.transfer_state == SDIO_IDLE)
  655. {
  656. rp2040_sdio_stop();
  657. return g_sdio.wr_status;
  658. }
  659. else if ((uint32_t)(millis() - g_sdio.transfer_start_time) > 1000)
  660. {
  661. dbgmsg("rp2040_sdio_tx_poll() timeout, "
  662. "PIO PC: ", (int)pio_sm_get_pc(SDIO_PIO, SDIO_DATA_SM) - (int)g_sdio.pio_data_tx_offset,
  663. " RXF: ", (int)pio_sm_get_rx_fifo_level(SDIO_PIO, SDIO_DATA_SM),
  664. " TXF: ", (int)pio_sm_get_tx_fifo_level(SDIO_PIO, SDIO_DATA_SM),
  665. " DMA CNT: ", dma_hw->ch[SDIO_DMA_CH].al2_transfer_count);
  666. rp2040_sdio_stop();
  667. return SDIO_ERR_DATA_TIMEOUT;
  668. }
  669. return SDIO_BUSY;
  670. }
  671. // Force everything to idle state
  672. sdio_status_t rp2040_sdio_stop()
  673. {
  674. dma_channel_abort(SDIO_DMA_CH);
  675. dma_channel_abort(SDIO_DMA_CHB);
  676. dma_set_irq1_channel_mask_enabled(1 << SDIO_DMA_CHB, 0);
  677. pio_sm_set_enabled(SDIO_PIO, SDIO_DATA_SM, false);
  678. pio_sm_set_consecutive_pindirs(SDIO_PIO, SDIO_DATA_SM, SDIO_D0, 4, false);
  679. g_sdio.transfer_state = SDIO_IDLE;
  680. return SDIO_OK;
  681. }
  682. void rp2040_sdio_init(int clock_divider)
  683. {
  684. // Mark resources as being in use, unless it has been done already.
  685. static bool resources_claimed = false;
  686. if (!resources_claimed)
  687. {
  688. pio_sm_claim(SDIO_PIO, SDIO_CMD_SM);
  689. pio_sm_claim(SDIO_PIO, SDIO_DATA_SM);
  690. dma_channel_claim(SDIO_DMA_CH);
  691. dma_channel_claim(SDIO_DMA_CHB);
  692. resources_claimed = true;
  693. }
  694. memset(&g_sdio, 0, sizeof(g_sdio));
  695. dma_channel_abort(SDIO_DMA_CH);
  696. dma_channel_abort(SDIO_DMA_CHB);
  697. pio_sm_set_enabled(SDIO_PIO, SDIO_CMD_SM, false);
  698. pio_sm_set_enabled(SDIO_PIO, SDIO_DATA_SM, false);
  699. // Load PIO programs
  700. pio_clear_instruction_memory(SDIO_PIO);
  701. // Command & clock state machine
  702. g_sdio.pio_cmd_clk_offset = pio_add_program(SDIO_PIO, &sdio_cmd_clk_program);
  703. pio_sm_config cfg = sdio_cmd_clk_program_get_default_config(g_sdio.pio_cmd_clk_offset);
  704. sm_config_set_out_pins(&cfg, SDIO_CMD, 1);
  705. sm_config_set_in_pins(&cfg, SDIO_CMD);
  706. sm_config_set_set_pins(&cfg, SDIO_CMD, 1);
  707. sm_config_set_jmp_pin(&cfg, SDIO_CMD);
  708. sm_config_set_sideset_pins(&cfg, SDIO_CLK);
  709. sm_config_set_out_shift(&cfg, false, true, 32);
  710. sm_config_set_in_shift(&cfg, false, true, 32);
  711. sm_config_set_clkdiv_int_frac(&cfg, clock_divider, 0);
  712. sm_config_set_mov_status(&cfg, STATUS_TX_LESSTHAN, 2);
  713. pio_sm_init(SDIO_PIO, SDIO_CMD_SM, g_sdio.pio_cmd_clk_offset, &cfg);
  714. pio_sm_set_consecutive_pindirs(SDIO_PIO, SDIO_CMD_SM, SDIO_CLK, 1, true);
  715. pio_sm_set_enabled(SDIO_PIO, SDIO_CMD_SM, true);
  716. // Data reception program
  717. g_sdio.pio_data_rx_offset = pio_add_program(SDIO_PIO, &sdio_data_rx_program);
  718. g_sdio.pio_cfg_data_rx = sdio_data_rx_program_get_default_config(g_sdio.pio_data_rx_offset);
  719. sm_config_set_in_pins(&g_sdio.pio_cfg_data_rx, SDIO_D0);
  720. sm_config_set_in_shift(&g_sdio.pio_cfg_data_rx, false, true, 32);
  721. sm_config_set_out_shift(&g_sdio.pio_cfg_data_rx, false, true, 32);
  722. sm_config_set_clkdiv_int_frac(&g_sdio.pio_cfg_data_rx, clock_divider, 0);
  723. // Data transmission program
  724. g_sdio.pio_data_tx_offset = pio_add_program(SDIO_PIO, &sdio_data_tx_program);
  725. g_sdio.pio_cfg_data_tx = sdio_data_tx_program_get_default_config(g_sdio.pio_data_tx_offset);
  726. sm_config_set_in_pins(&g_sdio.pio_cfg_data_tx, SDIO_D0);
  727. sm_config_set_set_pins(&g_sdio.pio_cfg_data_tx, SDIO_D0, 4);
  728. sm_config_set_out_pins(&g_sdio.pio_cfg_data_tx, SDIO_D0, 4);
  729. sm_config_set_in_shift(&g_sdio.pio_cfg_data_tx, false, false, 32);
  730. sm_config_set_out_shift(&g_sdio.pio_cfg_data_tx, false, true, 32);
  731. sm_config_set_clkdiv_int_frac(&g_sdio.pio_cfg_data_tx, clock_divider, 0);
  732. // Disable SDIO pins input synchronizer.
  733. // This reduces input delay.
  734. // Because the CLK is driven synchronously to CPU clock,
  735. // there should be no metastability problems.
  736. SDIO_PIO->input_sync_bypass |= (1 << SDIO_CLK) | (1 << SDIO_CMD)
  737. | (1 << SDIO_D0) | (1 << SDIO_D1) | (1 << SDIO_D2) | (1 << SDIO_D3);
  738. // Redirect GPIOs to PIO
  739. gpio_set_function(SDIO_CMD, GPIO_FUNC_PIO1);
  740. gpio_set_function(SDIO_CLK, GPIO_FUNC_PIO1);
  741. gpio_set_function(SDIO_D0, GPIO_FUNC_PIO1);
  742. gpio_set_function(SDIO_D1, GPIO_FUNC_PIO1);
  743. gpio_set_function(SDIO_D2, GPIO_FUNC_PIO1);
  744. gpio_set_function(SDIO_D3, GPIO_FUNC_PIO1);
  745. // Set up IRQ handler when DMA completes.
  746. irq_set_exclusive_handler(DMA_IRQ_1, rp2040_sdio_tx_irq);
  747. irq_set_enabled(DMA_IRQ_1, true);
  748. #if 0
  749. #ifndef ENABLE_AUDIO_OUTPUT
  750. irq_set_exclusive_handler(DMA_IRQ_1, rp2040_sdio_tx_irq);
  751. #else
  752. // seem to hit assertion in _exclusive_handler call due to DMA_IRQ_0 being shared?
  753. // slightly less efficient to do it this way, so investigate further at some point
  754. irq_add_shared_handler(DMA_IRQ_1, rp2040_sdio_tx_irq, 0xFF);
  755. #endif
  756. irq_set_enabled(DMA_IRQ_1, true);
  757. #endif
  758. }