sdspi_host.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  1. // Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <stdbool.h>
  18. #include <stddef.h>
  19. #include <sys/param.h>
  20. #include "esp_log.h"
  21. #include "esp_heap_caps.h"
  22. #include "driver/gpio.h"
  23. #include "driver/sdmmc_defs.h"
  24. #include "driver/sdspi_host.h"
  25. #include "sdspi_private.h"
  26. #include "sdspi_crc.h"
  27. #include "esp_timer.h"
  28. /// Max number of transactions in flight (used in start_command_write_blocks)
  29. #define SDSPI_TRANSACTION_COUNT 4
  30. #define SDSPI_MOSI_IDLE_VAL 0xff //!< Data value which causes MOSI to stay high
  31. #define GPIO_UNUSED 0xff //!< Flag indicating that CD/WP is unused
  32. /// Size of the buffer returned by get_block_buf
  33. #define SDSPI_BLOCK_BUF_SIZE (SDSPI_MAX_DATA_LEN + 4)
  34. /// Maximum number of dummy bytes between the request and response (minimum is 1)
  35. #define SDSPI_RESPONSE_MAX_DELAY 8
  36. /// Structure containing run time configuration for a single SD slot
  37. typedef struct {
  38. spi_device_handle_t handle; //!< SPI device handle, used for transactions
  39. uint8_t gpio_cs; //!< CS GPIO
  40. uint8_t gpio_cd; //!< Card detect GPIO, or GPIO_UNUSED
  41. uint8_t gpio_wp; //!< Write protect GPIO, or GPIO_UNUSED
  42. /// Set to 1 if the higher layer has asked the card to enable CRC checks
  43. uint8_t data_crc_enabled : 1;
  44. /// Number of transactions in 'transactions' array which are in use
  45. uint8_t used_transaction_count: 3;
  46. /// Intermediate buffer used when application buffer is not in DMA memory;
  47. /// allocated on demand, SDSPI_BLOCK_BUF_SIZE bytes long. May be zero.
  48. uint8_t* block_buf;
  49. /// array with SDSPI_TRANSACTION_COUNT transaction structures
  50. spi_transaction_t* transactions;
  51. } slot_info_t;
  52. static slot_info_t s_slots[3];
  53. static const char *TAG = "sdspi_host";
  54. /// Functions to send out different kinds of commands
  55. static esp_err_t start_command_read_blocks(int slot, sdspi_hw_cmd_t *cmd,
  56. uint8_t *data, uint32_t rx_length);
  57. static esp_err_t start_command_write_blocks(int slot, sdspi_hw_cmd_t *cmd,
  58. const uint8_t *data, uint32_t tx_length);
  59. static esp_err_t start_command_default(int slot, int flags, sdspi_hw_cmd_t *cmd);
  60. /// A few helper functions
  61. /// Set CS high for given slot
  62. static void cs_high(int slot)
  63. {
  64. gpio_set_level(s_slots[slot].gpio_cs, 1);
  65. }
  66. /// Set CS low for given slot
  67. static void cs_low(int slot)
  68. {
  69. gpio_set_level(s_slots[slot].gpio_cs, 0);
  70. }
  71. /// Return true if WP pin is configured and is low
  72. static bool card_write_protected(int slot)
  73. {
  74. if (s_slots[slot].gpio_wp == GPIO_UNUSED) {
  75. return false;
  76. }
  77. return gpio_get_level(s_slots[slot].gpio_wp) == 0;
  78. }
  79. /// Return true if CD pin is configured and is high
  80. static bool card_missing(int slot)
  81. {
  82. if (s_slots[slot].gpio_cd == GPIO_UNUSED) {
  83. return false;
  84. }
  85. return gpio_get_level(s_slots[slot].gpio_cd) == 1;
  86. }
  87. /// Check if slot number is within bounds
  88. static bool is_valid_slot(int slot)
  89. {
  90. return slot == VSPI_HOST || slot == HSPI_HOST;
  91. }
  92. static spi_device_handle_t spi_handle(int slot)
  93. {
  94. return s_slots[slot].handle;
  95. }
  96. static bool is_slot_initialized(int slot)
  97. {
  98. return spi_handle(slot) != NULL;
  99. }
  100. static bool data_crc_enabled(int slot)
  101. {
  102. return s_slots[slot].data_crc_enabled;
  103. }
  104. /// Get pointer to a block of DMA memory, allocate if necessary.
  105. /// This is used if the application provided buffer is not in DMA capable memory.
  106. static esp_err_t get_block_buf(int slot, uint8_t** out_buf)
  107. {
  108. if (s_slots[slot].block_buf == NULL) {
  109. s_slots[slot].block_buf = heap_caps_malloc(SDSPI_BLOCK_BUF_SIZE, MALLOC_CAP_DMA);
  110. if (s_slots[slot].block_buf == NULL) {
  111. return ESP_ERR_NO_MEM;
  112. }
  113. }
  114. *out_buf = s_slots[slot].block_buf;
  115. return ESP_OK;
  116. }
  117. static spi_transaction_t* get_transaction(int slot)
  118. {
  119. size_t used_transaction_count = s_slots[slot].used_transaction_count;
  120. assert(used_transaction_count < SDSPI_TRANSACTION_COUNT);
  121. spi_transaction_t* ret = &s_slots[slot].transactions[used_transaction_count];
  122. ++s_slots[slot].used_transaction_count;
  123. return ret;
  124. }
  125. static void release_transaction(int slot)
  126. {
  127. --s_slots[slot].used_transaction_count;
  128. }
  129. static void wait_for_transactions(int slot)
  130. {
  131. size_t used_transaction_count = s_slots[slot].used_transaction_count;
  132. for (size_t i = 0; i < used_transaction_count; ++i) {
  133. spi_transaction_t* t_out;
  134. spi_device_get_trans_result(spi_handle(slot), &t_out, portMAX_DELAY);
  135. release_transaction(slot);
  136. }
  137. }
  138. /// Clock out one byte (CS has to be high) to make the card release MISO
  139. /// (clocking one bit would work as well, but that triggers a bug in SPI DMA)
  140. static void release_bus(int slot)
  141. {
  142. spi_transaction_t t = {
  143. .flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA,
  144. .length = 8,
  145. .tx_data = {0xff}
  146. };
  147. spi_device_transmit(spi_handle(slot), &t);
  148. // don't care if this failed
  149. }
  150. /// Clock out 80 cycles (10 bytes) before GO_IDLE command
  151. static void go_idle_clockout(int slot)
  152. {
  153. //actually we need 10, declare 12 to meet requirement of RXDMA
  154. uint8_t data[12];
  155. memset(data, 0xff, sizeof(data));
  156. spi_transaction_t t = {
  157. .length = 10*8,
  158. .tx_buffer = data,
  159. .rx_buffer = data,
  160. };
  161. spi_device_transmit(spi_handle(slot), &t);
  162. // don't care if this failed
  163. }
  164. /// Return true if the pointer can be used for DMA
  165. static bool ptr_dma_compatible(const void* ptr)
  166. {
  167. return (uintptr_t) ptr >= 0x3FFAE000 &&
  168. (uintptr_t) ptr < 0x40000000;
  169. }
  170. /**
  171. * Initialize SPI device. Used to change clock speed.
  172. * @param slot SPI host number
  173. * @param clock_speed_hz clock speed, Hz
  174. * @return ESP_OK on success
  175. */
  176. static esp_err_t init_spi_dev(int slot, int clock_speed_hz)
  177. {
  178. if (spi_handle(slot)) {
  179. // Reinitializing
  180. spi_bus_remove_device(spi_handle(slot));
  181. s_slots[slot].handle = NULL;
  182. }
  183. spi_device_interface_config_t devcfg = {
  184. .clock_speed_hz = clock_speed_hz,
  185. .mode = 0,
  186. // For SD cards, CS must stay low during the whole read/write operation,
  187. // rather than a single SPI transaction.
  188. .spics_io_num = -1,
  189. .queue_size = SDSPI_TRANSACTION_COUNT,
  190. };
  191. return spi_bus_add_device((spi_host_device_t) slot, &devcfg, &s_slots[slot].handle);
  192. }
  193. esp_err_t sdspi_host_init()
  194. {
  195. return ESP_OK;
  196. }
  197. esp_err_t sdspi_host_deinit()
  198. {
  199. for (size_t i = 0; i < sizeof(s_slots)/sizeof(s_slots[0]); ++i) {
  200. if (s_slots[i].handle) {
  201. spi_bus_remove_device(s_slots[i].handle);
  202. free(s_slots[i].block_buf);
  203. s_slots[i].block_buf = NULL;
  204. free(s_slots[i].transactions);
  205. s_slots[i].transactions = NULL;
  206. spi_bus_free((spi_host_device_t) i);
  207. s_slots[i].handle = NULL;
  208. }
  209. }
  210. return ESP_OK;
  211. }
  212. esp_err_t sdspi_host_set_card_clk(int slot, uint32_t freq_khz)
  213. {
  214. if (!is_valid_slot(slot)) {
  215. return ESP_ERR_INVALID_ARG;
  216. }
  217. if (!is_slot_initialized(slot)) {
  218. return ESP_ERR_INVALID_STATE;
  219. }
  220. ESP_LOGD(TAG, "Setting card clock to %d kHz", freq_khz);
  221. return init_spi_dev(slot, freq_khz * 1000);
  222. }
  223. esp_err_t sdspi_host_init_slot(int slot, const sdspi_slot_config_t* slot_config)
  224. {
  225. ESP_LOGD(TAG, "%s: SPI%d miso=%d mosi=%d sck=%d cs=%d cd=%d wp=%d, dma_ch=%d",
  226. __func__, slot + 1,
  227. slot_config->gpio_miso, slot_config->gpio_mosi,
  228. slot_config->gpio_sck, slot_config->gpio_cs,
  229. slot_config->gpio_cd, slot_config->gpio_wp,
  230. slot_config->dma_channel);
  231. spi_host_device_t host = (spi_host_device_t) slot;
  232. if (!is_valid_slot(slot)) {
  233. return ESP_ERR_INVALID_ARG;
  234. }
  235. spi_bus_config_t buscfg = {
  236. .miso_io_num = slot_config->gpio_miso,
  237. .mosi_io_num = slot_config->gpio_mosi,
  238. .sclk_io_num = slot_config->gpio_sck,
  239. .quadwp_io_num = -1,
  240. .quadhd_io_num = -1
  241. };
  242. // Initialize SPI bus
  243. esp_err_t ret = spi_bus_initialize((spi_host_device_t)slot, &buscfg,
  244. slot_config->dma_channel);
  245. if (ret != ESP_OK) {
  246. ESP_LOGD(TAG, "spi_bus_initialize failed with rc=0x%x", ret);
  247. return ret;
  248. }
  249. // Attach the SD card to the SPI bus
  250. ret = init_spi_dev(slot, SDMMC_FREQ_PROBING * 1000);
  251. if (ret != ESP_OK) {
  252. ESP_LOGD(TAG, "spi_bus_add_device failed with rc=0x%x", ret);
  253. spi_bus_free(host);
  254. return ret;
  255. }
  256. // Configure CS pin
  257. s_slots[slot].gpio_cs = (uint8_t) slot_config->gpio_cs;
  258. gpio_config_t io_conf = {
  259. .intr_type = GPIO_PIN_INTR_DISABLE,
  260. .mode = GPIO_MODE_OUTPUT,
  261. .pin_bit_mask = 1LL << slot_config->gpio_cs,
  262. };
  263. ret = gpio_config(&io_conf);
  264. if (ret != ESP_OK) {
  265. ESP_LOGD(TAG, "gpio_config (CS) failed with rc=0x%x", ret);
  266. spi_bus_remove_device(spi_handle(slot));
  267. s_slots[slot].handle = NULL;
  268. spi_bus_free(host);
  269. return ret;
  270. }
  271. cs_high(slot);
  272. // Configure CD and WP pins
  273. io_conf = (gpio_config_t) {
  274. .intr_type = GPIO_PIN_INTR_DISABLE,
  275. .mode = GPIO_MODE_OUTPUT,
  276. .pin_bit_mask = 0,
  277. .pull_up_en = true
  278. };
  279. if (slot_config->gpio_cd != SDSPI_SLOT_NO_CD) {
  280. io_conf.pin_bit_mask |= (1 << slot_config->gpio_cd);
  281. s_slots[slot].gpio_wp = slot_config->gpio_wp;
  282. } else {
  283. s_slots[slot].gpio_wp = GPIO_UNUSED;
  284. }
  285. if (slot_config->gpio_wp != SDSPI_SLOT_NO_WP) {
  286. io_conf.pin_bit_mask |= (1 << slot_config->gpio_wp);
  287. s_slots[slot].gpio_cd = slot_config->gpio_cd;
  288. } else {
  289. s_slots[slot].gpio_cd = GPIO_UNUSED;
  290. }
  291. if (io_conf.pin_bit_mask != 0) {
  292. ret = gpio_config(&io_conf);
  293. if (ret != ESP_OK) {
  294. ESP_LOGD(TAG, "gpio_config (CD/WP) failed with rc=0x%x", ret);
  295. spi_bus_remove_device(spi_handle(slot));
  296. s_slots[slot].handle = NULL;
  297. spi_bus_free(host);
  298. return ret;
  299. }
  300. }
  301. s_slots[slot].transactions = calloc(SDSPI_TRANSACTION_COUNT, sizeof(spi_transaction_t));
  302. if (s_slots[slot].transactions == NULL) {
  303. spi_bus_remove_device(spi_handle(slot));
  304. s_slots[slot].handle = NULL;
  305. spi_bus_free(host);
  306. return ESP_ERR_NO_MEM;
  307. }
  308. return ESP_OK;
  309. }
  310. esp_err_t sdspi_host_start_command(int slot, sdspi_hw_cmd_t *cmd, void *data,
  311. uint32_t data_size, int flags)
  312. {
  313. if (!is_valid_slot(slot)) {
  314. return ESP_ERR_INVALID_ARG;
  315. }
  316. if (!is_slot_initialized(slot)) {
  317. return ESP_ERR_INVALID_STATE;
  318. }
  319. if (card_missing(slot)) {
  320. return ESP_ERR_NOT_FOUND;
  321. }
  322. // save some parts of cmd, as its contents will be overwritten
  323. int cmd_index = cmd->cmd_index;
  324. uint32_t cmd_arg;
  325. memcpy(&cmd_arg, cmd->arguments, sizeof(cmd_arg));
  326. cmd_arg = __builtin_bswap32(cmd_arg);
  327. ESP_LOGV(TAG, "%s: slot=%i, CMD%d, arg=0x%08x flags=0x%x, data=%p, data_size=%i crc=0x%02x",
  328. __func__, slot, cmd_index, cmd_arg, flags, data, data_size, cmd->crc7);
  329. // For CMD0, clock out 80 cycles to help the card enter idle state,
  330. // *before* CS is asserted.
  331. if (cmd_index == MMC_GO_IDLE_STATE) {
  332. go_idle_clockout(slot);
  333. }
  334. // actual transaction
  335. esp_err_t ret = ESP_OK;
  336. cs_low(slot);
  337. if (flags & SDSPI_CMD_FLAG_DATA) {
  338. if (flags & SDSPI_CMD_FLAG_WRITE) {
  339. ret = start_command_write_blocks(slot, cmd, data, data_size);
  340. } else {
  341. ret = start_command_read_blocks(slot, cmd, data, data_size);
  342. }
  343. } else {
  344. ret = start_command_default(slot, flags, cmd);
  345. }
  346. cs_high(slot);
  347. release_bus(slot);
  348. if (ret != ESP_OK) {
  349. ESP_LOGE(TAG, "%s: cmd=%d error=0x%x", __func__, cmd_index, ret);
  350. } else {
  351. // Update internal state when some commands are sent successfully
  352. if (cmd_index == SD_CRC_ON_OFF) {
  353. s_slots[slot].data_crc_enabled = (uint8_t) cmd_arg;
  354. ESP_LOGD(TAG, "data CRC set=%d", s_slots[slot].data_crc_enabled);
  355. }
  356. }
  357. return ret;
  358. }
  359. static esp_err_t start_command_default(int slot, int flags, sdspi_hw_cmd_t *cmd)
  360. {
  361. size_t cmd_size = SDSPI_CMD_R1_SIZE;
  362. if (flags & SDSPI_CMD_FLAG_RSP_R1) {
  363. cmd_size = SDSPI_CMD_R1_SIZE;
  364. } else if (flags & SDSPI_CMD_FLAG_RSP_R2) {
  365. cmd_size = SDSPI_CMD_R2_SIZE;
  366. } else if (flags & SDSPI_CMD_FLAG_RSP_R3) {
  367. cmd_size = SDSPI_CMD_R3_SIZE;
  368. } else if (flags & SDSPI_CMD_FLAG_RSP_R7) {
  369. cmd_size = SDSPI_CMD_R7_SIZE;
  370. }
  371. spi_transaction_t t = {
  372. .flags = 0,
  373. .length = cmd_size * 8,
  374. .tx_buffer = cmd,
  375. .rx_buffer = cmd
  376. };
  377. esp_err_t ret = spi_device_transmit(spi_handle(slot), &t);
  378. if (cmd->cmd_index == MMC_STOP_TRANSMISSION) {
  379. /* response is a stuff byte from previous transfer, ignore it */
  380. cmd->r1 = 0xff;
  381. }
  382. int response_delay_bytes = SDSPI_RESPONSE_MAX_DELAY;
  383. while ((cmd->r1 & SD_SPI_R1_NO_RESPONSE) != 0 && response_delay_bytes-- > 0) {
  384. spi_transaction_t* t = get_transaction(slot);
  385. *t = (spi_transaction_t) {
  386. .flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA,
  387. .length = 8,
  388. };
  389. t->tx_data[0] = 0xff;
  390. ret = spi_device_transmit(spi_handle(slot), t);
  391. uint8_t r1 = t->rx_data[0];
  392. release_transaction(slot);
  393. if (ret != ESP_OK) {
  394. return ret;
  395. }
  396. cmd->r1 = r1;
  397. }
  398. if (cmd->r1 & SD_SPI_R1_NO_RESPONSE) {
  399. ESP_LOGD(TAG, "%s: no response token found", __func__);
  400. return ESP_ERR_TIMEOUT;
  401. }
  402. return ret;
  403. }
  404. // Wait until MISO goes high
  405. static esp_err_t poll_busy(int slot, spi_transaction_t* t, int timeout_ms)
  406. {
  407. uint8_t t_rx;
  408. *t = (spi_transaction_t) {
  409. .tx_buffer = &t_rx,
  410. .flags = SPI_TRANS_USE_RXDATA, //data stored in rx_data
  411. .length = 8,
  412. };
  413. esp_err_t ret;
  414. uint64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  415. int nonzero_count = 0;
  416. do {
  417. t_rx = SDSPI_MOSI_IDLE_VAL;
  418. t->rx_data[0] = 0;
  419. ret = spi_device_transmit(spi_handle(slot), t);
  420. if (ret != ESP_OK) {
  421. return ret;
  422. }
  423. if (t->rx_data[0] != 0) {
  424. if (++nonzero_count == 2) {
  425. return ESP_OK;
  426. }
  427. }
  428. } while(esp_timer_get_time() < t_end);
  429. ESP_LOGD(TAG, "%s: timeout", __func__);
  430. return ESP_ERR_TIMEOUT;
  431. }
  432. // Wait for response token
  433. static esp_err_t poll_response_token(int slot, spi_transaction_t* t, int timeout_ms)
  434. {
  435. uint8_t t_rx;
  436. *t = (spi_transaction_t) {
  437. .tx_buffer = &t_rx,
  438. .flags = SPI_TRANS_USE_RXDATA,
  439. .length = 8,
  440. };
  441. esp_err_t ret;
  442. uint64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  443. do {
  444. t_rx = SDSPI_MOSI_IDLE_VAL;
  445. t->rx_data[0] = 0;
  446. ret = spi_device_transmit(spi_handle(slot), t);
  447. if (ret != ESP_OK) {
  448. return ret;
  449. }
  450. if ((t->rx_data[0] & TOKEN_RSP_MASK) == TOKEN_RSP_OK) {
  451. return ESP_OK;
  452. }
  453. if ((t->rx_data[0] & TOKEN_RSP_MASK) == TOKEN_RSP_CRC_ERR) {
  454. return ESP_ERR_INVALID_CRC;
  455. }
  456. if ((t->rx_data[0] & TOKEN_RSP_MASK) == TOKEN_RSP_WRITE_ERR) {
  457. return ESP_ERR_INVALID_RESPONSE;
  458. }
  459. } while (esp_timer_get_time() < t_end);
  460. ESP_LOGD(TAG, "%s: timeout", __func__);
  461. return ESP_ERR_TIMEOUT;
  462. }
  463. // Wait for data token, reading 8 bytes at a time.
  464. // If the token is found, write all subsequent bytes to extra_ptr,
  465. // and store the number of bytes written to extra_size.
  466. static esp_err_t poll_data_token(int slot, spi_transaction_t* t,
  467. uint8_t* extra_ptr, size_t* extra_size, int timeout_ms)
  468. {
  469. uint8_t t_rx[8];
  470. *t = (spi_transaction_t) {
  471. .tx_buffer = &t_rx,
  472. .rx_buffer = &t_rx,
  473. .length = sizeof(t_rx) * 8,
  474. };
  475. esp_err_t ret;
  476. uint64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  477. do {
  478. memset(t_rx, SDSPI_MOSI_IDLE_VAL, sizeof(t_rx));
  479. ret = spi_device_transmit(spi_handle(slot), t);
  480. if (ret != ESP_OK) {
  481. return ret;
  482. }
  483. bool found = false;
  484. for (int byte_idx = 0; byte_idx < sizeof(t_rx); byte_idx++) {
  485. uint8_t rd_data = t_rx[byte_idx];
  486. if (rd_data == TOKEN_BLOCK_START) {
  487. found = true;
  488. memcpy(extra_ptr, t_rx + byte_idx + 1, sizeof(t_rx) - byte_idx - 1);
  489. *extra_size = sizeof(t_rx) - byte_idx - 1;
  490. break;
  491. }
  492. if (rd_data != 0xff && rd_data != 0) {
  493. ESP_LOGD(TAG, "%s: received 0x%02x while waiting for data",
  494. __func__, rd_data);
  495. return ESP_ERR_INVALID_RESPONSE;
  496. }
  497. }
  498. if (found) {
  499. return ESP_OK;
  500. }
  501. } while (esp_timer_get_time() < t_end);
  502. ESP_LOGD(TAG, "%s: timeout", __func__);
  503. return ESP_ERR_TIMEOUT;
  504. }
  505. /**
  506. * Receiving one or more blocks of data happens as follows:
  507. * 1. send command + receive r1 response (SDSPI_CMD_R1_SIZE bytes total)
  508. * 2. keep receiving bytes until TOKEN_BLOCK_START is encountered (this may
  509. * take a while, depending on card's read speed)
  510. * 3. receive up to SDSPI_MAX_DATA_LEN = 512 bytes of actual data
  511. * 4. receive 2 bytes of CRC
  512. * 5. for multi block transfers, go to step 2
  513. *
  514. * These steps can be done separately, but that leads to a less than optimal
  515. * performance on large transfers because of delays between each step.
  516. * For example, if steps 3 and 4 are separate SPI transactions queued one after
  517. * another, there will be ~16 microseconds of dead time between end of step 3
  518. * and the beginning of step 4. A delay between two blocking SPI transactions
  519. * in step 2 is even higher (~60 microseconds).
  520. *
  521. * To improve read performance the following sequence is adopted:
  522. * 1. Do the first transfer: command + r1 response + 8 extra bytes.
  523. * Set pre_scan_data_ptr to point to the 8 extra bytes, and set
  524. * pre_scan_data_size to 8.
  525. * 2. Search pre_scan_data_size bytes for TOKEN_BLOCK_START.
  526. * If found, the rest of the bytes contain part of the actual data.
  527. * Store pointer to and size of that extra data as extra_data_{ptr,size}.
  528. * If not found, fall back to polling for TOKEN_BLOCK_START, 8 bytes at a
  529. * time (in poll_data_token function). Deal with extra data in the same way,
  530. * by setting extra_data_{ptr,size}.
  531. * 3. Receive the remaining 512 - extra_data_size bytes, plus 4 extra bytes
  532. * (i.e. 516 - extra_data_size). Of the 4 extra bytes, first two will capture
  533. * the CRC value, and the other two will capture 0xff 0xfe sequence
  534. * indicating the start of the next block. Actual scanning is done by
  535. * setting pre_scan_data_ptr to point to these last 2 bytes, and setting
  536. * pre_scan_data_size = 2, then going to step 2 to receive the next block.
  537. * When the final block is being received, the number of extra bytes is 2
  538. * (only for CRC), because we don't need to wait for start token of the
  539. * next block, and some cards are getting confused by these two extra bytes.
  540. *
  541. * With this approach the delay between blocks of a multi-block transfer is
  542. * ~95 microseconds, out of which 35 microseconds are spend doing the CRC check.
  543. * Further speedup is possible by pipelining transfers and CRC checks, at an
  544. * expense of one extra temporary buffer.
  545. */
  546. static esp_err_t start_command_read_blocks(int slot, sdspi_hw_cmd_t *cmd,
  547. uint8_t *data, uint32_t rx_length)
  548. {
  549. bool need_stop_command = rx_length > SDSPI_MAX_DATA_LEN;
  550. spi_transaction_t* t_command = get_transaction(slot);
  551. *t_command = (spi_transaction_t) {
  552. .length = (SDSPI_CMD_R1_SIZE + SDSPI_RESPONSE_MAX_DELAY) * 8,
  553. .tx_buffer = cmd,
  554. .rx_buffer = cmd,
  555. };
  556. esp_err_t ret = spi_device_transmit(spi_handle(slot), t_command);
  557. if (ret != ESP_OK) {
  558. return ret;
  559. }
  560. release_transaction(slot);
  561. uint8_t* cmd_u8 = (uint8_t*) cmd;
  562. size_t pre_scan_data_size = SDSPI_RESPONSE_MAX_DELAY;
  563. uint8_t* pre_scan_data_ptr = cmd_u8 + SDSPI_CMD_R1_SIZE;
  564. /* R1 response is delayed by 1-8 bytes from the request.
  565. * This loop searches for the response and writes it to cmd->r1.
  566. */
  567. while ((cmd->r1 & SD_SPI_R1_NO_RESPONSE) != 0 && pre_scan_data_size > 0) {
  568. cmd->r1 = *pre_scan_data_ptr;
  569. ++pre_scan_data_ptr;
  570. --pre_scan_data_size;
  571. }
  572. if (cmd->r1 & SD_SPI_R1_NO_RESPONSE) {
  573. ESP_LOGD(TAG, "no response token found");
  574. return ESP_ERR_TIMEOUT;
  575. }
  576. while (rx_length > 0) {
  577. size_t extra_data_size = 0;
  578. const uint8_t* extra_data_ptr = NULL;
  579. bool need_poll = true;
  580. for (int i = 0; i < pre_scan_data_size; ++i) {
  581. if (pre_scan_data_ptr[i] == TOKEN_BLOCK_START) {
  582. extra_data_size = pre_scan_data_size - i - 1;
  583. extra_data_ptr = pre_scan_data_ptr + i + 1;
  584. need_poll = false;
  585. break;
  586. }
  587. }
  588. if (need_poll) {
  589. // Wait for data to be ready
  590. spi_transaction_t* t_poll = get_transaction(slot);
  591. ret = poll_data_token(slot, t_poll, cmd_u8 + SDSPI_CMD_R1_SIZE, &extra_data_size, cmd->timeout_ms);
  592. release_transaction(slot);
  593. if (ret != ESP_OK) {
  594. return ret;
  595. }
  596. if (extra_data_size) {
  597. extra_data_ptr = cmd_u8 + SDSPI_CMD_R1_SIZE;
  598. }
  599. }
  600. // Arrange RX buffer
  601. size_t will_receive = MIN(rx_length, SDSPI_MAX_DATA_LEN) - extra_data_size;
  602. uint8_t* rx_data;
  603. ret = get_block_buf(slot, &rx_data);
  604. if (ret != ESP_OK) {
  605. return ret;
  606. }
  607. // receive actual data
  608. const size_t receive_extra_bytes = (rx_length > SDSPI_MAX_DATA_LEN) ? 4 : 2;
  609. memset(rx_data, 0xff, will_receive + receive_extra_bytes);
  610. spi_transaction_t* t_data = get_transaction(slot);
  611. *t_data = (spi_transaction_t) {
  612. .length = (will_receive + receive_extra_bytes) * 8,
  613. .rx_buffer = rx_data,
  614. .tx_buffer = rx_data
  615. };
  616. ret = spi_device_transmit(spi_handle(slot), t_data);
  617. if (ret != ESP_OK) {
  618. return ret;
  619. }
  620. release_transaction(slot);
  621. // CRC bytes need to be received even if CRC is not enabled
  622. uint16_t crc = UINT16_MAX;
  623. memcpy(&crc, rx_data + will_receive, sizeof(crc));
  624. // Bytes to scan for the start token
  625. pre_scan_data_size = receive_extra_bytes - sizeof(crc);
  626. pre_scan_data_ptr = rx_data + will_receive + sizeof(crc);
  627. // Copy data to the destination buffer
  628. memcpy(data + extra_data_size, rx_data, will_receive);
  629. if (extra_data_size) {
  630. memcpy(data, extra_data_ptr, extra_data_size);
  631. }
  632. // compute CRC of the received data
  633. uint16_t crc_of_data = 0;
  634. if (data_crc_enabled(slot)) {
  635. crc_of_data = sdspi_crc16(data, will_receive + extra_data_size);
  636. if (crc_of_data != crc) {
  637. ESP_LOGE(TAG, "data CRC failed, got=0x%04x expected=0x%04x", crc_of_data, crc);
  638. esp_log_buffer_hex(TAG, data, 16);
  639. return ESP_ERR_INVALID_CRC;
  640. }
  641. }
  642. data += will_receive + extra_data_size;
  643. rx_length -= will_receive + extra_data_size;
  644. extra_data_size = 0;
  645. extra_data_ptr = NULL;
  646. }
  647. if (need_stop_command) {
  648. // To end multi block transfer, send stop command and wait for the
  649. // card to process it
  650. sdspi_hw_cmd_t stop_cmd;
  651. make_hw_cmd(MMC_STOP_TRANSMISSION, 0, cmd->timeout_ms, &stop_cmd);
  652. ret = start_command_default(slot, SDSPI_CMD_FLAG_RSP_R1, &stop_cmd);
  653. if (ret != ESP_OK) {
  654. return ret;
  655. }
  656. if (stop_cmd.r1 != 0) {
  657. ESP_LOGD(TAG, "%s: STOP_TRANSMISSION response 0x%02x", __func__, stop_cmd.r1);
  658. }
  659. spi_transaction_t* t_poll = get_transaction(slot);
  660. ret = poll_busy(slot, t_poll, cmd->timeout_ms);
  661. release_transaction(slot);
  662. if (ret != ESP_OK) {
  663. return ret;
  664. }
  665. }
  666. return ESP_OK;
  667. }
  668. static esp_err_t start_command_write_blocks(int slot, sdspi_hw_cmd_t *cmd,
  669. const uint8_t *data, uint32_t tx_length)
  670. {
  671. if (card_write_protected(slot)) {
  672. ESP_LOGW(TAG, "%s: card write protected", __func__);
  673. return ESP_ERR_INVALID_STATE;
  674. }
  675. spi_transaction_t* t_command = get_transaction(slot);
  676. *t_command = (spi_transaction_t) {
  677. .length = SDSPI_CMD_R1_SIZE * 8,
  678. .tx_buffer = cmd,
  679. .rx_buffer = cmd,
  680. };
  681. esp_err_t ret = spi_device_queue_trans(spi_handle(slot), t_command, 0);
  682. if (ret != ESP_OK) {
  683. return ret;
  684. }
  685. uint8_t start_token = tx_length <= SDSPI_MAX_DATA_LEN ?
  686. TOKEN_BLOCK_START : TOKEN_BLOCK_START_WRITE_MULTI;
  687. wait_for_transactions(slot);
  688. while (tx_length > 0) {
  689. // Write block start token
  690. spi_transaction_t* t_start_token = get_transaction(slot);
  691. *t_start_token = (spi_transaction_t) {
  692. .length = sizeof(start_token) * 8,
  693. .tx_buffer = &start_token
  694. };
  695. esp_err_t ret = spi_device_queue_trans(spi_handle(slot), t_start_token, 0);
  696. if (ret != ESP_OK) {
  697. return ret;
  698. }
  699. // Prepare data to be sent
  700. size_t will_send = MIN(tx_length, SDSPI_MAX_DATA_LEN);
  701. const uint8_t* tx_data = data;
  702. if (!ptr_dma_compatible(tx_data)) {
  703. // If the pointer can't be used with DMA, copy data into a new buffer
  704. uint8_t* tmp;
  705. ret = get_block_buf(slot, &tmp);
  706. if (ret != ESP_OK) {
  707. return ret;
  708. }
  709. memcpy(tmp, tx_data, will_send);
  710. tx_data = tmp;
  711. }
  712. // Write data
  713. spi_transaction_t* t_data = get_transaction(slot);
  714. *t_data = (spi_transaction_t) {
  715. .length = will_send * 8,
  716. .tx_buffer = tx_data,
  717. };
  718. ret = spi_device_queue_trans(spi_handle(slot), t_data, 0);
  719. if (ret != ESP_OK) {
  720. return ret;
  721. }
  722. // Write CRC
  723. uint16_t crc = sdspi_crc16(data, will_send);
  724. spi_transaction_t* t_crc = get_transaction(slot);
  725. *t_crc = (spi_transaction_t) {
  726. .length = sizeof(crc) * 8,
  727. .tx_buffer = (uint8_t*) &crc,
  728. };
  729. ret = spi_device_queue_trans(spi_handle(slot), t_crc, 0);
  730. if (ret != ESP_OK) {
  731. return ret;
  732. }
  733. // Wait for data to be sent
  734. wait_for_transactions(slot);
  735. // Check if R1 response for the command was correct
  736. if (cmd->r1 != 0) {
  737. ESP_LOGD(TAG, "%s: invalid R1 response: 0x%02x", __func__, cmd->r1);
  738. return ESP_ERR_INVALID_RESPONSE;
  739. }
  740. // Poll for response
  741. spi_transaction_t* t_poll = get_transaction(slot);
  742. ret = poll_response_token(slot, t_poll, cmd->timeout_ms);
  743. release_transaction(slot);
  744. if (ret != ESP_OK) {
  745. return ret;
  746. }
  747. // Wait for the card to finish writing data
  748. t_poll = get_transaction(slot);
  749. ret = poll_busy(slot, t_poll, cmd->timeout_ms);
  750. release_transaction(slot);
  751. if (ret != ESP_OK) {
  752. return ret;
  753. }
  754. tx_length -= will_send;
  755. data += will_send;
  756. }
  757. if (start_token == TOKEN_BLOCK_START_WRITE_MULTI) {
  758. uint8_t stop_token[2] = {
  759. TOKEN_BLOCK_STOP_WRITE_MULTI,
  760. SDSPI_MOSI_IDLE_VAL
  761. };
  762. spi_transaction_t* t_stop_token = get_transaction(slot);
  763. *t_stop_token = (spi_transaction_t) {
  764. .length = sizeof(stop_token) * 8,
  765. .tx_buffer = &stop_token,
  766. };
  767. ret = spi_device_queue_trans(spi_handle(slot), t_stop_token, 0);
  768. if (ret != ESP_OK) {
  769. return ret;
  770. }
  771. wait_for_transactions(slot);
  772. spi_transaction_t* t_poll = get_transaction(slot);
  773. ret = poll_busy(slot, t_poll, cmd->timeout_ms);
  774. release_transaction(slot);
  775. if (ret != ESP_OK) {
  776. return ret;
  777. }
  778. }
  779. return ESP_OK;
  780. }