sdspi_host.c 33 KB

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