rp2040_sdio.cpp 31 KB

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