]> git.sesse.net Git - bcachefs-tools-debian/blob - c_src/include/linux/bit_spinlock.h
move Rust sources to top level, C sources into c_src
[bcachefs-tools-debian] / c_src / include / linux / bit_spinlock.h
1 #ifndef __LINUX_BIT_SPINLOCK_H
2 #define __LINUX_BIT_SPINLOCK_H
3
4 #include <linux/kernel.h>
5 #include <linux/preempt.h>
6 #include <linux/futex.h>
7 #include <urcu/futex.h>
8
9 /*
10  * The futex wait op wants an explicit 32-bit address and value. If the bitmap
11  * used for the spinlock is 64-bit, cast down and pass the right 32-bit region
12  * for the in-kernel checks. The value is the copy that has already been read
13  * from the atomic op.
14  *
15  * The futex wake op interprets the value as the number of waiters to wake (up
16  * to INT_MAX), so pass that along directly.
17  */
18 static inline void do_futex(int nr, unsigned long *addr, unsigned long v, int futex_flags)
19 {
20         u32 *addr32 = (u32 *) addr;
21         u32 *v32 = (u32 *) &v;
22         int shift = 0;
23
24         futex_flags |= FUTEX_PRIVATE_FLAG;
25
26 #if BITS_PER_LONG == 64
27 #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
28         shift = (nr >= 32) ? 1 : 0;
29 #else
30         shift = (nr < 32) ? 1 : 0;
31 #endif
32 #endif
33         if (shift) {
34                 addr32 += shift;
35                 v32 += shift;
36         }
37         /*
38          * The shift to determine the futex address may have cast away a
39          * literal wake count value. The value is capped to INT_MAX and thus
40          * always in the low bytes of v regardless of bit nr. Copy in the wake
41          * count to whatever 32-bit range was selected.
42          */
43         if (futex_flags == FUTEX_WAKE_PRIVATE)
44                 *v32 = (u32) v;
45         futex(addr32, futex_flags, *v32, NULL, NULL, 0);
46 }
47
48 static inline void bit_spin_lock(int nr, unsigned long *_addr)
49 {
50         unsigned long mask;
51         unsigned long *addr = _addr + (nr / BITS_PER_LONG);
52         unsigned long v;
53
54         nr &= BITS_PER_LONG - 1;
55         mask = 1UL << nr;
56
57         while (1) {
58                 v = __atomic_fetch_or(addr, mask, __ATOMIC_ACQUIRE);
59                 if (!(v & mask))
60                         break;
61
62                 do_futex(nr, addr, v, FUTEX_WAIT);
63         }
64 }
65
66 static inline void bit_spin_wake(int nr, unsigned long *_addr)
67 {
68         do_futex(nr, _addr, INT_MAX, FUTEX_WAKE);
69 }
70
71 static inline void bit_spin_unlock(int nr, unsigned long *_addr)
72 {
73         unsigned long mask;
74         unsigned long *addr = _addr + (nr / BITS_PER_LONG);
75
76         nr &= BITS_PER_LONG - 1;
77         mask = 1UL << nr;
78
79         __atomic_and_fetch(addr, ~mask, __ATOMIC_RELEASE);
80         do_futex(nr, addr, INT_MAX, FUTEX_WAKE);
81 }
82
83 #endif /* __LINUX_BIT_SPINLOCK_H */
84