1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
//TODO: this adjustement may be adapted to
//      plateform processor
//
/// The lock gives priority to write locks when
/// one is waiting to be fair with write locks. This
/// fairness somehow equilibrate with the fact read locks
/// are extremely fair with other read locks.
///
/// But this mitigation can lead to the opposite. If there
/// are many attempts to get a write lock, read locks will
/// never be awaken. So if concecutive `READ_FAIRNESS_PERIOD`
/// write locks are awaked, gives priority to awake read locks
const READ_FAIRNESS_PERIOD: u16 = 32;
#[cfg(all(
    not(feature = "parking_lot_core"),
    any(target_os = "linux", target_os = "android")
))]
mod linux {
    use super::READ_FAIRNESS_PERIOD;
    use crate::phase::*;
    use core::ops::{Deref, DerefMut};
    use core::ptr;
    use core::sync::atomic::{compiler_fence, AtomicU16, AtomicU32, Ordering};
    use libc::{syscall, SYS_futex, FUTEX_PRIVATE_FLAG, FUTEX_WAIT_BITSET, FUTEX_WAKE_BITSET};

    pub(crate) struct Futex {
        futex: AtomicU32,
        writer_count: AtomicU32,
        fairness: AtomicU16,
    }

    const READER_BIT: u32 = 0b01;
    const WRITER_BIT: u32 = 0b10;

    impl Futex {
        pub(crate) const fn new(value: u32) -> Self {
            Self {
                futex: AtomicU32::new(value),
                writer_count: AtomicU32::new(0),
                fairness: AtomicU16::new(0),
                //to allow the static to be placed zeroed segment
                //and fairness with threads who attempted but failed to
                //initialize the static
            }
        }

        pub(crate) fn prefer_wake_one_writer(&self) -> bool {
            self.fairness.load(Ordering::Relaxed) % READ_FAIRNESS_PERIOD != 0
        }

        pub(crate) fn compare_and_wait_as_reader(&self, value: u32) -> bool {
            unsafe {
                syscall(
                    SYS_futex,
                    &self.futex as *const _ as *const _,
                    FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG,
                    value,
                    ptr::null::<u32>(),
                    ptr::null::<u32>(),
                    READER_BIT,
                ) == 0
            }
        }
        pub(crate) fn compare_and_wait_as_writer(&self, value: u32) -> bool {
            assert_ne!(self.writer_count.fetch_add(1, Ordering::Relaxed), u32::MAX);
            compiler_fence(Ordering::AcqRel);
            let res = unsafe {
                syscall(
                    SYS_futex,
                    &self.futex as *const _ as *const _,
                    FUTEX_WAIT_BITSET | FUTEX_PRIVATE_FLAG,
                    value,
                    ptr::null::<u32>(),
                    ptr::null::<u32>(),
                    WRITER_BIT,
                ) == 0
            };
            compiler_fence(Ordering::AcqRel);
            let prev_count = self.writer_count.fetch_sub(1, Ordering::Relaxed);
            assert_ne!(prev_count, 0);
            //// count = number of threads waiting at the time of wake + those
            ////         for which the futex syscall as been interrupted but count not
            ////         yet substracted + those that are in the process of waiting
            //// so here count is larger than the number of waiting threads
            if res && prev_count > 1 {
                self.futex.fetch_or(WRITE_WAITER_BIT, Ordering::Relaxed);
            }
            res
        }
        pub(crate) fn wake_readers(&self) -> usize {
            self.fairness.store(1, Ordering::Relaxed);
            let count = unsafe {
                syscall(
                    SYS_futex,
                    &self.futex as *const _ as *const _,
                    FUTEX_WAKE_BITSET | FUTEX_PRIVATE_FLAG,
                    MAX_WAKED_READERS as i32,
                    ptr::null::<u32>(),
                    ptr::null::<u32>(),
                    READER_BIT,
                ) as usize
            };
            if count == MAX_WAKED_READERS {
                self.futex.fetch_or(READ_WAITER_BIT, Ordering::Relaxed);
            }
            count
        }
        pub(crate) fn wake_one_writer(&self) -> bool {
            self.fairness.fetch_add(1, Ordering::Relaxed);
            unsafe {
                syscall(
                    SYS_futex,
                    &self.futex as *const _ as *const _,
                    FUTEX_WAKE_BITSET | FUTEX_PRIVATE_FLAG,
                    1,
                    ptr::null::<u32>(),
                    ptr::null::<u32>(),
                    WRITER_BIT,
                ) == 1
            }
        }
    }

    impl Deref for Futex {
        type Target = AtomicU32;
        fn deref(&self) -> &Self::Target {
            &self.futex
        }
    }
    impl DerefMut for Futex {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.futex
        }
    }
}
#[cfg(all(
    not(feature = "parking_lot_core"),
    any(target_os = "linux", target_os = "android")
))]
pub(crate) use linux::Futex;

#[cfg(any(
    feature = "parking_lot_core",
    not(any(target_os = "linux", target_os = "android"))
))]
mod other {
    use super::READ_FAIRNESS_PERIOD;
    use crate::phase::*;
    use core::ops::{Deref, DerefMut};
    use core::sync::atomic::{compiler_fence, AtomicU16, AtomicU32, Ordering};
    use parking_lot_core::{
        park, unpark_filter, unpark_one, FilterOp, ParkResult, DEFAULT_PARK_TOKEN,
        DEFAULT_UNPARK_TOKEN,
    };

    pub(crate) struct Futex {
        futex: AtomicU32,
        writer_count: AtomicU32,
        fairness: AtomicU16,
    }

    impl Futex {
        pub(crate) const fn new(value: u32) -> Self {
            Self {
                futex: AtomicU32::new(value),
                writer_count: AtomicU32::new(0),
                fairness: AtomicU16::new(0),
            }
        }

        pub(crate) fn prefer_wake_one_writer(&self) -> bool {
            self.fairness.load(Ordering::Relaxed) % READ_FAIRNESS_PERIOD == 0
        }

        pub(crate) fn compare_and_wait_as_reader(&self, value: u32) -> bool {
            unsafe {
                matches!(
                    park(
                        self.reader_key(),
                        || self.futex.load(Ordering::Relaxed) == value,
                        || {},
                        |_, _| {},
                        DEFAULT_PARK_TOKEN,
                        None,
                    ),
                    ParkResult::Unparked(_)
                )
            }
        }
        pub(crate) fn compare_and_wait_as_writer(&self, value: u32) -> bool {
            assert_ne!(self.writer_count.fetch_add(1, Ordering::Relaxed), u32::MAX);
            compiler_fence(Ordering::AcqRel);
            let res = unsafe {
                matches!(
                    park(
                        self.writer_key(),
                        || self.futex.load(Ordering::Relaxed) == value,
                        || {},
                        |_, _| {},
                        DEFAULT_PARK_TOKEN,
                        None,
                    ),
                    ParkResult::Unparked(_)
                )
            };
            compiler_fence(Ordering::AcqRel);
            let prev_count = self.writer_count.fetch_sub(1, Ordering::Relaxed);
            assert_ne!(prev_count, 0);
            //// count = number of threads waiting at the time of unpark + those
            ////         for which the futex syscall as been interrupted but count not
            ////         yet substracted + those that are in the process of waiting
            //// so here count is larger than the number of waiting threads
            if res && prev_count > 1 {
                self.futex.fetch_or(WRITE_WAITER_BIT, Ordering::Relaxed);
            }
            res
        }
        pub(crate) fn wake_readers(&self) -> usize {
            self.fairness.store(1, Ordering::Relaxed);
            let mut c = 0;
            let r = unsafe {
                unpark_filter(
                    self.reader_key(),
                    |_| {
                        if c < MAX_WAKED_READERS {
                            c += 1;
                            FilterOp::Unpark
                        } else {
                            FilterOp::Stop
                        }
                    },
                    |_| DEFAULT_UNPARK_TOKEN,
                )
            };

            if c == MAX_WAKED_READERS {
                self.futex.fetch_or(READ_WAITER_BIT, Ordering::Relaxed);
            }

            r.unparked_threads
        }
        pub(crate) fn wake_one_writer(&self) -> bool {
            self.fairness.fetch_add(1, Ordering::Relaxed);
            let r = unsafe { unpark_one(self.writer_key(), |_| DEFAULT_UNPARK_TOKEN) };
            r.unparked_threads == 1
        }

        fn reader_key(&self) -> usize {
            &self.futex as *const _ as usize
        }
        fn writer_key(&self) -> usize {
            (&self.futex as *const _ as usize) + 1
        }
    }

    impl Deref for Futex {
        type Target = AtomicU32;
        fn deref(&self) -> &Self::Target {
            &self.futex
        }
    }
    impl DerefMut for Futex {
        fn deref_mut(&mut self) -> &mut Self::Target {
            &mut self.futex
        }
    }
}
#[cfg(any(
    feature = "parking_lot_core",
    not(any(target_os = "linux", target_os = "android"))
))]
pub(crate) use other::Futex;