sdspi_host.c 34 KB

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