forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfutex.zig
402 lines (342 loc) · 14.7 KB
/
futex.zig
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
//! Futex is a mechanism used to block (`wait`) and unblock (`wake`) threads using a 32bit memory address as hints.
//! Blocking a thread is acknowledged only if the 32bit memory address is equal to a given value.
//! This check helps avoid block/unblock deadlocks which occur if a `wake()` happens before a `wait()`.
//! Using Futex, other Thread synchronization primitives can be built which efficiently wait for cross-thread events or signals.
// This is copy-pasted from Zig's source code to fix an issue with linking on macOS Catalina and earlier.
const std = @import("std");
const bun = @import("root").bun;
const builtin = @import("builtin");
const Futex = @This();
const target = builtin.target;
const single_threaded = builtin.single_threaded;
const assert = bun.assert;
const testing = std.testing;
const Atomic = std.atomic.Value;
const spinLoopHint = std.atomic.spinLoopHint;
/// Checks if `ptr` still contains the value `expect` and, if so, blocks the caller until either:
/// - The value at `ptr` is no longer equal to `expect`.
/// - The caller is unblocked by a matching `wake()`.
/// - The caller is unblocked spuriously by an arbitrary internal signal.
///
/// If `timeout` is provided, and the caller is blocked for longer than `timeout` nanoseconds`, `error.TimedOut` is returned.
///
/// The checking of `ptr` and `expect`, along with blocking the caller, is done atomically
/// and totally ordered (sequentially consistent) with respect to other wait()/wake() calls on the same `ptr`.
pub fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
if (single_threaded) {
// check whether the caller should block
if (ptr.raw != expect) {
return;
}
// There are no other threads which could notify the caller on single_threaded.
// Therefore a wait() without a timeout would block indefinitely.
const timeout_ns = timeout orelse {
@panic("deadlock");
};
// Simulate blocking with the timeout knowing that:
// - no other thread can change the ptr value
// - no other thread could unblock us if we waiting on the ptr
std.time.sleep(timeout_ns);
return error.TimedOut;
}
// Avoid calling into the OS for no-op waits()
if (timeout) |timeout_ns| {
if (timeout_ns == 0) {
if (ptr.load(.seq_cst) != expect) return;
return error.TimedOut;
}
}
return OsFutex.wait(ptr, expect, timeout);
}
/// Unblocks at most `num_waiters` callers blocked in a `wait()` call on `ptr`.
/// `num_waiters` of 1 unblocks at most one `wait(ptr, ...)` and `maxInt(u32)` unblocks effectively all `wait(ptr, ...)`.
pub fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
if (single_threaded) return;
if (num_waiters == 0) return;
return OsFutex.wake(ptr, num_waiters);
}
const OsFutex = if (target.os.tag == .windows)
WindowsFutex
else if (target.os.tag == .linux)
LinuxFutex
else if (target.isDarwin())
DarwinFutex
else if (builtin.link_libc)
PosixFutex
else
UnsupportedFutex;
const UnsupportedFutex = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
return unsupported(.{ ptr, expect, timeout });
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
return unsupported(.{ ptr, num_waiters });
}
fn unsupported(unused: anytype) noreturn {
_ = unused;
@compileError("Unsupported operating system: " ++ @tagName(target.os.tag));
}
};
const WindowsFutex = struct {
const windows = std.os.windows;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
var timeout_value: windows.LARGE_INTEGER = undefined;
var timeout_ptr: ?*const windows.LARGE_INTEGER = null;
// NTDLL functions work with time in units of 100 nanoseconds.
// Positive values for timeouts are absolute time while negative is relative.
if (timeout) |timeout_ns| {
timeout_ptr = &timeout_value;
timeout_value = -@as(windows.LARGE_INTEGER, @intCast(timeout_ns / 100));
}
switch (windows.ntdll.RtlWaitOnAddress(
@as(?*const anyopaque, @ptrCast(ptr)),
@as(?*const anyopaque, @ptrCast(&expect)),
@sizeOf(@TypeOf(expect)),
timeout_ptr,
)) {
.SUCCESS => {},
.TIMEOUT => return error.TimedOut,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
const address = @as(?*const anyopaque, @ptrCast(ptr));
switch (num_waiters) {
1 => windows.ntdll.RtlWakeAddressSingle(address),
else => windows.ntdll.RtlWakeAddressAll(address),
}
}
};
const LinuxFutex = struct {
const linux = std.os.linux;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
var ts: std.posix.timespec = undefined;
var ts_ptr: ?*std.posix.timespec = null;
// Futex timespec timeout is already in relative time.
if (timeout) |timeout_ns| {
ts_ptr = &ts;
ts.tv_sec = @as(@TypeOf(ts.tv_sec), @intCast(timeout_ns / std.time.ns_per_s));
ts.tv_nsec = @as(@TypeOf(ts.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s));
}
switch (bun.C.getErrno(linux.futex_wait(
@as(*const i32, @ptrCast(ptr)),
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAIT,
@as(i32, @bitCast(expect)),
ts_ptr,
))) {
.SUCCESS => {}, // notified by `wake()`
.INTR => {}, // spurious wakeup
.AGAIN => {}, // ptr.* != expect
.TIMEDOUT => return error.TimedOut,
.INVAL => {}, // possibly timeout overflow
.FAULT => unreachable,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
switch (bun.C.getErrno(linux.futex_wake(
@as(*const i32, @ptrCast(ptr)),
linux.FUTEX.PRIVATE_FLAG | linux.FUTEX.WAKE,
std.math.cast(i32, num_waiters) orelse std.math.maxInt(i32),
))) {
.SUCCESS => {}, // successful wake up
.INVAL => {}, // invalid futex_wait() on ptr done elsewhere
.FAULT => {}, // pointer became invalid while doing the wake
else => unreachable,
}
}
};
const DarwinFutex = struct {
const darwin = std.c;
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
// Darwin XNU 7195.50.7.100.1 introduced __ulock_wait2 and migrated code paths (notably pthread_cond_t) towards it:
// https://github.com/apple/darwin-xnu/commit/d4061fb0260b3ed486147341b72468f836ed6c8f#diff-08f993cc40af475663274687b7c326cc6c3031e0db3ac8de7b24624610616be6
//
// This XNU version appears to correspond to 11.0.1:
// https://kernelshaman.blogspot.com/2021/01/building-xnu-for-macos-big-sur-1101.html
//
// ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout
// ulock_wait2() uses 64-bit nano-second timeouts (with the same convention)
var timeout_ns: u64 = 0;
if (timeout) |timeout_value| {
// This should be checked by the caller.
assert(timeout_value != 0);
timeout_ns = timeout_value;
}
const addr = @as(*const anyopaque, @ptrCast(ptr));
const flags = darwin.UL_COMPARE_AND_WAIT | darwin.ULF_NO_ERRNO;
// If we're using `__ulock_wait` and `timeout` is too big to fit inside a `u32` count of
// micro-seconds (around 70min), we'll request a shorter timeout. This is fine (users
// should handle spurious wakeups), but we need to remember that we did so, so that
// we don't return `TimedOut` incorrectly. If that happens, we set this variable to
// true so that we we know to ignore the ETIMEDOUT result.
var timeout_overflowed = false;
const status = blk: {
const timeout_us = cast: {
const timeout_u32 = std.math.cast(u32, timeout_ns / std.time.ns_per_us);
timeout_overflowed = timeout_u32 == null;
break :cast timeout_u32 orelse std.math.maxInt(u32);
};
break :blk darwin.__ulock_wait(flags, addr, expect, timeout_us);
};
if (status >= 0) return;
switch (@as(std.posix.E, @enumFromInt(-status))) {
.INTR => {},
// Address of the futex is paged out. This is unlikely, but possible in theory, and
// pthread/libdispatch on darwin bother to handle it. In this case we'll return
// without waiting, but the caller should retry anyway.
.FAULT => {},
.TIMEDOUT => if (!timeout_overflowed) return error.TimedOut,
else => unreachable,
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
var flags: u32 = darwin.UL_COMPARE_AND_WAIT | darwin.ULF_NO_ERRNO;
if (num_waiters > 1) {
flags |= darwin.ULF_WAKE_ALL;
}
while (true) {
const addr = @as(*const anyopaque, @ptrCast(ptr));
const status = darwin.__ulock_wake(flags, addr, 0);
if (status >= 0) return;
switch (@as(std.posix.E, @enumFromInt(-status))) {
.INTR => continue, // spurious wake()
.FAULT => continue, // address of the lock was paged out
.NOENT => return, // nothing was woken up
.ALREADY => unreachable, // only for ULF_WAKE_THREAD
else => unreachable,
}
}
}
};
const PosixFutex = struct {
fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{TimedOut}!void {
const address = @intFromPtr(ptr);
const bucket = Bucket.from(address);
var waiter: List.Node = undefined;
{
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
if (ptr.load(.seq_cst) != expect) {
return;
}
waiter.data = .{ .address = address };
bucket.list.prepend(&waiter);
}
var timed_out = false;
waiter.data.wait(timeout) catch {
defer if (!timed_out) {
waiter.data.wait(null) catch unreachable;
};
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
if (waiter.data.address == address) {
timed_out = true;
bucket.list.remove(&waiter);
}
};
waiter.data.deinit();
if (timed_out) {
return error.TimedOut;
}
}
fn wake(ptr: *const Atomic(u32), num_waiters: u32) void {
const address = @intFromPtr(ptr);
const bucket = Bucket.from(address);
var can_notify = num_waiters;
var notified = List{};
defer while (notified.popFirst()) |waiter| {
waiter.data.notify();
};
assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS);
var waiters = bucket.list.first;
while (waiters) |waiter| {
assert(waiter.data.address != null);
waiters = waiter.next;
if (waiter.data.address != address) continue;
if (can_notify == 0) break;
can_notify -= 1;
bucket.list.remove(waiter);
waiter.data.address = null;
notified.prepend(waiter);
}
}
const Bucket = struct {
mutex: std.c.pthread_mutex_t = .{},
list: List = .{},
var buckets = [_]Bucket{.{}} ** 64;
fn from(address: usize) *Bucket {
return &buckets[address % buckets.len];
}
};
const List = std.TailQueue(struct {
address: ?usize,
state: State = .empty,
cond: std.c.pthread_cond_t = .{},
mutex: std.c.pthread_mutex_t = .{},
const Self = @This();
const State = enum {
empty,
waiting,
notified,
};
fn deinit(self: *Self) void {
_ = std.c.pthread_cond_destroy(&self.cond);
_ = std.c.pthread_mutex_destroy(&self.mutex);
}
fn wait(self: *Self, timeout: ?u64) error{TimedOut}!void {
assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
switch (self.state) {
.empty => self.state = .waiting,
.waiting => unreachable,
.notified => return,
}
var ts: std.posix.timespec = undefined;
var ts_ptr: ?*const std.posix.timespec = null;
if (timeout) |timeout_ns| {
ts_ptr = &ts;
std.posix.clock_gettime(std.posix.CLOCK_REALTIME, &ts) catch unreachable;
ts.tv_sec += @as(@TypeOf(ts.tv_sec), @intCast(timeout_ns / std.time.ns_per_s));
ts.tv_nsec += @as(@TypeOf(ts.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s));
if (ts.tv_nsec >= std.time.ns_per_s) {
ts.tv_sec += 1;
ts.tv_nsec -= std.time.ns_per_s;
}
}
while (true) {
switch (self.state) {
.empty => unreachable,
.waiting => {},
.notified => return,
}
const ts_ref = ts_ptr orelse {
assert(std.c.pthread_cond_wait(&self.cond, &self.mutex) == .SUCCESS);
continue;
};
const rc = std.c.pthread_cond_timedwait(&self.cond, &self.mutex, ts_ref);
switch (rc) {
.SUCCESS => {},
.TIMEDOUT => {
self.state = .empty;
return error.TimedOut;
},
else => unreachable,
}
}
}
fn notify(self: *Self) void {
assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS);
defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS);
switch (self.state) {
.empty => self.state = .notified,
.waiting => {
self.state = .notified;
assert(std.c.pthread_cond_signal(&self.cond) == .SUCCESS);
},
.notified => unreachable,
}
}
});
};