Commit 4648578
committed
OS/FreeRTOS: Correct recursive spinlock for weak memory models in FreeRTOS SMP
The previous implementation of `vPortRecursiveLock` was unsafe on systems with weak memory ordering (like RISC-V), leading to potential race conditions. This commit corrects the implementation by introducing necessary memory barriers and optimizes the spin-wait loop.
**Correctness Fixes:**
* **Acquire Barrier**: An acquire memory barrier (`__RWMB()`) is added immediately after a successful atomic swap (`__AMOSWAP_W`). This is critical to prevent the compiler or CPU from reordering memory operations from within the critical section to before the lock is actually acquired. Without this, the lock provides no protection.
* **Release Barrier**: A release memory barrier (`__RWMB()`) is added before the lock variable is cleared. This ensures that all memory writes within the critical section are globally visible *before* the lock is released. This prevents other cores from acquiring the lock and seeing stale data.
**Performance and Logic Improvements:**
* **Test-and-Test-and-Set (TTS)**: The lock acquisition logic has been restructured into a more efficient TTS pattern. The code now spins on a cheap, non-atomic read (`while (*pxSpinLock == 0)`) and only attempts the expensive atomic swap when the lock appears to be free. This significantly reduces bus contention and improves system performance when multiple cores are contending for a lock.
* **NOP in Spin Loop**: A `__NOP()` has been added to the spin-wait loop. This can help reduce power consumption and pipeline pressure on some CPU architectures during tight spins.
* **Improved Readability**: Added comments to clarify the logic for recursive locking, lock acquisition, and the purpose of the memory barriers.
Signed-off-by: Huaqi Fang <578567190@qq.com>1 parent 029689f commit 4648578
1 file changed
Lines changed: 22 additions & 11 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
176 | 176 | | |
177 | 177 | | |
178 | 178 | | |
| 179 | + | |
179 | 180 | | |
| 181 | + | |
180 | 182 | | |
181 | 183 | | |
182 | 184 | | |
183 | | - | |
184 | | - | |
| 185 | + | |
| 186 | + | |
185 | 187 | | |
186 | 188 | | |
187 | | - | |
| 189 | + | |
| 190 | + | |
188 | 191 | | |
189 | 192 | | |
190 | 193 | | |
191 | 194 | | |
192 | 195 | | |
193 | 196 | | |
194 | | - | |
195 | | - | |
196 | | - | |
197 | 197 | | |
198 | 198 | | |
| 199 | + | |
199 | 200 | | |
200 | | - | |
201 | | - | |
| 201 | + | |
| 202 | + | |
| 203 | + | |
| 204 | + | |
| 205 | + | |
| 206 | + | |
| 207 | + | |
| 208 | + | |
202 | 209 | | |
203 | 210 | | |
204 | 211 | | |
| 212 | + | |
205 | 213 | | |
206 | 214 | | |
207 | | - | |
208 | | - | |
| 215 | + | |
| 216 | + | |
209 | 217 | | |
210 | 218 | | |
211 | 219 | | |
| 220 | + | |
212 | 221 | | |
| 222 | + | |
213 | 223 | | |
214 | | - | |
| 224 | + | |
| 225 | + | |
215 | 226 | | |
216 | 227 | | |
217 | 228 | | |
| |||
0 commit comments