sdspi_host.c 29 KB

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