sdspi_host.c 32 KB

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