spi_master.c 44 KB

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