sdspi_host.c 33 KB

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