spi_bus_lock.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. /*
  2. * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include "freertos/FreeRTOS.h"
  7. #include "freertos/semphr.h"
  8. #include <stdatomic.h>
  9. #include "sdkconfig.h"
  10. #include "spi_common_internal.h"
  11. #include "esp_intr_alloc.h"
  12. #include "soc/soc_caps.h"
  13. #include "stdatomic.h"
  14. #include "esp_log.h"
  15. #include <strings.h>
  16. #include "esp_heap_caps.h"
  17. /*
  18. * This lock is designed to solve the conflicts between SPI devices (used in tasks) and
  19. * the background operations (ISR or cache access).
  20. *
  21. * There are N (device/task) + 1 (BG) acquiring processer candidates that may touch the bus.
  22. *
  23. * The core of the lock is a `status` atomic variable, which is always available. No intermediate
  24. * status is allowed. The atomic operations (mainly `atomic_fetch_and`, `atomic_fetch_or`)
  25. * atomically read the status, and bitwisely write status value ORed / ANDed with given masks.
  26. *
  27. * Definitions of the status:
  28. * - [30] WEAK_BG_FLAG, active when the BG is the cache
  29. * - [29:20] LOCK bits, active when corresponding device is asking for acquiring
  30. * - [19:10] PENDING bits, active when the BG acknowledges the REQ bits, but hasn't fully handled them.
  31. * - [ 9: 0] REQ bits, active when corresponding device is requesting for BG operations.
  32. *
  33. * The REQ bits together PENDING bits are called BG bits, which represent the actual BG request
  34. * state of devices. Either one of REQ or PENDING being active indicates the device has pending BG
  35. * requests. Reason of having two bits instead of one is in the appendix below.
  36. *
  37. * Acquiring processer means the current processor (task or ISR) allowed to touch the critical
  38. * resources, or the SPI bus.
  39. *
  40. * States of the lock:
  41. * - STATE_IDLE: There's no acquiring processor. No device is acquiring the bus, and no BG
  42. * operation is in progress.
  43. *
  44. * - STATE_ACQ: The acquiring processor is a device task. This means one of the devices is
  45. * acquiring the bus.
  46. *
  47. * - STATE_BG: The acquiring processor is the ISR, and there is no acquiring device.
  48. *
  49. * - STATE_BG_ACQ: The acquiring processor is the ISR, and there is an acquiring device.
  50. *
  51. *
  52. * Whenever a bit is written to the status, it means the a device on a task is trying to acquire
  53. * the lock (either for the task, or the ISR). When there is no LOCK bits or BG bits active, the
  54. * caller immediately become the acquiring processor. Otherwise, the task has to block, and the ISR
  55. * will not be invoked until scheduled by the current acquiring processor.
  56. *
  57. * The acquiring processor is responsible to assign the next acquiring processor by calling the
  58. * scheduler, usually after it finishes some requests, and cleared the corresponding status bit.
  59. * But there is one exception, when the last bit is cleared from the status, after which there is
  60. * no other LOCK bits or BG bits active, the acquiring processor lost its role immediately, and
  61. * don't need to call the scheduler to assign the next acquiring processor.
  62. *
  63. * The acquiring processor may also choose to assign a new acquiring device when there is no, by
  64. * calling `spi_bus_lock_bg_rotate_acq_dev` in the ISR. But the acquiring processor, in this case,
  65. * is still the ISR, until it calls the scheduler.
  66. *
  67. *
  68. * Transition of the FSM:
  69. *
  70. * - STATE_IDLE: no acquiring device, nor acquiring processor, no LOCK or BG bits active
  71. * -> STATE_BG: by `req_core`
  72. * -> STATE_ACQ: by `acquire_core`
  73. *
  74. * - STATE_BG:
  75. * * No acquiring device, the ISR is the acquiring processor, there is BG bits active, but no LOCK
  76. * bits
  77. * * The BG operation should be enabled while turning into this state.
  78. *
  79. * -> STATE_IDLE: by `bg_exit_core` after `clear_pend_core` for all BG bits
  80. * -> STATE_BG_ACQ: by `schedule_core`, when there is new LOCK bit set (by `acquire_core`)
  81. *
  82. * - STATE_BG_ACQ:
  83. * * There is acquiring device, the ISR is the acquiring processor, there may be BG bits active for
  84. * the acquiring device.
  85. * * The BG operation should be enabled while turning into this state.
  86. *
  87. * -> STATE_ACQ: by `bg_exit_core` after `clear_pend_core` for all BG bits for the acquiring
  88. * device.
  89. *
  90. * Should not go to the STATE_ACQ (unblock the acquiring task) until all requests of the
  91. * acquiring device are finished. This is to preserve the sequence of foreground (polling) and
  92. * background operations of the device. The background operations queued before the acquiring
  93. * should be completed first.
  94. *
  95. * - STATE_ACQ:
  96. * * There is acquiring device, the task is the acquiring processor, there is no BG bits active for
  97. * the acquiring device.
  98. * * The acquiring task (if blocked at `spi_bus_lock_acquire_start` or `spi_bus_lock_wait_bg_done`)
  99. * should be resumed while turning into this state.
  100. *
  101. * -> STATE_BG_ACQ: by `req_core`
  102. * -> STATE_BG_ACQ (other device): by `acquire_end_core`, when there is LOCK bit for another
  103. * device, and the new acquiring device has active BG bits.
  104. * -> STATE_ACQ (other device): by `acquire_end_core`, when there is LOCK bit for another devices,
  105. * but the new acquiring device has no active BG bits.
  106. * -> STATE_BG: by `acquire_end_core` when there is no LOCK bit active, but there are active BG
  107. * bits.
  108. * -> STATE_IDLE: by `acquire_end_core` when there is no LOCK bit, nor BG bit active.
  109. *
  110. * The `req_core` used in the task is a little special. It asks for acquiring processor for the
  111. * ISR. When it succeed for the first time, it will invoke the ISR (hence passing the acquiring
  112. * role to the BG). Otherwise it will not block, the ISR will be automatically be invoked by other
  113. * acquiring processor. The caller of `req_core` will never become acquiring processor by this
  114. * function.
  115. *
  116. *
  117. * Appendix: The design, that having both request bit and pending bit, is to solve the
  118. * concurrency issue between tasks and the bg, when the task can queue several requests,
  119. * however the request bit cannot represent the number of requests queued.
  120. *
  121. * Here's the workflow of task and ISR work concurrently:
  122. * - Task: (a) Write to Queue -> (b) Write request bit
  123. * The Task have to write request bit (b) after the data is prepared in the queue (a),
  124. * otherwise the BG may fail to read from the queue when it sees the request bit set.
  125. *
  126. * - BG: (c) Read queue -> (d) Clear request bit
  127. * Since the BG cannot know the number of requests queued, it have to repeatedly check the
  128. * queue (c), until it find the data is empty, and then clear the request bit (d).
  129. *
  130. * The events are possible to happen in the order: (c) -> (a) -> (b) -> (d). This may cause a false
  131. * clear of the request bit. And there will be data prepared in the queue, but the request bit is
  132. * inactive.
  133. *
  134. * (e) move REQ bits to PEND bits, happen before (c) is introduced to solve this problem. In this
  135. * case (d) is changed to clear the PEND bit. Even if (e) -> (c) -> (a) -> (b) -> (d), only PEND
  136. * bit is cleared, while the REQ bit is still active.
  137. */
  138. struct spi_bus_lock_dev_t;
  139. typedef struct spi_bus_lock_dev_t spi_bus_lock_dev_t;
  140. typedef struct spi_bus_lock_t spi_bus_lock_t;
  141. #define MAX_DEV_NUM 10
  142. // Bit 29-20: lock bits, Bit 19-10: pending bits
  143. // Bit 9-0: request bits, Bit 30:
  144. #define LOCK_SHIFT 20
  145. #define PENDING_SHIFT 10
  146. #define REQ_SHIFT 0
  147. #define WEAK_BG_FLAG BIT(30) /**< The bus is permanently requested by background operations.
  148. * This flag is weak, will not prevent acquiring of devices. But will help the BG to be re-enabled again after the bus is release.
  149. */
  150. // get the bit mask wher bit [high-1, low] are all 1'b1 s.
  151. #define BIT1_MASK(high, low) ((UINT32_MAX << (high)) ^ (UINT32_MAX << (low)))
  152. #define LOCK_BIT(mask) ((mask) << LOCK_SHIFT)
  153. #define REQUEST_BIT(mask) ((mask) << REQ_SHIFT)
  154. #define PENDING_BIT(mask) ((mask) << PENDING_SHIFT)
  155. #define DEV_MASK(id) (LOCK_BIT(1<<id) | PENDING_BIT(1<<id) | REQUEST_BIT(1<<id))
  156. #define ID_DEV_MASK(mask) (ffs(mask) - 1)
  157. #define REQ_MASK BIT1_MASK(REQ_SHIFT+MAX_DEV_NUM, REQ_SHIFT)
  158. #define PEND_MASK BIT1_MASK(PENDING_SHIFT+MAX_DEV_NUM, PENDING_SHIFT)
  159. #define BG_MASK BIT1_MASK(REQ_SHIFT+MAX_DEV_NUM*2, REQ_SHIFT)
  160. #define LOCK_MASK BIT1_MASK(LOCK_SHIFT+MAX_DEV_NUM, LOCK_SHIFT)
  161. #define DEV_REQ_MASK(dev) ((dev)->mask & REQ_MASK)
  162. #define DEV_PEND_MASK(dev) ((dev)->mask & PEND_MASK)
  163. #define DEV_BG_MASK(dev) ((dev)->mask & BG_MASK)
  164. struct spi_bus_lock_t {
  165. /**
  166. * The core of the lock. These bits are status of the lock, which should be always available.
  167. * No intermediate status is allowed. This is realized by atomic operations, mainly
  168. * `atomic_fetch_and`, `atomic_fetch_or`, which atomically read the status, and bitwise write
  169. * status value ORed / ANDed with given masks.
  170. *
  171. * The request bits together pending bits represent the actual bg request state of one device.
  172. * Either one of them being active indicates the device has pending bg requests.
  173. *
  174. * Whenever a bit is written to the status, it means the a device on a task is trying to
  175. * acquire the lock. But this will succeed only when no LOCK or BG bits active.
  176. *
  177. * The acquiring processor is responsible to call the scheduler to pass its role to other tasks
  178. * or the BG, unless it clear the last bit in the status register.
  179. */
  180. //// Critical resources, they are only writable by acquiring processor, and stable only when read by the acquiring processor.
  181. atomic_uint_fast32_t status;
  182. spi_bus_lock_dev_t* volatile acquiring_dev; ///< The acquiring device
  183. bool volatile acq_dev_bg_active; ///< BG is the acquiring processor serving the acquiring device, used for the wait_bg to skip waiting quickly.
  184. bool volatile in_isr; ///< ISR is touching HW
  185. //// End of critical resources
  186. atomic_intptr_t dev[DEV_NUM_MAX]; ///< Child locks.
  187. bg_ctrl_func_t bg_enable; ///< Function to enable background operations.
  188. bg_ctrl_func_t bg_disable; ///< Function to disable background operations
  189. void* bg_arg; ///< Argument for `bg_enable` and `bg_disable` functions.
  190. spi_bus_lock_dev_t* last_dev; ///< Last used device, to decide whether to refresh all registers.
  191. int periph_cs_num; ///< Number of the CS pins the HW has.
  192. //debug information
  193. int host_id; ///< Host ID, for debug information printing
  194. uint32_t new_req; ///< Last int_req when `spi_bus_lock_bg_start` is called. Debug use.
  195. };
  196. struct spi_bus_lock_dev_t {
  197. SemaphoreHandle_t semphr; ///< Binray semaphore to notify the device it claimed the bus
  198. spi_bus_lock_t* parent; ///< Pointer to parent spi_bus_lock_t
  199. uint32_t mask; ///< Bitwise OR-ed mask of the REQ, PEND, LOCK bits of this device
  200. };
  201. DRAM_ATTR static const char TAG[] = "bus_lock";
  202. #define LOCK_CHECK(a, str, ret_val, ...) \
  203. if (!(a)) { \
  204. ESP_LOGE(TAG,"%s(%d): "str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
  205. return (ret_val); \
  206. }
  207. static inline int mask_get_id(uint32_t mask);
  208. static inline int dev_lock_get_id(spi_bus_lock_dev_t *dev_lock);
  209. /*******************************************************************************
  210. * atomic operations to the status
  211. ******************************************************************************/
  212. SPI_MASTER_ISR_ATTR static inline uint32_t lock_status_fetch_set(spi_bus_lock_t *lock, uint32_t set)
  213. {
  214. return atomic_fetch_or(&lock->status, set);
  215. }
  216. IRAM_ATTR static inline uint32_t lock_status_fetch_clear(spi_bus_lock_t *lock, uint32_t clear)
  217. {
  218. return atomic_fetch_and(&lock->status, ~clear);
  219. }
  220. IRAM_ATTR static inline uint32_t lock_status_fetch(spi_bus_lock_t *lock)
  221. {
  222. return atomic_load(&lock->status);
  223. }
  224. SPI_MASTER_ISR_ATTR static inline void lock_status_init(spi_bus_lock_t *lock)
  225. {
  226. atomic_store(&lock->status, 0);
  227. }
  228. // return the remaining status bits
  229. IRAM_ATTR static inline uint32_t lock_status_clear(spi_bus_lock_t* lock, uint32_t clear)
  230. {
  231. //the fetch and clear should be atomic, avoid missing the all '0' status when all bits are clear.
  232. uint32_t state = lock_status_fetch_clear(lock, clear);
  233. return state & (~clear);
  234. }
  235. /*******************************************************************************
  236. * Schedule service
  237. *
  238. * The modification to the status bits may cause rotating of the acquiring processor. It also have
  239. * effects to `acquired_dev` (the acquiring device), `in_isr` (HW used in BG), and
  240. * `acq_dev_bg_active` (wait_bg_end can be skipped) members of the lock structure.
  241. *
  242. * Most of them should be atomic, and special attention should be paid to the operation
  243. * sequence.
  244. ******************************************************************************/
  245. SPI_MASTER_ISR_ATTR static inline void resume_dev_in_isr(spi_bus_lock_dev_t *dev_lock, BaseType_t *do_yield)
  246. {
  247. xSemaphoreGiveFromISR(dev_lock->semphr, do_yield);
  248. }
  249. IRAM_ATTR static inline void resume_dev(const spi_bus_lock_dev_t *dev_lock)
  250. {
  251. xSemaphoreGive(dev_lock->semphr);
  252. }
  253. SPI_MASTER_ISR_ATTR static inline void bg_disable(spi_bus_lock_t *lock)
  254. {
  255. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->bg_disable);
  256. lock->bg_disable(lock->bg_arg);
  257. }
  258. IRAM_ATTR static inline void bg_enable(spi_bus_lock_t* lock)
  259. {
  260. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->bg_enable);
  261. lock->bg_enable(lock->bg_arg);
  262. }
  263. // Set the REQ bit. If we become the acquiring processor, invoke the ISR and pass that to it.
  264. // The caller will never become the acquiring processor after this function returns.
  265. SPI_MASTER_ATTR static inline void req_core(spi_bus_lock_dev_t *dev_handle)
  266. {
  267. spi_bus_lock_t *lock = dev_handle->parent;
  268. // Though `acquired_dev` is critical resource, `dev_handle == lock->acquired_dev`
  269. // is a stable statement unless `acquire_start` or `acquire_end` is called by current
  270. // device.
  271. if (dev_handle == lock->acquiring_dev){
  272. // Set the REQ bit and check BG bits if we are the acquiring processor.
  273. // If the BG bits were not active before, invoke the BG again.
  274. // Avoid competitive risk against the `clear_pend_core`, `acq_dev_bg_active` should be set before
  275. // setting REQ bit.
  276. lock->acq_dev_bg_active = true;
  277. uint32_t status = lock_status_fetch_set(lock, DEV_REQ_MASK(dev_handle));
  278. if ((status & DEV_BG_MASK(dev_handle)) == 0) {
  279. bg_enable(lock); //acquiring processor passed to BG
  280. }
  281. } else {
  282. uint32_t status = lock_status_fetch_set(lock, DEV_REQ_MASK(dev_handle));
  283. if (status == 0) {
  284. bg_enable(lock); //acquiring processor passed to BG
  285. }
  286. }
  287. }
  288. //Set the LOCK bit. Handle related stuff and return true if we become the acquiring processor.
  289. SPI_MASTER_ISR_ATTR static inline bool acquire_core(spi_bus_lock_dev_t *dev_handle)
  290. {
  291. spi_bus_lock_t* lock = dev_handle->parent;
  292. uint32_t status = lock_status_fetch_set(lock, dev_handle->mask & LOCK_MASK);
  293. // Check all bits except WEAK_BG
  294. if ((status & (BG_MASK | LOCK_MASK)) == 0) {
  295. //succeed at once
  296. lock->acquiring_dev = dev_handle;
  297. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
  298. if (status & WEAK_BG_FLAG) {
  299. //Mainly to disable the cache (Weak_BG), that is not able to disable itself
  300. bg_disable(lock);
  301. }
  302. return true;
  303. }
  304. return false;
  305. }
  306. /**
  307. * Find the next acquiring processor according to the status. Will directly change
  308. * the acquiring device if new one found.
  309. *
  310. * Cases:
  311. * - BG should still be the acquiring processor (Return false):
  312. * 1. Acquiring device has active BG bits: out_desired_dev = new acquiring device
  313. * 2. No acquiring device, but BG active: out_desired_dev = randomly pick one device with active BG bits
  314. * - BG should yield to the task (Return true):
  315. * 3. Acquiring device has no active BG bits: out_desired_dev = new acquiring device
  316. * 4. No acquiring device while no active BG bits: out_desired_dev=NULL
  317. *
  318. * Acquiring device task need to be resumed only when case 3.
  319. *
  320. * This scheduling can happen in either task or ISR, so `in_isr` or `bg_active` not touched.
  321. *
  322. * @param lock
  323. * @param status Current status
  324. * @param out_desired_dev Desired device to work next, see above.
  325. *
  326. * @return False if BG should still be the acquiring processor, otherwise True (yield to task).
  327. */
  328. IRAM_ATTR static inline bool
  329. schedule_core(spi_bus_lock_t *lock, uint32_t status, spi_bus_lock_dev_t **out_desired_dev)
  330. {
  331. spi_bus_lock_dev_t* desired_dev = NULL;
  332. uint32_t lock_bits = (status & LOCK_MASK) >> LOCK_SHIFT;
  333. uint32_t bg_bits = status & BG_MASK;
  334. bg_bits = ((bg_bits >> REQ_SHIFT) | (bg_bits >> PENDING_SHIFT)) & REQ_MASK;
  335. bool bg_yield;
  336. if (lock_bits) {
  337. int dev_id = mask_get_id(lock_bits);
  338. desired_dev = (spi_bus_lock_dev_t *)atomic_load(&lock->dev[dev_id]);
  339. BUS_LOCK_DEBUG_EXECUTE_CHECK(desired_dev);
  340. lock->acquiring_dev = desired_dev;
  341. bg_yield = ((bg_bits & desired_dev->mask) == 0);
  342. lock->acq_dev_bg_active = !bg_yield;
  343. } else {
  344. lock->acq_dev_bg_active = false;
  345. if (bg_bits) {
  346. int dev_id = mask_get_id(bg_bits);
  347. desired_dev = (spi_bus_lock_dev_t *)atomic_load(&lock->dev[dev_id]);
  348. BUS_LOCK_DEBUG_EXECUTE_CHECK(desired_dev);
  349. lock->acquiring_dev = NULL;
  350. bg_yield = false;
  351. } else {
  352. desired_dev = NULL;
  353. lock->acquiring_dev = NULL;
  354. bg_yield = true;
  355. }
  356. }
  357. *out_desired_dev = desired_dev;
  358. return bg_yield;
  359. }
  360. //Clear the LOCK bit and trigger a rescheduling.
  361. IRAM_ATTR static inline void acquire_end_core(spi_bus_lock_dev_t *dev_handle)
  362. {
  363. spi_bus_lock_t* lock = dev_handle->parent;
  364. uint32_t status = lock_status_clear(lock, dev_handle->mask & LOCK_MASK);
  365. spi_bus_lock_dev_t* desired_dev = NULL;
  366. bool invoke_bg = !schedule_core(lock, status, &desired_dev);
  367. if (invoke_bg) {
  368. bg_enable(lock);
  369. } else if (desired_dev) {
  370. resume_dev(desired_dev);
  371. } else if (status & WEAK_BG_FLAG) {
  372. bg_enable(lock);
  373. }
  374. }
  375. // Move the REQ bits to corresponding PEND bits. Must be called by acquiring processor.
  376. // Have no side effects on the acquiring device/processor.
  377. SPI_MASTER_ISR_ATTR static inline void update_pend_core(spi_bus_lock_t *lock, uint32_t status)
  378. {
  379. uint32_t active_req_bits = status & REQ_MASK;
  380. #if PENDING_SHIFT > REQ_SHIFT
  381. uint32_t pending_mask = active_req_bits << (PENDING_SHIFT - REQ_SHIFT);
  382. #else
  383. uint32_t pending_mask = active_req_bits >> (REQ_SHIFT - PENDING_SHIFT);
  384. #endif
  385. // We have to set the PEND bits and then clear the REQ bits, since BG bits are using bitwise OR logic,
  386. // this will not influence the effectiveness of the BG bits of every device.
  387. lock_status_fetch_set(lock, pending_mask);
  388. lock_status_fetch_clear(lock, active_req_bits);
  389. }
  390. // Clear the PEND bit (not REQ bit!) of a device, return the suggestion whether we can try to quit the ISR.
  391. // Lost the acquiring processor immediately when the BG bits for active device are inactive, indiciating by the return value.
  392. // Can be called only when ISR is acting as the acquiring processor.
  393. SPI_MASTER_ISR_ATTR static inline bool clear_pend_core(spi_bus_lock_dev_t *dev_handle)
  394. {
  395. bool finished;
  396. spi_bus_lock_t *lock = dev_handle->parent;
  397. uint32_t pend_mask = DEV_PEND_MASK(dev_handle);
  398. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock_status_fetch(lock) & pend_mask);
  399. uint32_t status = lock_status_clear(lock, pend_mask);
  400. if (lock->acquiring_dev == dev_handle) {
  401. finished = ((status & DEV_REQ_MASK(dev_handle)) == 0);
  402. if (finished) {
  403. lock->acq_dev_bg_active = false;
  404. }
  405. } else {
  406. finished = (status == 0);
  407. }
  408. return finished;
  409. }
  410. // Return true if the ISR has already touched the HW, which means previous operations should
  411. // be terminated first, before we use the HW again. Otherwise return false.
  412. // In either case `in_isr` will be marked as true, until call to `bg_exit_core` with `wip=false` successfully.
  413. SPI_MASTER_ISR_ATTR static inline bool bg_entry_core(spi_bus_lock_t *lock)
  414. {
  415. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev || lock->acq_dev_bg_active);
  416. /*
  417. * The interrupt is disabled at the entry of ISR to avoid competitive risk as below:
  418. *
  419. * The `esp_intr_enable` will be called (b) after new BG request is queued (a) in the task;
  420. * while `esp_intr_disable` should be called (c) if we check and found the sending queue is empty (d).
  421. * If (c) happens after (d), if things happens in this sequence:
  422. * (d) -> (a) -> (b) -> (c), the interrupt will be disabled while there's pending BG request in the queue.
  423. *
  424. * To avoid this, interrupt is disabled here, and re-enabled later if required. (c) -> (d) -> (a) -> (b) -> revert (c) if !d
  425. */
  426. bg_disable(lock);
  427. if (lock->in_isr) {
  428. return false;
  429. } else {
  430. lock->in_isr = true;
  431. return true;
  432. }
  433. }
  434. // Handle the conditions of status and interrupt, avoiding the ISR being disabled when there is any new coming BG requests.
  435. // When called with `wip=true`, means the ISR is performing some operations. Will enable the interrupt again and exit unconditionally.
  436. // When called with `wip=false`, will only return `true` when there is no coming BG request. If return value is `false`, the ISR should try again.
  437. // Will not change acquiring device.
  438. SPI_MASTER_ISR_ATTR static inline bool bg_exit_core(spi_bus_lock_t *lock, bool wip, BaseType_t *do_yield)
  439. {
  440. //See comments in `bg_entry_core`, re-enable interrupt disabled in entry if we do need the interrupt
  441. if (wip) {
  442. bg_enable(lock);
  443. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev || lock->acq_dev_bg_active);
  444. return true;
  445. }
  446. bool ret;
  447. uint32_t status = lock_status_fetch(lock);
  448. if (lock->acquiring_dev) {
  449. if (status & DEV_BG_MASK(lock->acquiring_dev)) {
  450. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->acq_dev_bg_active);
  451. ret = false;
  452. } else {
  453. // The request may happen any time, even after we fetched the status.
  454. // The value of `acq_dev_bg_active` is random.
  455. resume_dev_in_isr(lock->acquiring_dev, do_yield);
  456. ret = true;
  457. }
  458. } else {
  459. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
  460. ret = !(status & BG_MASK);
  461. }
  462. if (ret) {
  463. //when successfully exit, but no transaction done, mark BG as inactive
  464. lock->in_isr = false;
  465. }
  466. return ret;
  467. }
  468. IRAM_ATTR static inline void dev_wait_prepare(spi_bus_lock_dev_t *dev_handle)
  469. {
  470. xSemaphoreTake(dev_handle->semphr, 0);
  471. }
  472. SPI_MASTER_ISR_ATTR static inline esp_err_t dev_wait(spi_bus_lock_dev_t *dev_handle, TickType_t wait)
  473. {
  474. BaseType_t ret = xSemaphoreTake(dev_handle->semphr, wait);
  475. if (ret == pdFALSE) return ESP_ERR_TIMEOUT;
  476. return ESP_OK;
  477. }
  478. /*******************************************************************************
  479. * Initialization & Deinitialization
  480. ******************************************************************************/
  481. esp_err_t spi_bus_init_lock(spi_bus_lock_handle_t *out_lock, const spi_bus_lock_config_t *config)
  482. {
  483. spi_bus_lock_t* lock = (spi_bus_lock_t*)calloc(sizeof(spi_bus_lock_t), 1);
  484. if (lock == NULL) {
  485. return ESP_ERR_NO_MEM;
  486. }
  487. lock_status_init(lock);
  488. lock->acquiring_dev = NULL;
  489. lock->last_dev = NULL;
  490. lock->periph_cs_num = config->cs_num;
  491. lock->host_id = config->host_id;
  492. *out_lock = lock;
  493. return ESP_OK;
  494. }
  495. void spi_bus_deinit_lock(spi_bus_lock_handle_t lock)
  496. {
  497. for (int i = 0; i < DEV_NUM_MAX; i++) {
  498. assert(atomic_load(&lock->dev[i]) == (intptr_t)NULL);
  499. }
  500. free(lock);
  501. }
  502. static int try_acquire_free_dev(spi_bus_lock_t *lock, bool cs_required)
  503. {
  504. if (cs_required) {
  505. int i;
  506. for (i = 0; i < lock->periph_cs_num; i++) {
  507. intptr_t null = (intptr_t) NULL;
  508. //use 1 to occupy the slot, actual setup comes later
  509. if (atomic_compare_exchange_strong(&lock->dev[i], &null, (intptr_t) 1)) {
  510. break;
  511. }
  512. }
  513. return ((i == lock->periph_cs_num)? -1: i);
  514. } else {
  515. int i;
  516. for (i = DEV_NUM_MAX - 1; i >= 0; i--) {
  517. intptr_t null = (intptr_t) NULL;
  518. //use 1 to occupy the slot, actual setup comes later
  519. if (atomic_compare_exchange_strong(&lock->dev[i], &null, (intptr_t) 1)) {
  520. break;
  521. }
  522. }
  523. return i;
  524. }
  525. }
  526. esp_err_t spi_bus_lock_register_dev(spi_bus_lock_handle_t lock, spi_bus_lock_dev_config_t *config,
  527. spi_bus_lock_dev_handle_t *out_dev_handle)
  528. {
  529. if (lock == NULL) return ESP_ERR_INVALID_ARG;
  530. int id = try_acquire_free_dev(lock, config->flags & SPI_BUS_LOCK_DEV_FLAG_CS_REQUIRED);
  531. if (id == -1) return ESP_ERR_NOT_SUPPORTED;
  532. spi_bus_lock_dev_t* dev_lock = (spi_bus_lock_dev_t*)heap_caps_calloc(sizeof(spi_bus_lock_dev_t), 1, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT);
  533. if (dev_lock == NULL) {
  534. return ESP_ERR_NO_MEM;
  535. }
  536. dev_lock->semphr = xSemaphoreCreateBinary();
  537. if (dev_lock->semphr == NULL) {
  538. free(dev_lock);
  539. atomic_store(&lock->dev[id], (intptr_t)NULL);
  540. return ESP_ERR_NO_MEM;
  541. }
  542. dev_lock->parent = lock;
  543. dev_lock->mask = DEV_MASK(id);
  544. ESP_LOGV(TAG, "device registered on bus %d slot %d.", lock->host_id, id);
  545. atomic_store(&lock->dev[id], (intptr_t)dev_lock);
  546. *out_dev_handle = dev_lock;
  547. return ESP_OK;
  548. }
  549. void spi_bus_lock_unregister_dev(spi_bus_lock_dev_handle_t dev_handle)
  550. {
  551. int id = dev_lock_get_id(dev_handle);
  552. spi_bus_lock_t* lock = dev_handle->parent;
  553. BUS_LOCK_DEBUG_EXECUTE_CHECK(atomic_load(&lock->dev[id]) == (intptr_t)dev_handle);
  554. if (lock->last_dev == dev_handle) lock->last_dev = NULL;
  555. atomic_store(&lock->dev[id], (intptr_t)NULL);
  556. if (dev_handle->semphr) {
  557. vSemaphoreDelete(dev_handle->semphr);
  558. }
  559. free(dev_handle);
  560. }
  561. IRAM_ATTR static inline int mask_get_id(uint32_t mask)
  562. {
  563. return ID_DEV_MASK(mask);
  564. }
  565. IRAM_ATTR static inline int dev_lock_get_id(spi_bus_lock_dev_t *dev_lock)
  566. {
  567. return mask_get_id(dev_lock->mask);
  568. }
  569. void spi_bus_lock_set_bg_control(spi_bus_lock_handle_t lock, bg_ctrl_func_t bg_enable, bg_ctrl_func_t bg_disable, void *arg)
  570. {
  571. lock->bg_enable = bg_enable;
  572. lock->bg_disable = bg_disable;
  573. lock->bg_arg = arg;
  574. }
  575. IRAM_ATTR int spi_bus_lock_get_dev_id(spi_bus_lock_dev_handle_t dev_handle)
  576. {
  577. return (dev_handle? dev_lock_get_id(dev_handle): -1);
  578. }
  579. //will be called when cache disabled
  580. IRAM_ATTR bool spi_bus_lock_touch(spi_bus_lock_dev_handle_t dev_handle)
  581. {
  582. spi_bus_lock_dev_t* last_dev = dev_handle->parent->last_dev;
  583. dev_handle->parent->last_dev = dev_handle;
  584. if (last_dev != dev_handle) {
  585. int last_dev_id = (last_dev? dev_lock_get_id(last_dev): -1);
  586. ESP_DRAM_LOGV(TAG, "SPI dev changed from %d to %d",
  587. last_dev_id, dev_lock_get_id(dev_handle));
  588. }
  589. return (dev_handle != last_dev);
  590. }
  591. /*******************************************************************************
  592. * Acquiring service
  593. ******************************************************************************/
  594. IRAM_ATTR esp_err_t spi_bus_lock_acquire_start(spi_bus_lock_dev_t *dev_handle, TickType_t wait)
  595. {
  596. LOCK_CHECK(wait == portMAX_DELAY, "timeout other than portMAX_DELAY not supported", ESP_ERR_INVALID_ARG);
  597. spi_bus_lock_t* lock = dev_handle->parent;
  598. // Clear the semaphore before checking
  599. dev_wait_prepare(dev_handle);
  600. if (!acquire_core(dev_handle)) {
  601. //block until becoming the acquiring processor (help by previous acquiring processor)
  602. esp_err_t err = dev_wait(dev_handle, wait);
  603. //TODO: add timeout handling here.
  604. if (err != ESP_OK) return err;
  605. }
  606. ESP_DRAM_LOGV(TAG, "dev %d acquired.", dev_lock_get_id(dev_handle));
  607. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->acquiring_dev == dev_handle);
  608. //When arrives at here, requests of this device should already be handled
  609. uint32_t status = lock_status_fetch(lock);
  610. (void) status;
  611. BUS_LOCK_DEBUG_EXECUTE_CHECK((status & DEV_BG_MASK(dev_handle)) == 0);
  612. return ESP_OK;
  613. }
  614. IRAM_ATTR esp_err_t spi_bus_lock_acquire_end(spi_bus_lock_dev_t *dev_handle)
  615. {
  616. //release the bus
  617. spi_bus_lock_t* lock = dev_handle->parent;
  618. LOCK_CHECK(lock->acquiring_dev == dev_handle, "Cannot release a lock that hasn't been acquired.", ESP_ERR_INVALID_STATE);
  619. acquire_end_core(dev_handle);
  620. ESP_LOGV(TAG, "dev %d released.", dev_lock_get_id(dev_handle));
  621. return ESP_OK;
  622. }
  623. SPI_MASTER_ISR_ATTR spi_bus_lock_dev_handle_t spi_bus_lock_get_acquiring_dev(spi_bus_lock_t *lock)
  624. {
  625. return lock->acquiring_dev;
  626. }
  627. /*******************************************************************************
  628. * BG (background operation) service
  629. ******************************************************************************/
  630. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_entry(spi_bus_lock_t* lock)
  631. {
  632. return bg_entry_core(lock);
  633. }
  634. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_exit(spi_bus_lock_t* lock, bool wip, BaseType_t* do_yield)
  635. {
  636. return bg_exit_core(lock, wip, do_yield);
  637. }
  638. SPI_MASTER_ATTR esp_err_t spi_bus_lock_bg_request(spi_bus_lock_dev_t *dev_handle)
  639. {
  640. req_core(dev_handle);
  641. return ESP_OK;
  642. }
  643. IRAM_ATTR esp_err_t spi_bus_lock_wait_bg_done(spi_bus_lock_dev_handle_t dev_handle, TickType_t wait)
  644. {
  645. spi_bus_lock_t *lock = dev_handle->parent;
  646. LOCK_CHECK(lock->acquiring_dev == dev_handle, "Cannot wait for a device that is not acquired", ESP_ERR_INVALID_STATE);
  647. LOCK_CHECK(wait == portMAX_DELAY, "timeout other than portMAX_DELAY not supported", ESP_ERR_INVALID_ARG);
  648. // If no BG bits active, skip quickly. This is ensured by `spi_bus_lock_wait_bg_done`
  649. // cannot be executed with `bg_request` on the same device concurrently.
  650. if (lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) {
  651. // Clear the semaphore before checking
  652. dev_wait_prepare(dev_handle);
  653. if (lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) {
  654. //block until becoming the acquiring processor (help by previous acquiring processor)
  655. esp_err_t err = dev_wait(dev_handle, wait);
  656. //TODO: add timeout handling here.
  657. if (err != ESP_OK) return err;
  658. }
  659. }
  660. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
  661. BUS_LOCK_DEBUG_EXECUTE_CHECK((lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) == 0);
  662. return ESP_OK;
  663. }
  664. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_clear_req(spi_bus_lock_dev_t *dev_handle)
  665. {
  666. bool finished = clear_pend_core(dev_handle);
  667. ESP_EARLY_LOGV(TAG, "dev %d served from bg.", dev_lock_get_id(dev_handle));
  668. return finished;
  669. }
  670. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_check_dev_acq(spi_bus_lock_t *lock,
  671. spi_bus_lock_dev_handle_t *out_dev_lock)
  672. {
  673. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev);
  674. uint32_t status = lock_status_fetch(lock);
  675. return schedule_core(lock, status, out_dev_lock);
  676. }
  677. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_check_dev_req(spi_bus_lock_dev_t *dev_lock)
  678. {
  679. spi_bus_lock_t* lock = dev_lock->parent;
  680. uint32_t status = lock_status_fetch(lock);
  681. uint32_t dev_status = status & dev_lock->mask;
  682. // move REQ bits of all device to corresponding PEND bits.
  683. // To reduce executing time, only done when the REQ bit of the calling device is set.
  684. if (dev_status & REQ_MASK) {
  685. update_pend_core(lock, status);
  686. return true;
  687. } else {
  688. return dev_status & PEND_MASK;
  689. }
  690. }
  691. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_req_exist(spi_bus_lock_t *lock)
  692. {
  693. uint32_t status = lock_status_fetch(lock);
  694. return status & BG_MASK;
  695. }
  696. /*******************************************************************************
  697. * Static variables of the locks of the main flash
  698. ******************************************************************************/
  699. #if CONFIG_SPI_FLASH_SHARE_SPI1_BUS
  700. static spi_bus_lock_dev_t lock_main_flash_dev;
  701. static spi_bus_lock_t main_spi_bus_lock = {
  702. /*
  703. * the main bus cache is permanently required, this flag is set here and never clear so that the
  704. * cache will always be enabled if acquiring devices yield.
  705. */
  706. .status = ATOMIC_VAR_INIT(WEAK_BG_FLAG),
  707. .acquiring_dev = NULL,
  708. .dev = {ATOMIC_VAR_INIT((intptr_t)&lock_main_flash_dev)},
  709. .new_req = 0,
  710. .periph_cs_num = SOC_SPI_PERIPH_CS_NUM(0),
  711. };
  712. const spi_bus_lock_handle_t g_main_spi_bus_lock = &main_spi_bus_lock;
  713. esp_err_t spi_bus_lock_init_main_bus(void)
  714. {
  715. spi_bus_main_set_lock(g_main_spi_bus_lock);
  716. return ESP_OK;
  717. }
  718. static StaticSemaphore_t main_flash_semphr;
  719. static spi_bus_lock_dev_t lock_main_flash_dev = {
  720. .semphr = NULL,
  721. .parent = &main_spi_bus_lock,
  722. .mask = DEV_MASK(0),
  723. };
  724. const spi_bus_lock_dev_handle_t g_spi_lock_main_flash_dev = &lock_main_flash_dev;
  725. esp_err_t spi_bus_lock_init_main_dev(void)
  726. {
  727. g_spi_lock_main_flash_dev->semphr = xSemaphoreCreateBinaryStatic(&main_flash_semphr);
  728. if (g_spi_lock_main_flash_dev->semphr == NULL) {
  729. return ESP_ERR_NO_MEM;
  730. }
  731. return ESP_OK;
  732. }
  733. #else //CONFIG_SPI_FLASH_SHARE_SPI1_BUS
  734. //when the dev lock is not initialized, point to NULL
  735. const spi_bus_lock_dev_handle_t g_spi_lock_main_flash_dev = NULL;
  736. #endif