| 1 | #include <asm.h> |
| 2 | #include <crypto/prng.h> |
| 3 | #include <stddef.h> |
| 4 | |
| 5 | /* jitter to avoid lockstep */ |
| 6 | static inline int32_t backoff_jitter(size_t backoff, size_t pct) { |
| 7 | uint32_t v = (uint32_t) prng_next(); |
| 8 | int32_t denom = (int32_t) (backoff * pct / 100); |
| 9 | |
| 10 | if (denom <= 0) |
| 11 | denom = 1; |
| 12 | |
| 13 | return (int32_t) (v % (uint32_t) denom); |
| 14 | } |
| 15 | |
| 16 | static inline void lock_delay(size_t backoff, size_t pct) { |
| 17 | /* give it jitter so we don't all spin for |
| 18 | * precisely the same amount of cycles */ |
| 19 | int32_t jitter = backoff_jitter(backoff, pct); |
| 20 | |
| 21 | if ((int64_t) backoff + (int64_t) jitter < 0) |
| 22 | jitter = 0; /* no jitter, we are underflowing */ |
| 23 | |
| 24 | backoff += jitter; |
| 25 | |
| 26 | for (size_t i = 0; i < backoff; i++) |
| 27 | cpu_relax(); |
| 28 | } |
| 29 | |