spi_master.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. // Copyright 2015-2016 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. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. /*
  14. Architecture:
  15. We can initialize a SPI driver, but we don't talk to the SPI driver itself, we address a device. A device essentially
  16. is a combination of SPI port and CS pin, plus some information about the specifics of communication to the device
  17. (timing, command/address length etc)
  18. The essence of the interface to a device is a set of queues; one per device. The idea is that to send something to a SPI
  19. device, you allocate a transaction descriptor. It contains some information about the transfer like the lenghth, address,
  20. command etc, plus pointers to transmit and receive buffer. The address of this block gets pushed into the transmit queue.
  21. The SPI driver does its magic, and sends and retrieves the data eventually. The data gets written to the receive buffers,
  22. if needed the transaction descriptor is modified to indicate returned parameters and the entire thing goes into the return
  23. queue, where whatever software initiated the transaction can retrieve it.
  24. The entire thing is run from the SPI interrupt handler. If SPI is done transmitting/receiving but nothing is in the queue,
  25. it will not clear the SPI interrupt but just disable it. This way, when a new thing is sent, pushing the packet into the send
  26. queue and re-enabling the interrupt will trigger the interrupt again, which can then take care of the sending.
  27. */
  28. #include <string.h>
  29. #include "driver/spi_common.h"
  30. #include "driver/spi_master.h"
  31. #include "soc/gpio_sig_map.h"
  32. #include "soc/spi_reg.h"
  33. #include "soc/dport_reg.h"
  34. #include "soc/spi_struct.h"
  35. #include "rom/ets_sys.h"
  36. #include "esp_types.h"
  37. #include "esp_attr.h"
  38. #include "esp_intr.h"
  39. #include "esp_intr_alloc.h"
  40. #include "esp_log.h"
  41. #include "esp_err.h"
  42. #include "esp_pm.h"
  43. #include "freertos/FreeRTOS.h"
  44. #include "freertos/semphr.h"
  45. #include "freertos/xtensa_api.h"
  46. #include "freertos/task.h"
  47. #include "freertos/ringbuf.h"
  48. #include "soc/soc.h"
  49. #include "soc/soc_memory_layout.h"
  50. #include "soc/dport_reg.h"
  51. #include "rom/lldesc.h"
  52. #include "driver/gpio.h"
  53. #include "driver/periph_ctrl.h"
  54. #include "esp_heap_caps.h"
  55. typedef struct spi_device_t spi_device_t;
  56. typedef typeof(SPI1.clock) spi_clock_reg_t;
  57. #define NO_CS 3 //Number of CS pins per SPI host
  58. /// struct to hold private transaction data (like tx and rx buffer for DMA).
  59. typedef struct {
  60. spi_transaction_t *trans;
  61. uint32_t *buffer_to_send; //equals to tx_data, if SPI_TRANS_USE_RXDATA is applied; otherwise if original buffer wasn't in DMA-capable memory, this gets the address of a temporary buffer that is;
  62. //otherwise sets to the original buffer or NULL if no buffer is assigned.
  63. uint32_t *buffer_to_rcv; // similar to buffer_to_send
  64. } spi_trans_priv;
  65. typedef struct {
  66. spi_device_t *device[NO_CS];
  67. intr_handle_t intr;
  68. spi_dev_t *hw;
  69. spi_trans_priv cur_trans_buf;
  70. int cur_cs;
  71. int prev_cs;
  72. lldesc_t *dmadesc_tx;
  73. lldesc_t *dmadesc_rx;
  74. bool no_gpio_matrix;
  75. int dma_chan;
  76. int max_transfer_sz;
  77. #ifdef CONFIG_PM_ENABLE
  78. esp_pm_lock_handle_t pm_lock;
  79. #endif
  80. } spi_host_t;
  81. typedef struct {
  82. spi_clock_reg_t reg;
  83. int eff_clk;
  84. int dummy_num;
  85. } clock_config_t;
  86. struct spi_device_t {
  87. QueueHandle_t trans_queue;
  88. QueueHandle_t ret_queue;
  89. spi_device_interface_config_t cfg;
  90. clock_config_t clk_cfg;
  91. spi_host_t *host;
  92. };
  93. static spi_host_t *spihost[3];
  94. static const char *SPI_TAG = "spi_master";
  95. #define SPI_CHECK(a, str, ret_val) \
  96. if (!(a)) { \
  97. ESP_LOGE(SPI_TAG,"%s(%d): %s", __FUNCTION__, __LINE__, str); \
  98. return (ret_val); \
  99. }
  100. static void spi_intr(void *arg);
  101. esp_err_t spi_bus_initialize(spi_host_device_t host, const spi_bus_config_t *bus_config, int dma_chan)
  102. {
  103. bool native, spi_chan_claimed, dma_chan_claimed;
  104. /* ToDo: remove this when we have flash operations cooperating with this */
  105. SPI_CHECK(host!=SPI_HOST, "SPI1 is not supported", ESP_ERR_NOT_SUPPORTED);
  106. SPI_CHECK(host>=SPI_HOST && host<=VSPI_HOST, "invalid host", ESP_ERR_INVALID_ARG);
  107. SPI_CHECK( dma_chan >= 0 && dma_chan <= 2, "invalid dma channel", ESP_ERR_INVALID_ARG );
  108. spi_chan_claimed=spicommon_periph_claim(host);
  109. SPI_CHECK(spi_chan_claimed, "host already in use", ESP_ERR_INVALID_STATE);
  110. if ( dma_chan != 0 ) {
  111. dma_chan_claimed=spicommon_dma_chan_claim(dma_chan);
  112. if ( !dma_chan_claimed ) {
  113. spicommon_periph_free( host );
  114. SPI_CHECK(dma_chan_claimed, "dma channel already in use", ESP_ERR_INVALID_STATE);
  115. }
  116. }
  117. spihost[host]=malloc(sizeof(spi_host_t));
  118. if (spihost[host]==NULL) goto nomem;
  119. memset(spihost[host], 0, sizeof(spi_host_t));
  120. #ifdef CONFIG_PM_ENABLE
  121. esp_err_t err = esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "spi_master",
  122. &spihost[host]->pm_lock);
  123. if (err != ESP_OK) {
  124. goto nomem;
  125. }
  126. #endif //CONFIG_PM_ENABLE
  127. spicommon_bus_initialize_io(host, bus_config, dma_chan, SPICOMMON_BUSFLAG_MASTER|SPICOMMON_BUSFLAG_QUAD, &native);
  128. spihost[host]->no_gpio_matrix=native;
  129. spihost[host]->dma_chan=dma_chan;
  130. if (dma_chan == 0) {
  131. spihost[host]->max_transfer_sz = 32;
  132. } else {
  133. //See how many dma descriptors we need and allocate them
  134. int dma_desc_ct=(bus_config->max_transfer_sz+SPI_MAX_DMA_LEN-1)/SPI_MAX_DMA_LEN;
  135. if (dma_desc_ct==0) dma_desc_ct=1; //default to 4k when max is not given
  136. spihost[host]->max_transfer_sz = dma_desc_ct*SPI_MAX_DMA_LEN;
  137. spihost[host]->dmadesc_tx=heap_caps_malloc(sizeof(lldesc_t)*dma_desc_ct, MALLOC_CAP_DMA);
  138. spihost[host]->dmadesc_rx=heap_caps_malloc(sizeof(lldesc_t)*dma_desc_ct, MALLOC_CAP_DMA);
  139. if (!spihost[host]->dmadesc_tx || !spihost[host]->dmadesc_rx) goto nomem;
  140. }
  141. esp_intr_alloc(spicommon_irqsource_for_host(host), ESP_INTR_FLAG_INTRDISABLED, spi_intr, (void*)spihost[host], &spihost[host]->intr);
  142. spihost[host]->hw=spicommon_hw_for_host(host);
  143. spihost[host]->cur_cs = NO_CS;
  144. spihost[host]->prev_cs = NO_CS;
  145. //Reset DMA
  146. spihost[host]->hw->dma_conf.val|=SPI_OUT_RST|SPI_IN_RST|SPI_AHBM_RST|SPI_AHBM_FIFO_RST;
  147. spihost[host]->hw->dma_out_link.start=0;
  148. spihost[host]->hw->dma_in_link.start=0;
  149. spihost[host]->hw->dma_conf.val&=~(SPI_OUT_RST|SPI_IN_RST|SPI_AHBM_RST|SPI_AHBM_FIFO_RST);
  150. //Reset timing
  151. spihost[host]->hw->ctrl2.val=0;
  152. //Disable unneeded ints
  153. spihost[host]->hw->slave.rd_buf_done=0;
  154. spihost[host]->hw->slave.wr_buf_done=0;
  155. spihost[host]->hw->slave.rd_sta_done=0;
  156. spihost[host]->hw->slave.wr_sta_done=0;
  157. spihost[host]->hw->slave.rd_buf_inten=0;
  158. spihost[host]->hw->slave.wr_buf_inten=0;
  159. spihost[host]->hw->slave.rd_sta_inten=0;
  160. spihost[host]->hw->slave.wr_sta_inten=0;
  161. //Force a transaction done interrupt. This interrupt won't fire yet because we initialized the SPI interrupt as
  162. //disabled. This way, we can just enable the SPI interrupt and the interrupt handler will kick in, handling
  163. //any transactions that are queued.
  164. spihost[host]->hw->slave.trans_inten=1;
  165. spihost[host]->hw->slave.trans_done=1;
  166. return ESP_OK;
  167. nomem:
  168. if (spihost[host]) {
  169. free(spihost[host]->dmadesc_tx);
  170. free(spihost[host]->dmadesc_rx);
  171. #ifdef CONFIG_PM_ENABLE
  172. if (spihost[host]->pm_lock) {
  173. esp_pm_lock_delete(spihost[host]->pm_lock);
  174. }
  175. #endif
  176. }
  177. free(spihost[host]);
  178. spicommon_periph_free(host);
  179. spicommon_dma_chan_free(dma_chan);
  180. return ESP_ERR_NO_MEM;
  181. }
  182. esp_err_t spi_bus_free(spi_host_device_t host)
  183. {
  184. int x;
  185. SPI_CHECK(host>=SPI_HOST && host<=VSPI_HOST, "invalid host", ESP_ERR_INVALID_ARG);
  186. SPI_CHECK(spihost[host]!=NULL, "host not in use", ESP_ERR_INVALID_STATE);
  187. for (x=0; x<NO_CS; x++) {
  188. SPI_CHECK(spihost[host]->device[x]==NULL, "not all CSses freed", ESP_ERR_INVALID_STATE);
  189. }
  190. if ( spihost[host]->dma_chan > 0 ) {
  191. spicommon_dma_chan_free ( spihost[host]->dma_chan );
  192. }
  193. #ifdef CONFIG_PM_ENABLE
  194. esp_pm_lock_delete(spihost[host]->pm_lock);
  195. #endif
  196. spihost[host]->hw->slave.trans_inten=0;
  197. spihost[host]->hw->slave.trans_done=0;
  198. esp_intr_free(spihost[host]->intr);
  199. spicommon_periph_free(host);
  200. free(spihost[host]->dmadesc_tx);
  201. free(spihost[host]->dmadesc_rx);
  202. free(spihost[host]);
  203. spihost[host]=NULL;
  204. return ESP_OK;
  205. }
  206. static inline uint32_t spi_dummy_limit(bool gpio_is_used)
  207. {
  208. const int apbclk=APB_CLK_FREQ;
  209. if (!gpio_is_used) {
  210. return apbclk; //dummy bit workaround is not used when native pins are used
  211. } else {
  212. return apbclk/2; //the dummy bit workaround is used when freq is 40MHz and GPIO matrix is used.
  213. }
  214. }
  215. /*
  216. Add a device. This allocates a CS line for the device, allocates memory for the device structure and hooks
  217. up the CS pin to whatever is specified.
  218. */
  219. esp_err_t spi_bus_add_device(spi_host_device_t host, const spi_device_interface_config_t *dev_config, spi_device_handle_t *handle)
  220. {
  221. int freecs;
  222. int apbclk=APB_CLK_FREQ;
  223. int eff_clk;
  224. int duty_cycle;
  225. spi_clock_reg_t clk_reg;
  226. SPI_CHECK(host>=SPI_HOST && host<=VSPI_HOST, "invalid host", ESP_ERR_INVALID_ARG);
  227. SPI_CHECK(spihost[host]!=NULL, "host not initialized", ESP_ERR_INVALID_STATE);
  228. SPI_CHECK(dev_config->spics_io_num < 0 || GPIO_IS_VALID_OUTPUT_GPIO(dev_config->spics_io_num), "spics pin invalid", ESP_ERR_INVALID_ARG);
  229. SPI_CHECK(dev_config->clock_speed_hz > 0, "invalid sclk speed", ESP_ERR_INVALID_ARG);
  230. for (freecs=0; freecs<NO_CS; freecs++) {
  231. //See if this slot is free; reserve if it is by putting a dummy pointer in the slot. We use an atomic compare&swap to make this thread-safe.
  232. if (__sync_bool_compare_and_swap(&spihost[host]->device[freecs], NULL, (spi_device_t *)1)) break;
  233. }
  234. SPI_CHECK(freecs!=NO_CS, "no free cs pins for host", ESP_ERR_NOT_FOUND);
  235. //The hardware looks like it would support this, but actually setting cs_ena_pretrans when transferring in full
  236. //duplex mode does absolutely nothing on the ESP32.
  237. SPI_CHECK(dev_config->cs_ena_pretrans==0 || (dev_config->flags & SPI_DEVICE_HALFDUPLEX), "cs pretrans delay incompatible with full-duplex", ESP_ERR_INVALID_ARG);
  238. //Speeds >=40MHz over GPIO matrix needs a dummy cycle, but these don't work for full-duplex connections.
  239. duty_cycle = (dev_config->duty_cycle_pos==0? 128: dev_config->duty_cycle_pos);
  240. eff_clk = spi_cal_clock(apbclk, dev_config->clock_speed_hz, duty_cycle, (uint32_t*)&clk_reg);
  241. uint32_t dummy_limit = spi_dummy_limit(!spihost[host]->no_gpio_matrix);
  242. SPI_CHECK( dev_config->flags & SPI_DEVICE_HALFDUPLEX || (eff_clk/1000/1000) < (dummy_limit/1000/1000) ||
  243. dev_config->flags & SPI_DEVICE_NO_DUMMY,
  244. "When GPIO matrix is used in full-duplex mode at frequency > 26MHz, device cannot read correct data.\n\
  245. Please note the SPI can only work at divisors of 80MHz, and the driver always tries to find the closest frequency to your configuration.\n\
  246. Specify ``SPI_DEVICE_NO_DUMMY`` to ignore this checking. Then you can output data at higher speed, or read data at your own risk.",
  247. ESP_ERR_INVALID_ARG );
  248. //Allocate memory for device
  249. spi_device_t *dev=malloc(sizeof(spi_device_t));
  250. if (dev==NULL) goto nomem;
  251. memset(dev, 0, sizeof(spi_device_t));
  252. spihost[host]->device[freecs]=dev;
  253. //Allocate queues, set defaults
  254. dev->trans_queue=xQueueCreate(dev_config->queue_size, sizeof(spi_trans_priv));
  255. dev->ret_queue=xQueueCreate(dev_config->queue_size, sizeof(spi_trans_priv));
  256. if (!dev->trans_queue || !dev->ret_queue) goto nomem;
  257. dev->host=spihost[host];
  258. //We want to save a copy of the dev config in the dev struct.
  259. memcpy(&dev->cfg, dev_config, sizeof(spi_device_interface_config_t));
  260. dev->cfg.duty_cycle_pos = duty_cycle;
  261. // TODO: if we have to change the apb clock among transactions, re-calculate this each time the apb clock lock is acquired.
  262. dev->clk_cfg= (clock_config_t) {
  263. .eff_clk = eff_clk,
  264. .dummy_num = (dev->clk_cfg.eff_clk >= dummy_limit? 1: 0),
  265. .reg = clk_reg,
  266. };
  267. //Set CS pin, CS options
  268. if (dev_config->spics_io_num >= 0) {
  269. gpio_set_direction(dev_config->spics_io_num, GPIO_MODE_OUTPUT);
  270. spicommon_cs_initialize(host, dev_config->spics_io_num, freecs, spihost[host]->no_gpio_matrix == false);
  271. }
  272. if (dev_config->flags&SPI_DEVICE_CLK_AS_CS) {
  273. spihost[host]->hw->pin.master_ck_sel |= (1<<freecs);
  274. } else {
  275. spihost[host]->hw->pin.master_ck_sel &= (1<<freecs);
  276. }
  277. if (dev_config->flags&SPI_DEVICE_POSITIVE_CS) {
  278. spihost[host]->hw->pin.master_cs_pol |= (1<<freecs);
  279. } else {
  280. spihost[host]->hw->pin.master_cs_pol &= (1<<freecs);
  281. }
  282. *handle=dev;
  283. ESP_LOGD(SPI_TAG, "SPI%d: New device added to CS%d, effective clock: %dkHz", host, freecs, dev->clk_cfg.eff_clk/1000);
  284. return ESP_OK;
  285. nomem:
  286. if (dev) {
  287. if (dev->trans_queue) vQueueDelete(dev->trans_queue);
  288. if (dev->ret_queue) vQueueDelete(dev->ret_queue);
  289. }
  290. free(dev);
  291. return ESP_ERR_NO_MEM;
  292. }
  293. esp_err_t spi_bus_remove_device(spi_device_handle_t handle)
  294. {
  295. int x;
  296. SPI_CHECK(handle!=NULL, "invalid handle", ESP_ERR_INVALID_ARG);
  297. //These checks aren't exhaustive; another thread could sneak in a transaction inbetween. These are only here to
  298. //catch design errors and aren't meant to be triggered during normal operation.
  299. SPI_CHECK(uxQueueMessagesWaiting(handle->trans_queue)==0, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  300. SPI_CHECK(handle->host->cur_cs == NO_CS || handle->host->device[handle->host->cur_cs]!=handle, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  301. SPI_CHECK(uxQueueMessagesWaiting(handle->ret_queue)==0, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  302. //Kill queues
  303. vQueueDelete(handle->trans_queue);
  304. vQueueDelete(handle->ret_queue);
  305. //Remove device from list of csses and free memory
  306. for (x=0; x<NO_CS; x++) {
  307. if (handle->host->device[x] == handle){
  308. handle->host->device[x]=NULL;
  309. if ( x == handle->host->prev_cs ) handle->host->prev_cs = NO_CS;
  310. }
  311. }
  312. free(handle);
  313. return ESP_OK;
  314. }
  315. static int spi_freq_for_pre_n(int fapb, int pre, int n) {
  316. return (fapb / (pre * n));
  317. }
  318. int spi_cal_clock(int fapb, int hz, int duty_cycle, uint32_t *reg_o)
  319. {
  320. spi_clock_reg_t reg;
  321. int eff_clk;
  322. //In hw, n, h and l are 1-64, pre is 1-8K. Value written to register is one lower than used value.
  323. if (hz>((fapb/4)*3)) {
  324. //Using Fapb directly will give us the best result here.
  325. reg.clkcnt_l=0;
  326. reg.clkcnt_h=0;
  327. reg.clkcnt_n=0;
  328. reg.clkdiv_pre=0;
  329. reg.clk_equ_sysclk=1;
  330. eff_clk=fapb;
  331. } else {
  332. //For best duty cycle resolution, we want n to be as close to 32 as possible, but
  333. //we also need a pre/n combo that gets us as close as possible to the intended freq.
  334. //To do this, we bruteforce n and calculate the best pre to go along with that.
  335. //If there's a choice between pre/n combos that give the same result, use the one
  336. //with the higher n.
  337. int pre, n, h, l;
  338. int bestn=-1;
  339. int bestpre=-1;
  340. int besterr=0;
  341. int errval;
  342. for (n=2; n<=64; n++) { //Start at 2: we need to be able to set h/l so we have at least one high and one low pulse.
  343. //Effectively, this does pre=round((fapb/n)/hz).
  344. pre=((fapb/n)+(hz/2))/hz;
  345. if (pre<=0) pre=1;
  346. if (pre>8192) pre=8192;
  347. errval=abs(spi_freq_for_pre_n(fapb, pre, n)-hz);
  348. if (bestn==-1 || errval<=besterr) {
  349. besterr=errval;
  350. bestn=n;
  351. bestpre=pre;
  352. }
  353. }
  354. n=bestn;
  355. pre=bestpre;
  356. l=n;
  357. //This effectively does round((duty_cycle*n)/256)
  358. h=(duty_cycle*n+127)/256;
  359. if (h<=0) h=1;
  360. reg.clk_equ_sysclk=0;
  361. reg.clkcnt_n=n-1;
  362. reg.clkdiv_pre=pre-1;
  363. reg.clkcnt_h=h-1;
  364. reg.clkcnt_l=l-1;
  365. eff_clk=spi_freq_for_pre_n(fapb, pre, n);
  366. }
  367. if ( reg_o != NULL ) *reg_o = reg.val;
  368. return eff_clk;
  369. }
  370. /*
  371. * Set the spi clock according to pre-calculated register value.
  372. */
  373. static inline void spi_set_clock(spi_dev_t *hw, spi_clock_reg_t reg) {
  374. hw->clock.val = reg.val;
  375. }
  376. //This is run in interrupt context and apart from initialization and destruction, this is the only code
  377. //touching the host (=spihost[x]) variable. The rest of the data arrives in queues. That is why there are
  378. //no muxes in this code.
  379. static void IRAM_ATTR spi_intr(void *arg)
  380. {
  381. int i;
  382. BaseType_t r;
  383. BaseType_t do_yield=pdFALSE;
  384. spi_trans_priv *trans_buf=NULL;
  385. spi_transaction_t *trans=NULL;
  386. spi_host_t *host=(spi_host_t*)arg;
  387. //Ignore all but the trans_done int.
  388. if (!host->hw->slave.trans_done) return;
  389. /*------------ deal with the in-flight transaction -----------------*/
  390. if (host->cur_cs != NO_CS) {
  391. spi_transaction_t *cur_trans = host->cur_trans_buf.trans;
  392. //Okay, transaction is done.
  393. if (host->cur_trans_buf.buffer_to_rcv && host->dma_chan == 0 ) {
  394. //Need to copy from SPI regs to result buffer.
  395. for (int x=0; x < cur_trans->rxlength; x+=32) {
  396. //Do a memcpy to get around possible alignment issues in rx_buffer
  397. uint32_t word=host->hw->data_buf[x/32];
  398. int len=cur_trans->rxlength-x;
  399. if (len>32) len=32;
  400. memcpy(&host->cur_trans_buf.buffer_to_rcv[x/32], &word, (len+7)/8);
  401. }
  402. }
  403. //Call post-transaction callback, if any
  404. if (host->device[host->cur_cs]->cfg.post_cb) host->device[host->cur_cs]->cfg.post_cb(cur_trans);
  405. //Return transaction descriptor.
  406. xQueueSendFromISR(host->device[host->cur_cs]->ret_queue, &host->cur_trans_buf, &do_yield);
  407. host->cur_cs = NO_CS;
  408. }
  409. //Tell common code DMA workaround that our DMA channel is idle. If needed, the code will do a DMA reset.
  410. if (host->dma_chan) spicommon_dmaworkaround_idle(host->dma_chan);
  411. /*------------ new transaction starts here ------------------*/
  412. //ToDo: This is a stupidly simple low-cs-first priority scheme. Make this configurable somehow. - JD
  413. for (i=0; i<NO_CS; i++) {
  414. if (host->device[i]) {
  415. r=xQueueReceiveFromISR(host->device[i]->trans_queue, &host->cur_trans_buf, &do_yield);
  416. trans_buf = &host->cur_trans_buf;
  417. //Stop looking if we have a transaction to send.
  418. if (r) break;
  419. }
  420. }
  421. if (i==NO_CS) {
  422. //No packet waiting. Disable interrupt.
  423. esp_intr_disable(host->intr);
  424. #ifdef CONFIG_PM_ENABLE
  425. //Release APB frequency lock
  426. esp_pm_lock_release(host->pm_lock);
  427. #endif
  428. } else {
  429. host->hw->slave.trans_done=0; //clear int bit
  430. //We have a transaction. Send it.
  431. spi_device_t *dev=host->device[i];
  432. trans = trans_buf->trans;
  433. host->cur_cs=i;
  434. //We should be done with the transmission.
  435. assert(host->hw->cmd.usr == 0);
  436. //Reconfigure according to device settings, but only if we change CSses.
  437. if (i!=host->prev_cs) {
  438. const int apbclk=APB_CLK_FREQ;
  439. int effclk=dev->clk_cfg.eff_clk;
  440. spi_set_clock(host->hw, dev->clk_cfg.reg);
  441. //Configure bit order
  442. host->hw->ctrl.rd_bit_order=(dev->cfg.flags & SPI_DEVICE_RXBIT_LSBFIRST)?1:0;
  443. host->hw->ctrl.wr_bit_order=(dev->cfg.flags & SPI_DEVICE_TXBIT_LSBFIRST)?1:0;
  444. //Configure polarity
  445. //SPI iface needs to be configured for a delay in some cases.
  446. int nodelay=0;
  447. if (host->no_gpio_matrix) {
  448. if (effclk >= apbclk/2) {
  449. nodelay=1;
  450. }
  451. } else {
  452. uint32_t delay_limit = apbclk/4;
  453. if (effclk >= delay_limit) {
  454. nodelay=1;
  455. }
  456. }
  457. if (dev->cfg.mode==0) {
  458. host->hw->pin.ck_idle_edge=0;
  459. host->hw->user.ck_out_edge=0;
  460. host->hw->ctrl2.miso_delay_mode=nodelay?0:2;
  461. } else if (dev->cfg.mode==1) {
  462. host->hw->pin.ck_idle_edge=0;
  463. host->hw->user.ck_out_edge=1;
  464. host->hw->ctrl2.miso_delay_mode=nodelay?0:1;
  465. } else if (dev->cfg.mode==2) {
  466. host->hw->pin.ck_idle_edge=1;
  467. host->hw->user.ck_out_edge=1;
  468. host->hw->ctrl2.miso_delay_mode=nodelay?0:1;
  469. } else if (dev->cfg.mode==3) {
  470. host->hw->pin.ck_idle_edge=1;
  471. host->hw->user.ck_out_edge=0;
  472. host->hw->ctrl2.miso_delay_mode=nodelay?0:2;
  473. }
  474. //Configure misc stuff
  475. host->hw->user.doutdin=(dev->cfg.flags & SPI_DEVICE_HALFDUPLEX)?0:1;
  476. host->hw->user.sio=(dev->cfg.flags & SPI_DEVICE_3WIRE)?1:0;
  477. host->hw->ctrl2.setup_time=dev->cfg.cs_ena_pretrans-1;
  478. host->hw->user.cs_setup=dev->cfg.cs_ena_pretrans?1:0;
  479. host->hw->ctrl2.hold_time=dev->cfg.cs_ena_posttrans-1;
  480. host->hw->user.cs_hold=(dev->cfg.cs_ena_posttrans)?1:0;
  481. //Configure CS pin
  482. host->hw->pin.cs0_dis=(i==0)?0:1;
  483. host->hw->pin.cs1_dis=(i==1)?0:1;
  484. host->hw->pin.cs2_dis=(i==2)?0:1;
  485. }
  486. host->prev_cs = i;
  487. //Reset SPI peripheral
  488. host->hw->dma_conf.val |= SPI_OUT_RST|SPI_IN_RST|SPI_AHBM_RST|SPI_AHBM_FIFO_RST;
  489. host->hw->dma_out_link.start=0;
  490. host->hw->dma_in_link.start=0;
  491. host->hw->dma_conf.val &= ~(SPI_OUT_RST|SPI_IN_RST|SPI_AHBM_RST|SPI_AHBM_FIFO_RST);
  492. host->hw->dma_conf.out_data_burst_en=1;
  493. //Set up QIO/DIO if needed
  494. host->hw->ctrl.val &= ~(SPI_FREAD_DUAL|SPI_FREAD_QUAD|SPI_FREAD_DIO|SPI_FREAD_QIO);
  495. host->hw->user.val &= ~(SPI_FWRITE_DUAL|SPI_FWRITE_QUAD|SPI_FWRITE_DIO|SPI_FWRITE_QIO);
  496. if (trans->flags & SPI_TRANS_MODE_DIO) {
  497. if (trans->flags & SPI_TRANS_MODE_DIOQIO_ADDR) {
  498. host->hw->ctrl.fread_dio=1;
  499. host->hw->user.fwrite_dio=1;
  500. } else {
  501. host->hw->ctrl.fread_dual=1;
  502. host->hw->user.fwrite_dual=1;
  503. }
  504. host->hw->ctrl.fastrd_mode=1;
  505. } else if (trans->flags & SPI_TRANS_MODE_QIO) {
  506. if (trans->flags & SPI_TRANS_MODE_DIOQIO_ADDR) {
  507. host->hw->ctrl.fread_qio=1;
  508. host->hw->user.fwrite_qio=1;
  509. } else {
  510. host->hw->ctrl.fread_quad=1;
  511. host->hw->user.fwrite_quad=1;
  512. }
  513. host->hw->ctrl.fastrd_mode=1;
  514. }
  515. //Fill DMA descriptors
  516. int extra_dummy=0;
  517. if (trans_buf->buffer_to_rcv) {
  518. host->hw->user.usr_miso_highpart=0;
  519. if (host->dma_chan == 0) {
  520. //No need to setup anything; we'll copy the result out of the work registers directly later.
  521. } else {
  522. spicommon_dmaworkaround_transfer_active(host->dma_chan); //mark channel as active
  523. spicommon_setup_dma_desc_links(host->dmadesc_rx, ((trans->rxlength+7)/8), (uint8_t*)trans_buf->buffer_to_rcv, true);
  524. host->hw->dma_in_link.addr=(int)(&host->dmadesc_rx[0]) & 0xFFFFF;
  525. host->hw->dma_in_link.start=1;
  526. }
  527. //when no_dummy is not set and in half-duplex mode, sets the dummy bit if RX phase exist
  528. if (((dev->cfg.flags&SPI_DEVICE_NO_DUMMY)==0) && (dev->cfg.flags&SPI_DEVICE_HALFDUPLEX)) {
  529. extra_dummy=dev->clk_cfg.dummy_num;
  530. }
  531. } else {
  532. //DMA temporary workaround: let RX DMA work somehow to avoid the issue in ESP32 v0/v1 silicon
  533. if (host->dma_chan != 0 ) {
  534. host->hw->dma_in_link.addr=0;
  535. host->hw->dma_in_link.start=1;
  536. }
  537. }
  538. if (trans_buf->buffer_to_send) {
  539. if (host->dma_chan == 0) {
  540. //Need to copy data to registers manually
  541. for (int x=0; x < trans->length; x+=32) {
  542. //Use memcpy to get around alignment issues for txdata
  543. uint32_t word;
  544. memcpy(&word, &trans_buf->buffer_to_send[x/32], 4);
  545. host->hw->data_buf[(x/32)+8]=word;
  546. }
  547. host->hw->user.usr_mosi_highpart=1;
  548. } else {
  549. spicommon_dmaworkaround_transfer_active(host->dma_chan); //mark channel as active
  550. spicommon_setup_dma_desc_links(host->dmadesc_tx, (trans->length+7)/8, (uint8_t*)trans_buf->buffer_to_send, false);
  551. host->hw->user.usr_mosi_highpart=0;
  552. host->hw->dma_out_link.addr=(int)(&host->dmadesc_tx[0]) & 0xFFFFF;
  553. host->hw->dma_out_link.start=1;
  554. host->hw->user.usr_mosi_highpart=0;
  555. }
  556. }
  557. //configure dummy bits
  558. host->hw->user.usr_dummy=(dev->cfg.dummy_bits+extra_dummy)?1:0;
  559. host->hw->user1.usr_dummy_cyclelen=dev->cfg.dummy_bits+extra_dummy-1;
  560. host->hw->mosi_dlen.usr_mosi_dbitlen=trans->length-1;
  561. if ( dev->cfg.flags & SPI_DEVICE_HALFDUPLEX ) {
  562. host->hw->miso_dlen.usr_miso_dbitlen=trans->rxlength-1;
  563. } else {
  564. //rxlength is not used in full-duplex mode
  565. host->hw->miso_dlen.usr_miso_dbitlen=trans->length-1;
  566. }
  567. //Configure bit sizes, load addr and command
  568. int cmdlen;
  569. if ( trans->flags & SPI_TRANS_VARIABLE_CMD ) {
  570. cmdlen = ((spi_transaction_ext_t*)trans)->command_bits;
  571. } else {
  572. cmdlen = dev->cfg.command_bits;
  573. }
  574. int addrlen;
  575. if ( trans->flags & SPI_TRANS_VARIABLE_ADDR ) {
  576. addrlen = ((spi_transaction_ext_t*)trans)->address_bits;
  577. } else {
  578. addrlen = dev->cfg.address_bits;
  579. }
  580. host->hw->user1.usr_addr_bitlen=addrlen-1;
  581. host->hw->user2.usr_command_bitlen=cmdlen-1;
  582. host->hw->user.usr_addr=addrlen?1:0;
  583. host->hw->user.usr_command=cmdlen?1:0;
  584. // output command will be sent from bit 7 to 0 of command_value, and then bit 15 to 8 of the same register field.
  585. uint16_t command = trans->cmd << (16-cmdlen); //shift to MSB
  586. host->hw->user2.usr_command_value = (command>>8)|(command<<8); //swap the first and second byte
  587. // shift the address to MSB of addr (and maybe slv_wr_status) register.
  588. // output address will be sent from MSB to LSB of addr register, then comes the MSB to LSB of slv_wr_status register.
  589. if (addrlen>32) {
  590. host->hw->addr = trans->addr >> (addrlen- 32);
  591. host->hw->slv_wr_status = trans->addr << (64 - addrlen);
  592. } else {
  593. host->hw->addr = trans->addr << (32 - addrlen);
  594. }
  595. host->hw->user.usr_mosi=( (!(dev->cfg.flags & SPI_DEVICE_HALFDUPLEX) && trans_buf->buffer_to_rcv) || trans_buf->buffer_to_send)?1:0;
  596. host->hw->user.usr_miso=(trans_buf->buffer_to_rcv)?1:0;
  597. //Call pre-transmission callback, if any
  598. if (dev->cfg.pre_cb) dev->cfg.pre_cb(trans);
  599. //Kick off transfer
  600. host->hw->cmd.usr=1;
  601. }
  602. if (do_yield) portYIELD_FROM_ISR();
  603. }
  604. esp_err_t spi_device_queue_trans(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait)
  605. {
  606. esp_err_t ret = ESP_OK;
  607. BaseType_t r;
  608. SPI_CHECK(handle!=NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  609. //check transmission length
  610. SPI_CHECK((trans_desc->flags & SPI_TRANS_USE_RXDATA)==0 ||trans_desc->rxlength <= 32, "rxdata transfer > 32 bits without configured DMA", ESP_ERR_INVALID_ARG);
  611. SPI_CHECK((trans_desc->flags & SPI_TRANS_USE_TXDATA)==0 ||trans_desc->length <= 32, "txdata transfer > 32 bits without configured DMA", ESP_ERR_INVALID_ARG);
  612. SPI_CHECK(trans_desc->length <= handle->host->max_transfer_sz*8, "txdata transfer > host maximum", ESP_ERR_INVALID_ARG);
  613. SPI_CHECK(trans_desc->rxlength <= handle->host->max_transfer_sz*8, "rxdata transfer > host maximum", ESP_ERR_INVALID_ARG);
  614. SPI_CHECK((handle->cfg.flags & SPI_DEVICE_HALFDUPLEX) || trans_desc->rxlength <= trans_desc->length, "rx length > tx length in full duplex mode", ESP_ERR_INVALID_ARG);
  615. //check working mode
  616. SPI_CHECK(!((trans_desc->flags & (SPI_TRANS_MODE_DIO|SPI_TRANS_MODE_QIO)) && (handle->cfg.flags & SPI_DEVICE_3WIRE)), "incompatible iface params", ESP_ERR_INVALID_ARG);
  617. SPI_CHECK(!((trans_desc->flags & (SPI_TRANS_MODE_DIO|SPI_TRANS_MODE_QIO)) && (!(handle->cfg.flags & SPI_DEVICE_HALFDUPLEX))), "incompatible iface params", ESP_ERR_INVALID_ARG);
  618. SPI_CHECK( !(handle->cfg.flags & SPI_DEVICE_HALFDUPLEX) || handle->host->dma_chan == 0 || !(trans_desc->flags & SPI_TRANS_USE_RXDATA || trans_desc->rx_buffer != NULL)
  619. || !(trans_desc->flags & SPI_TRANS_USE_TXDATA || trans_desc->tx_buffer!=NULL), "SPI half duplex mode does not support using DMA with both MOSI and MISO phases.", ESP_ERR_INVALID_ARG );
  620. //In Full duplex mode, default rxlength to be the same as length, if not filled in.
  621. // set rxlength to length is ok, even when rx buffer=NULL
  622. if (trans_desc->rxlength==0 && !(handle->cfg.flags & SPI_DEVICE_HALFDUPLEX)) {
  623. trans_desc->rxlength=trans_desc->length;
  624. }
  625. spi_trans_priv trans_buf;
  626. memset( &trans_buf, 0, sizeof(spi_trans_priv) );
  627. trans_buf.trans = trans_desc;
  628. // rx memory assign
  629. if ( trans_desc->flags & SPI_TRANS_USE_RXDATA ) {
  630. trans_buf.buffer_to_rcv = (uint32_t*)&trans_desc->rx_data[0];
  631. } else {
  632. //if not use RXDATA neither rx_buffer, buffer_to_rcv assigned to NULL
  633. trans_buf.buffer_to_rcv = trans_desc->rx_buffer;
  634. }
  635. if ( trans_buf.buffer_to_rcv && handle->host->dma_chan && (!esp_ptr_dma_capable( trans_buf.buffer_to_rcv ) || ((int)trans_buf.buffer_to_rcv%4!=0)) ) {
  636. //if rxbuf in the desc not DMA-capable, malloc a new one. The rx buffer need to be length of multiples of 32 bits to avoid heap corruption.
  637. ESP_LOGV( SPI_TAG, "Allocate RX buffer for DMA" );
  638. trans_buf.buffer_to_rcv = heap_caps_malloc((trans_desc->rxlength+31)/8, MALLOC_CAP_DMA);
  639. if ( trans_buf.buffer_to_rcv==NULL ) {
  640. ret = ESP_ERR_NO_MEM;
  641. goto clean_up;
  642. }
  643. }
  644. const uint32_t *txdata;
  645. // tx memory assign
  646. if ( trans_desc->flags & SPI_TRANS_USE_TXDATA ) {
  647. txdata = (uint32_t*)&trans_desc->tx_data[0];
  648. } else {
  649. //if not use TXDATA neither tx_buffer, tx data assigned to NULL
  650. txdata = trans_desc->tx_buffer ;
  651. }
  652. if ( txdata && handle->host->dma_chan && !esp_ptr_dma_capable( txdata )) {
  653. //if txbuf in the desc not DMA-capable, malloc a new one
  654. ESP_LOGV( SPI_TAG, "Allocate TX buffer for DMA" );
  655. trans_buf.buffer_to_send = heap_caps_malloc((trans_desc->length+7)/8, MALLOC_CAP_DMA);
  656. if ( trans_buf.buffer_to_send==NULL ) {
  657. ret = ESP_ERR_NO_MEM;
  658. goto clean_up;
  659. }
  660. memcpy( trans_buf.buffer_to_send, txdata, (trans_desc->length+7)/8 );
  661. } else {
  662. // else use the original buffer (forced-conversion) or assign to NULL
  663. trans_buf.buffer_to_send = (uint32_t*)txdata;
  664. }
  665. #ifdef CONFIG_PM_ENABLE
  666. esp_pm_lock_acquire(handle->host->pm_lock);
  667. #endif
  668. r=xQueueSend(handle->trans_queue, (void*)&trans_buf, ticks_to_wait);
  669. if (!r) {
  670. ret = ESP_ERR_TIMEOUT;
  671. #ifdef CONFIG_PM_ENABLE
  672. //Release APB frequency lock
  673. esp_pm_lock_release(handle->host->pm_lock);
  674. #endif
  675. goto clean_up;
  676. }
  677. esp_intr_enable(handle->host->intr);
  678. return ESP_OK;
  679. clean_up:
  680. // free malloc-ed buffer (if needed) before return.
  681. if ( (void*)trans_buf.buffer_to_rcv != trans_desc->rx_buffer && (void*)trans_buf.buffer_to_rcv != &trans_desc->rx_data[0] ) {
  682. free( trans_buf.buffer_to_rcv );
  683. }
  684. if ( (void*)trans_buf.buffer_to_send!= trans_desc->tx_buffer && (void*)trans_buf.buffer_to_send != &trans_desc->tx_data[0] ) {
  685. free( trans_buf.buffer_to_send );
  686. }
  687. assert( ret != ESP_OK );
  688. return ret;
  689. }
  690. esp_err_t spi_device_get_trans_result(spi_device_handle_t handle, spi_transaction_t **trans_desc, TickType_t ticks_to_wait)
  691. {
  692. BaseType_t r;
  693. spi_trans_priv trans_buf;
  694. SPI_CHECK(handle!=NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  695. r=xQueueReceive(handle->ret_queue, (void*)&trans_buf, ticks_to_wait);
  696. if (!r) {
  697. // The memory occupied by rx and tx DMA buffer destroyed only when receiving from the queue (transaction finished).
  698. // If timeout, wait and retry.
  699. // Every on-flight transaction request occupies internal memory as DMA buffer if needed.
  700. return ESP_ERR_TIMEOUT;
  701. }
  702. (*trans_desc) = trans_buf.trans;
  703. if ( (void*)trans_buf.buffer_to_send != &(*trans_desc)->tx_data[0] && trans_buf.buffer_to_send != (*trans_desc)->tx_buffer ) {
  704. free( trans_buf.buffer_to_send );
  705. }
  706. //copy data from temporary DMA-capable buffer back to IRAM buffer and free the temporary one.
  707. if ( (void*)trans_buf.buffer_to_rcv != &(*trans_desc)->rx_data[0] && trans_buf.buffer_to_rcv != (*trans_desc)->rx_buffer ) {
  708. if ( (*trans_desc)->flags & SPI_TRANS_USE_RXDATA ) {
  709. memcpy( (uint8_t*)&(*trans_desc)->rx_data[0], trans_buf.buffer_to_rcv, ((*trans_desc)->rxlength+7)/8 );
  710. } else {
  711. memcpy( (*trans_desc)->rx_buffer, trans_buf.buffer_to_rcv, ((*trans_desc)->rxlength+7)/8 );
  712. }
  713. free( trans_buf.buffer_to_rcv );
  714. }
  715. return ESP_OK;
  716. }
  717. //Porcelain to do one blocking transmission.
  718. esp_err_t spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc)
  719. {
  720. esp_err_t ret;
  721. spi_transaction_t *ret_trans;
  722. //ToDo: check if any spi transfers in flight
  723. ret=spi_device_queue_trans(handle, trans_desc, portMAX_DELAY);
  724. if (ret!=ESP_OK) return ret;
  725. ret=spi_device_get_trans_result(handle, &ret_trans, portMAX_DELAY);
  726. if (ret!=ESP_OK) return ret;
  727. assert(ret_trans==trans_desc);
  728. return ESP_OK;
  729. }