spi_master.c 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. // Copyright 2015-2019 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. /*
  15. Architecture:
  16. We can initialize a SPI driver, but we don't talk to the SPI driver itself, we address a device. A device essentially
  17. is a combination of SPI port and CS pin, plus some information about the specifics of communication to the device
  18. (timing, command/address length etc). The arbitration between tasks is also in conception of devices.
  19. A device can work in interrupt mode and polling mode, and a third but
  20. complicated mode which combines the two modes above:
  21. 1. Work in the ISR with a set of queues; one per device.
  22. The idea is that to send something to a SPI device, you allocate a
  23. transaction descriptor. It contains some information about the transfer
  24. like the lenghth, address, command etc, plus pointers to transmit and
  25. receive buffer. The address of this block gets pushed into the transmit
  26. queue. The SPI driver does its magic, and sends and retrieves the data
  27. eventually. The data gets written to the receive buffers, if needed the
  28. transaction descriptor is modified to indicate returned parameters and
  29. the entire thing goes into the return queue, where whatever software
  30. initiated the transaction can retrieve it.
  31. The entire thing is run from the SPI interrupt handler. If SPI is done
  32. transmitting/receiving but nothing is in the queue, it will not clear the
  33. SPI interrupt but just disable it by esp_intr_disable. This way, when a
  34. new thing is sent, pushing the packet into the send queue and re-enabling
  35. the interrupt (by esp_intr_enable) will trigger the interrupt again, which
  36. can then take care of the sending.
  37. 2. Work in the polling mode in the task.
  38. In this mode we get rid of the ISR, FreeRTOS queue and task switching, the
  39. task is no longer blocked during a transaction. This increase the cpu
  40. load, but decrease the interval of SPI transactions. Each time only one
  41. device (in one task) can send polling transactions, transactions to
  42. other devices are blocked until the polling transaction of current device
  43. is done.
  44. In the polling mode, the queue is not used, all the operations are done
  45. in the task. The task calls ``spi_device_polling_start`` to setup and start
  46. a new transaction, then call ``spi_device_polling_end`` to handle the
  47. return value of the transaction.
  48. To handle the arbitration among devices, the device "temporarily" acquire
  49. a bus by the ``device_acquire_bus_internal`` function, which writes
  50. acquire_cs by CAS operation. Other devices which wants to send polling
  51. transactions but don't own the bus will block and wait until given the
  52. semaphore which indicates the ownership of bus.
  53. In case of the ISR is still sending transactions to other devices, the ISR
  54. should maintain an ``isr_free`` flag indicating that it's not doing
  55. transactions. When the bus is acquired, the ISR can only send new
  56. transactions to the acquiring device. The ISR will automatically disable
  57. itself and send semaphore to the device if the ISR is free. If the device
  58. sees the isr_free flag, it can directly start its polling transaction.
  59. Otherwise it should block and wait for the semaphore from the ISR.
  60. After the polling transaction, the driver will release the bus. During the
  61. release of the bus, the driver search all other devices to see whether
  62. there is any device waiting to acquire the bus, if so, acquire for it and
  63. send it a semaphore if the device queue is empty, or invoke the ISR for
  64. it. If all other devices don't need to acquire the bus, but there are
  65. still transactions in the queues, the ISR will also be invoked.
  66. To get better polling efficiency, user can call ``spi_device_acquire_bus``
  67. function, which also calls the ``device_acquire_bus_internal`` function,
  68. before a series of polling transactions to a device. The bus acquiring and
  69. task switching before and after the polling transaction will be escaped.
  70. 3. Mixed mode
  71. The driver is written under the assumption that polling and interrupt
  72. transactions are not happening simultaneously. When sending polling
  73. transactions, it will check whether the ISR is active, which includes the
  74. case the ISR is sending the interrupt transactions of the acquiring
  75. device. If the ISR is still working, the routine sending a polling
  76. transaction will get blocked and wait until the semaphore from the ISR
  77. which indicates the ISR is free now.
  78. A fatal case is, a polling transaction is in flight, but the ISR received
  79. an interrupt transaction. The behavior of the driver is unpredictable,
  80. which should be strictly forbidden.
  81. We have two bits to control the interrupt:
  82. 1. The slave->trans_done bit, which is automatically asserted when a transaction is done.
  83. This bit is cleared during an interrupt transaction, so that the interrupt
  84. will be triggered when the transaction is done, or the SW can check the
  85. bit to see if the transaction is done for polling transactions.
  86. When no transaction is in-flight, the bit is kept active, so that the SW
  87. can easily invoke the ISR by enable the interrupt.
  88. 2. The system interrupt enable/disable, controlled by esp_intr_enable and esp_intr_disable.
  89. The interrupt is disabled (by the ISR itself) when no interrupt transaction
  90. is queued. When the bus is not occupied, any task, which queues a
  91. transaction into the queue, will enable the interrupt to invoke the ISR.
  92. When the bus is occupied by a device, other device will put off the
  93. invoking of ISR to the moment when the bus is released. The device
  94. acquiring the bus can still send interrupt transactions by enable the
  95. interrupt.
  96. */
  97. #include <string.h>
  98. #include "driver/spi_common_internal.h"
  99. #include "driver/spi_master.h"
  100. #include "soc/spi_periph.h"
  101. #include "esp32/rom/ets_sys.h"
  102. #include "esp_types.h"
  103. #include "esp_attr.h"
  104. #include "esp_intr_alloc.h"
  105. #include "esp_log.h"
  106. #include "esp_err.h"
  107. #include "esp_pm.h"
  108. #include "freertos/FreeRTOS.h"
  109. #include "freertos/semphr.h"
  110. #include "freertos/xtensa_api.h"
  111. #include "freertos/task.h"
  112. #include "soc/soc_memory_layout.h"
  113. #include "esp32/rom/lldesc.h"
  114. #include "driver/gpio.h"
  115. #include "esp_heap_caps.h"
  116. #include "stdatomic.h"
  117. #include "sdkconfig.h"
  118. #include "hal/spi_hal.h"
  119. typedef struct spi_device_t spi_device_t;
  120. #define NO_CS 3 //Number of CS pins per SPI host
  121. #ifdef CONFIG_SPI_MASTER_ISR_IN_IRAM
  122. #define SPI_MASTER_ISR_ATTR IRAM_ATTR
  123. #else
  124. #define SPI_MASTER_ISR_ATTR
  125. #endif
  126. #ifdef CONFIG_SPI_MASTER_IN_IRAM
  127. #define SPI_MASTER_ATTR IRAM_ATTR
  128. #else
  129. #define SPI_MASTER_ATTR
  130. #endif
  131. /// struct to hold private transaction data (like tx and rx buffer for DMA).
  132. typedef struct {
  133. spi_transaction_t *trans;
  134. const 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;
  135. //otherwise sets to the original buffer or NULL if no buffer is assigned.
  136. uint32_t *buffer_to_rcv; // similar to buffer_to_send
  137. } spi_trans_priv_t;
  138. typedef struct {
  139. int id;
  140. _Atomic(spi_device_t*) device[NO_CS];
  141. intr_handle_t intr;
  142. spi_hal_context_t hal;
  143. spi_trans_priv_t cur_trans_buf;
  144. int cur_cs; //current device doing transaction
  145. int prev_cs; //last device doing transaction, used to avoid re-configure registers if the device not changed
  146. atomic_int acquire_cs; //the device acquiring the bus, NO_CS if no one is doing so.
  147. bool polling; //in process of a polling, avoid of queue new transactions into ISR
  148. bool isr_free; //the isr is not sending transactions
  149. bool bus_locked;//the bus is controlled by a device
  150. uint32_t flags;
  151. int dma_chan;
  152. int max_transfer_sz;
  153. spi_bus_config_t bus_cfg;
  154. #ifdef CONFIG_PM_ENABLE
  155. esp_pm_lock_handle_t pm_lock;
  156. #endif
  157. } spi_host_t;
  158. struct spi_device_t {
  159. int id;
  160. QueueHandle_t trans_queue;
  161. QueueHandle_t ret_queue;
  162. spi_device_interface_config_t cfg;
  163. spi_hal_timing_conf_t timing_conf;
  164. spi_host_t *host;
  165. SemaphoreHandle_t semphr_polling; //semaphore to notify the device it claimed the bus
  166. bool waiting; //the device is waiting for the exclusive control of the bus
  167. };
  168. static spi_host_t *spihost[SOC_SPI_PERIPH_NUM];
  169. static const char *SPI_TAG = "spi_master";
  170. #define SPI_CHECK(a, str, ret_val, ...) \
  171. if (!(a)) { \
  172. ESP_LOGE(SPI_TAG,"%s(%d): "str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
  173. return (ret_val); \
  174. }
  175. static void spi_intr(void *arg);
  176. esp_err_t spi_bus_initialize(spi_host_device_t host, const spi_bus_config_t *bus_config, int dma_chan)
  177. {
  178. bool spi_chan_claimed, dma_chan_claimed;
  179. esp_err_t ret = ESP_OK;
  180. esp_err_t err;
  181. /* ToDo: remove this when we have flash operations cooperating with this */
  182. SPI_CHECK(host!=SPI_HOST, "SPI1 is not supported", ESP_ERR_NOT_SUPPORTED);
  183. SPI_CHECK(host>=SPI_HOST && host<=VSPI_HOST, "invalid host", ESP_ERR_INVALID_ARG);
  184. SPI_CHECK( dma_chan >= 0 && dma_chan <= 2, "invalid dma channel", ESP_ERR_INVALID_ARG );
  185. SPI_CHECK((bus_config->intr_flags & (ESP_INTR_FLAG_HIGH|ESP_INTR_FLAG_EDGE|ESP_INTR_FLAG_INTRDISABLED))==0, "intr flag not allowed", ESP_ERR_INVALID_ARG);
  186. #ifndef CONFIG_SPI_MASTER_ISR_IN_IRAM
  187. SPI_CHECK((bus_config->intr_flags & ESP_INTR_FLAG_IRAM)==0, "ESP_INTR_FLAG_IRAM should be disabled when CONFIG_SPI_MASTER_ISR_IN_IRAM is not set.", ESP_ERR_INVALID_ARG);
  188. #endif
  189. spi_chan_claimed=spicommon_periph_claim(host, "spi master");
  190. SPI_CHECK(spi_chan_claimed, "host already in use", ESP_ERR_INVALID_STATE);
  191. if ( dma_chan != 0 ) {
  192. dma_chan_claimed=spicommon_dma_chan_claim(dma_chan);
  193. if ( !dma_chan_claimed ) {
  194. spicommon_periph_free( host );
  195. SPI_CHECK(false, "dma channel already in use", ESP_ERR_INVALID_STATE);
  196. }
  197. }
  198. // spihost contains atomic variables, which should not be put in PSRAM
  199. spihost[host] = heap_caps_malloc(sizeof(spi_host_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  200. if (spihost[host]==NULL) {
  201. ret = ESP_ERR_NO_MEM;
  202. goto cleanup;
  203. }
  204. memset(spihost[host], 0, sizeof(spi_host_t));
  205. memcpy( &spihost[host]->bus_cfg, bus_config, sizeof(spi_bus_config_t));
  206. #ifdef CONFIG_PM_ENABLE
  207. err = esp_pm_lock_create(ESP_PM_APB_FREQ_MAX, 0, "spi_master",
  208. &spihost[host]->pm_lock);
  209. if (err != ESP_OK) {
  210. ret = err;
  211. goto cleanup;
  212. }
  213. #endif //CONFIG_PM_ENABLE
  214. err = spicommon_bus_initialize_io(host, bus_config, dma_chan, SPICOMMON_BUSFLAG_MASTER|bus_config->flags, &spihost[host]->flags);
  215. if (err != ESP_OK) {
  216. ret = err;
  217. goto cleanup;
  218. }
  219. int dma_desc_ct=0;
  220. spihost[host]->dma_chan=dma_chan;
  221. if (dma_chan == 0) {
  222. spihost[host]->max_transfer_sz = SOC_SPI_MAXIMUM_BUFFER_SIZE;
  223. } else {
  224. //See how many dma descriptors we need and allocate them
  225. dma_desc_ct=lldesc_get_required_num(bus_config->max_transfer_sz);
  226. if (dma_desc_ct==0) dma_desc_ct = 1; //default to 4k when max is not given
  227. spihost[host]->max_transfer_sz = dma_desc_ct*LLDESC_MAX_NUM_PER_DESC;
  228. }
  229. int flags = bus_config->intr_flags | ESP_INTR_FLAG_INTRDISABLED;
  230. err = esp_intr_alloc(spicommon_irqsource_for_host(host), flags, spi_intr, (void*)spihost[host], &spihost[host]->intr);
  231. if (err != ESP_OK) {
  232. ret = err;
  233. goto cleanup;
  234. }
  235. spihost[host]->id = host;
  236. spihost[host]->cur_cs = NO_CS;
  237. spihost[host]->prev_cs = NO_CS;
  238. atomic_store(&spihost[host]->acquire_cs, NO_CS);
  239. spihost[host]->polling = false;
  240. spihost[host]->isr_free = true;
  241. spihost[host]->bus_locked = false;
  242. spi_hal_init(&spihost[host]->hal, host);
  243. spihost[host]->hal.dma_enabled = (dma_chan!=0);
  244. if (dma_desc_ct) {
  245. spihost[host]->hal.dmadesc_tx=heap_caps_malloc(sizeof(lldesc_t) * dma_desc_ct, MALLOC_CAP_DMA);
  246. spihost[host]->hal.dmadesc_rx=heap_caps_malloc(sizeof(lldesc_t) * dma_desc_ct, MALLOC_CAP_DMA);
  247. if (!spihost[host]->hal.dmadesc_tx || !spihost[host]->hal.dmadesc_rx) {
  248. ret = ESP_ERR_NO_MEM;
  249. goto cleanup;
  250. }
  251. }
  252. spihost[host]->hal.dmadesc_n = dma_desc_ct;
  253. return ESP_OK;
  254. cleanup:
  255. if (spihost[host]) {
  256. spi_hal_deinit(&spihost[host]->hal);
  257. #ifdef CONFIG_PM_ENABLE
  258. if (spihost[host]->pm_lock) {
  259. esp_pm_lock_delete(spihost[host]->pm_lock);
  260. }
  261. #endif
  262. free(spihost[host]->hal.dmadesc_rx);
  263. free(spihost[host]->hal.dmadesc_tx);
  264. }
  265. free(spihost[host]);
  266. spihost[host] = NULL;
  267. spicommon_periph_free(host);
  268. if (dma_chan != 0) spicommon_dma_chan_free(dma_chan);
  269. return ret;
  270. }
  271. esp_err_t spi_bus_free(spi_host_device_t host)
  272. {
  273. int x;
  274. SPI_CHECK(host>=SPI_HOST && host<=VSPI_HOST, "invalid host", ESP_ERR_INVALID_ARG);
  275. SPI_CHECK(spihost[host]!=NULL, "host not in use", ESP_ERR_INVALID_STATE);
  276. for (x=0; x<NO_CS; x++) {
  277. SPI_CHECK(atomic_load(&spihost[host]->device[x])==NULL, "not all CSses freed", ESP_ERR_INVALID_STATE);
  278. }
  279. spicommon_bus_free_io_cfg(&spihost[host]->bus_cfg);
  280. if ( spihost[host]->dma_chan > 0 ) {
  281. spicommon_dma_chan_free ( spihost[host]->dma_chan );
  282. }
  283. #ifdef CONFIG_PM_ENABLE
  284. esp_pm_lock_delete(spihost[host]->pm_lock);
  285. #endif
  286. spi_hal_deinit(&spihost[host]->hal);
  287. free(spihost[host]->hal.dmadesc_rx);
  288. free(spihost[host]->hal.dmadesc_tx);
  289. esp_intr_free(spihost[host]->intr);
  290. spicommon_periph_free(host);
  291. free(spihost[host]);
  292. spihost[host]=NULL;
  293. return ESP_OK;
  294. }
  295. void spi_get_timing(bool gpio_is_used, int input_delay_ns, int eff_clk, int* dummy_o, int* cycles_remain_o)
  296. {
  297. int timing_dummy;
  298. int timing_miso_delay;
  299. spi_hal_cal_timing(eff_clk, gpio_is_used, input_delay_ns, &timing_dummy, &timing_miso_delay);
  300. if (dummy_o) *dummy_o = timing_dummy;
  301. if (cycles_remain_o) *cycles_remain_o = timing_miso_delay;
  302. }
  303. int spi_get_freq_limit(bool gpio_is_used, int input_delay_ns)
  304. {
  305. return spi_hal_get_freq_limit(gpio_is_used, input_delay_ns);
  306. }
  307. /*
  308. Add a device. This allocates a CS line for the device, allocates memory for the device structure and hooks
  309. up the CS pin to whatever is specified.
  310. */
  311. 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)
  312. {
  313. int freecs;
  314. int duty_cycle;
  315. SPI_CHECK(host>=SPI_HOST && host<=VSPI_HOST, "invalid host", ESP_ERR_INVALID_ARG);
  316. SPI_CHECK(spihost[host]!=NULL, "host not initialized", ESP_ERR_INVALID_STATE);
  317. 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);
  318. SPI_CHECK(dev_config->clock_speed_hz > 0, "invalid sclk speed", ESP_ERR_INVALID_ARG);
  319. for (freecs=0; freecs<NO_CS; freecs++) {
  320. //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.
  321. void* null=NULL;
  322. if (atomic_compare_exchange_strong(&spihost[host]->device[freecs], &null, (spi_device_t *)1)) break;
  323. }
  324. SPI_CHECK(freecs!=NO_CS, "no free cs pins for host", ESP_ERR_NOT_FOUND);
  325. //The hardware looks like it would support this, but actually setting cs_ena_pretrans when transferring in full
  326. //duplex mode does absolutely nothing on the ESP32.
  327. SPI_CHECK( dev_config->cs_ena_pretrans <= 1 || (dev_config->address_bits == 0 && dev_config->command_bits == 0) ||
  328. (dev_config->flags & SPI_DEVICE_HALFDUPLEX), "In full-duplex mode, only support cs pretrans delay = 1 and without address_bits and command_bits", ESP_ERR_INVALID_ARG);
  329. duty_cycle = (dev_config->duty_cycle_pos==0) ? 128 : dev_config->duty_cycle_pos;
  330. int freq;
  331. spi_hal_context_t *hal = &spihost[host]->hal;
  332. hal->half_duplex = dev_config->flags & SPI_DEVICE_HALFDUPLEX ? 1 : 0;
  333. hal->no_compensate = dev_config->flags & SPI_DEVICE_NO_DUMMY ? 1 : 0;
  334. spi_hal_timing_conf_t temp_timing_conf;
  335. esp_err_t ret = spi_hal_get_clock_conf(hal, dev_config->clock_speed_hz, duty_cycle,
  336. !(spihost[host]->flags & SPICOMMON_BUSFLAG_IOMUX_PINS),
  337. dev_config->input_delay_ns, &freq,
  338. &temp_timing_conf);
  339. SPI_CHECK(ret==ESP_OK, "assigned clock speed not supported", ret);
  340. //Allocate memory for device
  341. spi_device_t *dev=malloc(sizeof(spi_device_t));
  342. if (dev==NULL) goto nomem;
  343. memset(dev, 0, sizeof(spi_device_t));
  344. atomic_store(&spihost[host]->device[freecs], dev);
  345. dev->id = freecs;
  346. dev->waiting = false;
  347. dev->timing_conf = temp_timing_conf;
  348. //Allocate queues, set defaults
  349. dev->trans_queue = xQueueCreate(dev_config->queue_size, sizeof(spi_trans_priv_t));
  350. dev->ret_queue = xQueueCreate(dev_config->queue_size, sizeof(spi_trans_priv_t));
  351. dev->semphr_polling = xSemaphoreCreateBinary();
  352. if (!dev->trans_queue || !dev->ret_queue || !dev->semphr_polling) {
  353. goto nomem;
  354. }
  355. dev->host=spihost[host];
  356. //We want to save a copy of the dev config in the dev struct.
  357. memcpy(&dev->cfg, dev_config, sizeof(spi_device_interface_config_t));
  358. dev->cfg.duty_cycle_pos = duty_cycle;
  359. // TODO: if we have to change the apb clock among transactions, re-calculate this each time the apb clock lock is acquired.
  360. //Set CS pin, CS options
  361. if (dev_config->spics_io_num >= 0) {
  362. spicommon_cs_initialize(host, dev_config->spics_io_num, freecs, !(spihost[host]->flags&SPICOMMON_BUSFLAG_IOMUX_PINS));
  363. }
  364. *handle=dev;
  365. ESP_LOGD(SPI_TAG, "SPI%d: New device added to CS%d, effective clock: %dkHz", host+1, freecs, freq/1000);
  366. return ESP_OK;
  367. nomem:
  368. if (dev) {
  369. if (dev->trans_queue) vQueueDelete(dev->trans_queue);
  370. if (dev->ret_queue) vQueueDelete(dev->ret_queue);
  371. if (dev->semphr_polling) vSemaphoreDelete(dev->semphr_polling);
  372. }
  373. free(dev);
  374. return ESP_ERR_NO_MEM;
  375. }
  376. esp_err_t spi_bus_remove_device(spi_device_handle_t handle)
  377. {
  378. int x;
  379. SPI_CHECK(handle!=NULL, "invalid handle", ESP_ERR_INVALID_ARG);
  380. //These checks aren't exhaustive; another thread could sneak in a transaction inbetween. These are only here to
  381. //catch design errors and aren't meant to be triggered during normal operation.
  382. SPI_CHECK(uxQueueMessagesWaiting(handle->trans_queue)==0, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  383. SPI_CHECK(handle->host->cur_cs == NO_CS || atomic_load(&handle->host->device[handle->host->cur_cs])!=handle, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  384. SPI_CHECK(uxQueueMessagesWaiting(handle->ret_queue)==0, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  385. //return
  386. int spics_io_num = handle->cfg.spics_io_num;
  387. if (spics_io_num >= 0) spicommon_cs_free_io(spics_io_num);
  388. //Kill queues
  389. vQueueDelete(handle->trans_queue);
  390. vQueueDelete(handle->ret_queue);
  391. vSemaphoreDelete(handle->semphr_polling);
  392. //Remove device from list of csses and free memory
  393. for (x=0; x<NO_CS; x++) {
  394. if (atomic_load(&handle->host->device[x]) == handle){
  395. atomic_store(&handle->host->device[x], NULL);
  396. if (x == handle->host->prev_cs) handle->host->prev_cs = NO_CS;
  397. }
  398. }
  399. free(handle);
  400. return ESP_OK;
  401. }
  402. int spi_cal_clock(int fapb, int hz, int duty_cycle, uint32_t *reg_o)
  403. {
  404. return spi_ll_master_cal_clock(fapb, hz, duty_cycle, reg_o);
  405. }
  406. int spi_get_actual_clock(int fapb, int hz, int duty_cycle)
  407. {
  408. return spi_hal_master_cal_clock(fapb, hz, duty_cycle);
  409. }
  410. // Setup the device-specified configuration registers. Called every time a new
  411. // transaction is to be sent, but only apply new configurations when the device
  412. // changes.
  413. static void SPI_MASTER_ISR_ATTR spi_setup_device(spi_host_t *host, int dev_id)
  414. {
  415. //if the configuration is already applied, skip the following.
  416. if (dev_id == host->prev_cs) {
  417. return;
  418. }
  419. ESP_EARLY_LOGD(SPI_TAG, "SPI device changed from %d to %d", host->prev_cs, dev_id);
  420. spi_device_t *dev = atomic_load(&host->device[dev_id]);
  421. spi_hal_context_t *hal = &host->hal;
  422. hal->mode = dev->cfg.mode;
  423. hal->tx_lsbfirst = dev->cfg.flags & SPI_DEVICE_TXBIT_LSBFIRST ? 1 : 0;
  424. hal->rx_lsbfirst = dev->cfg.flags & SPI_DEVICE_RXBIT_LSBFIRST ? 1 : 0;
  425. hal->sio = dev->cfg.flags & SPI_DEVICE_3WIRE ? 1 : 0;
  426. hal->cs_setup = dev->cfg.cs_ena_pretrans;
  427. hal->cs_hold =dev->cfg.cs_ena_posttrans;
  428. //set hold_time to 0 will not actually append delay to CS
  429. //set it to 1 since we do need at least one clock of hold time in most cases
  430. if (hal->cs_hold == 0) hal->cs_hold = 1;
  431. hal->cs_pin_id = dev_id;
  432. hal->timing_conf = &dev->timing_conf;
  433. hal->half_duplex = dev->cfg.flags & SPI_DEVICE_HALFDUPLEX ? 1 : 0;
  434. #ifdef SOC_SPI_SUPPORT_AS_CS
  435. hal->as_cs = dev->cfg.flags & SPI_DEVICE_CLK_AS_CS ? 1 : 0;
  436. #endif
  437. hal->positive_cs = dev->cfg.flags & SPI_DEVICE_POSITIVE_CS ? 1 : 0;
  438. hal->no_compensate = dev->cfg.flags & SPI_DEVICE_NO_DUMMY ? 1 : 0;
  439. spi_hal_setup_device(hal);
  440. //Record the device just configured to save time for next time
  441. host->prev_cs = dev_id;
  442. }
  443. /*-----------------------------------------------------------------------------
  444. Arbitration Functions
  445. -----------------------------------------------------------------------------*/
  446. static inline void spi_isr_invoke(spi_device_t *dev)
  447. {
  448. int acquire_cs = atomic_load(&dev->host->acquire_cs);
  449. if (acquire_cs == dev->id || acquire_cs == NO_CS) {
  450. esp_intr_enable(dev->host->intr);
  451. }
  452. //otherwise wait for bus release to invoke
  453. }
  454. /* This function try to race for the arbitration between devices.
  455. * Even if this returns successfully, the ISR may be still running.
  456. * Call device_wait_for_isr_idle to make sure the ISR is done.
  457. */
  458. static SPI_MASTER_ISR_ATTR esp_err_t device_acquire_bus_internal(spi_device_t *handle, TickType_t wait)
  459. {
  460. spi_host_t *host = handle->host;
  461. SPI_CHECK(wait==portMAX_DELAY, "acquire finite time not supported now.", ESP_ERR_INVALID_ARG);
  462. if (atomic_load(&host->acquire_cs) == handle->id) {
  463. // Quickly skip if the bus is already acquired.
  464. // Usually this is only when the bus is locked.
  465. assert(host->bus_locked);
  466. return ESP_OK;
  467. } else {
  468. // Declare we are waiting for the bus so that if we get blocked later, other device or the ISR will yield to us after their using.
  469. handle->waiting = true;
  470. // Clear the semaphore before checking
  471. xSemaphoreTake(handle->semphr_polling, 0);
  472. int no_cs = NO_CS;
  473. atomic_compare_exchange_weak(&host->acquire_cs, &no_cs, handle->id);
  474. if (atomic_load(&host->acquire_cs) != handle->id) {
  475. //block until the bus is acquired (help by other task)
  476. BaseType_t ret = xSemaphoreTake(handle->semphr_polling, wait);
  477. //TODO: add timeout handling here.
  478. if (ret == pdFALSE) return ESP_ERR_TIMEOUT;
  479. }
  480. handle->waiting = false;
  481. }
  482. return ESP_OK;
  483. }
  484. /* This function check for whether the ISR is done, if not, block until semaphore given.
  485. */
  486. static inline SPI_MASTER_ISR_ATTR esp_err_t device_wait_for_isr_idle(spi_device_t *handle, TickType_t wait)
  487. {
  488. //quickly skip if the isr is already free
  489. if (!handle->host->isr_free) {
  490. // Clear the semaphore before checking
  491. xSemaphoreTake(handle->semphr_polling, 0);
  492. if (!handle->host->isr_free) {
  493. //block until the the isr is free and give us the semaphore
  494. BaseType_t ret = xSemaphoreTake(handle->semphr_polling, wait);
  495. //TODO: add timeout handling here.
  496. if (ret == pdFALSE) return ESP_ERR_TIMEOUT;
  497. }
  498. }
  499. return ESP_OK;
  500. }
  501. /* This function release the bus acquired by device_acquire_internal.
  502. And it also tries to help other device to acquire the bus.
  503. If the bus acquring is not needed, it goes through all device queues to see whether to invoke the ISR
  504. */
  505. static SPI_MASTER_ISR_ATTR void device_release_bus_internal(spi_host_t *host)
  506. {
  507. //release the bus
  508. atomic_store(&host->acquire_cs, NO_CS);
  509. //first try to restore the acquiring device
  510. for (int i = 0; i < NO_CS; i++) {
  511. //search for all registered devices
  512. spi_device_t* dev = atomic_load(&host->device[i]);
  513. if (dev && dev->waiting) {
  514. int no_cs = NO_CS;
  515. atomic_compare_exchange_weak(&host->acquire_cs, &no_cs, i);
  516. if (atomic_load(&host->acquire_cs) == i) {
  517. // Success to acquire for new device
  518. BaseType_t ret = uxQueueMessagesWaiting(dev->trans_queue);
  519. if (ret > 0) {
  520. // If there are transactions in the queue, the ISR should be invoked first
  521. // Resume the interrupt to send the task a signal
  522. spi_isr_invoke(dev);
  523. } else {
  524. // Otherwise resume the task directly.
  525. xSemaphoreGive(dev->semphr_polling);
  526. }
  527. }
  528. return;
  529. }
  530. }
  531. //if no devices waiting, searching in device queues to see whether to recover the ISR
  532. for( int i = 0; i < NO_CS; i++) {
  533. spi_device_t *dev = atomic_load(&host->device[i]);
  534. if (dev == NULL) continue;
  535. BaseType_t ret = uxQueueMessagesWaiting(dev->trans_queue);
  536. if ( ret != 0) {
  537. spi_isr_invoke(dev);
  538. return;
  539. }
  540. }
  541. }
  542. static inline SPI_MASTER_ISR_ATTR bool device_is_polling(spi_device_t *handle)
  543. {
  544. return atomic_load(&handle->host->acquire_cs) == handle->id && handle->host->polling;
  545. }
  546. /*-----------------------------------------------------------------------------
  547. Working Functions
  548. -----------------------------------------------------------------------------*/
  549. // The function is called to send a new transaction, in ISR or in the task.
  550. // Setup the transaction-specified registers and linked-list used by the DMA (or FIFO if DMA is not used)
  551. static void SPI_MASTER_ISR_ATTR spi_new_trans(spi_device_t *dev, spi_trans_priv_t *trans_buf, spi_hal_context_t *hal)
  552. {
  553. spi_transaction_t *trans = NULL;
  554. spi_host_t *host = dev->host;
  555. int dev_id = dev->id;
  556. trans = trans_buf->trans;
  557. host->cur_cs = dev_id;
  558. //Reconfigure according to device settings, the function only has effect when the dev_id is changed.
  559. spi_setup_device(host, dev_id);
  560. hal->tx_bitlen = trans->length;
  561. hal->rx_bitlen = trans->rxlength;
  562. hal->rcv_buffer = (uint8_t*)host->cur_trans_buf.buffer_to_rcv;
  563. hal->send_buffer = (uint8_t*)host->cur_trans_buf.buffer_to_send;
  564. hal->cmd = trans->cmd;
  565. hal->addr = trans->addr;
  566. //Set up QIO/DIO if needed
  567. hal->io_mode = (trans->flags & SPI_TRANS_MODE_DIO ?
  568. (trans->flags & SPI_TRANS_MODE_DIOQIO_ADDR ? SPI_LL_IO_MODE_DIO : SPI_LL_IO_MODE_DUAL) :
  569. (trans->flags & SPI_TRANS_MODE_QIO ?
  570. (trans->flags & SPI_TRANS_MODE_DIOQIO_ADDR ? SPI_LL_IO_MODE_QIO : SPI_LL_IO_MODE_QUAD) :
  571. SPI_LL_IO_MODE_NORMAL
  572. ));
  573. hal->tx_bitlen = trans->length;
  574. hal->rx_bitlen = trans->rxlength;
  575. if (trans->flags & SPI_TRANS_VARIABLE_CMD) {
  576. hal->cmd_bits = ((spi_transaction_ext_t *)trans)->command_bits;
  577. } else {
  578. hal->cmd_bits = dev->cfg.command_bits;
  579. }
  580. if (trans->flags & SPI_TRANS_VARIABLE_ADDR) {
  581. hal->addr_bits = ((spi_transaction_ext_t *)trans)->address_bits;
  582. } else {
  583. hal->addr_bits = dev->cfg.address_bits;
  584. }
  585. if (trans->flags & SPI_TRANS_VARIABLE_DUMMY) {
  586. hal->dummy_bits = ((spi_transaction_ext_t *)trans)->dummy_bits;
  587. } else {
  588. hal->dummy_bits = dev->cfg.dummy_bits;
  589. }
  590. spi_hal_setup_trans(hal);
  591. spi_hal_prepare_data(hal);
  592. //Call pre-transmission callback, if any
  593. if (dev->cfg.pre_cb) dev->cfg.pre_cb(trans);
  594. //Kick off transfer
  595. spi_hal_user_start(hal);
  596. }
  597. // The function is called when a transaction is done, in ISR or in the task.
  598. // Fetch the data from FIFO and call the ``post_cb``.
  599. static void SPI_MASTER_ISR_ATTR spi_post_trans(spi_host_t *host)
  600. {
  601. spi_transaction_t *cur_trans = host->cur_trans_buf.trans;
  602. spi_hal_fetch_result(&host->hal);
  603. //Call post-transaction callback, if any
  604. spi_device_t* dev = atomic_load(&host->device[host->cur_cs]);
  605. if (dev->cfg.post_cb) dev->cfg.post_cb(cur_trans);
  606. host->cur_cs = NO_CS;
  607. }
  608. // This is run in interrupt context.
  609. static void SPI_MASTER_ISR_ATTR spi_intr(void *arg)
  610. {
  611. int i;
  612. BaseType_t r;
  613. BaseType_t do_yield = pdFALSE;
  614. spi_host_t *host = (spi_host_t *)arg;
  615. assert(spi_hal_usr_is_done(&host->hal));
  616. /*------------ deal with the in-flight transaction -----------------*/
  617. if (host->cur_cs != NO_CS) {
  618. //Okay, transaction is done.
  619. const int cs = host->cur_cs;
  620. //Tell common code DMA workaround that our DMA channel is idle. If needed, the code will do a DMA reset.
  621. if (host->dma_chan) {
  622. spicommon_dmaworkaround_idle(host->dma_chan);
  623. }
  624. //cur_cs is changed to NO_CS here
  625. spi_post_trans(host);
  626. //Return transaction descriptor.
  627. xQueueSendFromISR(atomic_load(&host->device[cs])->ret_queue, &host->cur_trans_buf, &do_yield);
  628. #ifdef CONFIG_PM_ENABLE
  629. //Release APB frequency lock
  630. esp_pm_lock_release(host->pm_lock);
  631. #endif
  632. }
  633. /*------------ new transaction starts here ------------------*/
  634. assert(host->cur_cs == NO_CS);
  635. // Clear isr_free before the checking of acquire_cs so that the task will always block if we find the bus is not acquired.
  636. // Small possiblility that the task is blocked but we find the bus is acquired.
  637. host->isr_free = false;
  638. /* When the bus is not occupied, the task uses esp_intr_enable to inform the ISR there's new transaction.
  639. * If the queue is empty, we disable the system interrupt.
  640. * We disable this first, to avoid the conflict when the task enable and the ISR disable at the same time
  641. * If the transaction is sent (queue not empty), we will re-ebale it (see below).
  642. */
  643. esp_intr_disable( host->intr );
  644. int acquire_cs = atomic_load(&host->acquire_cs);
  645. if (acquire_cs != NO_CS) {
  646. // Only look in the queue of the occupying device.
  647. i = acquire_cs;
  648. spi_device_t* dev = atomic_load(&host->device[i]);
  649. assert(dev);
  650. r = xQueueReceiveFromISR(dev->trans_queue, &host->cur_trans_buf, &do_yield);
  651. // If the Queue is empty, skip the sending by setting i=NO_CS
  652. // Otherwise i is kept as is and the transaction will be sent.
  653. if (!r) {
  654. // Set the free to true before resume the task
  655. host->isr_free = true;
  656. xSemaphoreGiveFromISR(dev->semphr_polling, &do_yield);
  657. i = NO_CS;
  658. }
  659. } else {
  660. //Go through all device queues to find a transaction to send
  661. //ToDo: This is a stupidly simple low-cs-first priority scheme. Make this configurable somehow. - JD
  662. for (i = 0; i < NO_CS; i++) {
  663. spi_device_t* dev = atomic_load(&host->device[i]);
  664. if (dev) {
  665. r = xQueueReceiveFromISR(dev->trans_queue, &host->cur_trans_buf, &do_yield);
  666. //Stop looking if we have a transaction to send.
  667. if (r) break;
  668. }
  669. }
  670. if (i==NO_CS) {
  671. host->isr_free = true;
  672. }
  673. }
  674. // Actually send the transaction
  675. if (i != NO_CS) {
  676. spi_trans_priv_t *const cur_trans_buf = &host->cur_trans_buf;
  677. if (host->dma_chan != 0 && (cur_trans_buf->buffer_to_rcv || cur_trans_buf->buffer_to_send)) {
  678. //mark channel as active, so that the DMA will not be reset by the slave
  679. spicommon_dmaworkaround_transfer_active(host->dma_chan);
  680. }
  681. spi_new_trans(atomic_load(&host->device[i]), cur_trans_buf, (&host->hal));
  682. //re-enable interrupt disabled above
  683. esp_intr_enable(host->intr);
  684. }
  685. if (do_yield) portYIELD_FROM_ISR();
  686. }
  687. static SPI_MASTER_ISR_ATTR esp_err_t check_trans_valid(spi_device_handle_t handle, spi_transaction_t *trans_desc)
  688. {
  689. SPI_CHECK(handle!=NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  690. spi_host_t *host = handle->host;
  691. //check transmission length
  692. 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);
  693. 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);
  694. SPI_CHECK(trans_desc->length <= handle->host->max_transfer_sz*8, "txdata transfer > host maximum", ESP_ERR_INVALID_ARG);
  695. SPI_CHECK(trans_desc->rxlength <= handle->host->max_transfer_sz*8, "rxdata transfer > host maximum", ESP_ERR_INVALID_ARG);
  696. 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);
  697. //check working mode
  698. 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);
  699. 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);
  700. SPI_CHECK( !(handle->cfg.flags & SPI_DEVICE_HALFDUPLEX) || host->dma_chan == 0 || !(trans_desc->flags & SPI_TRANS_USE_RXDATA || trans_desc->rx_buffer != NULL)
  701. || !(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 );
  702. //MOSI phase is skipped only when both tx_buffer and SPI_TRANS_USE_TXDATA are not set.
  703. SPI_CHECK(trans_desc->length != 0 || (trans_desc->tx_buffer == NULL && !(trans_desc->flags & SPI_TRANS_USE_TXDATA)),
  704. "trans tx_buffer should be NULL and SPI_TRANS_USE_TXDATA should be cleared to skip MOSI phase.", ESP_ERR_INVALID_ARG);
  705. //MISO phase is skipped only when both rx_buffer and SPI_TRANS_USE_RXDATA are not set.
  706. //If set rxlength=0 in full_duplex mode, it will be automatically set to length
  707. SPI_CHECK(!(handle->cfg.flags & SPI_DEVICE_HALFDUPLEX) || trans_desc->rxlength != 0 ||
  708. (trans_desc->rx_buffer == NULL && ((trans_desc->flags & SPI_TRANS_USE_RXDATA)==0)),
  709. "trans rx_buffer should be NULL and SPI_TRANS_USE_RXDATA should be cleared to skip MISO phase.", ESP_ERR_INVALID_ARG);
  710. //In Full duplex mode, default rxlength to be the same as length, if not filled in.
  711. // set rxlength to length is ok, even when rx buffer=NULL
  712. if (trans_desc->rxlength==0 && !(handle->cfg.flags & SPI_DEVICE_HALFDUPLEX)) {
  713. trans_desc->rxlength=trans_desc->length;
  714. }
  715. return ESP_OK;
  716. }
  717. static SPI_MASTER_ISR_ATTR void uninstall_priv_desc(spi_trans_priv_t* trans_buf)
  718. {
  719. spi_transaction_t *trans_desc = trans_buf->trans;
  720. if ((void *)trans_buf->buffer_to_send != &trans_desc->tx_data[0] &&
  721. trans_buf->buffer_to_send != trans_desc->tx_buffer) {
  722. free((void *)trans_buf->buffer_to_send); //force free, ignore const
  723. }
  724. //copy data from temporary DMA-capable buffer back to IRAM buffer and free the temporary one.
  725. if ((void *)trans_buf->buffer_to_rcv != &trans_desc->rx_data[0] &&
  726. trans_buf->buffer_to_rcv != trans_desc->rx_buffer) {
  727. if (trans_desc->flags & SPI_TRANS_USE_RXDATA) {
  728. memcpy((uint8_t *) & trans_desc->rx_data[0], trans_buf->buffer_to_rcv, (trans_desc->rxlength + 7) / 8);
  729. } else {
  730. memcpy(trans_desc->rx_buffer, trans_buf->buffer_to_rcv, (trans_desc->rxlength + 7) / 8);
  731. }
  732. free(trans_buf->buffer_to_rcv);
  733. }
  734. }
  735. static SPI_MASTER_ISR_ATTR esp_err_t setup_priv_desc(spi_transaction_t *trans_desc, spi_trans_priv_t* new_desc, bool isdma)
  736. {
  737. *new_desc = (spi_trans_priv_t) { .trans = trans_desc, };
  738. // rx memory assign
  739. uint32_t* rcv_ptr;
  740. if ( trans_desc->flags & SPI_TRANS_USE_RXDATA ) {
  741. rcv_ptr = (uint32_t *)&trans_desc->rx_data[0];
  742. } else {
  743. //if not use RXDATA neither rx_buffer, buffer_to_rcv assigned to NULL
  744. rcv_ptr = trans_desc->rx_buffer;
  745. }
  746. if (rcv_ptr && isdma && (!esp_ptr_dma_capable(rcv_ptr) || ((int)rcv_ptr % 4 != 0))) {
  747. //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.
  748. ESP_LOGI( SPI_TAG, "Allocate RX buffer for DMA" );
  749. rcv_ptr = heap_caps_malloc((trans_desc->rxlength + 31) / 8, MALLOC_CAP_DMA);
  750. if (rcv_ptr == NULL) goto clean_up;
  751. }
  752. new_desc->buffer_to_rcv = rcv_ptr;
  753. // tx memory assign
  754. const uint32_t *send_ptr;
  755. if ( trans_desc->flags & SPI_TRANS_USE_TXDATA ) {
  756. send_ptr = (uint32_t *)&trans_desc->tx_data[0];
  757. } else {
  758. //if not use TXDATA neither tx_buffer, tx data assigned to NULL
  759. send_ptr = trans_desc->tx_buffer ;
  760. }
  761. if (send_ptr && isdma && !esp_ptr_dma_capable( send_ptr )) {
  762. //if txbuf in the desc not DMA-capable, malloc a new one
  763. ESP_LOGD( SPI_TAG, "Allocate TX buffer for DMA" );
  764. uint32_t *temp = heap_caps_malloc((trans_desc->length + 7) / 8, MALLOC_CAP_DMA);
  765. if (temp == NULL) goto clean_up;
  766. memcpy( temp, send_ptr, (trans_desc->length + 7) / 8 );
  767. send_ptr = temp;
  768. }
  769. new_desc->buffer_to_send = send_ptr;
  770. return ESP_OK;
  771. clean_up:
  772. uninstall_priv_desc(new_desc);
  773. return ESP_ERR_NO_MEM;
  774. }
  775. esp_err_t SPI_MASTER_ATTR spi_device_queue_trans(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait)
  776. {
  777. esp_err_t ret = check_trans_valid(handle, trans_desc);
  778. if (ret != ESP_OK) return ret;
  779. spi_host_t *host = handle->host;
  780. SPI_CHECK( !device_is_polling(handle), "Cannot queue new transaction while previous polling transaction is not terminated.", ESP_ERR_INVALID_STATE );
  781. spi_trans_priv_t trans_buf;
  782. ret = setup_priv_desc(trans_desc, &trans_buf, (host->dma_chan!=0));
  783. if (ret != ESP_OK) return ret;
  784. #ifdef CONFIG_PM_ENABLE
  785. esp_pm_lock_acquire(host->pm_lock);
  786. #endif
  787. //Send to queue and invoke the ISR.
  788. BaseType_t r = xQueueSend(handle->trans_queue, (void *)&trans_buf, ticks_to_wait);
  789. if (!r) {
  790. ret = ESP_ERR_TIMEOUT;
  791. #ifdef CONFIG_PM_ENABLE
  792. //Release APB frequency lock
  793. esp_pm_lock_release(host->pm_lock);
  794. #endif
  795. goto clean_up;
  796. }
  797. spi_isr_invoke(handle);
  798. return ESP_OK;
  799. clean_up:
  800. uninstall_priv_desc(&trans_buf);
  801. return ret;
  802. }
  803. esp_err_t SPI_MASTER_ATTR spi_device_get_trans_result(spi_device_handle_t handle, spi_transaction_t **trans_desc, TickType_t ticks_to_wait)
  804. {
  805. BaseType_t r;
  806. spi_trans_priv_t trans_buf;
  807. SPI_CHECK(handle!=NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  808. //use the interrupt, block until return
  809. r=xQueueReceive(handle->ret_queue, (void*)&trans_buf, ticks_to_wait);
  810. if (!r) {
  811. // The memory occupied by rx and tx DMA buffer destroyed only when receiving from the queue (transaction finished).
  812. // If timeout, wait and retry.
  813. // Every in-flight transaction request occupies internal memory as DMA buffer if needed.
  814. return ESP_ERR_TIMEOUT;
  815. }
  816. //release temporary buffers
  817. uninstall_priv_desc(&trans_buf);
  818. (*trans_desc) = trans_buf.trans;
  819. return ESP_OK;
  820. }
  821. //Porcelain to do one blocking transmission.
  822. esp_err_t SPI_MASTER_ATTR spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc)
  823. {
  824. esp_err_t ret;
  825. spi_transaction_t *ret_trans;
  826. //ToDo: check if any spi transfers in flight
  827. ret = spi_device_queue_trans(handle, trans_desc, portMAX_DELAY);
  828. if (ret != ESP_OK) return ret;
  829. ret = spi_device_get_trans_result(handle, &ret_trans, portMAX_DELAY);
  830. if (ret != ESP_OK) return ret;
  831. assert(ret_trans == trans_desc);
  832. return ESP_OK;
  833. }
  834. esp_err_t SPI_MASTER_ATTR spi_device_acquire_bus(spi_device_t *device, TickType_t wait)
  835. {
  836. spi_host_t *const host = device->host;
  837. SPI_CHECK(wait==portMAX_DELAY, "acquire finite time not supported now.", ESP_ERR_INVALID_ARG);
  838. SPI_CHECK( !device_is_polling(device), "Cannot acquire bus when a polling transaction is in progress.", ESP_ERR_INVALID_STATE );
  839. esp_err_t ret = device_acquire_bus_internal(device, portMAX_DELAY);
  840. if (ret != ESP_OK) return ret;
  841. ret = device_wait_for_isr_idle(device, portMAX_DELAY);
  842. if (ret != ESP_OK) return ret;
  843. device->host->bus_locked = true;
  844. ESP_LOGD(SPI_TAG, "device%d acquired the bus", device->id);
  845. #ifdef CONFIG_PM_ENABLE
  846. // though we don't suggest to block the task before ``release_bus``, still allow doing so.
  847. // this keeps the spi clock at 80MHz even if all tasks are blocked
  848. esp_pm_lock_acquire(device->host->pm_lock);
  849. #endif
  850. //configure the device so that we don't need to do it again in the following transactions
  851. spi_setup_device(host, device->id);
  852. //the DMA is also occupied by the device, all the slave devices that using DMA should wait until bus released.
  853. if (host->dma_chan != 0) {
  854. spicommon_dmaworkaround_transfer_active(host->dma_chan);
  855. }
  856. return ESP_OK;
  857. }
  858. // This function restore configurations required in the non-polling mode
  859. void SPI_MASTER_ATTR spi_device_release_bus(spi_device_t *dev)
  860. {
  861. spi_host_t *host = dev->host;
  862. if (device_is_polling(dev)){
  863. ESP_LOGE(SPI_TAG, "Cannot release bus when a polling transaction is in progress.");
  864. assert(0);
  865. }
  866. if (host->dma_chan != 0) {
  867. spicommon_dmaworkaround_idle(host->dma_chan);
  868. }
  869. //Tell common code DMA workaround that our DMA channel is idle. If needed, the code will do a DMA reset.
  870. //allow clock to be lower than 80MHz when all tasks blocked
  871. #ifdef CONFIG_PM_ENABLE
  872. //Release APB frequency lock
  873. esp_pm_lock_release(host->pm_lock);
  874. #endif
  875. ESP_LOGD(SPI_TAG, "device%d release bus", dev->id);
  876. dev->host->bus_locked = false;
  877. device_release_bus_internal(dev->host);
  878. }
  879. esp_err_t SPI_MASTER_ISR_ATTR spi_device_polling_start(spi_device_handle_t handle, spi_transaction_t *trans_desc, TickType_t ticks_to_wait)
  880. {
  881. esp_err_t ret;
  882. SPI_CHECK(ticks_to_wait == portMAX_DELAY, "currently timeout is not available for polling transactions", ESP_ERR_INVALID_ARG);
  883. spi_host_t *host = handle->host;
  884. ret = check_trans_valid(handle, trans_desc);
  885. if (ret!=ESP_OK) return ret;
  886. SPI_CHECK( !device_is_polling(handle), "Cannot send polling transaction while the previous polling transaction is not terminated.", ESP_ERR_INVALID_STATE );
  887. ret = setup_priv_desc(trans_desc, &host->cur_trans_buf, (handle->host->dma_chan!=0));
  888. if (ret!=ESP_OK) return ret;
  889. device_acquire_bus_internal(handle, portMAX_DELAY);
  890. device_wait_for_isr_idle(handle, portMAX_DELAY);
  891. assert(atomic_load(&host->acquire_cs) == handle->id);
  892. assert(host->isr_free);
  893. //Polling, no interrupt is used.
  894. host->polling = true;
  895. ESP_LOGV(SPI_TAG, "polling trans");
  896. spi_new_trans(handle, &host->cur_trans_buf, (&host->hal));
  897. return ESP_OK;
  898. }
  899. esp_err_t SPI_MASTER_ISR_ATTR spi_device_polling_end(spi_device_handle_t handle, TickType_t ticks_to_wait)
  900. {
  901. SPI_CHECK(handle != NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  902. spi_host_t *host = handle->host;
  903. //if (host->acquire_cs == handle->id && host->polling) {
  904. assert(host->cur_cs == atomic_load(&host->acquire_cs));
  905. TickType_t start = xTaskGetTickCount();
  906. while (!spi_hal_usr_is_done(&host->hal)) {
  907. TickType_t end = xTaskGetTickCount();
  908. if (end - start > ticks_to_wait) {
  909. return ESP_ERR_TIMEOUT;
  910. }
  911. }
  912. ESP_LOGV(SPI_TAG, "polling trans done");
  913. //deal with the in-flight transaction
  914. spi_post_trans(host);
  915. //release temporary buffers
  916. uninstall_priv_desc(&host->cur_trans_buf);
  917. host->polling = false;
  918. if (!host->bus_locked) {
  919. device_release_bus_internal(host);
  920. }
  921. return ESP_OK;
  922. }
  923. esp_err_t SPI_MASTER_ISR_ATTR spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t* trans_desc)
  924. {
  925. esp_err_t ret;
  926. ret = spi_device_polling_start(handle, trans_desc, portMAX_DELAY);
  927. if (ret != ESP_OK) return ret;
  928. ret = spi_device_polling_end(handle, portMAX_DELAY);
  929. if (ret != ESP_OK) return ret;
  930. return ESP_OK;
  931. }