spi_master.c.unused 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. // Copyright 2015-2020 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. dev_request 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 ``random_idle`` flag indicating that it's not doing
  55. transactions. When the bus is locked, 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 random_idle 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 ``spi_bus_lock_acquire_core`` 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 "esp_log.h"
  101. #include "freertos/task.h"
  102. #include "freertos/queue.h"
  103. #include "freertos/semphr.h"
  104. #include "soc/soc_memory_layout.h"
  105. #include "driver/gpio.h"
  106. #include "hal/spi_hal.h"
  107. #include "esp_heap_caps.h"
  108. typedef struct spi_device_t spi_device_t;
  109. /// struct to hold private transaction data (like tx and rx buffer for DMA).
  110. typedef struct {
  111. spi_transaction_t *trans;
  112. 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;
  113. //otherwise sets to the original buffer or NULL if no buffer is assigned.
  114. uint32_t *buffer_to_rcv; // similar to buffer_to_send
  115. } spi_trans_priv_t;
  116. typedef struct {
  117. int id;
  118. spi_device_t* device[DEV_NUM_MAX];
  119. intr_handle_t intr;
  120. spi_hal_context_t hal;
  121. spi_trans_priv_t cur_trans_buf;
  122. int cur_cs; //current device doing transaction
  123. const spi_bus_attr_t* bus_attr;
  124. /**
  125. * the bus is permanently controlled by a device until `spi_bus_release_bus`` is called. Otherwise
  126. * the acquiring of SPI bus will be freed when `spi_device_polling_end` is called.
  127. */
  128. spi_device_t* device_acquiring_lock;
  129. //debug information
  130. bool polling; //in process of a polling, avoid of queue new transactions into ISR
  131. // PATCH
  132. SemaphoreHandle_t mutex;
  133. int count;
  134. } spi_host_t;
  135. struct spi_device_t {
  136. int id;
  137. QueueHandle_t trans_queue;
  138. QueueHandle_t ret_queue;
  139. spi_device_interface_config_t cfg;
  140. spi_hal_dev_config_t hal_dev;
  141. spi_host_t *host;
  142. spi_bus_lock_dev_handle_t dev_lock;
  143. };
  144. static spi_host_t* bus_driver_ctx[SOC_SPI_PERIPH_NUM] = {};
  145. static const char *SPI_TAG = "spi_master";
  146. #define SPI_CHECK(a, str, ret_val, ...) \
  147. if (unlikely(!(a))) { \
  148. ESP_LOGE(SPI_TAG,"%s(%d): "str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
  149. return (ret_val); \
  150. }
  151. static void spi_intr(void *arg);
  152. static void spi_bus_intr_enable(void *host);
  153. static void spi_bus_intr_disable(void *host);
  154. static esp_err_t spi_master_deinit_driver(void* arg);
  155. static inline bool is_valid_host(spi_host_device_t host)
  156. {
  157. //SPI1 can be used as GPSPI only on ESP32
  158. #if CONFIG_IDF_TARGET_ESP32
  159. return host >= SPI1_HOST && host <= SPI3_HOST;
  160. #elif (SOC_SPI_PERIPH_NUM == 2)
  161. return host == SPI2_HOST;
  162. #elif (SOC_SPI_PERIPH_NUM == 3)
  163. return host >= SPI2_HOST && host <= SPI3_HOST;
  164. #endif
  165. }
  166. // Should be called before any devices are actually registered or used.
  167. // Currently automatically called after `spi_bus_initialize()` and when first device is registered.
  168. static esp_err_t spi_master_init_driver(spi_host_device_t host_id)
  169. {
  170. esp_err_t err = ESP_OK;
  171. const spi_bus_attr_t* bus_attr = spi_bus_get_attr(host_id);
  172. SPI_CHECK(bus_attr != NULL, "host_id not initialized", ESP_ERR_INVALID_STATE);
  173. SPI_CHECK(bus_attr->lock != NULL, "SPI Master cannot attach to bus. (Check CONFIG_SPI_FLASH_SHARE_SPI1_BUS)", ESP_ERR_INVALID_ARG);
  174. // spihost contains atomic variables, which should not be put in PSRAM
  175. spi_host_t* host = heap_caps_malloc(sizeof(spi_host_t), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  176. if (host == NULL) {
  177. err = ESP_ERR_NO_MEM;
  178. goto cleanup;
  179. }
  180. *host = (spi_host_t) {
  181. .id = host_id,
  182. .cur_cs = DEV_NUM_MAX,
  183. .polling = false,
  184. .device_acquiring_lock = NULL,
  185. .bus_attr = bus_attr,
  186. };
  187. if (host_id != SPI1_HOST) {
  188. // interrupts are not allowed on SPI1 bus
  189. err = esp_intr_alloc(spicommon_irqsource_for_host(host_id),
  190. bus_attr->bus_cfg.intr_flags | ESP_INTR_FLAG_INTRDISABLED,
  191. spi_intr, host, &host->intr);
  192. if (err != ESP_OK) {
  193. goto cleanup;
  194. }
  195. }
  196. //assign the SPI, RX DMA and TX DMA peripheral registers beginning address
  197. spi_hal_config_t hal_config = {
  198. //On ESP32-S2 and earlier chips, DMA registers are part of SPI registers. Pass the registers of SPI peripheral to control it.
  199. .dma_in = SPI_LL_GET_HW(host_id),
  200. .dma_out = SPI_LL_GET_HW(host_id),
  201. .dma_enabled = bus_attr->dma_enabled,
  202. .dmadesc_tx = bus_attr->dmadesc_tx,
  203. .dmadesc_rx = bus_attr->dmadesc_rx,
  204. .tx_dma_chan = bus_attr->tx_dma_chan,
  205. .rx_dma_chan = bus_attr->rx_dma_chan,
  206. .dmadesc_n = bus_attr->dma_desc_num,
  207. };
  208. spi_hal_init(&host->hal, host_id, &hal_config);
  209. if (host_id != SPI1_HOST) {
  210. //SPI1 attributes are already initialized at start up.
  211. spi_bus_lock_handle_t lock = spi_bus_lock_get_by_id(host_id);
  212. spi_bus_lock_set_bg_control(lock, spi_bus_intr_enable, spi_bus_intr_disable, host);
  213. spi_bus_register_destroy_func(host_id, spi_master_deinit_driver, host);
  214. }
  215. bus_driver_ctx[host_id] = host;
  216. return ESP_OK;
  217. cleanup:
  218. if (host) {
  219. spi_hal_deinit(&host->hal);
  220. if (host->intr) {
  221. esp_intr_free(host->intr);
  222. }
  223. }
  224. free(host);
  225. return err;
  226. }
  227. static esp_err_t spi_master_deinit_driver(void* arg)
  228. {
  229. spi_host_t *host = (spi_host_t*)arg;
  230. SPI_CHECK(host != NULL, "host_id not in use", ESP_ERR_INVALID_STATE);
  231. int host_id = host->id;
  232. SPI_CHECK(is_valid_host(host_id), "invalid host_id", ESP_ERR_INVALID_ARG);
  233. int x;
  234. for (x=0; x<DEV_NUM_MAX; x++) {
  235. SPI_CHECK(host->device[x] == NULL, "not all CSses freed", ESP_ERR_INVALID_STATE);
  236. }
  237. spi_hal_deinit(&host->hal);
  238. if (host->intr) {
  239. esp_intr_free(host->intr);
  240. }
  241. free(host);
  242. bus_driver_ctx[host_id] = NULL;
  243. return ESP_OK;
  244. }
  245. void spi_get_timing(bool gpio_is_used, int input_delay_ns, int eff_clk, int* dummy_o, int* cycles_remain_o)
  246. {
  247. int timing_dummy;
  248. int timing_miso_delay;
  249. spi_hal_cal_timing(eff_clk, gpio_is_used, input_delay_ns, &timing_dummy, &timing_miso_delay);
  250. if (dummy_o) *dummy_o = timing_dummy;
  251. if (cycles_remain_o) *cycles_remain_o = timing_miso_delay;
  252. }
  253. int spi_get_freq_limit(bool gpio_is_used, int input_delay_ns)
  254. {
  255. return spi_hal_get_freq_limit(gpio_is_used, input_delay_ns);
  256. }
  257. /*
  258. Add a device. This allocates a CS line for the device, allocates memory for the device structure and hooks
  259. up the CS pin to whatever is specified.
  260. */
  261. esp_err_t spi_bus_add_device(spi_host_device_t host_id, const spi_device_interface_config_t *dev_config, spi_device_handle_t *handle)
  262. {
  263. spi_device_t *dev = NULL;
  264. esp_err_t err = ESP_OK;
  265. SPI_CHECK(is_valid_host(host_id), "invalid host", ESP_ERR_INVALID_ARG);
  266. if (bus_driver_ctx[host_id] == NULL) {
  267. //lazy initialization the driver, get deinitialized by the bus is freed
  268. err = spi_master_init_driver(host_id);
  269. if (err != ESP_OK) {
  270. return err;
  271. }
  272. }
  273. spi_host_t *host = bus_driver_ctx[host_id];
  274. const spi_bus_attr_t* bus_attr = host->bus_attr;
  275. 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);
  276. SPI_CHECK(dev_config->clock_speed_hz > 0, "invalid sclk speed", ESP_ERR_INVALID_ARG);
  277. #ifdef CONFIG_IDF_TARGET_ESP32
  278. //The hardware looks like it would support this, but actually setting cs_ena_pretrans when transferring in full
  279. //duplex mode does absolutely nothing on the ESP32.
  280. SPI_CHECK(dev_config->cs_ena_pretrans <= 1 || (dev_config->address_bits == 0 && dev_config->command_bits == 0) ||
  281. (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);
  282. #endif
  283. uint32_t lock_flag = ((dev_config->spics_io_num != -1)? SPI_BUS_LOCK_DEV_FLAG_CS_REQUIRED: 0);
  284. spi_bus_lock_dev_config_t lock_config = {
  285. .flags = lock_flag,
  286. };
  287. spi_bus_lock_dev_handle_t dev_handle;
  288. err = spi_bus_lock_register_dev(bus_attr->lock, &lock_config, &dev_handle);
  289. if (err != ESP_OK) {
  290. goto nomem;
  291. }
  292. int freecs = spi_bus_lock_get_dev_id(dev_handle);
  293. SPI_CHECK(freecs != -1, "no free cs pins for the host", ESP_ERR_NOT_FOUND);
  294. //input parameters to calculate timing configuration
  295. int half_duplex = dev_config->flags & SPI_DEVICE_HALFDUPLEX ? 1 : 0;
  296. int no_compensate = dev_config->flags & SPI_DEVICE_NO_DUMMY ? 1 : 0;
  297. int duty_cycle = (dev_config->duty_cycle_pos==0) ? 128 : dev_config->duty_cycle_pos;
  298. int use_gpio = !(bus_attr->flags & SPICOMMON_BUSFLAG_IOMUX_PINS);
  299. spi_hal_timing_param_t timing_param = {
  300. .half_duplex = half_duplex,
  301. .no_compensate = no_compensate,
  302. .clock_speed_hz = dev_config->clock_speed_hz,
  303. .duty_cycle = duty_cycle,
  304. .input_delay_ns = dev_config->input_delay_ns,
  305. .use_gpio = use_gpio
  306. };
  307. //output values of timing configuration
  308. spi_hal_timing_conf_t temp_timing_conf;
  309. int freq;
  310. esp_err_t ret = spi_hal_cal_clock_conf(&timing_param, &freq, &temp_timing_conf);
  311. SPI_CHECK(ret==ESP_OK, "assigned clock speed not supported", ret);
  312. //Allocate memory for device
  313. dev = malloc(sizeof(spi_device_t));
  314. if (dev == NULL) goto nomem;
  315. memset(dev, 0, sizeof(spi_device_t));
  316. dev->id = freecs;
  317. dev->dev_lock = dev_handle;
  318. //Allocate queues, set defaults
  319. dev->trans_queue = xQueueCreate(dev_config->queue_size, sizeof(spi_trans_priv_t));
  320. dev->ret_queue = xQueueCreate(dev_config->queue_size, sizeof(spi_trans_priv_t));
  321. if (!dev->trans_queue || !dev->ret_queue) {
  322. goto nomem;
  323. }
  324. //We want to save a copy of the dev config in the dev struct.
  325. memcpy(&dev->cfg, dev_config, sizeof(spi_device_interface_config_t));
  326. dev->cfg.duty_cycle_pos = duty_cycle;
  327. // TODO: if we have to change the apb clock among transactions, re-calculate this each time the apb clock lock is locked.
  328. //Set CS pin, CS options
  329. if (dev_config->spics_io_num >= 0) {
  330. spicommon_cs_initialize(host_id, dev_config->spics_io_num, freecs, use_gpio);
  331. }
  332. // create a mutex if we have more than one client
  333. if (host->count++) {
  334. ESP_LOGI(SPI_TAG, "More than one device on SPI %d => creating mutex", host_id);
  335. host->mutex = xSemaphoreCreateMutex();
  336. }
  337. //save a pointer to device in spi_host_t
  338. host->device[freecs] = dev;
  339. //save a pointer to host in spi_device_t
  340. dev->host= host;
  341. //initialise the device specific configuration
  342. spi_hal_dev_config_t *hal_dev = &(dev->hal_dev);
  343. hal_dev->mode = dev_config->mode;
  344. hal_dev->cs_setup = dev_config->cs_ena_pretrans;
  345. hal_dev->cs_hold = dev_config->cs_ena_posttrans;
  346. //set hold_time to 0 will not actually append delay to CS
  347. //set it to 1 since we do need at least one clock of hold time in most cases
  348. if (hal_dev->cs_hold == 0) {
  349. hal_dev->cs_hold = 1;
  350. }
  351. hal_dev->cs_pin_id = dev->id;
  352. hal_dev->timing_conf = temp_timing_conf;
  353. hal_dev->sio = (dev_config->flags) & SPI_DEVICE_3WIRE ? 1 : 0;
  354. hal_dev->half_duplex = dev_config->flags & SPI_DEVICE_HALFDUPLEX ? 1 : 0;
  355. hal_dev->tx_lsbfirst = dev_config->flags & SPI_DEVICE_TXBIT_LSBFIRST ? 1 : 0;
  356. hal_dev->rx_lsbfirst = dev_config->flags & SPI_DEVICE_RXBIT_LSBFIRST ? 1 : 0;
  357. hal_dev->no_compensate = dev_config->flags & SPI_DEVICE_NO_DUMMY ? 1 : 0;
  358. #if SOC_SPI_SUPPORT_AS_CS
  359. hal_dev->as_cs = dev_config->flags& SPI_DEVICE_CLK_AS_CS ? 1 : 0;
  360. #endif
  361. hal_dev->positive_cs = dev_config->flags & SPI_DEVICE_POSITIVE_CS ? 1 : 0;
  362. *handle = dev;
  363. ESP_LOGD(SPI_TAG, "SPI%d: New device added to CS%d, effective clock: %dkHz", host_id+1, freecs, freq/1000);
  364. return ESP_OK;
  365. nomem:
  366. if (dev) {
  367. if (dev->trans_queue) vQueueDelete(dev->trans_queue);
  368. if (dev->ret_queue) vQueueDelete(dev->ret_queue);
  369. spi_bus_lock_unregister_dev(dev->dev_lock);
  370. }
  371. free(dev);
  372. return ESP_ERR_NO_MEM;
  373. }
  374. esp_err_t spi_bus_remove_device(spi_device_handle_t handle)
  375. {
  376. SPI_CHECK(handle!=NULL, "invalid handle", ESP_ERR_INVALID_ARG);
  377. //These checks aren't exhaustive; another thread could sneak in a transaction inbetween. These are only here to
  378. //catch design errors and aren't meant to be triggered during normal operation.
  379. SPI_CHECK(uxQueueMessagesWaiting(handle->trans_queue)==0, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  380. SPI_CHECK(handle->host->cur_cs == DEV_NUM_MAX || handle->host->device[handle->host->cur_cs] != handle, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  381. SPI_CHECK(uxQueueMessagesWaiting(handle->ret_queue)==0, "Have unfinished transactions", ESP_ERR_INVALID_STATE);
  382. //return
  383. int spics_io_num = handle->cfg.spics_io_num;
  384. if (spics_io_num >= 0) spicommon_cs_free_io(spics_io_num);
  385. //Kill queues
  386. vQueueDelete(handle->trans_queue);
  387. vQueueDelete(handle->ret_queue);
  388. spi_bus_lock_unregister_dev(handle->dev_lock);
  389. assert(handle->host->device[handle->id] == handle);
  390. handle->host->device[handle->id] = NULL;
  391. free(handle);
  392. return ESP_OK;
  393. }
  394. int spi_cal_clock(int fapb, int hz, int duty_cycle, uint32_t *reg_o)
  395. {
  396. return spi_ll_master_cal_clock(fapb, hz, duty_cycle, reg_o);
  397. }
  398. int spi_get_actual_clock(int fapb, int hz, int duty_cycle)
  399. {
  400. return spi_hal_master_cal_clock(fapb, hz, duty_cycle);
  401. }
  402. // Setup the device-specified configuration registers. Called every time a new
  403. // transaction is to be sent, but only apply new configurations when the device
  404. // changes.
  405. static SPI_MASTER_ISR_ATTR void spi_setup_device(spi_device_t *dev)
  406. {
  407. spi_bus_lock_dev_handle_t dev_lock = dev->dev_lock;
  408. if (!spi_bus_lock_touch(dev_lock)) {
  409. //if the configuration is already applied, skip the following.
  410. return;
  411. }
  412. spi_hal_context_t *hal = &dev->host->hal;
  413. spi_hal_dev_config_t *hal_dev = &(dev->hal_dev);
  414. spi_hal_setup_device(hal, hal_dev);
  415. }
  416. static SPI_MASTER_ISR_ATTR spi_device_t *get_acquiring_dev(spi_host_t *host)
  417. {
  418. spi_bus_lock_dev_handle_t dev_lock = spi_bus_lock_get_acquiring_dev(host->bus_attr->lock);
  419. if (!dev_lock) return NULL;
  420. return host->device[spi_bus_lock_get_dev_id(dev_lock)];
  421. }
  422. // Debug only
  423. // NOTE if the acquiring is not fully completed, `spi_bus_lock_get_acquiring_dev`
  424. // may return a false `NULL` cause the function returning false `false`.
  425. static inline SPI_MASTER_ISR_ATTR bool spi_bus_device_is_polling(spi_device_t *dev)
  426. {
  427. return get_acquiring_dev(dev->host) == dev && dev->host->polling;
  428. }
  429. /*-----------------------------------------------------------------------------
  430. Working Functions
  431. -----------------------------------------------------------------------------*/
  432. // The interrupt may get invoked by the bus lock.
  433. static void SPI_MASTER_ISR_ATTR spi_bus_intr_enable(void *host)
  434. {
  435. esp_intr_enable(((spi_host_t*)host)->intr);
  436. }
  437. // The interrupt is always disabled by the ISR itself, not exposed
  438. static void SPI_MASTER_ISR_ATTR spi_bus_intr_disable(void *host)
  439. {
  440. esp_intr_disable(((spi_host_t*)host)->intr);
  441. }
  442. // The function is called to send a new transaction, in ISR or in the task.
  443. // Setup the transaction-specified registers and linked-list used by the DMA (or FIFO if DMA is not used)
  444. static void SPI_MASTER_ISR_ATTR spi_new_trans(spi_device_t *dev, spi_trans_priv_t *trans_buf)
  445. {
  446. spi_transaction_t *trans = NULL;
  447. spi_host_t *host = dev->host;
  448. spi_hal_context_t *hal = &(host->hal);
  449. spi_hal_dev_config_t *hal_dev = &(dev->hal_dev);
  450. trans = trans_buf->trans;
  451. host->cur_cs = dev->id;
  452. //Reconfigure according to device settings, the function only has effect when the dev_id is changed.
  453. spi_setup_device(dev);
  454. //set the transaction specific configuration each time before a transaction setup
  455. spi_hal_trans_config_t hal_trans = {};
  456. hal_trans.tx_bitlen = trans->length;
  457. hal_trans.rx_bitlen = trans->rxlength;
  458. hal_trans.rcv_buffer = (uint8_t*)host->cur_trans_buf.buffer_to_rcv;
  459. hal_trans.send_buffer = (uint8_t*)host->cur_trans_buf.buffer_to_send;
  460. hal_trans.cmd = trans->cmd;
  461. hal_trans.addr = trans->addr;
  462. //Set up QIO/DIO if needed
  463. hal_trans.io_mode = (trans->flags & SPI_TRANS_MODE_DIO ?
  464. (trans->flags & SPI_TRANS_MODE_DIOQIO_ADDR ? SPI_LL_IO_MODE_DIO : SPI_LL_IO_MODE_DUAL) :
  465. (trans->flags & SPI_TRANS_MODE_QIO ?
  466. (trans->flags & SPI_TRANS_MODE_DIOQIO_ADDR ? SPI_LL_IO_MODE_QIO : SPI_LL_IO_MODE_QUAD) :
  467. SPI_LL_IO_MODE_NORMAL
  468. ));
  469. if (trans->flags & SPI_TRANS_VARIABLE_CMD) {
  470. hal_trans.cmd_bits = ((spi_transaction_ext_t *)trans)->command_bits;
  471. } else {
  472. hal_trans.cmd_bits = dev->cfg.command_bits;
  473. }
  474. if (trans->flags & SPI_TRANS_VARIABLE_ADDR) {
  475. hal_trans.addr_bits = ((spi_transaction_ext_t *)trans)->address_bits;
  476. } else {
  477. hal_trans.addr_bits = dev->cfg.address_bits;
  478. }
  479. if (trans->flags & SPI_TRANS_VARIABLE_DUMMY) {
  480. hal_trans.dummy_bits = ((spi_transaction_ext_t *)trans)->dummy_bits;
  481. } else {
  482. hal_trans.dummy_bits = dev->cfg.dummy_bits;
  483. }
  484. spi_hal_setup_trans(hal, hal_dev, &hal_trans);
  485. spi_hal_prepare_data(hal, hal_dev, &hal_trans);
  486. //Call pre-transmission callback, if any
  487. if (dev->cfg.pre_cb) dev->cfg.pre_cb(trans);
  488. //Kick off transfer
  489. spi_hal_user_start(hal);
  490. }
  491. // The function is called when a transaction is done, in ISR or in the task.
  492. // Fetch the data from FIFO and call the ``post_cb``.
  493. static void SPI_MASTER_ISR_ATTR spi_post_trans(spi_host_t *host)
  494. {
  495. spi_transaction_t *cur_trans = host->cur_trans_buf.trans;
  496. spi_hal_fetch_result(&host->hal);
  497. //Call post-transaction callback, if any
  498. spi_device_t* dev = host->device[host->cur_cs];
  499. if (dev->cfg.post_cb) dev->cfg.post_cb(cur_trans);
  500. host->cur_cs = DEV_NUM_MAX;
  501. }
  502. // This is run in interrupt context.
  503. static void SPI_MASTER_ISR_ATTR spi_intr(void *arg)
  504. {
  505. BaseType_t do_yield = pdFALSE;
  506. spi_host_t *host = (spi_host_t *)arg;
  507. const spi_bus_attr_t* bus_attr = host->bus_attr;
  508. assert(spi_hal_usr_is_done(&host->hal));
  509. /*
  510. * Help to skip the handling of in-flight transaction, and disable of the interrupt.
  511. * The esp_intr_enable will be called (b) after new BG request is queued (a) in the task;
  512. * while esp_intr_disable should be called (c) if we check and found the sending queue is empty (d).
  513. * If (c) is called after (d), then there is a risk that things happens in this sequence:
  514. * (d) -> (a) -> (b) -> (c), and in this case the interrupt is disabled while there's pending BG request in the queue.
  515. * To avoid this, interrupt is disabled here, and re-enabled later if required.
  516. */
  517. if (!spi_bus_lock_bg_entry(bus_attr->lock)) {
  518. /*------------ deal with the in-flight transaction -----------------*/
  519. assert(host->cur_cs != DEV_NUM_MAX);
  520. //Okay, transaction is done.
  521. const int cs = host->cur_cs;
  522. //Tell common code DMA workaround that our DMA channel is idle. If needed, the code will do a DMA reset.
  523. if (bus_attr->dma_enabled) {
  524. //This workaround is only for esp32, where tx_dma_chan and rx_dma_chan are always same
  525. spicommon_dmaworkaround_idle(bus_attr->tx_dma_chan);
  526. }
  527. //cur_cs is changed to DEV_NUM_MAX here
  528. spi_post_trans(host);
  529. // spi_bus_lock_bg_pause(bus_attr->lock);
  530. //Return transaction descriptor.
  531. xQueueSendFromISR(host->device[cs]->ret_queue, &host->cur_trans_buf, &do_yield);
  532. #ifdef CONFIG_PM_ENABLE
  533. //Release APB frequency lock
  534. esp_pm_lock_release(bus_attr->pm_lock);
  535. #endif
  536. }
  537. /*------------ new transaction starts here ------------------*/
  538. assert(host->cur_cs == DEV_NUM_MAX);
  539. spi_bus_lock_handle_t lock = host->bus_attr->lock;
  540. BaseType_t trans_found = pdFALSE;
  541. // There should be remaining requests
  542. BUS_LOCK_DEBUG_EXECUTE_CHECK(spi_bus_lock_bg_req_exist(lock));
  543. do {
  544. spi_bus_lock_dev_handle_t acq_dev_lock = spi_bus_lock_get_acquiring_dev(lock);
  545. spi_bus_lock_dev_handle_t desired_dev = acq_dev_lock;
  546. bool resume_task = false;
  547. spi_device_t* device_to_send = NULL;
  548. if (!acq_dev_lock) {
  549. // This function may assign a new acquiring device, otherwise it will suggest a desired device with BG active
  550. // We use either of them without further searching in the devices.
  551. // If the return value is true, it means either there's no acquiring device, or the acquiring device's BG is active,
  552. // We stay in the ISR to deal with those transactions of desired device, otherwise nothing will be done, check whether we need to resume some other tasks, or just quit the ISR
  553. resume_task = spi_bus_lock_bg_check_dev_acq(lock, &desired_dev);
  554. }
  555. if (!resume_task) {
  556. bool dev_has_req = spi_bus_lock_bg_check_dev_req(desired_dev);
  557. if (dev_has_req) {
  558. device_to_send = host->device[spi_bus_lock_get_dev_id(desired_dev)];
  559. trans_found = xQueueReceiveFromISR(device_to_send->trans_queue, &host->cur_trans_buf, &do_yield);
  560. if (!trans_found) {
  561. spi_bus_lock_bg_clear_req(desired_dev);
  562. }
  563. }
  564. }
  565. if (trans_found) {
  566. spi_trans_priv_t *const cur_trans_buf = &host->cur_trans_buf;
  567. if (bus_attr->dma_enabled && (cur_trans_buf->buffer_to_rcv || cur_trans_buf->buffer_to_send)) {
  568. //mark channel as active, so that the DMA will not be reset by the slave
  569. //This workaround is only for esp32, where tx_dma_chan and rx_dma_chan are always same
  570. spicommon_dmaworkaround_transfer_active(bus_attr->tx_dma_chan);
  571. }
  572. spi_new_trans(device_to_send, cur_trans_buf);
  573. }
  574. // Exit of the ISR, handle interrupt re-enable (if sending transaction), retry (if there's coming BG),
  575. // or resume acquiring device task (if quit due to bus acquiring).
  576. } while (!spi_bus_lock_bg_exit(lock, trans_found, &do_yield));
  577. if (do_yield) portYIELD_FROM_ISR();
  578. }
  579. static SPI_MASTER_ISR_ATTR esp_err_t check_trans_valid(spi_device_handle_t handle, spi_transaction_t *trans_desc)
  580. {
  581. SPI_CHECK(handle!=NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  582. spi_host_t *host = handle->host;
  583. const spi_bus_attr_t* bus_attr = host->bus_attr;
  584. bool tx_enabled = (trans_desc->flags & SPI_TRANS_USE_TXDATA) || (trans_desc->tx_buffer);
  585. bool rx_enabled = (trans_desc->flags & SPI_TRANS_USE_RXDATA) || (trans_desc->rx_buffer);
  586. spi_transaction_ext_t *t_ext = (spi_transaction_ext_t *)trans_desc;
  587. bool dummy_enabled = (((trans_desc->flags & SPI_TRANS_VARIABLE_DUMMY)? t_ext->dummy_bits: handle->cfg.dummy_bits) != 0);
  588. bool extra_dummy_enabled = handle->hal_dev.timing_conf.timing_dummy;
  589. bool is_half_duplex = ((handle->cfg.flags & SPI_DEVICE_HALFDUPLEX) != 0);
  590. //check transmission length
  591. SPI_CHECK((trans_desc->flags & SPI_TRANS_USE_RXDATA)==0 || trans_desc->rxlength <= 32, "SPI_TRANS_USE_RXDATA only available for rxdata transfer <= 32 bits", ESP_ERR_INVALID_ARG);
  592. SPI_CHECK((trans_desc->flags & SPI_TRANS_USE_TXDATA)==0 || trans_desc->length <= 32, "SPI_TRANS_USE_TXDATA only available for txdata transfer <= 32 bits", ESP_ERR_INVALID_ARG);
  593. SPI_CHECK(trans_desc->length <= bus_attr->max_transfer_sz*8, "txdata transfer > host maximum", ESP_ERR_INVALID_ARG);
  594. SPI_CHECK(trans_desc->rxlength <= bus_attr->max_transfer_sz*8, "rxdata transfer > host maximum", ESP_ERR_INVALID_ARG);
  595. SPI_CHECK(is_half_duplex || trans_desc->rxlength <= trans_desc->length, "rx length > tx length in full duplex mode", ESP_ERR_INVALID_ARG);
  596. //check working mode
  597. 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);
  598. SPI_CHECK(!((trans_desc->flags & (SPI_TRANS_MODE_DIO|SPI_TRANS_MODE_QIO)) && !is_half_duplex), "incompatible iface params", ESP_ERR_INVALID_ARG);
  599. #ifdef CONFIG_IDF_TARGET_ESP32
  600. SPI_CHECK(!is_half_duplex || !bus_attr->dma_enabled || !rx_enabled || !tx_enabled, "SPI half duplex mode does not support using DMA with both MOSI and MISO phases.", ESP_ERR_INVALID_ARG );
  601. #elif CONFIG_IDF_TARGET_ESP32S3
  602. SPI_CHECK(!is_half_duplex || !tx_enabled || !rx_enabled, "SPI half duplex mode is not supported when both MOSI and MISO phases are enabled.", ESP_ERR_INVALID_ARG);
  603. #endif
  604. //MOSI phase is skipped only when both tx_buffer and SPI_TRANS_USE_TXDATA are not set.
  605. SPI_CHECK(trans_desc->length != 0 || !tx_enabled, "trans tx_buffer should be NULL and SPI_TRANS_USE_TXDATA should be cleared to skip MOSI phase.", ESP_ERR_INVALID_ARG);
  606. //MISO phase is skipped only when both rx_buffer and SPI_TRANS_USE_RXDATA are not set.
  607. //If set rxlength=0 in full_duplex mode, it will be automatically set to length
  608. SPI_CHECK(!is_half_duplex || trans_desc->rxlength != 0 || !rx_enabled, "trans rx_buffer should be NULL and SPI_TRANS_USE_RXDATA should be cleared to skip MISO phase.", ESP_ERR_INVALID_ARG);
  609. //In Full duplex mode, default rxlength to be the same as length, if not filled in.
  610. // set rxlength to length is ok, even when rx buffer=NULL
  611. if (trans_desc->rxlength==0 && !is_half_duplex) {
  612. trans_desc->rxlength=trans_desc->length;
  613. }
  614. //Dummy phase is not available when both data out and in are enabled, regardless of FD or HD mode.
  615. SPI_CHECK(!tx_enabled || !rx_enabled || !dummy_enabled || !extra_dummy_enabled, "Dummy phase is not available when both data out and in are enabled", ESP_ERR_INVALID_ARG);
  616. return ESP_OK;
  617. }
  618. static SPI_MASTER_ISR_ATTR void uninstall_priv_desc(spi_trans_priv_t* trans_buf)
  619. {
  620. spi_transaction_t *trans_desc = trans_buf->trans;
  621. if ((void *)trans_buf->buffer_to_send != &trans_desc->tx_data[0] &&
  622. trans_buf->buffer_to_send != trans_desc->tx_buffer) {
  623. free((void *)trans_buf->buffer_to_send); //force free, ignore const
  624. }
  625. // copy data from temporary DMA-capable buffer back to IRAM buffer and free the temporary one.
  626. if ((void *)trans_buf->buffer_to_rcv != &trans_desc->rx_data[0] &&
  627. trans_buf->buffer_to_rcv != trans_desc->rx_buffer) { // NOLINT(clang-analyzer-unix.Malloc)
  628. if (trans_desc->flags & SPI_TRANS_USE_RXDATA) {
  629. memcpy((uint8_t *) & trans_desc->rx_data[0], trans_buf->buffer_to_rcv, (trans_desc->rxlength + 7) / 8);
  630. } else {
  631. memcpy(trans_desc->rx_buffer, trans_buf->buffer_to_rcv, (trans_desc->rxlength + 7) / 8);
  632. }
  633. free(trans_buf->buffer_to_rcv);
  634. }
  635. }
  636. static SPI_MASTER_ISR_ATTR esp_err_t setup_priv_desc(spi_transaction_t *trans_desc, spi_trans_priv_t* new_desc, bool isdma)
  637. {
  638. *new_desc = (spi_trans_priv_t) { .trans = trans_desc, };
  639. // rx memory assign
  640. uint32_t* rcv_ptr;
  641. if ( trans_desc->flags & SPI_TRANS_USE_RXDATA ) {
  642. rcv_ptr = (uint32_t *)&trans_desc->rx_data[0];
  643. } else {
  644. //if not use RXDATA neither rx_buffer, buffer_to_rcv assigned to NULL
  645. rcv_ptr = trans_desc->rx_buffer;
  646. }
  647. if (rcv_ptr && isdma && (!esp_ptr_dma_capable(rcv_ptr) || ((int)rcv_ptr % 4 != 0))) {
  648. //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.
  649. ESP_LOGD(SPI_TAG, "Allocate RX buffer for DMA" );
  650. rcv_ptr = heap_caps_malloc((trans_desc->rxlength + 31) / 8, MALLOC_CAP_DMA);
  651. if (rcv_ptr == NULL) goto clean_up;
  652. }
  653. new_desc->buffer_to_rcv = rcv_ptr;
  654. // tx memory assign
  655. const uint32_t *send_ptr;
  656. if ( trans_desc->flags & SPI_TRANS_USE_TXDATA ) {
  657. send_ptr = (uint32_t *)&trans_desc->tx_data[0];
  658. } else {
  659. //if not use TXDATA neither tx_buffer, tx data assigned to NULL
  660. send_ptr = trans_desc->tx_buffer ;
  661. }
  662. if (send_ptr && isdma && !esp_ptr_dma_capable( send_ptr )) {
  663. //if txbuf in the desc not DMA-capable, malloc a new one
  664. ESP_LOGD(SPI_TAG, "Allocate TX buffer for DMA" );
  665. uint32_t *temp = heap_caps_malloc((trans_desc->length + 7) / 8, MALLOC_CAP_DMA);
  666. if (temp == NULL) goto clean_up;
  667. memcpy( temp, send_ptr, (trans_desc->length + 7) / 8 );
  668. send_ptr = temp;
  669. }
  670. new_desc->buffer_to_send = send_ptr;
  671. return ESP_OK;
  672. clean_up:
  673. uninstall_priv_desc(new_desc);
  674. return ESP_ERR_NO_MEM;
  675. }
  676. 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)
  677. {
  678. esp_err_t ret = check_trans_valid(handle, trans_desc);
  679. if (ret != ESP_OK) return ret;
  680. spi_host_t *host = handle->host;
  681. SPI_CHECK(!spi_bus_device_is_polling(handle), "Cannot queue new transaction while previous polling transaction is not terminated.", ESP_ERR_INVALID_STATE );
  682. spi_trans_priv_t trans_buf;
  683. ret = setup_priv_desc(trans_desc, &trans_buf, (host->bus_attr->dma_enabled));
  684. if (ret != ESP_OK) return ret;
  685. #ifdef CONFIG_PM_ENABLE
  686. esp_pm_lock_acquire(host->bus_attr->pm_lock);
  687. #endif
  688. //Send to queue and invoke the ISR.
  689. BaseType_t r = xQueueSend(handle->trans_queue, (void *)&trans_buf, ticks_to_wait);
  690. if (!r) {
  691. ret = ESP_ERR_TIMEOUT;
  692. #ifdef CONFIG_PM_ENABLE
  693. //Release APB frequency lock
  694. esp_pm_lock_release(host->bus_attr->pm_lock);
  695. #endif
  696. goto clean_up;
  697. }
  698. // The ISR will be invoked at correct time by the lock with `spi_bus_intr_enable`.
  699. ret = spi_bus_lock_bg_request(handle->dev_lock);
  700. if (ret != ESP_OK) {
  701. goto clean_up;
  702. }
  703. return ESP_OK;
  704. clean_up:
  705. uninstall_priv_desc(&trans_buf);
  706. return ret;
  707. }
  708. 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)
  709. {
  710. BaseType_t r;
  711. spi_trans_priv_t trans_buf;
  712. SPI_CHECK(handle!=NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  713. //use the interrupt, block until return
  714. r=xQueueReceive(handle->ret_queue, (void*)&trans_buf, ticks_to_wait);
  715. if (!r) {
  716. // The memory occupied by rx and tx DMA buffer destroyed only when receiving from the queue (transaction finished).
  717. // If timeout, wait and retry.
  718. // Every in-flight transaction request occupies internal memory as DMA buffer if needed.
  719. return ESP_ERR_TIMEOUT;
  720. }
  721. //release temporary buffers
  722. uninstall_priv_desc(&trans_buf);
  723. (*trans_desc) = trans_buf.trans;
  724. return ESP_OK;
  725. }
  726. //Porcelain to do one blocking transmission.
  727. esp_err_t SPI_MASTER_ATTR spi_device_transmit(spi_device_handle_t handle, spi_transaction_t *trans_desc)
  728. {
  729. esp_err_t ret;
  730. spi_transaction_t *ret_trans;
  731. //ToDo: check if any spi transfers in flight
  732. ret = spi_device_queue_trans(handle, trans_desc, portMAX_DELAY);
  733. if (ret != ESP_OK) return ret;
  734. ret = spi_device_get_trans_result(handle, &ret_trans, portMAX_DELAY);
  735. if (ret != ESP_OK) return ret;
  736. assert(ret_trans == trans_desc);
  737. return ESP_OK;
  738. }
  739. esp_err_t SPI_MASTER_ISR_ATTR spi_device_acquire_bus(spi_device_t *device, TickType_t wait)
  740. {
  741. spi_host_t *const host = device->host;
  742. SPI_CHECK(wait==portMAX_DELAY, "acquire finite time not supported now.", ESP_ERR_INVALID_ARG);
  743. SPI_CHECK(!spi_bus_device_is_polling(device), "Cannot acquire bus when a polling transaction is in progress.", ESP_ERR_INVALID_STATE );
  744. esp_err_t ret = spi_bus_lock_acquire_start(device->dev_lock, wait);
  745. if (ret != ESP_OK) {
  746. return ret;
  747. }
  748. host->device_acquiring_lock = device;
  749. ESP_LOGD(SPI_TAG, "device%d locked the bus", device->id);
  750. #ifdef CONFIG_PM_ENABLE
  751. // though we don't suggest to block the task before ``release_bus``, still allow doing so.
  752. // this keeps the spi clock at 80MHz even if all tasks are blocked
  753. esp_pm_lock_acquire(host->bus_attr->pm_lock);
  754. #endif
  755. //configure the device ahead so that we don't need to do it again in the following transactions
  756. spi_setup_device(host->device[device->id]);
  757. //the DMA is also occupied by the device, all the slave devices that using DMA should wait until bus released.
  758. if (host->bus_attr->dma_enabled) {
  759. //This workaround is only for esp32, where tx_dma_chan and rx_dma_chan are always same
  760. spicommon_dmaworkaround_transfer_active(host->bus_attr->tx_dma_chan);
  761. }
  762. return ESP_OK;
  763. }
  764. // This function restore configurations required in the non-polling mode
  765. void SPI_MASTER_ISR_ATTR spi_device_release_bus(spi_device_t *dev)
  766. {
  767. spi_host_t *host = dev->host;
  768. if (spi_bus_device_is_polling(dev)){
  769. ESP_EARLY_LOGE(SPI_TAG, "Cannot release bus when a polling transaction is in progress.");
  770. assert(0);
  771. }
  772. if (host->bus_attr->dma_enabled) {
  773. //This workaround is only for esp32, where tx_dma_chan and rx_dma_chan are always same
  774. spicommon_dmaworkaround_idle(host->bus_attr->tx_dma_chan);
  775. }
  776. //Tell common code DMA workaround that our DMA channel is idle. If needed, the code will do a DMA reset.
  777. //allow clock to be lower than 80MHz when all tasks blocked
  778. #ifdef CONFIG_PM_ENABLE
  779. //Release APB frequency lock
  780. esp_pm_lock_release(host->bus_attr->pm_lock);
  781. #endif
  782. ESP_LOGD(SPI_TAG, "device%d release bus", dev->id);
  783. host->device_acquiring_lock = NULL;
  784. esp_err_t ret = spi_bus_lock_acquire_end(dev->dev_lock);
  785. assert(ret == ESP_OK);
  786. }
  787. 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)
  788. {
  789. esp_err_t ret;
  790. SPI_CHECK(ticks_to_wait == portMAX_DELAY, "currently timeout is not available for polling transactions", ESP_ERR_INVALID_ARG);
  791. ret = check_trans_valid(handle, trans_desc);
  792. if (ret!=ESP_OK) return ret;
  793. SPI_CHECK(!spi_bus_device_is_polling(handle), "Cannot send polling transaction while the previous polling transaction is not terminated.", ESP_ERR_INVALID_STATE );
  794. /* If device_acquiring_lock is set to handle, it means that the user has already
  795. * acquired the bus thanks to the function `spi_device_acquire_bus()`.
  796. * In that case, we don't need to take the lock again. */
  797. spi_host_t *host = handle->host;
  798. if (host->device_acquiring_lock != handle) {
  799. ret = spi_bus_lock_acquire_start(handle->dev_lock, ticks_to_wait);
  800. } else {
  801. ret = spi_bus_lock_wait_bg_done(handle->dev_lock, ticks_to_wait);
  802. }
  803. if (ret != ESP_OK) return ret;
  804. ret = setup_priv_desc(trans_desc, &host->cur_trans_buf, (host->bus_attr->dma_enabled));
  805. if (ret!=ESP_OK) return ret;
  806. //Polling, no interrupt is used.
  807. host->polling = true;
  808. ESP_LOGV(SPI_TAG, "polling trans");
  809. spi_new_trans(handle, &host->cur_trans_buf);
  810. return ESP_OK;
  811. }
  812. esp_err_t SPI_MASTER_ISR_ATTR spi_device_polling_end(spi_device_handle_t handle, TickType_t ticks_to_wait)
  813. {
  814. SPI_CHECK(handle != NULL, "invalid dev handle", ESP_ERR_INVALID_ARG);
  815. spi_host_t *host = handle->host;
  816. assert(host->cur_cs == handle->id);
  817. assert(handle == get_acquiring_dev(host));
  818. TickType_t start = xTaskGetTickCount();
  819. while (!spi_hal_usr_is_done(&host->hal)) {
  820. TickType_t end = xTaskGetTickCount();
  821. if (end - start > ticks_to_wait) {
  822. return ESP_ERR_TIMEOUT;
  823. }
  824. }
  825. ESP_LOGV(SPI_TAG, "polling trans done");
  826. //deal with the in-flight transaction
  827. spi_post_trans(host);
  828. //release temporary buffers
  829. uninstall_priv_desc(&host->cur_trans_buf);
  830. host->polling = false;
  831. if (host->device_acquiring_lock != handle) {
  832. assert(host->device_acquiring_lock == NULL);
  833. spi_bus_lock_acquire_end(handle->dev_lock);
  834. }
  835. return ESP_OK;
  836. }
  837. esp_err_t SPI_MASTER_ISR_ATTR spi_device_polling_transmit(spi_device_handle_t handle, spi_transaction_t* trans_desc)
  838. {
  839. esp_err_t ret;
  840. if (handle->host->mutex) xSemaphoreTake(handle->host->mutex, portMAX_DELAY);
  841. ret = spi_device_polling_start(handle, trans_desc, portMAX_DELAY);
  842. if (ret != ESP_OK) {
  843. if (handle->host->mutex) xSemaphoreGive(handle->host->mutex);
  844. return ret;
  845. }
  846. ret = spi_device_polling_end(handle, portMAX_DELAY);
  847. if (handle->host->mutex) xSemaphoreGive(handle->host->mutex);
  848. return ret;
  849. }