spi_bus_lock.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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. DRAM_ATTR static const char TAG[] = "bus_lock";
  210. #define LOCK_CHECK(a, str, ret_val, ...) \
  211. if (!(a)) { \
  212. ESP_LOGE(TAG,"%s(%d): "str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \
  213. return (ret_val); \
  214. }
  215. static inline int mask_get_id(uint32_t mask);
  216. static inline int dev_lock_get_id(spi_bus_lock_dev_t *dev_lock);
  217. /*******************************************************************************
  218. * atomic operations to the status
  219. ******************************************************************************/
  220. SPI_MASTER_ISR_ATTR static inline uint32_t lock_status_fetch_set(spi_bus_lock_t *lock, uint32_t set)
  221. {
  222. return atomic_fetch_or(&lock->status, set);
  223. }
  224. IRAM_ATTR static inline uint32_t lock_status_fetch_clear(spi_bus_lock_t *lock, uint32_t clear)
  225. {
  226. return atomic_fetch_and(&lock->status, ~clear);
  227. }
  228. IRAM_ATTR static inline uint32_t lock_status_fetch(spi_bus_lock_t *lock)
  229. {
  230. return atomic_load(&lock->status);
  231. }
  232. SPI_MASTER_ISR_ATTR static inline void lock_status_init(spi_bus_lock_t *lock)
  233. {
  234. atomic_store(&lock->status, 0);
  235. }
  236. // return the remaining status bits
  237. IRAM_ATTR static inline uint32_t lock_status_clear(spi_bus_lock_t* lock, uint32_t clear)
  238. {
  239. //the fetch and clear should be atomic, avoid missing the all '0' status when all bits are clear.
  240. uint32_t state = lock_status_fetch_clear(lock, clear);
  241. return state & (~clear);
  242. }
  243. /*******************************************************************************
  244. * Schedule service
  245. *
  246. * The modification to the status bits may cause rotating of the acquiring processor. It also have
  247. * effects to `acquired_dev` (the acquiring device), `in_isr` (HW used in BG), and
  248. * `acq_dev_bg_active` (wait_bg_end can be skipped) members of the lock structure.
  249. *
  250. * Most of them should be atomic, and special attention should be paid to the operation
  251. * sequence.
  252. ******************************************************************************/
  253. SPI_MASTER_ISR_ATTR static inline void resume_dev_in_isr(spi_bus_lock_dev_t *dev_lock, BaseType_t *do_yield)
  254. {
  255. xSemaphoreGiveFromISR(dev_lock->semphr, do_yield);
  256. }
  257. IRAM_ATTR static inline void resume_dev(const spi_bus_lock_dev_t *dev_lock)
  258. {
  259. xSemaphoreGive(dev_lock->semphr);
  260. }
  261. SPI_MASTER_ISR_ATTR static inline void bg_disable(spi_bus_lock_t *lock)
  262. {
  263. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->bg_disable);
  264. lock->bg_disable(lock->bg_arg);
  265. }
  266. IRAM_ATTR static inline void bg_enable(spi_bus_lock_t* lock)
  267. {
  268. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->bg_enable);
  269. lock->bg_enable(lock->bg_arg);
  270. }
  271. // Set the REQ bit. If we become the acquiring processor, invoke the ISR and pass that to it.
  272. // The caller will never become the acquiring processor after this function returns.
  273. SPI_MASTER_ATTR static inline void req_core(spi_bus_lock_dev_t *dev_handle)
  274. {
  275. spi_bus_lock_t *lock = dev_handle->parent;
  276. // Though `acquired_dev` is critical resource, `dev_handle == lock->acquired_dev`
  277. // is a stable statement unless `acquire_start` or `acquire_end` is called by current
  278. // device.
  279. if (dev_handle == lock->acquiring_dev){
  280. // Set the REQ bit and check BG bits if we are the acquiring processor.
  281. // If the BG bits were not active before, invoke the BG again.
  282. // Avoid competitive risk against the `clear_pend_core`, `acq_dev_bg_active` should be set before
  283. // setting REQ bit.
  284. lock->acq_dev_bg_active = true;
  285. uint32_t status = lock_status_fetch_set(lock, DEV_REQ_MASK(dev_handle));
  286. if ((status & DEV_BG_MASK(dev_handle)) == 0) {
  287. bg_enable(lock); //acquiring processor passed to BG
  288. }
  289. } else {
  290. uint32_t status = lock_status_fetch_set(lock, DEV_REQ_MASK(dev_handle));
  291. if (status == 0) {
  292. bg_enable(lock); //acquiring processor passed to BG
  293. }
  294. }
  295. }
  296. //Set the LOCK bit. Handle related stuff and return true if we become the acquiring processor.
  297. SPI_MASTER_ISR_ATTR static inline bool acquire_core(spi_bus_lock_dev_t *dev_handle)
  298. {
  299. spi_bus_lock_t* lock = dev_handle->parent;
  300. uint32_t status = lock_status_fetch_set(lock, dev_handle->mask & LOCK_MASK);
  301. // Check all bits except WEAK_BG
  302. if ((status & (BG_MASK | LOCK_MASK)) == 0) {
  303. //succeed at once
  304. lock->acquiring_dev = dev_handle;
  305. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
  306. if (status & WEAK_BG_FLAG) {
  307. //Mainly to disable the cache (Weak_BG), that is not able to disable itself
  308. bg_disable(lock);
  309. }
  310. return true;
  311. }
  312. return false;
  313. }
  314. /**
  315. * Find the next acquiring processor according to the status. Will directly change
  316. * the acquiring device if new one found.
  317. *
  318. * Cases:
  319. * - BG should still be the acquiring processor (Return false):
  320. * 1. Acquiring device has active BG bits: out_desired_dev = new acquiring device
  321. * 2. No acquiring device, but BG active: out_desired_dev = randomly pick one device with active BG bits
  322. * - BG should yield to the task (Return true):
  323. * 3. Acquiring device has no active BG bits: out_desired_dev = new acquiring device
  324. * 4. No acquiring device while no active BG bits: out_desired_dev=NULL
  325. *
  326. * Acquiring device task need to be resumed only when case 3.
  327. *
  328. * This scheduling can happen in either task or ISR, so `in_isr` or `bg_active` not touched.
  329. *
  330. * @param lock
  331. * @param status Current status
  332. * @param out_desired_dev Desired device to work next, see above.
  333. *
  334. * @return False if BG should still be the acquiring processor, otherwise True (yield to task).
  335. */
  336. IRAM_ATTR static inline bool
  337. schedule_core(spi_bus_lock_t *lock, uint32_t status, spi_bus_lock_dev_t **out_desired_dev)
  338. {
  339. spi_bus_lock_dev_t* desired_dev = NULL;
  340. uint32_t lock_bits = (status & LOCK_MASK) >> LOCK_SHIFT;
  341. uint32_t bg_bits = status & BG_MASK;
  342. bg_bits = ((bg_bits >> REQ_SHIFT) | (bg_bits >> PENDING_SHIFT)) & REQ_MASK;
  343. bool bg_yield;
  344. if (lock_bits) {
  345. int dev_id = mask_get_id(lock_bits);
  346. desired_dev = (spi_bus_lock_dev_t *)atomic_load(&lock->dev[dev_id]);
  347. BUS_LOCK_DEBUG_EXECUTE_CHECK(desired_dev);
  348. lock->acquiring_dev = desired_dev;
  349. bg_yield = ((bg_bits & desired_dev->mask) == 0);
  350. lock->acq_dev_bg_active = !bg_yield;
  351. } else {
  352. lock->acq_dev_bg_active = false;
  353. if (bg_bits) {
  354. int dev_id = mask_get_id(bg_bits);
  355. desired_dev = (spi_bus_lock_dev_t *)atomic_load(&lock->dev[dev_id]);
  356. BUS_LOCK_DEBUG_EXECUTE_CHECK(desired_dev);
  357. lock->acquiring_dev = NULL;
  358. bg_yield = false;
  359. } else {
  360. desired_dev = NULL;
  361. lock->acquiring_dev = NULL;
  362. bg_yield = true;
  363. }
  364. }
  365. *out_desired_dev = desired_dev;
  366. return bg_yield;
  367. }
  368. //Clear the LOCK bit and trigger a rescheduling.
  369. IRAM_ATTR static inline void acquire_end_core(spi_bus_lock_dev_t *dev_handle)
  370. {
  371. spi_bus_lock_t* lock = dev_handle->parent;
  372. uint32_t status = lock_status_clear(lock, dev_handle->mask & LOCK_MASK);
  373. spi_bus_lock_dev_t* desired_dev = NULL;
  374. bool invoke_bg = !schedule_core(lock, status, &desired_dev);
  375. if (invoke_bg) {
  376. bg_enable(lock);
  377. } else if (desired_dev) {
  378. resume_dev(desired_dev);
  379. } else if (status & WEAK_BG_FLAG) {
  380. bg_enable(lock);
  381. }
  382. }
  383. // Move the REQ bits to corresponding PEND bits. Must be called by acquiring processor.
  384. // Have no side effects on the acquiring device/processor.
  385. SPI_MASTER_ISR_ATTR static inline void update_pend_core(spi_bus_lock_t *lock, uint32_t status)
  386. {
  387. uint32_t active_req_bits = status & REQ_MASK;
  388. #if PENDING_SHIFT > REQ_SHIFT
  389. uint32_t pending_mask = active_req_bits << (PENDING_SHIFT - REQ_SHIFT);
  390. #else
  391. uint32_t pending_mask = active_req_bits >> (REQ_SHIFT - PENDING_SHIFT);
  392. #endif
  393. // We have to set the PEND bits and then clear the REQ bits, since BG bits are using bitwise OR logic,
  394. // this will not influence the effectiveness of the BG bits of every device.
  395. lock_status_fetch_set(lock, pending_mask);
  396. lock_status_fetch_clear(lock, active_req_bits);
  397. }
  398. // Clear the PEND bit (not REQ bit!) of a device, return the suggestion whether we can try to quit the ISR.
  399. // Lost the acquiring processor immediately when the BG bits for active device are inactive, indiciating by the return value.
  400. // Can be called only when ISR is acting as the acquiring processor.
  401. SPI_MASTER_ISR_ATTR static inline bool clear_pend_core(spi_bus_lock_dev_t *dev_handle)
  402. {
  403. bool finished;
  404. spi_bus_lock_t *lock = dev_handle->parent;
  405. uint32_t pend_mask = DEV_PEND_MASK(dev_handle);
  406. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock_status_fetch(lock) & pend_mask);
  407. uint32_t status = lock_status_clear(lock, pend_mask);
  408. if (lock->acquiring_dev == dev_handle) {
  409. finished = ((status & DEV_REQ_MASK(dev_handle)) == 0);
  410. if (finished) {
  411. lock->acq_dev_bg_active = false;
  412. }
  413. } else {
  414. finished = (status == 0);
  415. }
  416. return finished;
  417. }
  418. // Return true if the ISR has already touched the HW, which means previous operations should
  419. // be terminated first, before we use the HW again. Otherwise return false.
  420. // In either case `in_isr` will be marked as true, until call to `bg_exit_core` with `wip=false` successfully.
  421. SPI_MASTER_ISR_ATTR static inline bool bg_entry_core(spi_bus_lock_t *lock)
  422. {
  423. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev || lock->acq_dev_bg_active);
  424. /*
  425. * The interrupt is disabled at the entry of ISR to avoid competitive risk as below:
  426. *
  427. * The `esp_intr_enable` will be called (b) after new BG request is queued (a) in the task;
  428. * while `esp_intr_disable` should be called (c) if we check and found the sending queue is empty (d).
  429. * If (c) happens after (d), if things happens in this sequence:
  430. * (d) -> (a) -> (b) -> (c), the interrupt will be disabled while there's pending BG request in the queue.
  431. *
  432. * To avoid this, interrupt is disabled here, and re-enabled later if required. (c) -> (d) -> (a) -> (b) -> revert (c) if !d
  433. */
  434. bg_disable(lock);
  435. if (lock->in_isr) {
  436. return false;
  437. } else {
  438. lock->in_isr = true;
  439. return true;
  440. }
  441. }
  442. // Handle the conditions of status and interrupt, avoiding the ISR being disabled when there is any new coming BG requests.
  443. // When called with `wip=true`, means the ISR is performing some operations. Will enable the interrupt again and exit unconditionally.
  444. // 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.
  445. // Will not change acquiring device.
  446. SPI_MASTER_ISR_ATTR static inline bool bg_exit_core(spi_bus_lock_t *lock, bool wip, BaseType_t *do_yield)
  447. {
  448. //See comments in `bg_entry_core`, re-enable interrupt disabled in entry if we do need the interrupt
  449. if (wip) {
  450. bg_enable(lock);
  451. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev || lock->acq_dev_bg_active);
  452. return true;
  453. }
  454. bool ret;
  455. uint32_t status = lock_status_fetch(lock);
  456. if (lock->acquiring_dev) {
  457. if (status & DEV_BG_MASK(lock->acquiring_dev)) {
  458. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->acq_dev_bg_active);
  459. ret = false;
  460. } else {
  461. // The request may happen any time, even after we fetched the status.
  462. // The value of `acq_dev_bg_active` is random.
  463. resume_dev_in_isr(lock->acquiring_dev, do_yield);
  464. ret = true;
  465. }
  466. } else {
  467. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
  468. ret = !(status & BG_MASK);
  469. }
  470. if (ret) {
  471. //when successfully exit, but no transaction done, mark BG as inactive
  472. lock->in_isr = false;
  473. }
  474. return ret;
  475. }
  476. IRAM_ATTR static inline void dev_wait_prepare(spi_bus_lock_dev_t *dev_handle)
  477. {
  478. xSemaphoreTake(dev_handle->semphr, 0);
  479. }
  480. SPI_MASTER_ISR_ATTR static inline esp_err_t dev_wait(spi_bus_lock_dev_t *dev_handle, TickType_t wait)
  481. {
  482. BaseType_t ret = xSemaphoreTake(dev_handle->semphr, wait);
  483. if (ret == pdFALSE) return ESP_ERR_TIMEOUT;
  484. return ESP_OK;
  485. }
  486. /*******************************************************************************
  487. * Initialization & Deinitialization
  488. ******************************************************************************/
  489. esp_err_t spi_bus_init_lock(spi_bus_lock_handle_t *out_lock, const spi_bus_lock_config_t *config)
  490. {
  491. spi_bus_lock_t* lock = (spi_bus_lock_t*)calloc(sizeof(spi_bus_lock_t), 1);
  492. if (lock == NULL) {
  493. return ESP_ERR_NO_MEM;
  494. }
  495. lock_status_init(lock);
  496. lock->acquiring_dev = NULL;
  497. lock->last_dev = NULL;
  498. lock->periph_cs_num = config->cs_num;
  499. lock->host_id = config->host_id;
  500. *out_lock = lock;
  501. return ESP_OK;
  502. }
  503. void spi_bus_deinit_lock(spi_bus_lock_handle_t lock)
  504. {
  505. for (int i = 0; i < DEV_NUM_MAX; i++) {
  506. assert(atomic_load(&lock->dev[i]) == (intptr_t)NULL);
  507. }
  508. free(lock);
  509. }
  510. static int try_acquire_free_dev(spi_bus_lock_t *lock, bool cs_required)
  511. {
  512. if (cs_required) {
  513. int i;
  514. for (i = 0; i < lock->periph_cs_num; i++) {
  515. intptr_t null = (intptr_t) NULL;
  516. //use 1 to occupy the slot, actual setup comes later
  517. if (atomic_compare_exchange_strong(&lock->dev[i], &null, (intptr_t) 1)) {
  518. break;
  519. }
  520. }
  521. return ((i == lock->periph_cs_num)? -1: i);
  522. } else {
  523. int i;
  524. for (i = DEV_NUM_MAX - 1; i >= 0; i--) {
  525. intptr_t null = (intptr_t) NULL;
  526. //use 1 to occupy the slot, actual setup comes later
  527. if (atomic_compare_exchange_strong(&lock->dev[i], &null, (intptr_t) 1)) {
  528. break;
  529. }
  530. }
  531. return i;
  532. }
  533. }
  534. esp_err_t spi_bus_lock_register_dev(spi_bus_lock_handle_t lock, spi_bus_lock_dev_config_t *config,
  535. spi_bus_lock_dev_handle_t *out_dev_handle)
  536. {
  537. if (lock == NULL) return ESP_ERR_INVALID_ARG;
  538. int id = try_acquire_free_dev(lock, config->flags & SPI_BUS_LOCK_DEV_FLAG_CS_REQUIRED);
  539. if (id == -1) return ESP_ERR_NOT_SUPPORTED;
  540. 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);
  541. if (dev_lock == NULL) {
  542. return ESP_ERR_NO_MEM;
  543. }
  544. dev_lock->semphr = xSemaphoreCreateBinary();
  545. if (dev_lock->semphr == NULL) {
  546. free(dev_lock);
  547. atomic_store(&lock->dev[id], (intptr_t)NULL);
  548. return ESP_ERR_NO_MEM;
  549. }
  550. dev_lock->parent = lock;
  551. dev_lock->mask = DEV_MASK(id);
  552. ESP_LOGV(TAG, "device registered on bus %d slot %d.", lock->host_id, id);
  553. atomic_store(&lock->dev[id], (intptr_t)dev_lock);
  554. *out_dev_handle = dev_lock;
  555. return ESP_OK;
  556. }
  557. void spi_bus_lock_unregister_dev(spi_bus_lock_dev_handle_t dev_handle)
  558. {
  559. int id = dev_lock_get_id(dev_handle);
  560. spi_bus_lock_t* lock = dev_handle->parent;
  561. BUS_LOCK_DEBUG_EXECUTE_CHECK(atomic_load(&lock->dev[id]) == (intptr_t)dev_handle);
  562. if (lock->last_dev == dev_handle) lock->last_dev = NULL;
  563. atomic_store(&lock->dev[id], (intptr_t)NULL);
  564. if (dev_handle->semphr) {
  565. vSemaphoreDelete(dev_handle->semphr);
  566. }
  567. free(dev_handle);
  568. }
  569. IRAM_ATTR static inline int mask_get_id(uint32_t mask)
  570. {
  571. return ID_DEV_MASK(mask);
  572. }
  573. IRAM_ATTR static inline int dev_lock_get_id(spi_bus_lock_dev_t *dev_lock)
  574. {
  575. return mask_get_id(dev_lock->mask);
  576. }
  577. 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)
  578. {
  579. lock->bg_enable = bg_enable;
  580. lock->bg_disable = bg_disable;
  581. lock->bg_arg = arg;
  582. }
  583. IRAM_ATTR int spi_bus_lock_get_dev_id(spi_bus_lock_dev_handle_t dev_handle)
  584. {
  585. return (dev_handle? dev_lock_get_id(dev_handle): -1);
  586. }
  587. //will be called when cache disabled
  588. IRAM_ATTR bool spi_bus_lock_touch(spi_bus_lock_dev_handle_t dev_handle)
  589. {
  590. spi_bus_lock_dev_t* last_dev = dev_handle->parent->last_dev;
  591. dev_handle->parent->last_dev = dev_handle;
  592. if (last_dev != dev_handle) {
  593. int last_dev_id = (last_dev? dev_lock_get_id(last_dev): -1);
  594. ESP_DRAM_LOGV(TAG, "SPI dev changed from %d to %d",
  595. last_dev_id, dev_lock_get_id(dev_handle));
  596. }
  597. return (dev_handle != last_dev);
  598. }
  599. /*******************************************************************************
  600. * Acquiring service
  601. ******************************************************************************/
  602. IRAM_ATTR esp_err_t spi_bus_lock_acquire_start(spi_bus_lock_dev_t *dev_handle, TickType_t wait)
  603. {
  604. LOCK_CHECK(wait == portMAX_DELAY, "timeout other than portMAX_DELAY not supported", ESP_ERR_INVALID_ARG);
  605. spi_bus_lock_t* lock = dev_handle->parent;
  606. // Clear the semaphore before checking
  607. dev_wait_prepare(dev_handle);
  608. if (!acquire_core(dev_handle)) {
  609. //block until becoming the acquiring processor (help by previous acquiring processor)
  610. esp_err_t err = dev_wait(dev_handle, wait);
  611. //TODO: add timeout handling here.
  612. if (err != ESP_OK) return err;
  613. }
  614. ESP_DRAM_LOGV(TAG, "dev %d acquired.", dev_lock_get_id(dev_handle));
  615. BUS_LOCK_DEBUG_EXECUTE_CHECK(lock->acquiring_dev == dev_handle);
  616. //When arrives at here, requests of this device should already be handled
  617. uint32_t status = lock_status_fetch(lock);
  618. (void) status;
  619. BUS_LOCK_DEBUG_EXECUTE_CHECK((status & DEV_BG_MASK(dev_handle)) == 0);
  620. return ESP_OK;
  621. }
  622. IRAM_ATTR esp_err_t spi_bus_lock_acquire_end(spi_bus_lock_dev_t *dev_handle)
  623. {
  624. //release the bus
  625. spi_bus_lock_t* lock = dev_handle->parent;
  626. LOCK_CHECK(lock->acquiring_dev == dev_handle, "Cannot release a lock that hasn't been acquired.", ESP_ERR_INVALID_STATE);
  627. acquire_end_core(dev_handle);
  628. ESP_LOGV(TAG, "dev %d released.", dev_lock_get_id(dev_handle));
  629. return ESP_OK;
  630. }
  631. SPI_MASTER_ISR_ATTR spi_bus_lock_dev_handle_t spi_bus_lock_get_acquiring_dev(spi_bus_lock_t *lock)
  632. {
  633. return lock->acquiring_dev;
  634. }
  635. /*******************************************************************************
  636. * BG (background operation) service
  637. ******************************************************************************/
  638. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_entry(spi_bus_lock_t* lock)
  639. {
  640. return bg_entry_core(lock);
  641. }
  642. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_exit(spi_bus_lock_t* lock, bool wip, BaseType_t* do_yield)
  643. {
  644. return bg_exit_core(lock, wip, do_yield);
  645. }
  646. SPI_MASTER_ATTR esp_err_t spi_bus_lock_bg_request(spi_bus_lock_dev_t *dev_handle)
  647. {
  648. req_core(dev_handle);
  649. return ESP_OK;
  650. }
  651. IRAM_ATTR esp_err_t spi_bus_lock_wait_bg_done(spi_bus_lock_dev_handle_t dev_handle, TickType_t wait)
  652. {
  653. spi_bus_lock_t *lock = dev_handle->parent;
  654. LOCK_CHECK(lock->acquiring_dev == dev_handle, "Cannot wait for a device that is not acquired", ESP_ERR_INVALID_STATE);
  655. LOCK_CHECK(wait == portMAX_DELAY, "timeout other than portMAX_DELAY not supported", ESP_ERR_INVALID_ARG);
  656. // If no BG bits active, skip quickly. This is ensured by `spi_bus_lock_wait_bg_done`
  657. // cannot be executed with `bg_request` on the same device concurrently.
  658. if (lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) {
  659. // Clear the semaphore before checking
  660. dev_wait_prepare(dev_handle);
  661. if (lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) {
  662. //block until becoming the acquiring processor (help by previous acquiring processor)
  663. esp_err_t err = dev_wait(dev_handle, wait);
  664. //TODO: add timeout handling here.
  665. if (err != ESP_OK) return err;
  666. }
  667. }
  668. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acq_dev_bg_active);
  669. BUS_LOCK_DEBUG_EXECUTE_CHECK((lock_status_fetch(lock) & DEV_BG_MASK(dev_handle)) == 0);
  670. return ESP_OK;
  671. }
  672. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_clear_req(spi_bus_lock_dev_t *dev_handle)
  673. {
  674. bool finished = clear_pend_core(dev_handle);
  675. ESP_EARLY_LOGV(TAG, "dev %d served from bg.", dev_lock_get_id(dev_handle));
  676. return finished;
  677. }
  678. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_check_dev_acq(spi_bus_lock_t *lock,
  679. spi_bus_lock_dev_handle_t *out_dev_lock)
  680. {
  681. BUS_LOCK_DEBUG_EXECUTE_CHECK(!lock->acquiring_dev);
  682. uint32_t status = lock_status_fetch(lock);
  683. return schedule_core(lock, status, out_dev_lock);
  684. }
  685. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_check_dev_req(spi_bus_lock_dev_t *dev_lock)
  686. {
  687. spi_bus_lock_t* lock = dev_lock->parent;
  688. uint32_t status = lock_status_fetch(lock);
  689. uint32_t dev_status = status & dev_lock->mask;
  690. // move REQ bits of all device to corresponding PEND bits.
  691. // To reduce executing time, only done when the REQ bit of the calling device is set.
  692. if (dev_status & REQ_MASK) {
  693. update_pend_core(lock, status);
  694. return true;
  695. } else {
  696. return dev_status & PEND_MASK;
  697. }
  698. }
  699. SPI_MASTER_ISR_ATTR bool spi_bus_lock_bg_req_exist(spi_bus_lock_t *lock)
  700. {
  701. uint32_t status = lock_status_fetch(lock);
  702. return status & BG_MASK;
  703. }
  704. /*******************************************************************************
  705. * Static variables of the locks of the main flash
  706. ******************************************************************************/
  707. #if CONFIG_SPI_FLASH_SHARE_SPI1_BUS
  708. static spi_bus_lock_dev_t lock_main_flash_dev;
  709. static spi_bus_lock_t main_spi_bus_lock = {
  710. /*
  711. * the main bus cache is permanently required, this flag is set here and never clear so that the
  712. * cache will always be enabled if acquiring devices yield.
  713. */
  714. .status = ATOMIC_VAR_INIT(WEAK_BG_FLAG),
  715. .acquiring_dev = NULL,
  716. .dev = {ATOMIC_VAR_INIT((intptr_t)&lock_main_flash_dev)},
  717. .new_req = 0,
  718. .periph_cs_num = SOC_SPI_PERIPH_CS_NUM(0),
  719. };
  720. const spi_bus_lock_handle_t g_main_spi_bus_lock = &main_spi_bus_lock;
  721. esp_err_t spi_bus_lock_init_main_bus(void)
  722. {
  723. spi_bus_main_set_lock(g_main_spi_bus_lock);
  724. return ESP_OK;
  725. }
  726. static StaticSemaphore_t main_flash_semphr;
  727. static spi_bus_lock_dev_t lock_main_flash_dev = {
  728. .semphr = NULL,
  729. .parent = &main_spi_bus_lock,
  730. .mask = DEV_MASK(0),
  731. };
  732. const spi_bus_lock_dev_handle_t g_spi_lock_main_flash_dev = &lock_main_flash_dev;
  733. esp_err_t spi_bus_lock_init_main_dev(void)
  734. {
  735. g_spi_lock_main_flash_dev->semphr = xSemaphoreCreateBinaryStatic(&main_flash_semphr);
  736. if (g_spi_lock_main_flash_dev->semphr == NULL) {
  737. return ESP_ERR_NO_MEM;
  738. }
  739. return ESP_OK;
  740. }
  741. #else //CONFIG_SPI_FLASH_SHARE_SPI1_BUS
  742. //when the dev lock is not initialized, point to NULL
  743. const spi_bus_lock_dev_handle_t g_spi_lock_main_flash_dev = NULL;
  744. #endif