sdspi_host.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <string.h>
  9. #include <stdbool.h>
  10. #include <stddef.h>
  11. #include <sys/param.h>
  12. #include "esp_log.h"
  13. #include "esp_heap_caps.h"
  14. #include "driver/gpio.h"
  15. #include "driver/sdmmc_defs.h"
  16. #include "driver/sdspi_host.h"
  17. #include "sdspi_private.h"
  18. #include "sdspi_crc.h"
  19. #include "esp_timer.h"
  20. #include "freertos/FreeRTOS.h"
  21. #include "freertos/semphr.h"
  22. #include "soc/soc_memory_layout.h"
  23. /// Max number of transactions in flight (used in start_command_write_blocks)
  24. #define SDSPI_TRANSACTION_COUNT 4
  25. #define SDSPI_MOSI_IDLE_VAL 0xff //!< Data value which causes MOSI to stay high
  26. #define GPIO_UNUSED 0xff //!< Flag indicating that CD/WP is unused
  27. /// Size of the buffer returned by get_block_buf
  28. #define SDSPI_BLOCK_BUF_SIZE (SDSPI_MAX_DATA_LEN + 4)
  29. /// Maximum number of dummy bytes between the request and response (minimum is 1)
  30. #define SDSPI_RESPONSE_MAX_DELAY 8
  31. /**
  32. * @brief Structure containing run time configuration for a single SD slot
  33. *
  34. * The slot info is referenced to by an sdspi_dev_handle_t (alias int). The handle may be the raw
  35. * pointer to the slot info itself (force converted to, new API in IDFv4.2), or the index of the
  36. * s_slot array (deprecated API). Returning the raw pointer to the caller instead of storing it
  37. * locally can save some static memory.
  38. */
  39. typedef struct {
  40. spi_host_device_t host_id; //!< SPI host id.
  41. spi_device_handle_t spi_handle; //!< SPI device handle, used for transactions
  42. uint8_t gpio_cs; //!< CS GPIO, or GPIO_UNUSED
  43. uint8_t gpio_cd; //!< Card detect GPIO, or GPIO_UNUSED
  44. uint8_t gpio_wp; //!< Write protect GPIO, or GPIO_UNUSED
  45. uint8_t gpio_int; //!< Write protect GPIO, or GPIO_UNUSED
  46. /// Set to 1 if the higher layer has asked the card to enable CRC checks
  47. uint8_t data_crc_enabled : 1;
  48. /// Intermediate buffer used when application buffer is not in DMA memory;
  49. /// allocated on demand, SDSPI_BLOCK_BUF_SIZE bytes long. May be zero.
  50. uint8_t* block_buf;
  51. /// semaphore of gpio interrupt
  52. SemaphoreHandle_t semphr_int;
  53. } slot_info_t;
  54. // Reserved for old API to be back-compatible
  55. static slot_info_t *s_slots[SOC_SPI_PERIPH_NUM] = {};
  56. static const char *TAG = "sdspi_host";
  57. static const bool use_polling = true;
  58. static const bool no_use_polling = true;
  59. /// Functions to send out different kinds of commands
  60. static esp_err_t start_command_read_blocks(slot_info_t *slot, sdspi_hw_cmd_t *cmd,
  61. uint8_t *data, uint32_t rx_length, bool need_stop_command);
  62. static esp_err_t start_command_write_blocks(slot_info_t *slot, sdspi_hw_cmd_t *cmd,
  63. const uint8_t *data, uint32_t tx_length, bool multi_block, bool stop_trans);
  64. static esp_err_t start_command_default(slot_info_t *slot, int flags, sdspi_hw_cmd_t *cmd);
  65. static esp_err_t shift_cmd_response(sdspi_hw_cmd_t *cmd, int sent_bytes);
  66. static esp_err_t poll_busy(slot_info_t *slot, int timeout_ms, bool polling);
  67. /// A few helper functions
  68. /// Map handle to pointer of slot information
  69. static slot_info_t* get_slot_info(sdspi_dev_handle_t handle)
  70. {
  71. if ((uint32_t) handle < SOC_SPI_PERIPH_NUM) {
  72. return s_slots[handle];
  73. } else {
  74. return (slot_info_t *) handle;
  75. }
  76. }
  77. /// Store slot information (if possible) and return corresponding handle
  78. static sdspi_dev_handle_t store_slot_info(slot_info_t *slot)
  79. {
  80. /*
  81. * To be back-compatible, the first device of each bus will always be stored locally, and
  82. * referenced to by the handle `host_id`, otherwise the new API return the raw pointer to the
  83. * slot info as the handle, to save some static memory.
  84. */
  85. if (s_slots[slot->host_id] == NULL) {
  86. s_slots[slot->host_id] = slot;
  87. return slot->host_id;
  88. } else {
  89. return (sdspi_dev_handle_t)slot;
  90. }
  91. }
  92. /// Get the slot info for a specific handle, and remove the local reference (if exist).
  93. static slot_info_t* remove_slot_info(sdspi_dev_handle_t handle)
  94. {
  95. if ((uint32_t) handle < SOC_SPI_PERIPH_NUM) {
  96. slot_info_t* slot = s_slots[handle];
  97. s_slots[handle] = NULL;
  98. return slot;
  99. } else {
  100. return (slot_info_t *) handle;
  101. }
  102. }
  103. /// Set CS high for given slot
  104. static void cs_high(slot_info_t *slot)
  105. {
  106. if (slot->gpio_cs != GPIO_UNUSED) {
  107. gpio_set_level(slot->gpio_cs, 1);
  108. }
  109. }
  110. /// Set CS low for given slot
  111. static void cs_low(slot_info_t *slot)
  112. {
  113. if (slot->gpio_cs != GPIO_UNUSED) {
  114. gpio_set_level(slot->gpio_cs, 0);
  115. }
  116. }
  117. /// Return true if WP pin is configured and is low
  118. static bool card_write_protected(slot_info_t *slot)
  119. {
  120. if (slot->gpio_wp == GPIO_UNUSED) {
  121. return false;
  122. }
  123. return gpio_get_level(slot->gpio_wp) == 0;
  124. }
  125. /// Return true if CD pin is configured and is high
  126. static bool card_missing(slot_info_t *slot)
  127. {
  128. if (slot->gpio_cd == GPIO_UNUSED) {
  129. return false;
  130. }
  131. return gpio_get_level(slot->gpio_cd) == 1;
  132. }
  133. /// Get pointer to a block of DMA memory, allocate if necessary.
  134. /// This is used if the application provided buffer is not in DMA capable memory.
  135. static esp_err_t get_block_buf(slot_info_t *slot, uint8_t **out_buf)
  136. {
  137. if (slot->block_buf == NULL) {
  138. slot->block_buf = heap_caps_malloc(SDSPI_BLOCK_BUF_SIZE, MALLOC_CAP_DMA);
  139. if (slot->block_buf == NULL) {
  140. return ESP_ERR_NO_MEM;
  141. }
  142. }
  143. *out_buf = slot->block_buf;
  144. return ESP_OK;
  145. }
  146. /// Clock out one byte (CS has to be high) to make the card release MISO
  147. /// (clocking one bit would work as well, but that triggers a bug in SPI DMA)
  148. static void release_bus(slot_info_t *slot)
  149. {
  150. spi_transaction_t t = {
  151. .flags = SPI_TRANS_USE_RXDATA | SPI_TRANS_USE_TXDATA,
  152. .length = 8,
  153. .tx_data = {0xff}
  154. };
  155. spi_device_polling_transmit(slot->spi_handle, &t);
  156. // don't care if this failed
  157. }
  158. /// Clock out 80 cycles (10 bytes) before GO_IDLE command
  159. static void go_idle_clockout(slot_info_t *slot)
  160. {
  161. //actually we need 10, declare 12 to meet requirement of RXDMA
  162. uint8_t data[12];
  163. memset(data, 0xff, sizeof(data));
  164. spi_transaction_t t = {
  165. .length = 10*8,
  166. .tx_buffer = data,
  167. .rx_buffer = data,
  168. };
  169. spi_device_polling_transmit(slot->spi_handle, &t);
  170. // don't care if this failed
  171. }
  172. /**
  173. * (Re)Configure SPI device. Used to change clock speed.
  174. * @param slot Pointer to the slot to be configured
  175. * @param clock_speed_hz clock speed, Hz
  176. * @return ESP_OK on success
  177. */
  178. static esp_err_t configure_spi_dev(slot_info_t *slot, int clock_speed_hz)
  179. {
  180. if (slot->spi_handle) {
  181. // Reinitializing
  182. spi_bus_remove_device(slot->spi_handle);
  183. slot->spi_handle = NULL;
  184. }
  185. spi_device_interface_config_t devcfg = {
  186. .clock_speed_hz = clock_speed_hz,
  187. .mode = 0,
  188. // For SD cards, CS must stay low during the whole read/write operation,
  189. // rather than a single SPI transaction.
  190. .spics_io_num = GPIO_NUM_NC,
  191. .queue_size = SDSPI_TRANSACTION_COUNT,
  192. };
  193. return spi_bus_add_device(slot->host_id, &devcfg, &slot->spi_handle);
  194. }
  195. esp_err_t sdspi_host_init(void)
  196. {
  197. return ESP_OK;
  198. }
  199. static esp_err_t deinit_slot(slot_info_t *slot)
  200. {
  201. esp_err_t err = ESP_OK;
  202. if (slot->spi_handle) {
  203. spi_bus_remove_device(slot->spi_handle);
  204. slot->spi_handle = NULL;
  205. free(slot->block_buf);
  206. slot->block_buf = NULL;
  207. }
  208. uint64_t pin_bit_mask = 0;
  209. if (slot->gpio_cs != GPIO_UNUSED) {
  210. pin_bit_mask |= BIT64(slot->gpio_cs);
  211. }
  212. if (slot->gpio_cd != GPIO_UNUSED) {
  213. pin_bit_mask |= BIT64(slot->gpio_cd);
  214. }
  215. if (slot->gpio_wp != GPIO_UNUSED) {
  216. pin_bit_mask |= BIT64(slot->gpio_wp);
  217. }
  218. if (slot->gpio_int != GPIO_UNUSED) {
  219. pin_bit_mask |= BIT64(slot->gpio_int);
  220. gpio_intr_disable(slot->gpio_int);
  221. gpio_isr_handler_remove(slot->gpio_int);
  222. }
  223. gpio_config_t config = {
  224. .pin_bit_mask = pin_bit_mask,
  225. .mode = GPIO_MODE_INPUT,
  226. .intr_type = GPIO_INTR_DISABLE,
  227. };
  228. if (pin_bit_mask != 0) {
  229. gpio_config(&config);
  230. }
  231. if (slot->semphr_int) {
  232. vSemaphoreDelete(slot->semphr_int);
  233. slot->semphr_int = NULL;
  234. }
  235. free(slot);
  236. return err;
  237. }
  238. esp_err_t sdspi_host_remove_device(sdspi_dev_handle_t handle)
  239. {
  240. //Get the slot info and remove the reference in the static memory (if used)
  241. slot_info_t* slot = remove_slot_info(handle);
  242. if (slot == NULL) {
  243. return ESP_ERR_INVALID_ARG;
  244. }
  245. deinit_slot(slot);
  246. return ESP_OK;
  247. }
  248. //only the slots locally stored can be deinit in this function.
  249. esp_err_t sdspi_host_deinit(void)
  250. {
  251. for (size_t i = 0; i < sizeof(s_slots)/sizeof(s_slots[0]); ++i) {
  252. slot_info_t* slot = remove_slot_info(i);
  253. //slot isn't used, skip
  254. if (slot == NULL) continue;
  255. deinit_slot(slot);
  256. }
  257. return ESP_OK;
  258. }
  259. esp_err_t sdspi_host_set_card_clk(sdspi_dev_handle_t handle, uint32_t freq_khz)
  260. {
  261. slot_info_t *slot = get_slot_info(handle);
  262. if (slot == NULL) {
  263. return ESP_ERR_INVALID_ARG;
  264. }
  265. ESP_LOGD(TAG, "Setting card clock to %"PRIu32" kHz", freq_khz);
  266. return configure_spi_dev(slot, freq_khz * 1000);
  267. }
  268. static void gpio_intr(void* arg)
  269. {
  270. BaseType_t awoken = pdFALSE;
  271. slot_info_t* slot = (slot_info_t*)arg;
  272. xSemaphoreGiveFromISR(slot->semphr_int, &awoken);
  273. gpio_intr_disable(slot->gpio_int);
  274. if (awoken) {
  275. portYIELD_FROM_ISR();
  276. }
  277. }
  278. esp_err_t sdspi_host_init_device(const sdspi_device_config_t* slot_config, sdspi_dev_handle_t* out_handle)
  279. {
  280. ESP_LOGD(TAG, "%s: SPI%d cs=%d cd=%d wp=%d",
  281. __func__, slot_config->host_id + 1, slot_config->gpio_cs,
  282. slot_config->gpio_cd, slot_config->gpio_wp);
  283. slot_info_t* slot = (slot_info_t*)malloc(sizeof(slot_info_t));
  284. if (slot == NULL) {
  285. return ESP_ERR_NO_MEM;
  286. }
  287. *slot = (slot_info_t) {
  288. .host_id = slot_config->host_id,
  289. .gpio_cs = slot_config->gpio_cs,
  290. };
  291. // Attach the SD card to the SPI bus
  292. esp_err_t ret = configure_spi_dev(slot, SDMMC_FREQ_PROBING * 1000);
  293. if (ret != ESP_OK) {
  294. ESP_LOGD(TAG, "spi_bus_add_device failed with rc=0x%x", ret);
  295. goto cleanup;
  296. }
  297. // Configure CS pin
  298. gpio_config_t io_conf = {
  299. .intr_type = GPIO_INTR_DISABLE,
  300. .mode = GPIO_MODE_OUTPUT,
  301. .pin_bit_mask = 1ULL << slot_config->gpio_cs,
  302. };
  303. if (slot_config->gpio_cs != SDSPI_SLOT_NO_CS) {
  304. slot->gpio_cs = slot_config->gpio_cs;
  305. } else {
  306. slot->gpio_cs = GPIO_UNUSED;
  307. }
  308. if (slot->gpio_cs != GPIO_UNUSED) {
  309. ret = gpio_config(&io_conf);
  310. if (ret != ESP_OK) {
  311. ESP_LOGD(TAG, "gpio_config (CS) failed with rc=0x%x", ret);
  312. goto cleanup;
  313. }
  314. cs_high(slot);
  315. }
  316. // Configure CD and WP pins
  317. io_conf = (gpio_config_t) {
  318. .intr_type = GPIO_INTR_DISABLE,
  319. .mode = GPIO_MODE_INPUT,
  320. .pin_bit_mask = 0,
  321. .pull_up_en = true
  322. };
  323. if (slot_config->gpio_cd != SDSPI_SLOT_NO_CD) {
  324. io_conf.pin_bit_mask |= (1ULL << slot_config->gpio_cd);
  325. slot->gpio_cd = slot_config->gpio_cd;
  326. } else {
  327. slot->gpio_cd = GPIO_UNUSED;
  328. }
  329. if (slot_config->gpio_wp != SDSPI_SLOT_NO_WP) {
  330. io_conf.pin_bit_mask |= (1ULL << slot_config->gpio_wp);
  331. slot->gpio_wp = slot_config->gpio_wp;
  332. } else {
  333. slot->gpio_wp = GPIO_UNUSED;
  334. }
  335. if (io_conf.pin_bit_mask != 0) {
  336. ret = gpio_config(&io_conf);
  337. if (ret != ESP_OK) {
  338. ESP_LOGD(TAG, "gpio_config (CD/WP) failed with rc=0x%x", ret);
  339. goto cleanup;
  340. }
  341. }
  342. if (slot_config->gpio_int != SDSPI_SLOT_NO_INT) {
  343. slot->gpio_int = slot_config->gpio_int;
  344. io_conf = (gpio_config_t) {
  345. .intr_type = GPIO_INTR_LOW_LEVEL,
  346. .mode = GPIO_MODE_INPUT,
  347. .pull_up_en = true,
  348. .pin_bit_mask = (1ULL << slot_config->gpio_int),
  349. };
  350. ret = gpio_config(&io_conf);
  351. if (ret != ESP_OK) {
  352. ESP_LOGE(TAG, "gpio_config (interrupt) failed with rc=0x%x", ret);
  353. goto cleanup;
  354. }
  355. slot->semphr_int = xSemaphoreCreateBinary();
  356. if (slot->semphr_int == NULL) {
  357. ret = ESP_ERR_NO_MEM;
  358. goto cleanup;
  359. }
  360. gpio_intr_disable(slot->gpio_int);
  361. // 1. the interrupt is better to be disabled before the ISR is registered
  362. // 2. the semaphore MUST be initialized before the ISR is registered
  363. // 3. the gpio_int member should be filled before the ISR is registered
  364. ret = gpio_isr_handler_add(slot->gpio_int, &gpio_intr, slot);
  365. if (ret != ESP_OK) {
  366. ESP_LOGE(TAG, "gpio_isr_handle_add failed with rc=0x%x", ret);
  367. goto cleanup;
  368. }
  369. } else {
  370. slot->gpio_int = GPIO_UNUSED;
  371. }
  372. //Initialization finished, store the store information if possible
  373. //Then return corresponding handle
  374. *out_handle = store_slot_info(slot);
  375. return ESP_OK;
  376. cleanup:
  377. if (slot->semphr_int) {
  378. vSemaphoreDelete(slot->semphr_int);
  379. slot->semphr_int = NULL;
  380. }
  381. if (slot->spi_handle) {
  382. spi_bus_remove_device(slot->spi_handle);
  383. slot->spi_handle = NULL;
  384. }
  385. free(slot);
  386. return ret;
  387. }
  388. esp_err_t sdspi_host_start_command(sdspi_dev_handle_t handle, sdspi_hw_cmd_t *cmd, void *data,
  389. uint32_t data_size, int flags)
  390. {
  391. slot_info_t *slot = get_slot_info(handle);
  392. if (slot == NULL) {
  393. return ESP_ERR_INVALID_ARG;
  394. }
  395. if (card_missing(slot)) {
  396. return ESP_ERR_NOT_FOUND;
  397. }
  398. // save some parts of cmd, as its contents will be overwritten
  399. int cmd_index = cmd->cmd_index;
  400. uint32_t cmd_arg;
  401. memcpy(&cmd_arg, cmd->arguments, sizeof(cmd_arg));
  402. cmd_arg = __builtin_bswap32(cmd_arg);
  403. ESP_LOGV(TAG, "%s: slot=%i, CMD%d, arg=0x%08"PRIx32" flags=0x%x, data=%p, data_size=%"PRIu32" crc=0x%02x",
  404. __func__, handle, cmd_index, cmd_arg, flags, data, data_size, cmd->crc7);
  405. spi_device_acquire_bus(slot->spi_handle, portMAX_DELAY);
  406. poll_busy(slot, 40, true);
  407. // For CMD0, clock out 80 cycles to help the card enter idle state,
  408. // *before* CS is asserted.
  409. if (cmd_index == MMC_GO_IDLE_STATE) {
  410. go_idle_clockout(slot);
  411. }
  412. // actual transaction
  413. esp_err_t ret = ESP_OK;
  414. cs_low(slot);
  415. if (flags & SDSPI_CMD_FLAG_DATA) {
  416. const bool multi_block = flags & SDSPI_CMD_FLAG_MULTI_BLK;
  417. //send stop transmission token only when multi-block write and non-SDIO mode
  418. const bool stop_transmission = multi_block && !(flags & SDSPI_CMD_FLAG_RSP_R5);
  419. if (flags & SDSPI_CMD_FLAG_WRITE) {
  420. ret = start_command_write_blocks(slot, cmd, data, data_size, multi_block, stop_transmission);
  421. } else {
  422. ret = start_command_read_blocks(slot, cmd, data, data_size, stop_transmission);
  423. }
  424. } else {
  425. ret = start_command_default(slot, flags, cmd);
  426. }
  427. cs_high(slot);
  428. release_bus(slot);
  429. spi_device_release_bus(slot->spi_handle);
  430. if (ret != ESP_OK) {
  431. ESP_LOGD(TAG, "%s: cmd=%d error=0x%x", __func__, cmd_index, ret);
  432. } else {
  433. // Update internal state when some commands are sent successfully
  434. if (cmd_index == SD_CRC_ON_OFF) {
  435. slot->data_crc_enabled = (uint8_t) cmd_arg;
  436. ESP_LOGD(TAG, "data CRC set=%d", slot->data_crc_enabled);
  437. }
  438. }
  439. return ret;
  440. }
  441. static esp_err_t start_command_default(slot_info_t *slot, int flags, sdspi_hw_cmd_t *cmd)
  442. {
  443. size_t cmd_size = SDSPI_CMD_R1_SIZE;
  444. if ((flags & SDSPI_CMD_FLAG_RSP_R1) ||
  445. (flags & SDSPI_CMD_FLAG_NORSP) ||
  446. (flags & SDSPI_CMD_FLAG_RSP_R1B )) {
  447. cmd_size = SDSPI_CMD_R1_SIZE;
  448. } else if (flags & SDSPI_CMD_FLAG_RSP_R2) {
  449. cmd_size = SDSPI_CMD_R2_SIZE;
  450. } else if (flags & SDSPI_CMD_FLAG_RSP_R3) {
  451. cmd_size = SDSPI_CMD_R3_SIZE;
  452. } else if (flags & SDSPI_CMD_FLAG_RSP_R4) {
  453. cmd_size = SDSPI_CMD_R4_SIZE;
  454. } else if (flags & SDSPI_CMD_FLAG_RSP_R5) {
  455. cmd_size = SDSPI_CMD_R5_SIZE;
  456. } else if (flags & SDSPI_CMD_FLAG_RSP_R7) {
  457. cmd_size = SDSPI_CMD_R7_SIZE;
  458. }
  459. //add extra clocks to avoid polling
  460. cmd_size += (SDSPI_NCR_MAX_SIZE-SDSPI_NCR_MIN_SIZE);
  461. spi_transaction_t t = {
  462. .flags = 0,
  463. .length = cmd_size * 8,
  464. .tx_buffer = cmd,
  465. .rx_buffer = cmd,
  466. };
  467. esp_err_t ret = spi_device_polling_transmit(slot->spi_handle, &t);
  468. if (cmd->cmd_index == MMC_STOP_TRANSMISSION) {
  469. /* response is a stuff byte from previous transfer, ignore it */
  470. cmd->r1 = 0xff;
  471. }
  472. if (ret != ESP_OK) {
  473. ESP_LOGD(TAG, "%s: spi_device_polling_transmit returned 0x%x", __func__, ret);
  474. return ret;
  475. }
  476. if (flags & SDSPI_CMD_FLAG_NORSP) {
  477. /* no (correct) response expected from the card, so skip polling loop */
  478. ESP_LOGV(TAG, "%s: ignoring response byte", __func__);
  479. cmd->r1 = 0x00;
  480. }
  481. // we have sent and received bytes with enough length.
  482. // now shift the response to match the offset of sdspi_hw_cmd_t
  483. ret = shift_cmd_response(cmd, cmd_size);
  484. if (ret != ESP_OK) return ESP_ERR_TIMEOUT;
  485. if (flags & SDSPI_CMD_FLAG_RSP_R1B) {
  486. ret = poll_busy(slot, cmd->timeout_ms, no_use_polling);
  487. if (ret != ESP_OK) {
  488. return ret;
  489. }
  490. }
  491. return ESP_OK;
  492. }
  493. // Wait until MISO goes high
  494. static esp_err_t poll_busy(slot_info_t *slot, int timeout_ms, bool polling)
  495. {
  496. uint8_t t_rx;
  497. spi_transaction_t t = {
  498. .tx_buffer = &t_rx,
  499. .flags = SPI_TRANS_USE_RXDATA, //data stored in rx_data
  500. .length = 8,
  501. };
  502. esp_err_t ret;
  503. int64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  504. int nonzero_count = 0;
  505. do {
  506. t_rx = SDSPI_MOSI_IDLE_VAL;
  507. t.rx_data[0] = 0;
  508. if (polling) {
  509. ret = spi_device_polling_transmit(slot->spi_handle, &t);
  510. } else {
  511. ret = spi_device_transmit(slot->spi_handle, &t);
  512. }
  513. if (ret != ESP_OK) {
  514. return ret;
  515. }
  516. if (t.rx_data[0] != 0) {
  517. if (++nonzero_count == 2) {
  518. return ESP_OK;
  519. }
  520. }
  521. } while(esp_timer_get_time() < t_end);
  522. ESP_LOGD(TAG, "%s: timeout", __func__);
  523. return ESP_ERR_TIMEOUT;
  524. }
  525. // Wait for data token, reading 8 bytes at a time.
  526. // If the token is found, write all subsequent bytes to extra_ptr,
  527. // and store the number of bytes written to extra_size.
  528. static esp_err_t poll_data_token(slot_info_t *slot, uint8_t *extra_ptr, size_t *extra_size, int timeout_ms)
  529. {
  530. uint8_t t_rx[8];
  531. spi_transaction_t t = {
  532. .tx_buffer = &t_rx,
  533. .rx_buffer = &t_rx,
  534. .length = sizeof(t_rx) * 8,
  535. };
  536. esp_err_t ret;
  537. int64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  538. do {
  539. memset(t_rx, SDSPI_MOSI_IDLE_VAL, sizeof(t_rx));
  540. ret = spi_device_polling_transmit(slot->spi_handle, &t);
  541. if (ret != ESP_OK) {
  542. return ret;
  543. }
  544. bool found = false;
  545. for (size_t byte_idx = 0; byte_idx < sizeof(t_rx); byte_idx++) {
  546. uint8_t rd_data = t_rx[byte_idx];
  547. if (rd_data == TOKEN_BLOCK_START) {
  548. found = true;
  549. memcpy(extra_ptr, t_rx + byte_idx + 1, sizeof(t_rx) - byte_idx - 1);
  550. *extra_size = sizeof(t_rx) - byte_idx - 1;
  551. break;
  552. }
  553. if (rd_data != 0xff && rd_data != 0) {
  554. ESP_LOGD(TAG, "%s: received 0x%02x while waiting for data",
  555. __func__, rd_data);
  556. return ESP_ERR_INVALID_RESPONSE;
  557. }
  558. }
  559. if (found) {
  560. return ESP_OK;
  561. }
  562. } while (esp_timer_get_time() < t_end);
  563. ESP_LOGD(TAG, "%s: timeout", __func__);
  564. return ESP_ERR_TIMEOUT;
  565. }
  566. // the r1 respond could appear 1-8 clocks after the command token is sent
  567. // this function search for r1 in the buffer after 1 clocks to max 8 clocks
  568. // then shift the data after R1, to match the definition of sdspi_hw_cmd_t.
  569. static esp_err_t shift_cmd_response(sdspi_hw_cmd_t* cmd, int sent_bytes)
  570. {
  571. uint8_t* pr1 = &cmd->r1;
  572. int ncr_cnt = 1;
  573. while(true) {
  574. if ((*pr1 & SD_SPI_R1_NO_RESPONSE) == 0) break;
  575. pr1++;
  576. if (++ncr_cnt > 8) return ESP_ERR_NOT_FOUND;
  577. }
  578. int copy_bytes = sent_bytes - SDSPI_CMD_SIZE - ncr_cnt;
  579. if (copy_bytes > 0) {
  580. memcpy(&cmd->r1, pr1, copy_bytes);
  581. }
  582. return ESP_OK;
  583. }
  584. /**
  585. * Receiving one or more blocks of data happens as follows:
  586. * 1. send command + receive r1 response (SDSPI_CMD_R1_SIZE bytes total)
  587. * 2. keep receiving bytes until TOKEN_BLOCK_START is encountered (this may
  588. * take a while, depending on card's read speed)
  589. * 3. receive up to SDSPI_MAX_DATA_LEN = 512 bytes of actual data
  590. * 4. receive 2 bytes of CRC
  591. * 5. for multi block transfers, go to step 2
  592. *
  593. * These steps can be done separately, but that leads to a less than optimal
  594. * performance on large transfers because of delays between each step.
  595. * For example, if steps 3 and 4 are separate SPI transactions queued one after
  596. * another, there will be ~16 microseconds of dead time between end of step 3
  597. * and the beginning of step 4. A delay between two blocking SPI transactions
  598. * in step 2 is even higher (~60 microseconds).
  599. *
  600. * To improve read performance the following sequence is adopted:
  601. * 1. Do the first transfer: command + r1 response + 8 extra bytes.
  602. * Set pre_scan_data_ptr to point to the 8 extra bytes, and set
  603. * pre_scan_data_size to 8.
  604. * 2. Search pre_scan_data_size bytes for TOKEN_BLOCK_START.
  605. * If found, the rest of the bytes contain part of the actual data.
  606. * Store pointer to and size of that extra data as extra_data_{ptr,size}.
  607. * If not found, fall back to polling for TOKEN_BLOCK_START, 8 bytes at a
  608. * time (in poll_data_token function). Deal with extra data in the same way,
  609. * by setting extra_data_{ptr,size}.
  610. * 3. Receive the remaining 512 - extra_data_size bytes, plus 4 extra bytes
  611. * (i.e. 516 - extra_data_size). Of the 4 extra bytes, first two will capture
  612. * the CRC value, and the other two will capture 0xff 0xfe sequence
  613. * indicating the start of the next block. Actual scanning is done by
  614. * setting pre_scan_data_ptr to point to these last 2 bytes, and setting
  615. * pre_scan_data_size = 2, then going to step 2 to receive the next block.
  616. * When the final block is being received, the number of extra bytes is 2
  617. * (only for CRC), because we don't need to wait for start token of the
  618. * next block, and some cards are getting confused by these two extra bytes.
  619. *
  620. * With this approach the delay between blocks of a multi-block transfer is
  621. * ~95 microseconds, out of which 35 microseconds are spend doing the CRC check.
  622. * Further speedup is possible by pipelining transfers and CRC checks, at an
  623. * expense of one extra temporary buffer.
  624. */
  625. static esp_err_t start_command_read_blocks(slot_info_t *slot, sdspi_hw_cmd_t *cmd,
  626. uint8_t *data, uint32_t rx_length, bool need_stop_command)
  627. {
  628. spi_transaction_t t_command = {
  629. .length = (SDSPI_CMD_R1_SIZE + SDSPI_RESPONSE_MAX_DELAY) * 8,
  630. .tx_buffer = cmd,
  631. .rx_buffer = cmd,
  632. };
  633. esp_err_t ret = spi_device_polling_transmit(slot->spi_handle, &t_command);
  634. if (ret != ESP_OK) {
  635. return ret;
  636. }
  637. uint8_t* cmd_u8 = (uint8_t*) cmd;
  638. size_t pre_scan_data_size = SDSPI_RESPONSE_MAX_DELAY;
  639. uint8_t* pre_scan_data_ptr = cmd_u8 + SDSPI_CMD_R1_SIZE;
  640. /* R1 response is delayed by 1-8 bytes from the request.
  641. * This loop searches for the response and writes it to cmd->r1.
  642. */
  643. while ((cmd->r1 & SD_SPI_R1_NO_RESPONSE) != 0 && pre_scan_data_size > 0) {
  644. cmd->r1 = *pre_scan_data_ptr;
  645. ++pre_scan_data_ptr;
  646. --pre_scan_data_size;
  647. }
  648. if (cmd->r1 & SD_SPI_R1_NO_RESPONSE) {
  649. ESP_LOGD(TAG, "no response token found");
  650. return ESP_ERR_TIMEOUT;
  651. }
  652. while (rx_length > 0) {
  653. size_t extra_data_size = 0;
  654. const uint8_t* extra_data_ptr = NULL;
  655. bool need_poll = true;
  656. for (size_t i = 0; i < pre_scan_data_size; ++i) {
  657. if (pre_scan_data_ptr[i] == TOKEN_BLOCK_START) {
  658. extra_data_size = pre_scan_data_size - i - 1;
  659. extra_data_ptr = pre_scan_data_ptr + i + 1;
  660. need_poll = false;
  661. break;
  662. }
  663. }
  664. if (need_poll) {
  665. // Wait for data to be ready
  666. ret = poll_data_token(slot, cmd_u8 + SDSPI_CMD_R1_SIZE, &extra_data_size, cmd->timeout_ms);
  667. if (ret != ESP_OK) {
  668. return ret;
  669. }
  670. if (extra_data_size) {
  671. extra_data_ptr = cmd_u8 + SDSPI_CMD_R1_SIZE;
  672. }
  673. }
  674. // Arrange RX buffer
  675. size_t will_receive = MIN(rx_length, SDSPI_MAX_DATA_LEN) - extra_data_size;
  676. uint8_t* rx_data;
  677. ret = get_block_buf(slot, &rx_data);
  678. if (ret != ESP_OK) {
  679. return ret;
  680. }
  681. // receive actual data
  682. const size_t receive_extra_bytes = (rx_length > SDSPI_MAX_DATA_LEN) ? 4 : 2;
  683. memset(rx_data, 0xff, will_receive + receive_extra_bytes);
  684. spi_transaction_t t_data = {
  685. .length = (will_receive + receive_extra_bytes) * 8,
  686. .rx_buffer = rx_data,
  687. .tx_buffer = rx_data
  688. };
  689. ret = spi_device_transmit(slot->spi_handle, &t_data);
  690. if (ret != ESP_OK) {
  691. return ret;
  692. }
  693. // CRC bytes need to be received even if CRC is not enabled
  694. uint16_t crc = UINT16_MAX;
  695. memcpy(&crc, rx_data + will_receive, sizeof(crc));
  696. // Bytes to scan for the start token
  697. pre_scan_data_size = receive_extra_bytes - sizeof(crc);
  698. pre_scan_data_ptr = rx_data + will_receive + sizeof(crc);
  699. // Copy data to the destination buffer
  700. memcpy(data + extra_data_size, rx_data, will_receive);
  701. if (extra_data_size) {
  702. memcpy(data, extra_data_ptr, extra_data_size);
  703. }
  704. // compute CRC of the received data
  705. uint16_t crc_of_data = 0;
  706. if (slot->data_crc_enabled) {
  707. crc_of_data = sdspi_crc16(data, will_receive + extra_data_size);
  708. if (crc_of_data != crc) {
  709. ESP_LOGE(TAG, "data CRC failed, got=0x%04x expected=0x%04x", crc_of_data, crc);
  710. esp_log_buffer_hex(TAG, data, 16);
  711. return ESP_ERR_INVALID_CRC;
  712. }
  713. }
  714. data += will_receive + extra_data_size;
  715. rx_length -= will_receive + extra_data_size;
  716. extra_data_size = 0;
  717. extra_data_ptr = NULL;
  718. }
  719. if (need_stop_command) {
  720. // To end multi block transfer, send stop command and wait for the
  721. // card to process it
  722. sdspi_hw_cmd_t stop_cmd;
  723. make_hw_cmd(MMC_STOP_TRANSMISSION, 0, cmd->timeout_ms, &stop_cmd);
  724. ret = start_command_default(slot, SDSPI_CMD_FLAG_RSP_R1B, &stop_cmd);
  725. if (ret != ESP_OK) {
  726. return ret;
  727. }
  728. if (stop_cmd.r1 != 0) {
  729. ESP_LOGD(TAG, "%s: STOP_TRANSMISSION response 0x%02x", __func__, stop_cmd.r1);
  730. }
  731. ret = poll_busy(slot, cmd->timeout_ms, use_polling);
  732. if (ret != ESP_OK) {
  733. return ret;
  734. }
  735. }
  736. return ESP_OK;
  737. }
  738. /* For CMD53, we can send in byte mode, or block mode
  739. * The data start token is different, and cannot be determined by the length
  740. * That's why we need ``multi_block``.
  741. * It's also different that stop transmission token is not needed in the SDIO mode.
  742. */
  743. static esp_err_t start_command_write_blocks(slot_info_t *slot, sdspi_hw_cmd_t *cmd,
  744. const uint8_t *data, uint32_t tx_length, bool multi_block, bool stop_trans)
  745. {
  746. if (card_write_protected(slot)) {
  747. ESP_LOGW(TAG, "%s: card write protected", __func__);
  748. return ESP_ERR_INVALID_STATE;
  749. }
  750. // Send the minimum length that is sure to get the complete response
  751. // SD cards always return R1 (1bytes), SDIO returns R5 (2 bytes)
  752. const int send_bytes = SDSPI_CMD_R5_SIZE+SDSPI_NCR_MAX_SIZE-SDSPI_NCR_MIN_SIZE;
  753. spi_transaction_t t_command = {
  754. .length = send_bytes * 8,
  755. .tx_buffer = cmd,
  756. .rx_buffer = cmd,
  757. };
  758. esp_err_t ret = spi_device_polling_transmit(slot->spi_handle, &t_command);
  759. if (ret != ESP_OK) {
  760. return ret;
  761. }
  762. // check if command response valid
  763. ret = shift_cmd_response(cmd, send_bytes);
  764. if (ret != ESP_OK) {
  765. ESP_LOGD(TAG, "%s: check_cmd_response returned 0x%x", __func__, ret);
  766. return ret;
  767. }
  768. uint8_t start_token = multi_block ?
  769. TOKEN_BLOCK_START_WRITE_MULTI : TOKEN_BLOCK_START;
  770. while (tx_length > 0) {
  771. // Write block start token
  772. spi_transaction_t t_start_token = {
  773. .length = sizeof(start_token) * 8,
  774. .tx_buffer = &start_token
  775. };
  776. ret = spi_device_polling_transmit(slot->spi_handle, &t_start_token);
  777. if (ret != ESP_OK) {
  778. return ret;
  779. }
  780. // Prepare data to be sent
  781. size_t will_send = MIN(tx_length, SDSPI_MAX_DATA_LEN);
  782. const uint8_t* tx_data = data;
  783. if (!esp_ptr_in_dram(tx_data)) {
  784. // If the pointer can't be used with DMA, copy data into a new buffer
  785. uint8_t* tmp;
  786. ret = get_block_buf(slot, &tmp);
  787. if (ret != ESP_OK) {
  788. return ret;
  789. }
  790. memcpy(tmp, tx_data, will_send);
  791. tx_data = tmp;
  792. }
  793. // Write data
  794. spi_transaction_t t_data = {
  795. .length = will_send * 8,
  796. .tx_buffer = tx_data,
  797. };
  798. ret = spi_device_transmit(slot->spi_handle, &t_data);
  799. if (ret != ESP_OK) {
  800. return ret;
  801. }
  802. // Write CRC and get the response in one transaction
  803. uint16_t crc = sdspi_crc16(data, will_send);
  804. const int size_crc_response = sizeof(crc) + 1;
  805. spi_transaction_t t_crc_rsp = {
  806. .length = size_crc_response * 8,
  807. .flags = SPI_TRANS_USE_TXDATA|SPI_TRANS_USE_RXDATA,
  808. };
  809. memset(t_crc_rsp.tx_data, 0xff, 4);
  810. memcpy(t_crc_rsp.tx_data, &crc, sizeof(crc));
  811. ret = spi_device_polling_transmit(slot->spi_handle, &t_crc_rsp);
  812. if (ret != ESP_OK) {
  813. return ret;
  814. }
  815. uint8_t data_rsp = t_crc_rsp.rx_data[2];
  816. if (!SD_SPI_DATA_RSP_VALID(data_rsp)) return ESP_ERR_INVALID_RESPONSE;
  817. switch (SD_SPI_DATA_RSP(data_rsp)) {
  818. case SD_SPI_DATA_ACCEPTED:
  819. break;
  820. case SD_SPI_DATA_CRC_ERROR:
  821. return ESP_ERR_INVALID_CRC;
  822. case SD_SPI_DATA_WR_ERROR:
  823. return ESP_FAIL;
  824. default:
  825. return ESP_ERR_INVALID_RESPONSE;
  826. }
  827. // Wait for the card to finish writing data
  828. ret = poll_busy(slot, cmd->timeout_ms, no_use_polling);
  829. if (ret != ESP_OK) {
  830. return ret;
  831. }
  832. tx_length -= will_send;
  833. data += will_send;
  834. }
  835. if (stop_trans) {
  836. uint8_t stop_token[2] = {
  837. TOKEN_BLOCK_STOP_WRITE_MULTI,
  838. SDSPI_MOSI_IDLE_VAL
  839. };
  840. spi_transaction_t t_stop_token = {
  841. .length = sizeof(stop_token) * 8,
  842. .tx_buffer = &stop_token,
  843. };
  844. ret = spi_device_polling_transmit(slot->spi_handle, &t_stop_token);
  845. if (ret != ESP_OK) {
  846. return ret;
  847. }
  848. ret = poll_busy(slot, cmd->timeout_ms, use_polling);
  849. if (ret != ESP_OK) {
  850. return ret;
  851. }
  852. }
  853. return ESP_OK;
  854. }
  855. esp_err_t sdspi_host_io_int_enable(sdspi_dev_handle_t handle)
  856. {
  857. //the pin and its interrupt is already initialized, nothing to do here.
  858. return ESP_OK;
  859. }
  860. //the interrupt will give the semaphore and then disable itself
  861. esp_err_t sdspi_host_io_int_wait(sdspi_dev_handle_t handle, TickType_t timeout_ticks)
  862. {
  863. slot_info_t* slot = get_slot_info(handle);
  864. //skip the interrupt and semaphore if the gpio is already low.
  865. if (gpio_get_level(slot->gpio_int)==0) return ESP_OK;
  866. //clear the semaphore before wait
  867. xSemaphoreTake(slot->semphr_int, 0);
  868. //enable the interrupt and wait for the semaphore
  869. gpio_intr_enable(slot->gpio_int);
  870. BaseType_t ret = xSemaphoreTake(slot->semphr_int, timeout_ticks);
  871. if (ret == pdFALSE) {
  872. gpio_intr_disable(slot->gpio_int);
  873. return ESP_ERR_TIMEOUT;
  874. }
  875. return ESP_OK;
  876. }