sdspi_host.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  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(void)
  200. {
  201. return ESP_OK;
  202. }
  203. esp_err_t sdspi_host_deinit(void)
  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. uint64_t pin_bit_mask = BIT64(s_slots[i].gpio_cs);
  215. if (s_slots[i].gpio_cd != GPIO_UNUSED) {
  216. pin_bit_mask |= BIT64(s_slots[i].gpio_cd);
  217. }
  218. if (s_slots[i].gpio_wp != GPIO_UNUSED) {
  219. pin_bit_mask |= BIT64(s_slots[i].gpio_wp);
  220. }
  221. if (s_slots[i].gpio_int != GPIO_UNUSED) {
  222. pin_bit_mask |= BIT64(s_slots[i].gpio_int);
  223. }
  224. gpio_config_t config = {
  225. .pin_bit_mask = pin_bit_mask,
  226. .mode = GPIO_MODE_INPUT,
  227. };
  228. gpio_config(&config);
  229. }
  230. if (s_slots[i].semphr_int) {
  231. vSemaphoreDelete(s_slots[i].semphr_int);
  232. s_slots[i].semphr_int = NULL;
  233. }
  234. }
  235. return ESP_OK;
  236. }
  237. esp_err_t sdspi_host_set_card_clk(int slot, uint32_t freq_khz)
  238. {
  239. if (!is_valid_slot(slot)) {
  240. return ESP_ERR_INVALID_ARG;
  241. }
  242. if (!is_slot_initialized(slot)) {
  243. return ESP_ERR_INVALID_STATE;
  244. }
  245. ESP_LOGD(TAG, "Setting card clock to %d kHz", freq_khz);
  246. return init_spi_dev(slot, freq_khz * 1000);
  247. }
  248. static void gpio_intr(void* arg)
  249. {
  250. BaseType_t awoken = pdFALSE;
  251. slot_info_t* slot = (slot_info_t*)arg;
  252. xSemaphoreGiveFromISR(slot->semphr_int, &awoken);
  253. gpio_intr_disable(slot->gpio_int);
  254. if (awoken) {
  255. portYIELD_FROM_ISR();
  256. }
  257. }
  258. esp_err_t sdspi_host_init_slot(int slot, const sdspi_slot_config_t* slot_config)
  259. {
  260. ESP_LOGD(TAG, "%s: SPI%d miso=%d mosi=%d sck=%d cs=%d cd=%d wp=%d, dma_ch=%d",
  261. __func__, slot + 1,
  262. slot_config->gpio_miso, slot_config->gpio_mosi,
  263. slot_config->gpio_sck, slot_config->gpio_cs,
  264. slot_config->gpio_cd, slot_config->gpio_wp,
  265. slot_config->dma_channel);
  266. spi_host_device_t host = (spi_host_device_t) slot;
  267. if (!is_valid_slot(slot)) {
  268. return ESP_ERR_INVALID_ARG;
  269. }
  270. spi_bus_config_t buscfg = {
  271. .miso_io_num = slot_config->gpio_miso,
  272. .mosi_io_num = slot_config->gpio_mosi,
  273. .sclk_io_num = slot_config->gpio_sck,
  274. .quadwp_io_num = GPIO_NUM_NC,
  275. .quadhd_io_num = GPIO_NUM_NC
  276. };
  277. // Initialize SPI bus
  278. esp_err_t ret = spi_bus_initialize((spi_host_device_t)slot, &buscfg,
  279. slot_config->dma_channel);
  280. if (ret != ESP_OK) {
  281. ESP_LOGD(TAG, "spi_bus_initialize failed with rc=0x%x", ret);
  282. return ret;
  283. }
  284. // Attach the SD card to the SPI bus
  285. ret = init_spi_dev(slot, SDMMC_FREQ_PROBING * 1000);
  286. if (ret != ESP_OK) {
  287. ESP_LOGD(TAG, "spi_bus_add_device failed with rc=0x%x", ret);
  288. goto cleanup;
  289. }
  290. // Configure CS pin
  291. s_slots[slot].gpio_cs = (uint8_t) slot_config->gpio_cs;
  292. gpio_config_t io_conf = {
  293. .intr_type = GPIO_PIN_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_PIN_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. s_slots[slot].gpio_cd = slot_config->gpio_cd;
  313. } else {
  314. s_slots[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. s_slots[slot].gpio_wp = slot_config->gpio_wp;
  319. } else {
  320. s_slots[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. s_slots[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. gpio_intr_disable(slot_config->gpio_int);
  343. s_slots[slot].semphr_int = xSemaphoreCreateBinary();
  344. if (s_slots[slot].semphr_int == NULL) {
  345. ret = ESP_ERR_NO_MEM;
  346. goto cleanup;
  347. }
  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_config->gpio_int, &gpio_intr, &s_slots[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. s_slots[slot].gpio_int = GPIO_UNUSED;
  358. }
  359. s_slots[slot].transactions = calloc(SDSPI_TRANSACTION_COUNT, sizeof(spi_transaction_t));
  360. if (s_slots[slot].transactions == NULL) {
  361. ret = ESP_ERR_NO_MEM;
  362. goto cleanup;
  363. }
  364. return ESP_OK;
  365. cleanup:
  366. if (s_slots[slot].semphr_int) {
  367. vSemaphoreDelete(s_slots[slot].semphr_int);
  368. s_slots[slot].semphr_int = NULL;
  369. }
  370. if (s_slots[slot].handle) {
  371. spi_bus_remove_device(spi_handle(slot));
  372. s_slots[slot].handle = NULL;
  373. }
  374. spi_bus_free(host);
  375. return ret;
  376. }
  377. esp_err_t sdspi_host_start_command(int slot, sdspi_hw_cmd_t *cmd, void *data,
  378. uint32_t data_size, int flags)
  379. {
  380. if (!is_valid_slot(slot)) {
  381. return ESP_ERR_INVALID_ARG;
  382. }
  383. if (!is_slot_initialized(slot)) {
  384. return ESP_ERR_INVALID_STATE;
  385. }
  386. if (card_missing(slot)) {
  387. return ESP_ERR_NOT_FOUND;
  388. }
  389. // save some parts of cmd, as its contents will be overwritten
  390. int cmd_index = cmd->cmd_index;
  391. uint32_t cmd_arg;
  392. memcpy(&cmd_arg, cmd->arguments, sizeof(cmd_arg));
  393. cmd_arg = __builtin_bswap32(cmd_arg);
  394. ESP_LOGV(TAG, "%s: slot=%i, CMD%d, arg=0x%08x flags=0x%x, data=%p, data_size=%i crc=0x%02x",
  395. __func__, slot, cmd_index, cmd_arg, flags, data, data_size, cmd->crc7);
  396. // For CMD0, clock out 80 cycles to help the card enter idle state,
  397. // *before* CS is asserted.
  398. if (cmd_index == MMC_GO_IDLE_STATE) {
  399. go_idle_clockout(slot);
  400. }
  401. // actual transaction
  402. esp_err_t ret = ESP_OK;
  403. cs_low(slot);
  404. if (flags & SDSPI_CMD_FLAG_DATA) {
  405. const bool multi_block = flags & SDSPI_CMD_FLAG_MULTI_BLK;
  406. //send stop transmission token only when multi-block write and non-SDIO mode
  407. const bool stop_transmission = multi_block && !(flags & SDSPI_CMD_FLAG_RSP_R5);
  408. if (flags & SDSPI_CMD_FLAG_WRITE) {
  409. ret = start_command_write_blocks(slot, cmd, data, data_size, multi_block, stop_transmission);
  410. } else {
  411. ret = start_command_read_blocks(slot, cmd, data, data_size, stop_transmission);
  412. }
  413. } else {
  414. ret = start_command_default(slot, flags, cmd);
  415. }
  416. cs_high(slot);
  417. release_bus(slot);
  418. if (ret != ESP_OK) {
  419. ESP_LOGD(TAG, "%s: cmd=%d error=0x%x", __func__, cmd_index, ret);
  420. } else {
  421. // Update internal state when some commands are sent successfully
  422. if (cmd_index == SD_CRC_ON_OFF) {
  423. s_slots[slot].data_crc_enabled = (uint8_t) cmd_arg;
  424. ESP_LOGD(TAG, "data CRC set=%d", s_slots[slot].data_crc_enabled);
  425. }
  426. }
  427. return ret;
  428. }
  429. static esp_err_t start_command_default(int slot, int flags, sdspi_hw_cmd_t *cmd)
  430. {
  431. size_t cmd_size = SDSPI_CMD_R1_SIZE;
  432. if ((flags & SDSPI_CMD_FLAG_RSP_R1) ||
  433. (flags & SDSPI_CMD_FLAG_NORSP)) {
  434. cmd_size = SDSPI_CMD_R1_SIZE;
  435. } else if (flags & SDSPI_CMD_FLAG_RSP_R2) {
  436. cmd_size = SDSPI_CMD_R2_SIZE;
  437. } else if (flags & SDSPI_CMD_FLAG_RSP_R3) {
  438. cmd_size = SDSPI_CMD_R3_SIZE;
  439. } else if (flags & SDSPI_CMD_FLAG_RSP_R4) {
  440. cmd_size = SDSPI_CMD_R4_SIZE;
  441. } else if (flags & SDSPI_CMD_FLAG_RSP_R5) {
  442. cmd_size = SDSPI_CMD_R5_SIZE;
  443. } else if (flags & SDSPI_CMD_FLAG_RSP_R7) {
  444. cmd_size = SDSPI_CMD_R7_SIZE;
  445. }
  446. //add extra clocks to avoid polling
  447. cmd_size += (SDSPI_NCR_MAX_SIZE-SDSPI_NCR_MIN_SIZE);
  448. spi_transaction_t t = {
  449. .flags = 0,
  450. .length = cmd_size * 8,
  451. .tx_buffer = cmd,
  452. .rx_buffer = cmd,
  453. };
  454. esp_err_t ret = spi_device_transmit(spi_handle(slot), &t);
  455. if (cmd->cmd_index == MMC_STOP_TRANSMISSION) {
  456. /* response is a stuff byte from previous transfer, ignore it */
  457. cmd->r1 = 0xff;
  458. }
  459. if (ret != ESP_OK) {
  460. ESP_LOGD(TAG, "%s: spi_device_transmit returned 0x%x", __func__, ret);
  461. return ret;
  462. }
  463. if (flags & SDSPI_CMD_FLAG_NORSP) {
  464. /* no (correct) response expected from the card, so skip polling loop */
  465. ESP_LOGV(TAG, "%s: ignoring response byte", __func__);
  466. cmd->r1 = 0x00;
  467. }
  468. // we have sent and received bytes with enough length.
  469. // now shift the response to match the offset of sdspi_hw_cmd_t
  470. ret = shift_cmd_response(cmd, cmd_size);
  471. if (ret != ESP_OK) return ESP_ERR_TIMEOUT;
  472. return ESP_OK;
  473. }
  474. // Wait until MISO goes high
  475. static esp_err_t poll_busy(int slot, spi_transaction_t* t, int timeout_ms)
  476. {
  477. uint8_t t_rx;
  478. *t = (spi_transaction_t) {
  479. .tx_buffer = &t_rx,
  480. .flags = SPI_TRANS_USE_RXDATA, //data stored in rx_data
  481. .length = 8,
  482. };
  483. esp_err_t ret;
  484. uint64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  485. int nonzero_count = 0;
  486. do {
  487. t_rx = SDSPI_MOSI_IDLE_VAL;
  488. t->rx_data[0] = 0;
  489. ret = spi_device_transmit(spi_handle(slot), t);
  490. if (ret != ESP_OK) {
  491. return ret;
  492. }
  493. if (t->rx_data[0] != 0) {
  494. if (++nonzero_count == 2) {
  495. return ESP_OK;
  496. }
  497. }
  498. } while(esp_timer_get_time() < t_end);
  499. ESP_LOGD(TAG, "%s: timeout", __func__);
  500. return ESP_ERR_TIMEOUT;
  501. }
  502. // Wait for data token, reading 8 bytes at a time.
  503. // If the token is found, write all subsequent bytes to extra_ptr,
  504. // and store the number of bytes written to extra_size.
  505. static esp_err_t poll_data_token(int slot, spi_transaction_t* t,
  506. uint8_t* extra_ptr, size_t* extra_size, int timeout_ms)
  507. {
  508. uint8_t t_rx[8];
  509. *t = (spi_transaction_t) {
  510. .tx_buffer = &t_rx,
  511. .rx_buffer = &t_rx,
  512. .length = sizeof(t_rx) * 8,
  513. };
  514. esp_err_t ret;
  515. uint64_t t_end = esp_timer_get_time() + timeout_ms * 1000;
  516. do {
  517. memset(t_rx, SDSPI_MOSI_IDLE_VAL, sizeof(t_rx));
  518. ret = spi_device_transmit(spi_handle(slot), t);
  519. if (ret != ESP_OK) {
  520. return ret;
  521. }
  522. bool found = false;
  523. for (int byte_idx = 0; byte_idx < sizeof(t_rx); byte_idx++) {
  524. uint8_t rd_data = t_rx[byte_idx];
  525. if (rd_data == TOKEN_BLOCK_START) {
  526. found = true;
  527. memcpy(extra_ptr, t_rx + byte_idx + 1, sizeof(t_rx) - byte_idx - 1);
  528. *extra_size = sizeof(t_rx) - byte_idx - 1;
  529. break;
  530. }
  531. if (rd_data != 0xff && rd_data != 0) {
  532. ESP_LOGD(TAG, "%s: received 0x%02x while waiting for data",
  533. __func__, rd_data);
  534. return ESP_ERR_INVALID_RESPONSE;
  535. }
  536. }
  537. if (found) {
  538. return ESP_OK;
  539. }
  540. } while (esp_timer_get_time() < t_end);
  541. ESP_LOGD(TAG, "%s: timeout", __func__);
  542. return ESP_ERR_TIMEOUT;
  543. }
  544. // the r1 respond could appear 1-8 clocks after the command token is sent
  545. // this function search for r1 in the buffer after 1 clocks to max 8 clocks
  546. // then shift the data after R1, to match the definition of sdspi_hw_cmd_t.
  547. static esp_err_t shift_cmd_response(sdspi_hw_cmd_t* cmd, int sent_bytes)
  548. {
  549. uint8_t* pr1 = &cmd->r1;
  550. int ncr_cnt = 1;
  551. while(true) {
  552. if ((*pr1 & SD_SPI_R1_NO_RESPONSE) == 0) break;
  553. pr1++;
  554. if (++ncr_cnt > 8) return ESP_ERR_NOT_FOUND;
  555. }
  556. int copy_bytes = sent_bytes - SDSPI_CMD_SIZE - ncr_cnt;
  557. if (copy_bytes > 0) {
  558. memcpy(&cmd->r1, pr1, copy_bytes);
  559. }
  560. return ESP_OK;
  561. }
  562. /**
  563. * Receiving one or more blocks of data happens as follows:
  564. * 1. send command + receive r1 response (SDSPI_CMD_R1_SIZE bytes total)
  565. * 2. keep receiving bytes until TOKEN_BLOCK_START is encountered (this may
  566. * take a while, depending on card's read speed)
  567. * 3. receive up to SDSPI_MAX_DATA_LEN = 512 bytes of actual data
  568. * 4. receive 2 bytes of CRC
  569. * 5. for multi block transfers, go to step 2
  570. *
  571. * These steps can be done separately, but that leads to a less than optimal
  572. * performance on large transfers because of delays between each step.
  573. * For example, if steps 3 and 4 are separate SPI transactions queued one after
  574. * another, there will be ~16 microseconds of dead time between end of step 3
  575. * and the beginning of step 4. A delay between two blocking SPI transactions
  576. * in step 2 is even higher (~60 microseconds).
  577. *
  578. * To improve read performance the following sequence is adopted:
  579. * 1. Do the first transfer: command + r1 response + 8 extra bytes.
  580. * Set pre_scan_data_ptr to point to the 8 extra bytes, and set
  581. * pre_scan_data_size to 8.
  582. * 2. Search pre_scan_data_size bytes for TOKEN_BLOCK_START.
  583. * If found, the rest of the bytes contain part of the actual data.
  584. * Store pointer to and size of that extra data as extra_data_{ptr,size}.
  585. * If not found, fall back to polling for TOKEN_BLOCK_START, 8 bytes at a
  586. * time (in poll_data_token function). Deal with extra data in the same way,
  587. * by setting extra_data_{ptr,size}.
  588. * 3. Receive the remaining 512 - extra_data_size bytes, plus 4 extra bytes
  589. * (i.e. 516 - extra_data_size). Of the 4 extra bytes, first two will capture
  590. * the CRC value, and the other two will capture 0xff 0xfe sequence
  591. * indicating the start of the next block. Actual scanning is done by
  592. * setting pre_scan_data_ptr to point to these last 2 bytes, and setting
  593. * pre_scan_data_size = 2, then going to step 2 to receive the next block.
  594. * When the final block is being received, the number of extra bytes is 2
  595. * (only for CRC), because we don't need to wait for start token of the
  596. * next block, and some cards are getting confused by these two extra bytes.
  597. *
  598. * With this approach the delay between blocks of a multi-block transfer is
  599. * ~95 microseconds, out of which 35 microseconds are spend doing the CRC check.
  600. * Further speedup is possible by pipelining transfers and CRC checks, at an
  601. * expense of one extra temporary buffer.
  602. */
  603. static esp_err_t start_command_read_blocks(int slot, sdspi_hw_cmd_t *cmd,
  604. uint8_t *data, uint32_t rx_length, bool need_stop_command)
  605. {
  606. spi_transaction_t* t_command = get_transaction(slot);
  607. *t_command = (spi_transaction_t) {
  608. .length = (SDSPI_CMD_R1_SIZE + SDSPI_RESPONSE_MAX_DELAY) * 8,
  609. .tx_buffer = cmd,
  610. .rx_buffer = cmd,
  611. };
  612. esp_err_t ret = spi_device_transmit(spi_handle(slot), t_command);
  613. if (ret != ESP_OK) {
  614. return ret;
  615. }
  616. release_transaction(slot);
  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 (int 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. spi_transaction_t* t_poll = get_transaction(slot);
  647. ret = poll_data_token(slot, t_poll, cmd_u8 + SDSPI_CMD_R1_SIZE, &extra_data_size, cmd->timeout_ms);
  648. release_transaction(slot);
  649. if (ret != ESP_OK) {
  650. return ret;
  651. }
  652. if (extra_data_size) {
  653. extra_data_ptr = cmd_u8 + SDSPI_CMD_R1_SIZE;
  654. }
  655. }
  656. // Arrange RX buffer
  657. size_t will_receive = MIN(rx_length, SDSPI_MAX_DATA_LEN) - extra_data_size;
  658. uint8_t* rx_data;
  659. ret = get_block_buf(slot, &rx_data);
  660. if (ret != ESP_OK) {
  661. return ret;
  662. }
  663. // receive actual data
  664. const size_t receive_extra_bytes = (rx_length > SDSPI_MAX_DATA_LEN) ? 4 : 2;
  665. memset(rx_data, 0xff, will_receive + receive_extra_bytes);
  666. spi_transaction_t* t_data = get_transaction(slot);
  667. *t_data = (spi_transaction_t) {
  668. .length = (will_receive + receive_extra_bytes) * 8,
  669. .rx_buffer = rx_data,
  670. .tx_buffer = rx_data
  671. };
  672. ret = spi_device_transmit(spi_handle(slot), t_data);
  673. if (ret != ESP_OK) {
  674. return ret;
  675. }
  676. release_transaction(slot);
  677. // CRC bytes need to be received even if CRC is not enabled
  678. uint16_t crc = UINT16_MAX;
  679. memcpy(&crc, rx_data + will_receive, sizeof(crc));
  680. // Bytes to scan for the start token
  681. pre_scan_data_size = receive_extra_bytes - sizeof(crc);
  682. pre_scan_data_ptr = rx_data + will_receive + sizeof(crc);
  683. // Copy data to the destination buffer
  684. memcpy(data + extra_data_size, rx_data, will_receive);
  685. if (extra_data_size) {
  686. memcpy(data, extra_data_ptr, extra_data_size);
  687. }
  688. // compute CRC of the received data
  689. uint16_t crc_of_data = 0;
  690. if (data_crc_enabled(slot)) {
  691. crc_of_data = sdspi_crc16(data, will_receive + extra_data_size);
  692. if (crc_of_data != crc) {
  693. ESP_LOGE(TAG, "data CRC failed, got=0x%04x expected=0x%04x", crc_of_data, crc);
  694. esp_log_buffer_hex(TAG, data, 16);
  695. return ESP_ERR_INVALID_CRC;
  696. }
  697. }
  698. data += will_receive + extra_data_size;
  699. rx_length -= will_receive + extra_data_size;
  700. extra_data_size = 0;
  701. extra_data_ptr = NULL;
  702. }
  703. if (need_stop_command) {
  704. // To end multi block transfer, send stop command and wait for the
  705. // card to process it
  706. sdspi_hw_cmd_t stop_cmd;
  707. make_hw_cmd(MMC_STOP_TRANSMISSION, 0, cmd->timeout_ms, &stop_cmd);
  708. ret = start_command_default(slot, SDSPI_CMD_FLAG_RSP_R1, &stop_cmd);
  709. if (ret != ESP_OK) {
  710. return ret;
  711. }
  712. if (stop_cmd.r1 != 0) {
  713. ESP_LOGD(TAG, "%s: STOP_TRANSMISSION response 0x%02x", __func__, stop_cmd.r1);
  714. }
  715. spi_transaction_t* t_poll = get_transaction(slot);
  716. ret = poll_busy(slot, t_poll, cmd->timeout_ms);
  717. release_transaction(slot);
  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(int 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 = get_transaction(slot);
  740. *t_command = (spi_transaction_t) {
  741. .length = send_bytes * 8,
  742. .tx_buffer = cmd,
  743. .rx_buffer = cmd,
  744. };
  745. esp_err_t ret = spi_device_queue_trans(spi_handle(slot), t_command, 0);
  746. if (ret != ESP_OK) {
  747. return ret;
  748. }
  749. wait_for_transactions(slot);
  750. // check if command response valid
  751. ret = shift_cmd_response(cmd, send_bytes);
  752. if (ret != ESP_OK) {
  753. ESP_LOGD(TAG, "%s: check_cmd_response returned 0x%x", __func__, ret);
  754. return ret;
  755. }
  756. uint8_t start_token = multi_block ?
  757. TOKEN_BLOCK_START_WRITE_MULTI : TOKEN_BLOCK_START;
  758. while (tx_length > 0) {
  759. // Write block start token
  760. spi_transaction_t* t_start_token = get_transaction(slot);
  761. *t_start_token = (spi_transaction_t) {
  762. .length = sizeof(start_token) * 8,
  763. .tx_buffer = &start_token
  764. };
  765. ret = spi_device_queue_trans(spi_handle(slot), t_start_token, 0);
  766. if (ret != ESP_OK) {
  767. return ret;
  768. }
  769. // Prepare data to be sent
  770. size_t will_send = MIN(tx_length, SDSPI_MAX_DATA_LEN);
  771. const uint8_t* tx_data = data;
  772. if (!ptr_dma_compatible(tx_data)) {
  773. // If the pointer can't be used with DMA, copy data into a new buffer
  774. uint8_t* tmp;
  775. ret = get_block_buf(slot, &tmp);
  776. if (ret != ESP_OK) {
  777. return ret;
  778. }
  779. memcpy(tmp, tx_data, will_send);
  780. tx_data = tmp;
  781. }
  782. // Write data
  783. spi_transaction_t* t_data = get_transaction(slot);
  784. *t_data = (spi_transaction_t) {
  785. .length = will_send * 8,
  786. .tx_buffer = tx_data,
  787. };
  788. ret = spi_device_queue_trans(spi_handle(slot), t_data, 0);
  789. if (ret != ESP_OK) {
  790. return ret;
  791. }
  792. // Write CRC and get the response in one transaction
  793. uint16_t crc = sdspi_crc16(data, will_send);
  794. const int size_crc_response = sizeof(crc) + 1;
  795. spi_transaction_t* t_crc_rsp = get_transaction(slot);
  796. *t_crc_rsp = (spi_transaction_t) {
  797. .length = size_crc_response * 8,
  798. .flags = SPI_TRANS_USE_TXDATA|SPI_TRANS_USE_RXDATA,
  799. };
  800. memset(t_crc_rsp->tx_data, 0xff, 4);
  801. memcpy(t_crc_rsp->tx_data, &crc, sizeof(crc));
  802. ret = spi_device_queue_trans(spi_handle(slot), t_crc_rsp, 0);
  803. if (ret != ESP_OK) {
  804. return ret;
  805. }
  806. // Wait for data to be sent
  807. wait_for_transactions(slot);
  808. uint8_t data_rsp = t_crc_rsp->rx_data[2];
  809. if (!SD_SPI_DATA_RSP_VALID(data_rsp)) return ESP_ERR_INVALID_RESPONSE;
  810. switch (SD_SPI_DATA_RSP(data_rsp)) {
  811. case SD_SPI_DATA_ACCEPTED:
  812. break;
  813. case SD_SPI_DATA_CRC_ERROR:
  814. return ESP_ERR_INVALID_CRC;
  815. case SD_SPI_DATA_WR_ERROR:
  816. return ESP_FAIL;
  817. default:
  818. return ESP_ERR_INVALID_RESPONSE;
  819. }
  820. // Wait for the card to finish writing data
  821. spi_transaction_t* t_poll = get_transaction(slot);
  822. ret = poll_busy(slot, t_poll, cmd->timeout_ms);
  823. release_transaction(slot);
  824. if (ret != ESP_OK) {
  825. return ret;
  826. }
  827. tx_length -= will_send;
  828. data += will_send;
  829. }
  830. if (stop_trans) {
  831. uint8_t stop_token[2] = {
  832. TOKEN_BLOCK_STOP_WRITE_MULTI,
  833. SDSPI_MOSI_IDLE_VAL
  834. };
  835. spi_transaction_t *t_stop_token = get_transaction(slot);
  836. *t_stop_token = (spi_transaction_t) {
  837. .length = sizeof(stop_token) * 8,
  838. .tx_buffer = &stop_token,
  839. };
  840. ret = spi_device_queue_trans(spi_handle(slot), t_stop_token, 0);
  841. if (ret != ESP_OK) {
  842. return ret;
  843. }
  844. wait_for_transactions(slot);
  845. spi_transaction_t *t_poll = get_transaction(slot);
  846. ret = poll_busy(slot, t_poll, cmd->timeout_ms);
  847. release_transaction(slot);
  848. if (ret != ESP_OK) {
  849. return ret;
  850. }
  851. }
  852. return ESP_OK;
  853. }
  854. esp_err_t sdspi_host_io_int_enable(int slot)
  855. {
  856. //the pin and its interrupt is already initialized, nothing to do here.
  857. return ESP_OK;
  858. }
  859. //the interrupt will give the semaphore and then disable itself
  860. esp_err_t sdspi_host_io_int_wait(int slot, TickType_t timeout_ticks)
  861. {
  862. slot_info_t* pslot = &s_slots[slot];
  863. //skip the interrupt and semaphore if the gpio is already low.
  864. if (gpio_get_level(pslot->gpio_int)==0) return ESP_OK;
  865. //clear the semaphore before wait
  866. xSemaphoreTake(pslot->semphr_int, 0);
  867. //enable the interrupt and wait for the semaphore
  868. gpio_intr_enable(pslot->gpio_int);
  869. BaseType_t ret = xSemaphoreTake(pslot->semphr_int, timeout_ticks);
  870. if (ret == pdFALSE) {
  871. gpio_intr_disable(pslot->gpio_int);
  872. return ESP_ERR_TIMEOUT;
  873. }
  874. return ESP_OK;
  875. }