rp2040_sdio.cpp 32 KB

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