spi_bus_lock.c 34 KB

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