sdspi_host.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  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. esp_err_t sdspi_host_get_real_freq(sdspi_dev_handle_t handle, int* real_freq_khz)
  269. {
  270. slot_info_t *slot = get_slot_info(handle);
  271. if (slot == NULL) {
  272. return ESP_ERR_INVALID_ARG;
  273. }
  274. return spi_device_get_actual_freq(slot->spi_handle, real_freq_khz);
  275. }
  276. static void gpio_intr(void* arg)
  277. {
  278. BaseType_t awoken = pdFALSE;
  279. slot_info_t* slot = (slot_info_t*)arg;
  280. xSemaphoreGiveFromISR(slot->semphr_int, &awoken);
  281. gpio_intr_disable(slot->gpio_int);
  282. if (awoken) {
  283. portYIELD_FROM_ISR();
  284. }
  285. }
  286. esp_err_t sdspi_host_init_device(const sdspi_device_config_t* slot_config, sdspi_dev_handle_t* out_handle)
  287. {
  288. ESP_LOGD(TAG, "%s: SPI%d cs=%d cd=%d wp=%d",
  289. __func__, slot_config->host_id + 1, slot_config->gpio_cs,
  290. slot_config->gpio_cd, slot_config->gpio_wp);
  291. slot_info_t* slot = (slot_info_t*)malloc(sizeof(slot_info_t));
  292. if (slot == NULL) {
  293. return ESP_ERR_NO_MEM;
  294. }
  295. *slot = (slot_info_t) {
  296. .host_id = slot_config->host_id,
  297. .gpio_cs = slot_config->gpio_cs,
  298. };
  299. // Attach the SD card to the SPI bus
  300. esp_err_t ret = configure_spi_dev(slot, SDMMC_FREQ_PROBING * 1000);
  301. if (ret != ESP_OK) {
  302. ESP_LOGD(TAG, "spi_bus_add_device failed with rc=0x%x", ret);
  303. goto cleanup;
  304. }
  305. // Configure CS pin
  306. gpio_config_t io_conf = {
  307. .intr_type = GPIO_INTR_DISABLE,
  308. .mode = GPIO_MODE_OUTPUT,
  309. .pin_bit_mask = 1ULL << slot_config->gpio_cs,
  310. };
  311. if (slot_config->gpio_cs != SDSPI_SLOT_NO_CS) {
  312. slot->gpio_cs = slot_config->gpio_cs;
  313. } else {
  314. slot->gpio_cs = GPIO_UNUSED;
  315. }
  316. if (slot->gpio_cs != GPIO_UNUSED) {
  317. ret = gpio_config(&io_conf);
  318. if (ret != ESP_OK) {
  319. ESP_LOGD(TAG, "gpio_config (CS) failed with rc=0x%x", ret);
  320. goto cleanup;
  321. }
  322. cs_high(slot);
  323. }
  324. // Configure CD and WP pins
  325. io_conf = (gpio_config_t) {
  326. .intr_type = GPIO_INTR_DISABLE,
  327. .mode = GPIO_MODE_INPUT,
  328. .pin_bit_mask = 0,
  329. .pull_up_en = true
  330. };
  331. if (slot_config->gpio_cd != SDSPI_SLOT_NO_CD) {
  332. io_conf.pin_bit_mask |= (1ULL << slot_config->gpio_cd);
  333. slot->gpio_cd = slot_config->gpio_cd;
  334. } else {
  335. slot->gpio_cd = GPIO_UNUSED;
  336. }
  337. if (slot_config->gpio_wp != SDSPI_SLOT_NO_WP) {
  338. io_conf.pin_bit_mask |= (1ULL << slot_config->gpio_wp);
  339. slot->gpio_wp = slot_config->gpio_wp;
  340. } else {
  341. slot->gpio_wp = GPIO_UNUSED;
  342. }
  343. if (io_conf.pin_bit_mask != 0) {
  344. ret = gpio_config(&io_conf);
  345. if (ret != ESP_OK) {
  346. ESP_LOGD(TAG, "gpio_config (CD/WP) failed with rc=0x%x", ret);
  347. goto cleanup;
  348. }
  349. }
  350. if (slot_config->gpio_int != SDSPI_SLOT_NO_INT) {
  351. slot->gpio_int = slot_config->gpio_int;
  352. io_conf = (gpio_config_t) {
  353. .intr_type = GPIO_INTR_LOW_LEVEL,
  354. .mode = GPIO_MODE_INPUT,
  355. .pull_up_en = true,
  356. .pin_bit_mask = (1ULL << slot_config->gpio_int),
  357. };
  358. ret = gpio_config(&io_conf);
  359. if (ret != ESP_OK) {
  360. ESP_LOGE(TAG, "gpio_config (interrupt) failed with rc=0x%x", ret);
  361. goto cleanup;
  362. }
  363. slot->semphr_int = xSemaphoreCreateBinary();
  364. if (slot->semphr_int == NULL) {
  365. ret = ESP_ERR_NO_MEM;
  366. goto cleanup;
  367. }
  368. gpio_intr_disable(slot->gpio_int);
  369. // 1. the interrupt is better to be disabled before the ISR is registered
  370. // 2. the semaphore MUST be initialized before the ISR is registered
  371. // 3. the gpio_int member should be filled before the ISR is registered
  372. ret = gpio_isr_handler_add(slot->gpio_int, &gpio_intr, slot);
  373. if (ret != ESP_OK) {
  374. ESP_LOGE(TAG, "gpio_isr_handle_add failed with rc=0x%x", ret);
  375. goto cleanup;
  376. }
  377. } else {
  378. slot->gpio_int = GPIO_UNUSED;
  379. }
  380. //Initialization finished, store the store information if possible
  381. //Then return corresponding handle
  382. *out_handle = store_slot_info(slot);
  383. return ESP_OK;
  384. cleanup:
  385. if (slot->semphr_int) {
  386. vSemaphoreDelete(slot->semphr_int);
  387. slot->semphr_int = NULL;
  388. }
  389. if (slot->spi_handle) {
  390. spi_bus_remove_device(slot->spi_handle);
  391. slot->spi_handle = NULL;
  392. }
  393. free(slot);
  394. return ret;
  395. }
  396. esp_err_t sdspi_host_start_command(sdspi_dev_handle_t handle, sdspi_hw_cmd_t *cmd, void *data,
  397. uint32_t data_size, int flags)
  398. {
  399. slot_info_t *slot = get_slot_info(handle);
  400. if (slot == NULL) {
  401. return ESP_ERR_INVALID_ARG;
  402. }
  403. if (card_missing(slot)) {
  404. return ESP_ERR_NOT_FOUND;
  405. }
  406. // save some parts of cmd, as its contents will be overwritten
  407. int cmd_index = cmd->cmd_index;
  408. uint32_t cmd_arg;
  409. memcpy(&cmd_arg, cmd->arguments, sizeof(cmd_arg));
  410. cmd_arg = __builtin_bswap32(cmd_arg);
  411. ESP_LOGV(TAG, "%s: slot=%i, CMD%d, arg=0x%08"PRIx32" flags=0x%x, data=%p, data_size=%"PRIu32" crc=0x%02x",
  412. __func__, handle, cmd_index, cmd_arg, flags, data, data_size, cmd->crc7);
  413. spi_device_acquire_bus(slot->spi_handle, portMAX_DELAY);
  414. poll_busy(slot, 40, true);
  415. // For CMD0, clock out 80 cycles to help the card enter idle state,
  416. // *before* CS is asserted.
  417. if (cmd_index == MMC_GO_IDLE_STATE) {
  418. go_idle_clockout(slot);
  419. }
  420. // actual transaction
  421. esp_err_t ret = ESP_OK;
  422. cs_low(slot);
  423. if (flags & SDSPI_CMD_FLAG_DATA) {
  424. const bool multi_block = flags & SDSPI_CMD_FLAG_MULTI_BLK;
  425. //send stop transmission token only when multi-block write and non-SDIO mode
  426. const bool stop_transmission = multi_block && !(flags & SDSPI_CMD_FLAG_RSP_R5);
  427. if (flags & SDSPI_CMD_FLAG_WRITE) {
  428. ret = start_command_write_blocks(slot, cmd, data, data_size, multi_block, stop_transmission);
  429. } else {
  430. ret = start_command_read_blocks(slot, cmd, data, data_size, stop_transmission);
  431. }
  432. } else {
  433. ret = start_command_default(slot, flags, cmd);
  434. }
  435. cs_high(slot);
  436. release_bus(slot);
  437. spi_device_release_bus(slot->spi_handle);
  438. if (ret != ESP_OK) {
  439. ESP_LOGD(TAG, "%s: cmd=%d error=0x%x", __func__, cmd_index, ret);
  440. } else {
  441. // Update internal state when some commands are sent successfully
  442. if (cmd_index == SD_CRC_ON_OFF) {
  443. slot->data_crc_enabled = (uint8_t) cmd_arg;
  444. ESP_LOGD(TAG, "data CRC set=%d", slot->data_crc_enabled);
  445. }
  446. }
  447. return ret;
  448. }
  449. static esp_err_t start_command_default(slot_info_t *slot, int flags, sdspi_hw_cmd_t *cmd)
  450. {
  451. size_t cmd_size = SDSPI_CMD_R1_SIZE;
  452. if ((flags & SDSPI_CMD_FLAG_RSP_R1) ||
  453. (flags & SDSPI_CMD_FLAG_NORSP) ||
  454. (flags & SDSPI_CMD_FLAG_RSP_R1B )) {
  455. cmd_size = SDSPI_CMD_R1_SIZE;
  456. } else if (flags & SDSPI_CMD_FLAG_RSP_R2) {
  457. cmd_size = SDSPI_CMD_R2_SIZE;
  458. } else if (flags & SDSPI_CMD_FLAG_RSP_R3) {
  459. cmd_size = SDSPI_CMD_R3_SIZE;
  460. } else if (flags & SDSPI_CMD_FLAG_RSP_R4) {
  461. cmd_size = SDSPI_CMD_R4_SIZE;
  462. } else if (flags & SDSPI_CMD_FLAG_RSP_R5) {
  463. cmd_size = SDSPI_CMD_R5_SIZE;
  464. } else if (flags & SDSPI_CMD_FLAG_RSP_R7) {
  465. cmd_size = SDSPI_CMD_R7_SIZE;
  466. }
  467. //add extra clocks to avoid polling
  468. cmd_size += (SDSPI_NCR_MAX_SIZE-SDSPI_NCR_MIN_SIZE);
  469. spi_transaction_t t = {
  470. .flags = 0,
  471. .length = cmd_size * 8,
  472. .tx_buffer = cmd,
  473. .rx_buffer = cmd,
  474. };
  475. esp_err_t ret = spi_device_polling_transmit(slot->spi_handle, &t);
  476. if (cmd->cmd_index == MMC_STOP_TRANSMISSION) {
  477. /* response is a stuff byte from previous transfer, ignore it */
  478. cmd->r1 = 0xff;
  479. }
  480. if (ret != ESP_OK) {
  481. ESP_LOGD(TAG, "%s: spi_device_polling_transmit returned 0x%x", __func__, ret);
  482. return ret;
  483. }
  484. if (flags & SDSPI_CMD_FLAG_NORSP) {
  485. /* no (correct) response expected from the card, so skip polling loop */
  486. ESP_LOGV(TAG, "%s: ignoring response byte", __func__);
  487. cmd->r1 = 0x00;
  488. }
  489. // we have sent and received bytes with enough length.
  490. // now shift the response to match the offset of sdspi_hw_cmd_t
  491. ret = shift_cmd_response(cmd, cmd_size);
  492. if (ret != ESP_OK) return ESP_ERR_TIMEOUT;
  493. if (flags & SDSPI_CMD_FLAG_RSP_R1B) {
  494. ret = poll_busy(slot, cmd->timeout_ms, no_use_polling);
  495. if (ret != ESP_OK) {
  496. return ret;
  497. }
  498. }
  499. return ESP_OK;
  500. }
  501. // Wait until MISO goes high
  502. static esp_err_t poll_busy(slot_info_t *slot, int timeout_ms, bool polling)
  503. {
  504. uint8_t t_rx;
  505. spi_transaction_t t = {
  506. .tx_buffer = &t_rx,
  507. .flags = SPI_TRANS_USE_RXDATA, //data stored in rx_data
  508. .length = 8,
  509. };
  510. esp_err_t ret;
  511. int64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  512. int nonzero_count = 0;
  513. do {
  514. t_rx = SDSPI_MOSI_IDLE_VAL;
  515. t.rx_data[0] = 0;
  516. if (polling) {
  517. ret = spi_device_polling_transmit(slot->spi_handle, &t);
  518. } else {
  519. ret = spi_device_transmit(slot->spi_handle, &t);
  520. }
  521. if (ret != ESP_OK) {
  522. return ret;
  523. }
  524. if (t.rx_data[0] != 0) {
  525. if (++nonzero_count == 2) {
  526. return ESP_OK;
  527. }
  528. }
  529. } while(esp_timer_get_time() < t_end);
  530. ESP_LOGD(TAG, "%s: timeout", __func__);
  531. return ESP_ERR_TIMEOUT;
  532. }
  533. // Wait for data token, reading 8 bytes at a time.
  534. // If the token is found, write all subsequent bytes to extra_ptr,
  535. // and store the number of bytes written to extra_size.
  536. static esp_err_t poll_data_token(slot_info_t *slot, uint8_t *extra_ptr, size_t *extra_size, int timeout_ms)
  537. {
  538. uint8_t t_rx[8];
  539. spi_transaction_t t = {
  540. .tx_buffer = &t_rx,
  541. .rx_buffer = &t_rx,
  542. .length = sizeof(t_rx) * 8,
  543. };
  544. esp_err_t ret;
  545. int64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  546. do {
  547. memset(t_rx, SDSPI_MOSI_IDLE_VAL, sizeof(t_rx));
  548. ret = spi_device_polling_transmit(slot->spi_handle, &t);
  549. if (ret != ESP_OK) {
  550. return ret;
  551. }
  552. bool found = false;
  553. for (size_t byte_idx = 0; byte_idx < sizeof(t_rx); byte_idx++) {
  554. uint8_t rd_data = t_rx[byte_idx];
  555. if (rd_data == TOKEN_BLOCK_START) {
  556. found = true;
  557. memcpy(extra_ptr, t_rx + byte_idx + 1, sizeof(t_rx) - byte_idx - 1);
  558. *extra_size = sizeof(t_rx) - byte_idx - 1;
  559. break;
  560. }
  561. if (rd_data != 0xff && rd_data != 0) {
  562. ESP_LOGD(TAG, "%s: received 0x%02x while waiting for data",
  563. __func__, rd_data);
  564. return ESP_ERR_INVALID_RESPONSE;
  565. }
  566. }
  567. if (found) {
  568. return ESP_OK;
  569. }
  570. } while (esp_timer_get_time() < t_end);
  571. ESP_LOGD(TAG, "%s: timeout", __func__);
  572. return ESP_ERR_TIMEOUT;
  573. }
  574. // the r1 respond could appear 1-8 clocks after the command token is sent
  575. // this function search for r1 in the buffer after 1 clocks to max 8 clocks
  576. // then shift the data after R1, to match the definition of sdspi_hw_cmd_t.
  577. static esp_err_t shift_cmd_response(sdspi_hw_cmd_t* cmd, int sent_bytes)
  578. {
  579. uint8_t* pr1 = &cmd->r1;
  580. int ncr_cnt = 1;
  581. while(true) {
  582. if ((*pr1 & SD_SPI_R1_NO_RESPONSE) == 0) break;
  583. pr1++;
  584. if (++ncr_cnt > 8) return ESP_ERR_NOT_FOUND;
  585. }
  586. int copy_bytes = sent_bytes - SDSPI_CMD_SIZE - ncr_cnt;
  587. if (copy_bytes > 0) {
  588. memcpy(&cmd->r1, pr1, copy_bytes);
  589. }
  590. return ESP_OK;
  591. }
  592. /**
  593. * Receiving one or more blocks of data happens as follows:
  594. * 1. send command + receive r1 response (SDSPI_CMD_R1_SIZE bytes total)
  595. * 2. keep receiving bytes until TOKEN_BLOCK_START is encountered (this may
  596. * take a while, depending on card's read speed)
  597. * 3. receive up to SDSPI_MAX_DATA_LEN = 512 bytes of actual data
  598. * 4. receive 2 bytes of CRC
  599. * 5. for multi block transfers, go to step 2
  600. *
  601. * These steps can be done separately, but that leads to a less than optimal
  602. * performance on large transfers because of delays between each step.
  603. * For example, if steps 3 and 4 are separate SPI transactions queued one after
  604. * another, there will be ~16 microseconds of dead time between end of step 3
  605. * and the beginning of step 4. A delay between two blocking SPI transactions
  606. * in step 2 is even higher (~60 microseconds).
  607. *
  608. * To improve read performance the following sequence is adopted:
  609. * 1. Do the first transfer: command + r1 response + 8 extra bytes.
  610. * Set pre_scan_data_ptr to point to the 8 extra bytes, and set
  611. * pre_scan_data_size to 8.
  612. * 2. Search pre_scan_data_size bytes for TOKEN_BLOCK_START.
  613. * If found, the rest of the bytes contain part of the actual data.
  614. * Store pointer to and size of that extra data as extra_data_{ptr,size}.
  615. * If not found, fall back to polling for TOKEN_BLOCK_START, 8 bytes at a
  616. * time (in poll_data_token function). Deal with extra data in the same way,
  617. * by setting extra_data_{ptr,size}.
  618. * 3. Receive the remaining 512 - extra_data_size bytes, plus 4 extra bytes
  619. * (i.e. 516 - extra_data_size). Of the 4 extra bytes, first two will capture
  620. * the CRC value, and the other two will capture 0xff 0xfe sequence
  621. * indicating the start of the next block. Actual scanning is done by
  622. * setting pre_scan_data_ptr to point to these last 2 bytes, and setting
  623. * pre_scan_data_size = 2, then going to step 2 to receive the next block.
  624. * When the final block is being received, the number of extra bytes is 2
  625. * (only for CRC), because we don't need to wait for start token of the
  626. * next block, and some cards are getting confused by these two extra bytes.
  627. *
  628. * With this approach the delay between blocks of a multi-block transfer is
  629. * ~95 microseconds, out of which 35 microseconds are spend doing the CRC check.
  630. * Further speedup is possible by pipelining transfers and CRC checks, at an
  631. * expense of one extra temporary buffer.
  632. */
  633. static esp_err_t start_command_read_blocks(slot_info_t *slot, sdspi_hw_cmd_t *cmd,
  634. uint8_t *data, uint32_t rx_length, bool need_stop_command)
  635. {
  636. spi_transaction_t t_command = {
  637. .length = (SDSPI_CMD_R1_SIZE + SDSPI_RESPONSE_MAX_DELAY) * 8,
  638. .tx_buffer = cmd,
  639. .rx_buffer = cmd,
  640. };
  641. esp_err_t ret = spi_device_polling_transmit(slot->spi_handle, &t_command);
  642. if (ret != ESP_OK) {
  643. return ret;
  644. }
  645. uint8_t* cmd_u8 = (uint8_t*) cmd;
  646. size_t pre_scan_data_size = SDSPI_RESPONSE_MAX_DELAY;
  647. uint8_t* pre_scan_data_ptr = cmd_u8 + SDSPI_CMD_R1_SIZE;
  648. /* R1 response is delayed by 1-8 bytes from the request.
  649. * This loop searches for the response and writes it to cmd->r1.
  650. */
  651. while ((cmd->r1 & SD_SPI_R1_NO_RESPONSE) != 0 && pre_scan_data_size > 0) {
  652. cmd->r1 = *pre_scan_data_ptr;
  653. ++pre_scan_data_ptr;
  654. --pre_scan_data_size;
  655. }
  656. if (cmd->r1 & SD_SPI_R1_NO_RESPONSE) {
  657. ESP_LOGD(TAG, "no response token found");
  658. return ESP_ERR_TIMEOUT;
  659. }
  660. while (rx_length > 0) {
  661. size_t extra_data_size = 0;
  662. const uint8_t* extra_data_ptr = NULL;
  663. bool need_poll = true;
  664. for (size_t i = 0; i < pre_scan_data_size; ++i) {
  665. if (pre_scan_data_ptr[i] == TOKEN_BLOCK_START) {
  666. extra_data_size = pre_scan_data_size - i - 1;
  667. extra_data_ptr = pre_scan_data_ptr + i + 1;
  668. need_poll = false;
  669. break;
  670. }
  671. }
  672. if (need_poll) {
  673. // Wait for data to be ready
  674. ret = poll_data_token(slot, cmd_u8 + SDSPI_CMD_R1_SIZE, &extra_data_size, cmd->timeout_ms);
  675. if (ret != ESP_OK) {
  676. return ret;
  677. }
  678. if (extra_data_size) {
  679. extra_data_ptr = cmd_u8 + SDSPI_CMD_R1_SIZE;
  680. }
  681. }
  682. // Arrange RX buffer
  683. size_t will_receive = MIN(rx_length, SDSPI_MAX_DATA_LEN) - extra_data_size;
  684. uint8_t* rx_data;
  685. ret = get_block_buf(slot, &rx_data);
  686. if (ret != ESP_OK) {
  687. return ret;
  688. }
  689. // receive actual data
  690. const size_t receive_extra_bytes = (rx_length > SDSPI_MAX_DATA_LEN) ? 4 : 2;
  691. memset(rx_data, 0xff, will_receive + receive_extra_bytes);
  692. spi_transaction_t t_data = {
  693. .length = (will_receive + receive_extra_bytes) * 8,
  694. .rx_buffer = rx_data,
  695. .tx_buffer = rx_data
  696. };
  697. ret = spi_device_transmit(slot->spi_handle, &t_data);
  698. if (ret != ESP_OK) {
  699. return ret;
  700. }
  701. // CRC bytes need to be received even if CRC is not enabled
  702. uint16_t crc = UINT16_MAX;
  703. memcpy(&crc, rx_data + will_receive, sizeof(crc));
  704. // Bytes to scan for the start token
  705. pre_scan_data_size = receive_extra_bytes - sizeof(crc);
  706. pre_scan_data_ptr = rx_data + will_receive + sizeof(crc);
  707. // Copy data to the destination buffer
  708. memcpy(data + extra_data_size, rx_data, will_receive);
  709. if (extra_data_size) {
  710. memcpy(data, extra_data_ptr, extra_data_size);
  711. }
  712. // compute CRC of the received data
  713. uint16_t crc_of_data = 0;
  714. if (slot->data_crc_enabled) {
  715. crc_of_data = sdspi_crc16(data, will_receive + extra_data_size);
  716. if (crc_of_data != crc) {
  717. ESP_LOGE(TAG, "data CRC failed, got=0x%04x expected=0x%04x", crc_of_data, crc);
  718. esp_log_buffer_hex(TAG, data, 16);
  719. return ESP_ERR_INVALID_CRC;
  720. }
  721. }
  722. data += will_receive + extra_data_size;
  723. rx_length -= will_receive + extra_data_size;
  724. extra_data_size = 0;
  725. extra_data_ptr = NULL;
  726. }
  727. if (need_stop_command) {
  728. // To end multi block transfer, send stop command and wait for the
  729. // card to process it
  730. sdspi_hw_cmd_t stop_cmd;
  731. make_hw_cmd(MMC_STOP_TRANSMISSION, 0, cmd->timeout_ms, &stop_cmd);
  732. ret = start_command_default(slot, SDSPI_CMD_FLAG_RSP_R1B, &stop_cmd);
  733. if (ret != ESP_OK) {
  734. return ret;
  735. }
  736. if (stop_cmd.r1 != 0) {
  737. ESP_LOGD(TAG, "%s: STOP_TRANSMISSION response 0x%02x", __func__, stop_cmd.r1);
  738. }
  739. ret = poll_busy(slot, cmd->timeout_ms, use_polling);
  740. if (ret != ESP_OK) {
  741. return ret;
  742. }
  743. }
  744. return ESP_OK;
  745. }
  746. /* For CMD53, we can send in byte mode, or block mode
  747. * The data start token is different, and cannot be determined by the length
  748. * That's why we need ``multi_block``.
  749. * It's also different that stop transmission token is not needed in the SDIO mode.
  750. */
  751. static esp_err_t start_command_write_blocks(slot_info_t *slot, sdspi_hw_cmd_t *cmd,
  752. const uint8_t *data, uint32_t tx_length, bool multi_block, bool stop_trans)
  753. {
  754. if (card_write_protected(slot)) {
  755. ESP_LOGW(TAG, "%s: card write protected", __func__);
  756. return ESP_ERR_INVALID_STATE;
  757. }
  758. // Send the minimum length that is sure to get the complete response
  759. // SD cards always return R1 (1bytes), SDIO returns R5 (2 bytes)
  760. const int send_bytes = SDSPI_CMD_R5_SIZE+SDSPI_NCR_MAX_SIZE-SDSPI_NCR_MIN_SIZE;
  761. spi_transaction_t t_command = {
  762. .length = send_bytes * 8,
  763. .tx_buffer = cmd,
  764. .rx_buffer = cmd,
  765. };
  766. esp_err_t ret = spi_device_polling_transmit(slot->spi_handle, &t_command);
  767. if (ret != ESP_OK) {
  768. return ret;
  769. }
  770. // check if command response valid
  771. ret = shift_cmd_response(cmd, send_bytes);
  772. if (ret != ESP_OK) {
  773. ESP_LOGD(TAG, "%s: check_cmd_response returned 0x%x", __func__, ret);
  774. return ret;
  775. }
  776. uint8_t start_token = multi_block ?
  777. TOKEN_BLOCK_START_WRITE_MULTI : TOKEN_BLOCK_START;
  778. while (tx_length > 0) {
  779. // Write block start token
  780. spi_transaction_t t_start_token = {
  781. .length = sizeof(start_token) * 8,
  782. .tx_buffer = &start_token
  783. };
  784. ret = spi_device_polling_transmit(slot->spi_handle, &t_start_token);
  785. if (ret != ESP_OK) {
  786. return ret;
  787. }
  788. // Prepare data to be sent
  789. size_t will_send = MIN(tx_length, SDSPI_MAX_DATA_LEN);
  790. const uint8_t* tx_data = data;
  791. if (!esp_ptr_in_dram(tx_data)) {
  792. // If the pointer can't be used with DMA, copy data into a new buffer
  793. uint8_t* tmp;
  794. ret = get_block_buf(slot, &tmp);
  795. if (ret != ESP_OK) {
  796. return ret;
  797. }
  798. memcpy(tmp, tx_data, will_send);
  799. tx_data = tmp;
  800. }
  801. // Write data
  802. spi_transaction_t t_data = {
  803. .length = will_send * 8,
  804. .tx_buffer = tx_data,
  805. };
  806. ret = spi_device_transmit(slot->spi_handle, &t_data);
  807. if (ret != ESP_OK) {
  808. return ret;
  809. }
  810. // Write CRC and get the response in one transaction
  811. uint16_t crc = sdspi_crc16(data, will_send);
  812. const int size_crc_response = sizeof(crc) + 1;
  813. spi_transaction_t t_crc_rsp = {
  814. .length = size_crc_response * 8,
  815. .flags = SPI_TRANS_USE_TXDATA|SPI_TRANS_USE_RXDATA,
  816. };
  817. memset(t_crc_rsp.tx_data, 0xff, 4);
  818. memcpy(t_crc_rsp.tx_data, &crc, sizeof(crc));
  819. ret = spi_device_polling_transmit(slot->spi_handle, &t_crc_rsp);
  820. if (ret != ESP_OK) {
  821. return ret;
  822. }
  823. uint8_t data_rsp = t_crc_rsp.rx_data[2];
  824. if (!SD_SPI_DATA_RSP_VALID(data_rsp)) return ESP_ERR_INVALID_RESPONSE;
  825. switch (SD_SPI_DATA_RSP(data_rsp)) {
  826. case SD_SPI_DATA_ACCEPTED:
  827. break;
  828. case SD_SPI_DATA_CRC_ERROR:
  829. return ESP_ERR_INVALID_CRC;
  830. case SD_SPI_DATA_WR_ERROR:
  831. return ESP_FAIL;
  832. default:
  833. return ESP_ERR_INVALID_RESPONSE;
  834. }
  835. // Wait for the card to finish writing data
  836. ret = poll_busy(slot, cmd->timeout_ms, no_use_polling);
  837. if (ret != ESP_OK) {
  838. return ret;
  839. }
  840. tx_length -= will_send;
  841. data += will_send;
  842. }
  843. if (stop_trans) {
  844. uint8_t stop_token[2] = {
  845. TOKEN_BLOCK_STOP_WRITE_MULTI,
  846. SDSPI_MOSI_IDLE_VAL
  847. };
  848. spi_transaction_t t_stop_token = {
  849. .length = sizeof(stop_token) * 8,
  850. .tx_buffer = &stop_token,
  851. };
  852. ret = spi_device_polling_transmit(slot->spi_handle, &t_stop_token);
  853. if (ret != ESP_OK) {
  854. return ret;
  855. }
  856. ret = poll_busy(slot, cmd->timeout_ms, use_polling);
  857. if (ret != ESP_OK) {
  858. return ret;
  859. }
  860. }
  861. return ESP_OK;
  862. }
  863. esp_err_t sdspi_host_io_int_enable(sdspi_dev_handle_t handle)
  864. {
  865. //the pin and its interrupt is already initialized, nothing to do here.
  866. return ESP_OK;
  867. }
  868. //the interrupt will give the semaphore and then disable itself
  869. esp_err_t sdspi_host_io_int_wait(sdspi_dev_handle_t handle, TickType_t timeout_ticks)
  870. {
  871. slot_info_t* slot = get_slot_info(handle);
  872. //skip the interrupt and semaphore if the gpio is already low.
  873. if (gpio_get_level(slot->gpio_int)==0) return ESP_OK;
  874. //clear the semaphore before wait
  875. xSemaphoreTake(slot->semphr_int, 0);
  876. //enable the interrupt and wait for the semaphore
  877. gpio_intr_enable(slot->gpio_int);
  878. BaseType_t ret = xSemaphoreTake(slot->semphr_int, timeout_ticks);
  879. if (ret == pdFALSE) {
  880. gpio_intr_disable(slot->gpio_int);
  881. return ESP_ERR_TIMEOUT;
  882. }
  883. return ESP_OK;
  884. }