spi_bus_lock.c 34 KB

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