sdspi_host.c 33 KB

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