Skip to main content

c/
socket.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// ============================================================
5// sys/socket.h
6// ============================================================
7
8pub const AF_UNIX: c_int = 1;
9pub const AF_INET: c_int = 2;
10pub const AF_INET6: c_int = 10;
11
12pub const SOCK_STREAM: c_int = 1;
13pub const SOCK_DGRAM: c_int = 2;
14
15pub const SHUT_RD: c_int = 0;
16pub const SHUT_WR: c_int = 1;
17pub const SHUT_RDWR: c_int = 2;
18
19pub const SOL_SOCKET: c_int = 1;
20pub const SO_REUSEADDR: c_int = 2;
21
22#[repr(C)]
23pub struct sockaddr {
24    pub sa_family: u16,
25    pub sa_data: [u8; 14],
26}
27
28#[inline]
29unsafe fn sys_socket(domain: c_int, ty: c_int, protocol: c_int) -> i64 {
30    <Arch as Syscalls>::syscall3(SYS_SOCKET, domain as i64, ty as i64, protocol as i64)
31}
32
33#[inline]
34unsafe fn sys_socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> i64 {
35    <Arch as Syscalls>::syscall4(SYS_SOCKETPAIR, domain as i64, ty as i64, protocol as i64, sv as i64)
36}
37
38#[inline]
39unsafe fn sys_bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
40    <Arch as Syscalls>::syscall3(SYS_BIND, fd as i64, addr as i64, len as i64)
41}
42
43#[inline]
44unsafe fn sys_listen(fd: c_int, backlog: c_int) -> i64 {
45    <Arch as Syscalls>::syscall2(SYS_LISTEN, fd as i64, backlog as i64)
46}
47
48#[inline]
49unsafe fn sys_accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
50    <Arch as Syscalls>::syscall3(SYS_ACCEPT, fd as i64, addr as i64, len as i64)
51}
52
53#[inline]
54unsafe fn sys_connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> i64 {
55    <Arch as Syscalls>::syscall3(SYS_CONNECT, fd as i64, addr as i64, len as i64)
56}
57
58#[inline]
59unsafe fn sys_sendto(fd: c_int,
60    buf: *const c_void,
61    len: usize,
62    flags: c_int,
63    addr: *const sockaddr,
64    addrlen: c_uint,) -> i64 {
65    <Arch as Syscalls>::syscall6(SYS_SENDTO, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
66}
67
68#[inline]
69unsafe fn sys_recvfrom(fd: c_int,
70    buf: *mut c_void,
71    len: usize,
72    flags: c_int,
73    addr: *mut sockaddr,
74    addrlen: *mut c_uint,) -> i64 {
75    <Arch as Syscalls>::syscall6(SYS_RECVFROM, fd as i64, buf as i64, len as i64, flags as i64, addr as i64, addrlen as i64)
76}
77
78#[inline]
79unsafe fn sys_shutdown(fd: c_int, how: c_int) -> i64 {
80    <Arch as Syscalls>::syscall2(SYS_SHUTDOWN, fd as i64, how as i64)
81}
82
83#[inline]
84unsafe fn sys_setsockopt(fd: c_int,
85    level: c_int,
86    optname: c_int,
87    optval: *const c_void,
88    optlen: c_uint,) -> i64 {
89    <Arch as Syscalls>::syscall5(SYS_SETSOCKOPT, fd as i64, level as i64, optname as i64, optval as i64, optlen as i64)
90}
91
92#[inline]
93unsafe fn sys_getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> i64 {
94    <Arch as Syscalls>::syscall3(SYS_GETSOCKNAME, fd as i64, addr as i64, len as i64)
95}
96
97#[no_mangle]
98pub unsafe extern "C" fn socket(domain: c_int, ty: c_int, protocol: c_int) -> c_int {
99    let r = sys_socket(domain, ty, protocol);
100    syscall_ret(r) as c_int
101}
102
103#[no_mangle]
104pub unsafe extern "C" fn socketpair(domain: c_int, ty: c_int, protocol: c_int, sv: *mut c_int) -> c_int {
105    let r = sys_socketpair(domain, ty, protocol, sv);
106    syscall_ret(r) as c_int
107}
108
109#[no_mangle]
110pub unsafe extern "C" fn bind(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
111    let r = sys_bind(fd, addr, len);
112    syscall_ret(r) as c_int
113}
114
115#[no_mangle]
116pub unsafe extern "C" fn listen(fd: c_int, backlog: c_int) -> c_int {
117    let r = sys_listen(fd, backlog);
118    syscall_ret(r) as c_int
119}
120
121#[no_mangle]
122pub unsafe extern "C" fn accept(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
123    let r = sys_accept(fd, addr, len);
124    syscall_ret(r) as c_int
125}
126
127#[no_mangle]
128pub unsafe extern "C" fn connect(fd: c_int, addr: *const sockaddr, len: c_uint) -> c_int {
129    let r = sys_connect(fd, addr, len);
130    syscall_ret(r) as c_int
131}
132
133#[no_mangle]
134pub unsafe extern "C" fn send(fd: c_int, buf: *const c_void, len: usize, flags: c_int) -> isize {
135    let r = sys_sendto(fd, buf, len, flags, core::ptr::null(), 0);
136    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
137    r as isize
138}
139
140#[no_mangle]
141pub unsafe extern "C" fn recv(fd: c_int, buf: *mut c_void, len: usize, flags: c_int) -> isize {
142    let r = sys_recvfrom(fd, buf, len, flags, core::ptr::null_mut(), core::ptr::null_mut());
143    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
144    r as isize
145}
146
147#[no_mangle]
148pub unsafe extern "C" fn sendto(
149    fd: c_int,
150    buf: *const c_void,
151    len: usize,
152    flags: c_int,
153    addr: *const sockaddr,
154    addrlen: c_uint,
155) -> isize {
156    let r = sys_sendto(fd, buf, len, flags, addr, addrlen);
157    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
158    r as isize
159}
160
161#[no_mangle]
162pub unsafe extern "C" fn recvfrom(
163    fd: c_int,
164    buf: *mut c_void,
165    len: usize,
166    flags: c_int,
167    addr: *mut sockaddr,
168    addrlen: *mut c_uint,
169) -> isize {
170    let r = sys_recvfrom(fd, buf, len, flags, addr, addrlen);
171    if r < 0 { ERRNO!() = (-r) as c_int; return -1; }
172    r as isize
173}
174
175#[no_mangle]
176pub unsafe extern "C" fn shutdown(fd: c_int, how: c_int) -> c_int {
177    let r = sys_shutdown(fd, how);
178    syscall_ret(r) as c_int
179}
180
181#[no_mangle]
182pub unsafe extern "C" fn setsockopt(
183    fd: c_int,
184    level: c_int,
185    optname: c_int,
186    optval: *const c_void,
187    optlen: c_uint,
188) -> c_int {
189    let r = sys_setsockopt(fd, level, optname, optval, optlen);
190    syscall_ret(r) as c_int
191}
192
193#[no_mangle]
194pub unsafe extern "C" fn getsockname(fd: c_int, addr: *mut sockaddr, len: *mut c_uint) -> c_int {
195    let r = sys_getsockname(fd, addr, len);
196    syscall_ret(r) as c_int
197}
198
199#[no_mangle]
200pub extern "C" fn htonl(hostlong: c_uint) -> c_uint {
201    hostlong.to_be()
202}
203
204#[no_mangle]
205pub extern "C" fn ntohl(netlong: c_uint) -> c_uint {
206    c_uint::from_be(netlong)
207}
208
209#[no_mangle]
210pub extern "C" fn htons(hostshort: u16) -> u16 {
211    hostshort.to_be()
212}
213
214#[no_mangle]
215pub extern "C" fn ntohs(netshort: u16) -> u16 {
216    u16::from_be(netshort)
217}
218
219pub type PthreadT = c_ulong;
220
221// pthread_attr_t: musl 64-bit layout (56 bytes = int[14])
222#[repr(C)]
223pub struct pthread_attr_t {
224    __i: [c_int; 14],
225}
226
227// pthread_mutex_t: musl 64-bit layout (40 bytes = int[10])
228// _m_type=__i[0], _m_lock=__i[1], _m_waiters=__i[2], _m_count=__i[5]
229#[repr(C)]
230pub struct pthread_mutex_t {
231    __i: [c_int; 10],
232}
233
234#[repr(C)]
235pub struct pthread_mutexattr_t {
236    __attr: c_uint,
237}
238
239// pthread_cond_t: musl 64-bit layout (48 bytes = int[12])
240// _c_seq=__i[2], _c_waiters=__i[3], _c_clock=__i[4]
241#[repr(C)]
242pub struct pthread_cond_t {
243    __i: [c_int; 12],
244}
245
246#[repr(C)]
247pub struct pthread_condattr_t {
248    __attr: c_uint,
249}
250
251// pthread_rwlock_t: musl 64-bit layout (56 bytes = int[14])
252// _rw_lock=__i[0], _rw_waiters=__i[1], _rw_shared=__i[2]
253#[repr(C)]
254pub struct pthread_rwlock_t {
255    __i: [c_int; 14],
256}
257
258#[repr(C)]
259pub struct pthread_rwlockattr_t {
260    __attr: [c_uint; 2],
261}
262
263// pthread_barrier_t: musl 64-bit layout (32 bytes = int[8])
264#[repr(C)]
265pub struct pthread_barrier_t {
266    __i: [c_int; 8],
267}
268
269#[repr(C)]
270pub struct pthread_barrierattr_t {
271    __attr: c_uint,
272}
273
274pub type pthread_spinlock_t = c_int;
275pub type pthread_once_t = c_int;
276pub type pthread_key_t = c_uint;
277
278// sem_t: musl 64-bit layout (32 bytes = int[8])
279#[repr(C)]
280pub struct sem_t {
281    __val: [c_int; 8],
282}
283
284#[repr(C)]
285pub struct sched_param {
286    pub sched_priority: c_int,
287}
288
289const CLONE_VM: c_ulong = 0x00000100;
290const CLONE_FS: c_ulong = 0x00000200;
291const CLONE_FILES: c_ulong = 0x00000400;
292const CLONE_SIGHAND: c_ulong = 0x00000800;
293const CLONE_THREAD: c_ulong = 0x00010000;
294const CLONE_SYSVSEM: c_ulong = 0x00040000;
295const CLONE_SETTLS: c_ulong = 0x00080000;
296const CLONE_PARENT_SETTID: c_ulong = 0x00100000;
297const CLONE_CHILD_CLEARTID: c_ulong = 0x00200000;
298
299const FUTEX_WAIT: c_int = 0;
300const FUTEX_WAKE: c_int = 1;
301const FUTEX_LOCK_PI: c_int = 6;
302const FUTEX_UNLOCK_PI: c_int = 7;
303const FUTEX_TRYLOCK_PI: c_int = 8;
304
305// SIGCANCEL (32) is musl's internal cancel signal
306const SIGCANCEL: c_int = 32;
307
308const PTHREAD_MUTEX_NORMAL: c_int = 0;
309const PTHREAD_MUTEX_DEFAULT: c_int = 0;
310const PTHREAD_MUTEX_RECURSIVE: c_int = 1;
311const PTHREAD_MUTEX_ERRORCHECK: c_int = 2;
312
313const PTHREAD_CREATE_JOINABLE: c_int = 0;
314const PTHREAD_CREATE_DETACHED: c_int = 1;
315
316const PTHREAD_CANCEL_ENABLE: c_int = 0;
317const PTHREAD_CANCEL_DISABLE: c_int = 1;
318const PTHREAD_CANCEL_DEFERRED: c_int = 0;
319const PTHREAD_CANCEL_ASYNCHRONOUS: c_int = 1;
320
321const PTHREAD_SCOPE_SYSTEM: c_int = 0;
322const PTHREAD_PROCESS_PRIVATE: c_int = 0;
323const PTHREAD_PROCESS_SHARED: c_int = 1;
324const PTHREAD_INHERIT_SCHED: c_int = 0;
325const PTHREAD_EXPLICIT_SCHED: c_int = 1;
326
327const PTHREAD_BARRIER_SERIAL_THREAD: c_int = -1;
328
329const PTHREAD_KEYS_MAX: usize = 128;
330const PTHREAD_DESTRUCTOR_ITERATIONS: usize = 4;
331const SEM_VALUE_MAX: c_int = 0x7fffffff;
332
333const DT_EXITED: c_int = 0;
334const DT_EXITING: c_int = 1;
335const DT_JOINABLE: c_int = 2;
336const DT_DETACHED: c_int = 3;
337
338// musl __ptcb cleanup handler node
339#[repr(C)]
340#[derive(Copy, Clone)]
341pub struct __ptcb {
342    __f: Option<unsafe extern "C" fn(*mut c_void)>,
343    __x: *mut c_void,
344    __next: *mut __ptcb,
345}
346
347// robust_list_head for kernel robust mutex support
348#[repr(C)]
349#[derive(Copy, Clone)]
350struct robust_list {
351    next: *mut robust_list,
352}
353
354#[repr(C)]
355#[derive(Copy, Clone)]
356struct robust_list_head {
357    list: robust_list,
358    futex_offset: c_long,
359    pending: *mut robust_list,
360}
361
362// Adapted from musl's x86_64 clone.s.
363#[cfg(all(target_arch = "x86_64", not(test)))]
364core::arch::global_asm!(
365    ".global __keel_clone",
366    ".type __keel_clone, @function",
367    "__keel_clone:",
368    "mov rax, rdi",
369    "mov rdi, rdx",
370    "mov rdx, r8",
371    "mov r10, [rsp + 8]",
372    "mov r8, r9",
373    "mov r9, rax",
374    "and rsi, -16",
375    "sub rsi, 8",
376    "mov [rsi], rcx",
377    "mov eax, 56",
378    "syscall",
379    "test rax, rax",
380    "jnz 1f",
381    "pop rdi",
382    "call r9",
383    // A clone() child that returns from its function must exit with that
384    // value (musl does the same); falling through to hlt raises SIGSEGV.
385    "mov edi, eax",
386    "mov eax, 60",
387    "syscall",
388    "hlt",
389    "1:",
390    "ret",
391);
392
393// Adapted from musl's aarch64 clone.s.
394#[no_mangle]
395#[unsafe(naked)]
396#[cfg(target_arch = "aarch64")]
397pub unsafe extern "C" fn __keel_clone(
398    fn_: usize,
399    stack: *mut u8,
400    flags: c_ulong,
401    arg: *mut c_void,
402    ptid: *mut c_int,
403    tls: c_ulong,
404    ctid: *mut c_int,
405) -> i64 {
406    core::arch::naked_asm!(
407        "and x1, x1, #-16",
408        "stp x0, x3, [x1, #-16]!",
409        "uxtw x0, w2",
410        "mov x2, x4",
411        "mov x3, x5",
412        "mov x4, x6",
413        "mov x8, #220",
414        "svc #0",
415        "cbz x0, 1f",
416        "ret",
417        "1:",
418        "mov x29, #0",
419        "ldp x1, x0, [sp], #16",
420        "blr x1",
421        "mov x8, #93",
422        "svc #0",
423    );
424}
425
426#[no_mangle]
427#[unsafe(naked)]
428#[cfg(target_arch = "riscv64")]
429pub unsafe extern "C" fn __keel_clone(
430    fn_: usize,
431    stack: *mut u8,
432    flags: c_ulong,
433    arg: *mut c_void,
434    ptid: *mut c_int,
435    tls: c_ulong,
436    ctid: *mut c_int,
437) -> i64 {
438    core::arch::naked_asm!(
439        "andi a1, a1, -16",
440        "addi a1, a1, -16",
441        "sd a0, 0(a1)",
442        "sd a3, 8(a1)",
443        "mv a0, a2",
444        "mv a2, a4",
445        "mv a3, a5",
446        "mv a4, a6",
447        "li a7, 220",
448        "ecall",
449        "beqz a0, 1f",
450        "ret",
451        "1:",
452        "ld a1, 0(sp)",
453        "ld a0, 8(sp)",
454        "jalr a1",
455        "li a7, 93",
456        "ecall",
457    );
458}
459
460// Adapted from musl's powerpc64 clone.s.
461#[no_mangle]
462#[unsafe(naked)]
463#[cfg(target_arch = "powerpc64")]
464pub unsafe extern "C" fn __keel_clone(
465    fn_: usize,
466    stack: *mut u8,
467    flags: c_ulong,
468    arg: *mut c_void,
469    ptid: *mut c_int,
470    tls: c_ulong,
471    ctid: *mut c_int,
472) -> i64 {
473    core::arch::naked_asm!(
474        "clrrdi 4, 4, 4",
475        "li 0, 0",
476        "stdu 0, -32(4)",
477        "std 3, 8(4)",
478        "std 6, 16(4)",
479        "mr 3, 5",
480        "mr 5, 7",
481        "mr 6, 8",
482        "mr 7, 9",
483        "li 0, 120",
484        "sc",
485        "bns+ 1f",
486        "neg 3, 3",
487        "1:",
488        "cmpwi cr7, 3, 0",
489        "bnelr cr7",
490        "ld 3, 16(1)",
491        "ld 12, 8(1)",
492        "mtctr 12",
493        "bctrl",
494        "li 0, 1",
495        "sc",
496    );
497}
498
499// Adapted from musl's loongarch64 clone.s.
500#[no_mangle]
501#[unsafe(naked)]
502#[cfg(target_arch = "loongarch64")]
503pub unsafe extern "C" fn __keel_clone(
504    fn_: usize,
505    stack: *mut u8,
506    flags: c_ulong,
507    arg: *mut c_void,
508    ptid: *mut c_int,
509    tls: c_ulong,
510    ctid: *mut c_int,
511) -> i64 {
512    core::arch::naked_asm!(
513        "bstrins.d $a1, $zero, 3, 0",
514        "addi.d $a1, $a1, -16",
515        "st.d $a0, $a1, 0",
516        "st.d $a3, $a1, 8",
517        "or $a0, $a2, $zero",
518        "or $a2, $a4, $zero",
519        "or $a3, $a6, $zero",
520        "or $a4, $a5, $zero",
521        "ori $a7, $zero, 220",
522        "syscall 0",
523        "beqz $a0, 1f",
524        "jirl $zero, $ra, 0",
525        "1:",
526        "move $fp, $zero",
527        "ld.d $t8, $sp, 0",
528        "ld.d $a0, $sp, 8",
529        "jirl $ra, $t8, 0",
530        "ori $a7, $zero, 93",
531        "syscall 0",
532    );
533}
534
535#[cfg(all(target_arch = "x86_64", test))]
536#[inline(never)]
537unsafe fn __keel_clone(
538    _fn_: usize,
539    _stack: *mut u8,
540    _flags: c_ulong,
541    _arg: *mut c_void,
542    _ptid: *mut c_int,
543    _tls: c_ulong,
544    _ctid: *mut c_int,
545) -> i64 {
546    -1
547}
548
549#[cfg(all(target_arch = "x86_64", not(test)))]
550extern "C" {
551    fn __keel_clone(
552        fn_: usize,
553        stack: *mut u8,
554        flags: c_ulong,
555        arg: *mut c_void,
556        ptid: *mut c_int,
557        tls: c_ulong,
558        ctid: *mut c_int,
559    ) -> i64;
560}
561
562#[derive(Copy, Clone)]
563struct TlsHooks {
564    create: unsafe extern "C" fn() -> *mut u8,
565    init: unsafe extern "C" fn(*mut u8) -> *mut u8,
566    block_size: extern "C" fn() -> usize,
567    base_offset: extern "C" fn() -> usize,
568}
569
570// Installed by the dynamic loader before any thread is created. A static
571// executable leaves this as None and uses the weak fallbacks.
572static mut TLS_HOOKS: Option<TlsHooks> = None;
573
574/// Called by the dynamic loader once it is self-relocated.  A static
575/// executable does not call this and keeps the fallback behaviour.
576#[no_mangle]
577pub unsafe extern "C" fn __keel_set_thread_tls_hooks(
578    create: usize,
579    init: usize,
580    block_size: usize,
581    base_offset: usize,
582) {
583    TLS_HOOKS = Some(TlsHooks {
584        create: core::mem::transmute(create),
585        init: core::mem::transmute(init),
586        block_size: core::mem::transmute(block_size),
587        base_offset: core::mem::transmute(base_offset),
588    });
589}
590
591#[inline(never)]
592#[no_mangle]
593pub extern "C" fn __keel_create_thread_tls() -> *mut u8 {
594    match unsafe { TLS_HOOKS } {
595        Some(hooks) => unsafe { (hooks.create)() },
596        None => core::ptr::null_mut(),
597    }
598}
599
600#[inline(never)]
601#[no_mangle]
602pub unsafe extern "C" fn __keel_init_thread_tls_at(block: *mut u8) -> *mut u8 {
603    match TLS_HOOKS {
604        Some(hooks) => (hooks.init)(block),
605        None => core::ptr::null_mut(),
606    }
607}
608
609#[inline(never)]
610#[no_mangle]
611pub extern "C" fn __keel_tls_block_size() -> usize {
612    match unsafe { TLS_HOOKS } {
613        Some(hooks) => (hooks.block_size)(),
614        None => 0,
615    }
616}
617
618#[inline(never)]
619#[no_mangle]
620pub extern "C" fn __keel_tls_base_offset() -> usize {
621    match unsafe { TLS_HOOKS } {
622        Some(hooks) => (hooks.base_offset)(),
623        None => 0,
624    }
625}
626
627#[inline]
628unsafe fn sys_gettid() -> i64 {
629    <Arch as Syscalls>::syscall0(SYS_GETTID)
630}
631
632#[inline]
633unsafe fn sys_futex(uaddr: *mut c_int,
634    futex_op: c_int,
635    val: c_int,
636    timeout: *mut c_void,
637    uaddr2: *mut c_int,
638    val3: c_int,) -> i64 {
639    <Arch as Syscalls>::syscall6(SYS_FUTEX, uaddr as i64, futex_op as i64, val as i64, timeout as i64, uaddr2 as i64, val3 as i64)
640}
641
642const THREAD_CHUNK: usize = 1024;
643const STACK_SIZE: usize = 1024 * 1024;
644// Per-thread pointer to its Thread record.  The TCB has room after errno
645// (0x30), the vDSO getrandom state (0x38), and this pointer (0x40).
646const THREAD_TCB_OFFSET: usize = 0x40;
647
648#[repr(C)]
649#[derive(Copy, Clone)]
650struct Thread {
651    tid: c_int,
652    detach_state: c_int,
653    result: *mut c_void,
654    cancel: c_int,
655    cancel_state: c_int,
656    cancel_type: c_int,
657    user_fn: usize,
658    user_arg: *mut c_void,
659    stack: *mut u8,
660    stack_size: usize,
661    stack_owned: bool,
662    fs_base: *mut u8,
663    // TLS block as allocated at creation. The global TLS size can grow when
664    // a DSO is dlopen'ed, so it must not be used to free an older thread's
665    // block: the address and length would be wrong and could unmap a
666    // neighbouring thread stack.
667    tls_base: *mut u8,
668    tls_size: usize,
669    tsd: [*mut c_void; PTHREAD_KEYS_MAX],
670    cancelbuf: *mut __ptcb,
671    robust_list: robust_list_head,
672    free_next: *mut Thread,
673}
674
675static mut THREADS: [Thread; THREAD_CHUNK] = [Thread {
676    tid: -1,
677    detach_state: DT_JOINABLE,
678    result: core::ptr::null_mut(),
679    cancel: 0,
680    cancel_state: PTHREAD_CANCEL_ENABLE,
681    cancel_type: PTHREAD_CANCEL_DEFERRED,
682    user_fn: 0,
683    user_arg: core::ptr::null_mut(),
684    stack: core::ptr::null_mut(),
685    stack_size: 0,
686    stack_owned: false,
687    fs_base: core::ptr::null_mut(),
688    tls_base: core::ptr::null_mut(),
689    tls_size: 0,
690    tsd: [core::ptr::null_mut(); PTHREAD_KEYS_MAX],
691    cancelbuf: core::ptr::null_mut(),
692    robust_list: robust_list_head {
693        list: robust_list { next: core::ptr::null_mut() },
694        futex_offset: 0,
695        pending: core::ptr::null_mut(),
696    },
697    free_next: core::ptr::null_mut(),
698}; THREAD_CHUNK];
699#[repr(C)]
700struct ThreadChunk {
701    next: *mut ThreadChunk,
702    base: *mut Thread,
703}
704static THREAD_CHUNK_LIST: AtomicPtr<ThreadChunk> =
705    AtomicPtr::new(core::ptr::null_mut());
706static EXTRA_CHUNK_COUNT: AtomicUsize = AtomicUsize::new(0);
707// Free list of thread slots, protected by THREAD_LOCK.  Slots are never
708// moved, so pthread_t values stay valid for the life of a thread.
709static mut FREE_THREADS: *mut Thread = core::ptr::null_mut();
710static mut THREAD_TABLE_READY: bool = false;
711static mut THREAD_LOCK: c_int = 0;
712static mut THREAD_WAITERS: c_int = 0;
713static ACTIVE_THREADS: AtomicUsize = AtomicUsize::new(0);
714static mut KEY_DTORS: [Option<unsafe extern "C" fn(*mut c_void)>; PTHREAD_KEYS_MAX] = [None; PTHREAD_KEYS_MAX];
715static NEXT_KEY: AtomicUsize = AtomicUsize::new(0);
716
717// futex helpers
718unsafe fn futex_wait(addr: *mut c_int, expected: c_int) -> c_int {
719    let r = sys_futex(addr, FUTEX_WAIT, expected, null_mut(), null_mut(), 0);
720    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
721}
722
723unsafe fn futex_wake(addr: *mut c_int, count: c_int) {
724    let c = if count < 0 { c_int::MAX } else { count };
725    sys_futex(addr, FUTEX_WAKE, c, null_mut(), null_mut(), 0);
726}
727
728unsafe fn futex_lock_pi(addr: *mut c_int, abs_timeout: *const timespec) -> c_int {
729    let timeout_ptr = if abs_timeout.is_null() { null_mut() } else { abs_timeout as *mut c_void };
730    let r = sys_futex(addr, FUTEX_LOCK_PI, 0, timeout_ptr, null_mut(), 0);
731    if r < 0 { (-r) as c_int } else { 0 }
732}
733
734unsafe fn futex_unlock_pi(addr: *mut c_int) -> c_int {
735    let r = sys_futex(addr, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
736    if r < 0 { (-r) as c_int } else { 0 }
737}
738
739#[inline]
740unsafe fn sys_set_robust_list(head: *mut robust_list_head, len: usize) -> i64 {
741    <Arch as Syscalls>::syscall2(SYS_SET_ROBUST_LIST, head as i64, len as i64)
742}
743
744unsafe fn futex_timedwait(addr: *mut c_int, expected: c_int, abs_timeout: *const timespec) -> c_int {
745    if abs_timeout.is_null() { return futex_wait(addr, expected); }
746    let mut now: timespec = core::mem::zeroed();
747    if sys_clock_gettime(CLOCK_REALTIME, &mut now) < 0 { return EINVAL; }
748    let mut rel: timespec = core::mem::zeroed();
749    rel.tv_sec = (*abs_timeout).tv_sec - now.tv_sec;
750    rel.tv_nsec = (*abs_timeout).tv_nsec - now.tv_nsec;
751    if rel.tv_nsec < 0 { rel.tv_sec -= 1; rel.tv_nsec += 1_000_000_000; }
752    if rel.tv_sec < 0 { return ETIMEDOUT; }
753    let r = sys_futex(addr, FUTEX_WAIT, expected, &mut rel as *mut timespec as *mut c_void, null_mut(), 0);
754    if r < 0 { let e = (-r) as c_int; if e == EAGAIN { 0 } else { e } } else { 0 }
755}
756
757// atomic helpers wrapping AtomicI32
758unsafe fn a_cas(addr: *mut c_int, expected: c_int, desired: c_int) -> c_int {
759    let a = &*(addr as *const AtomicI32);
760    match a.compare_exchange(expected, desired, Ordering::AcqRel, Ordering::Acquire) {
761        Ok(v) | Err(v) => v,
762    }
763}
764
765unsafe fn a_store(addr: *mut c_int, val: c_int) {
766    (*(addr as *const AtomicI32)).store(val, Ordering::Release);
767}
768
769unsafe fn a_load(addr: *const c_int) -> c_int {
770    (*(addr as *const AtomicI32)).load(Ordering::Acquire)
771}
772
773unsafe fn a_swap(addr: *mut c_int, val: c_int) -> c_int {
774    (*(addr as *const AtomicI32)).swap(val, Ordering::AcqRel)
775}
776
777unsafe fn a_fetch_add(addr: *mut c_int, val: c_int) -> c_int {
778    (*(addr as *const AtomicI32)).fetch_add(val, Ordering::AcqRel)
779}
780
781unsafe fn a_fetch_sub(addr: *mut c_int, val: c_int) -> c_int {
782    (*(addr as *const AtomicI32)).fetch_sub(val, Ordering::AcqRel)
783}
784
785unsafe fn spinlock_lock(lock: *mut c_int, waiters: *mut c_int) {
786    while a_swap(lock, 1) != 0 {
787        let mut spins = 100;
788        while spins > 0 && a_load(lock) != 0 { core::hint::spin_loop(); spins -= 1; }
789        if a_load(lock) == 0 { continue; }
790        a_fetch_add(waiters, 1);
791        futex_wait(lock, 1);
792        a_fetch_sub(waiters, 1);
793    }
794}
795
796unsafe fn spinlock_unlock(lock: *mut c_int, waiters: *mut c_int) {
797    a_store(lock, 0);
798    if a_load(waiters) > 0 { futex_wake(lock, 1); }
799}
800
801unsafe fn thread_slot_count() -> usize {
802    THREAD_CHUNK + EXTRA_CHUNK_COUNT.load(Ordering::Acquire) * THREAD_CHUNK
803}
804
805unsafe fn thread_slot_at(index: usize) -> *mut Thread {
806    if index < THREAD_CHUNK {
807        core::ptr::addr_of_mut!(THREADS[index])
808    } else {
809        let extra = index - THREAD_CHUNK;
810        let chunk_index = extra / THREAD_CHUNK;
811        let offset = extra % THREAD_CHUNK;
812        let mut chunk = THREAD_CHUNK_LIST.load(Ordering::Acquire);
813        let mut i = 0usize;
814        while i < chunk_index && !chunk.is_null() {
815            chunk = (*chunk).next;
816            i += 1;
817        }
818        if chunk.is_null() {
819            return core::ptr::null_mut();
820        }
821        (*chunk).base.add(offset)
822    }
823}
824
825unsafe fn release_thread_slot(slot: *const Thread) {
826    let slot = slot as *mut Thread;
827    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
828    (*slot).tid = -1;
829    (*slot).free_next = FREE_THREADS;
830    FREE_THREADS = slot;
831    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
832}
833
834/// Link slots `start..THREAD_CHUNK` of `base` into the free list.  Caller
835/// holds THREAD_LOCK.
836unsafe fn push_free_slots(base: *mut Thread, start: usize) {
837    let mut i = THREAD_CHUNK;
838    while i > start {
839        i -= 1;
840        let slot = base.add(i);
841        (*slot).free_next = FREE_THREADS;
842        FREE_THREADS = slot;
843    }
844}
845
846unsafe fn alloc_thread_slot() -> Option<&'static mut Thread> {
847    spinlock_lock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
848    if !THREAD_TABLE_READY {
849        // Slot 0 is reserved for the process's initial thread.  Registering
850        // it must not require touching the rest of the table.
851        push_free_slots(core::ptr::addr_of_mut!(THREADS[0]), 1);
852        THREAD_TABLE_READY = true;
853    }
854    let mut slot = FREE_THREADS;
855    if slot.is_null() {
856        let bytes = core::mem::size_of::<ThreadChunk>()
857            + THREAD_CHUNK * core::mem::size_of::<Thread>();
858        let raw = sys_mmap(
859            core::ptr::null_mut(),
860            bytes,
861            PROT_READ | PROT_WRITE,
862            MAP_PRIVATE | MAP_ANONYMOUS,
863            -1,
864            0,
865        ) as *mut u8;
866        if raw.is_null() || raw == MMAP_FAILED {
867            spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
868            return None;
869        }
870        let header = raw as *mut ThreadChunk;
871        let base = raw.add(core::mem::size_of::<ThreadChunk>()) as *mut Thread;
872        (*header).base = base;
873        push_free_slots(base, 1);
874        (*header).next = THREAD_CHUNK_LIST.load(Ordering::Relaxed);
875        THREAD_CHUNK_LIST.store(header, Ordering::Release);
876        EXTRA_CHUNK_COUNT.fetch_add(1, Ordering::AcqRel);
877        slot = base;
878    } else {
879        FREE_THREADS = (*slot).free_next;
880        (*slot).free_next = core::ptr::null_mut();
881    }
882    spinlock_unlock(&raw mut THREAD_LOCK, &raw mut THREAD_WAITERS);
883    Some(&mut *slot)
884}
885
886/// The child of fork() keeps only the calling thread.  Rebuild the free list
887/// so slots belonging to vanished threads are reusable, and update the
888/// current thread's tid to the child's.
889unsafe fn thread_allocator_after_fork() {
890    a_store(&raw mut THREAD_LOCK, 0);
891    a_store(&raw mut THREAD_WAITERS, 0);
892    let tp = tcb_slot(THREAD_TCB_OFFSET);
893    let current = if tp.is_null() {
894        core::ptr::null_mut()
895    } else {
896        core::ptr::read_unaligned(tp) as *mut Thread
897    };
898    let child_tid = sys_gettid() as c_int;
899    if !THREAD_TABLE_READY {
900        // The initial thread is registered directly in slot 0, so the free
901        // list may never have been built.  Only update that one slot; the
902        // first pthread_create() will build the free list.
903        if !current.is_null() {
904            (*current).tid = child_tid;
905            ACTIVE_THREADS.store(1, Ordering::Release);
906        }
907        return;
908    }
909    let count = thread_slot_count();
910    let mut free = core::ptr::null_mut();
911    let mut active = 0usize;
912    let mut i = 0usize;
913    while i < count {
914        let slot = thread_slot_at(i);
915        if slot == current {
916            (*slot).tid = child_tid;
917            (*slot).free_next = core::ptr::null_mut();
918            active += 1;
919        } else {
920            (*slot).tid = -1;
921            (*slot).free_next = free;
922            free = slot;
923        }
924        i += 1;
925    }
926    FREE_THREADS = free;
927    ACTIVE_THREADS.store(active, Ordering::Release);
928}
929
930unsafe fn run_key_dtors(slot: &mut Thread) {
931    for _ in 0..PTHREAD_DESTRUCTOR_ITERATIONS {
932        let mut any = false;
933        for i in 0..PTHREAD_KEYS_MAX {
934            let val = slot.tsd[i];
935            if !val.is_null() {
936                if let Some(dtor) = KEY_DTORS[i] {
937                    slot.tsd[i] = core::ptr::null_mut();
938                    any = true;
939                    dtor(val);
940                }
941            }
942        }
943        if !any { break; }
944    }
945}
946
947unsafe extern "C" fn thread_entry(slot: *mut c_void) -> *mut c_void {
948    let slot = &mut *(slot as *mut Thread);
949    let tp = tcb_slot(THREAD_TCB_OFFSET);
950    if !tp.is_null() {
951        core::ptr::write_unaligned(tp, slot as *mut Thread as usize);
952    }
953    // A reused slot may still carry the previous thread's robust-list state;
954    // register a fresh list for this thread.
955    slot.robust_list.list.next = core::ptr::null_mut();
956    slot.robust_list.futex_offset = 0;
957    slot.robust_list.pending = core::ptr::null_mut();
958    ensure_robust_list(slot);
959    let mut set: SigSetT = 0;
960    sigemptyset(&mut set);
961    sigaddset(&mut set, SIGCANCEL);
962    pthread_sigmask(SIG_UNBLOCK, &set, core::ptr::null_mut());
963    let user_fn: unsafe extern "C" fn(*mut c_void) -> *mut c_void =
964        core::mem::transmute::<usize, _>(slot.user_fn);
965    let ret = user_fn(slot.user_arg);
966    thread_finish(slot, ret)
967}
968
969/// Common exit path for a thread that returned from its start routine and
970/// for pthread_exit(): run cleanup handlers and TSD destructors, publish the
971/// result, and give up the CPU.
972unsafe fn thread_finish(slot: &mut Thread, retval: *mut c_void) -> ! {
973    run_cleanup_handlers(slot);
974    run_key_dtors(slot);
975    vdso_getrandom_thread_exit();
976    slot.result = retval;
977    a_store(&raw mut slot.detach_state, DT_EXITED);
978    futex_wake(&raw mut slot.detach_state, 1);
979    if ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel) <= 1 {
980        exit(0);
981    }
982    sys_exit_thread(0)
983}
984
985unsafe fn init_thread_slot(slot: *mut Thread, me: c_int) {
986    (*slot).tid = me;
987    (*slot).detach_state = DT_JOINABLE;
988    (*slot).result = core::ptr::null_mut();
989    (*slot).cancel = 0;
990    (*slot).cancel_state = PTHREAD_CANCEL_ENABLE;
991    (*slot).cancel_type = PTHREAD_CANCEL_DEFERRED;
992    (*slot).cancelbuf = core::ptr::null_mut();
993    core::ptr::write_bytes((*slot).tsd.as_mut_ptr(), 0, PTHREAD_KEYS_MAX);
994    (*slot).robust_list.list.next = core::ptr::null_mut();
995    (*slot).robust_list.futex_offset = 0;
996    (*slot).robust_list.pending = core::ptr::null_mut();
997    (*slot).free_next = core::ptr::null_mut();
998}
999
1000unsafe fn register_main_thread() -> Option<&'static mut Thread> {
1001    let me = sys_gettid() as c_int;
1002    let tp = tcb_slot(THREAD_TCB_OFFSET);
1003    if !tp.is_null() {
1004        let p = core::ptr::read_unaligned(tp) as *mut Thread;
1005        if !p.is_null() && (*p).tid == me {
1006            return Some(&mut *p);
1007        }
1008    }
1009    let slot = core::ptr::addr_of_mut!(THREADS[0]);
1010    init_thread_slot(slot, me);
1011    if !tp.is_null() {
1012        core::ptr::write_unaligned(tp, slot as usize);
1013    }
1014    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
1015    Some(&mut *slot)
1016}
1017
1018unsafe fn register_current_thread() -> Option<&'static mut Thread> {
1019    let me = sys_gettid() as c_int;
1020    let slot_ref = alloc_thread_slot()?;
1021    let slot = slot_ref as *mut Thread;
1022    init_thread_slot(slot, me);
1023    let tp = tcb_slot(THREAD_TCB_OFFSET);
1024    if !tp.is_null() {
1025        core::ptr::write_unaligned(tp, slot as usize);
1026    }
1027    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
1028    Some(&mut *slot)
1029}
1030
1031unsafe fn find_thread() -> Option<&'static mut Thread> {
1032    let me = sys_gettid() as c_int;
1033    let tp = tcb_slot(THREAD_TCB_OFFSET);
1034    if !tp.is_null() {
1035        let p = core::ptr::read_unaligned(tp) as *mut Thread;
1036        if !p.is_null() && (*p).tid == me {
1037            return Some(&mut *p);
1038        }
1039    }
1040    let main = core::ptr::addr_of_mut!(THREADS[0]);
1041    if (*main).tid == me {
1042        if !tp.is_null() {
1043            core::ptr::write_unaligned(tp, main as usize);
1044        }
1045        return Some(&mut *main);
1046    }
1047    let count = thread_slot_count();
1048    let mut i = 0usize;
1049    while i < count {
1050        let slot = thread_slot_at(i);
1051        if core::ptr::read_volatile(&raw const (*slot).tid) == me {
1052            if !tp.is_null() {
1053                core::ptr::write_unaligned(tp, slot as usize);
1054            }
1055            return Some(&mut *slot);
1056        }
1057        i += 1;
1058    }
1059    register_current_thread()
1060}
1061
1062#[no_mangle]
1063pub unsafe extern "C" fn pthread_self() -> PthreadT {
1064    match find_thread() {
1065        Some(slot) => slot as *mut Thread as PthreadT,
1066        None => 0,
1067    }
1068}
1069
1070#[no_mangle]
1071pub unsafe extern "C" fn pthread_equal(t1: PthreadT, t2: PthreadT) -> c_int {
1072    (t1 == t2) as c_int
1073}
1074
1075unsafe fn dynamic_tls_init(block: *mut u8) -> *mut u8 {
1076    __keel_init_thread_tls_at(block)
1077}
1078
1079unsafe fn dynamic_tls_create() -> *mut u8 {
1080    __keel_create_thread_tls()
1081}
1082
1083/// Prefer carving TLS out of the top of an application-provided stack; a
1084/// separate mapping can land below a MAP_GROWSDOWN stack and block growth.
1085unsafe fn carve_thread_tls(
1086    init_at: unsafe fn(*mut u8) -> *mut u8,
1087    create: unsafe fn() -> *mut u8,
1088    user_top: *mut c_void,
1089    stack_size: usize,
1090    tls_total: usize,
1091    stack_owned: bool,
1092    stack_top: &mut *mut u8,
1093    tls_owned: &mut bool,
1094) -> *mut u8 {
1095    if !stack_owned && tls_total > 0 && stack_size > tls_total + PAGE {
1096        let block = ((user_top as usize - tls_total) & !63usize) as *mut u8;
1097        let fs = init_at(block);
1098        if !fs.is_null() {
1099            *stack_top = block;
1100            *tls_owned = false;
1101            return fs;
1102        }
1103    }
1104    create()
1105}
1106
1107#[no_mangle]
1108pub unsafe extern "C" fn pthread_create(
1109    thread: *mut PthreadT,
1110    attr: *const pthread_attr_t,
1111    start_routine: usize,
1112    arg: *mut c_void,
1113) -> c_int {
1114    if start_routine == 0 || thread.is_null() { return EINVAL; }
1115    let Some(slot_ref) = alloc_thread_slot() else { return EAGAIN; };
1116    let slot = slot_ref as *mut Thread;
1117    let stack_size = if !attr.is_null() {
1118        let s = attr_stack_size(attr);
1119        if s > 0 { s } else { STACK_SIZE }
1120    } else { STACK_SIZE };
1121    // musl stores the stack *top* in pthread_attr_t; zero means "allocate".
1122    let user_top = if !attr.is_null() {
1123        attr_stack_top(attr)
1124    } else {
1125        core::ptr::null_mut()
1126    };
1127    let stack_owned = user_top.is_null();
1128    let stack = if stack_owned {
1129        sys_mmap(null_mut(), stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
1130    } else {
1131        (user_top as *mut u8).sub(stack_size)
1132    };
1133    if stack == MMAP_FAILED { release_thread_slot(slot); return EAGAIN; }
1134    let static_mode = RC_STATIC_EXEC;
1135    let tls_total = if static_mode {
1136        STATIC_TLS_BLOCK_SIZE
1137    } else {
1138        __keel_tls_block_size()
1139    };
1140    let mut stack_top = stack.add(stack_size);
1141    let mut tls_owned = true;
1142    let fs_base = if static_mode {
1143        carve_thread_tls(
1144            static_tls_init_block,
1145            static_tls_create_block,
1146            user_top,
1147            stack_size,
1148            tls_total,
1149            stack_owned,
1150            &mut stack_top,
1151            &mut tls_owned,
1152        )
1153    } else {
1154        carve_thread_tls(
1155            dynamic_tls_init,
1156            dynamic_tls_create,
1157            user_top,
1158            stack_size,
1159            tls_total,
1160            stack_owned,
1161            &mut stack_top,
1162            &mut tls_owned,
1163        )
1164    };
1165    if fs_base.is_null() {
1166        if stack_owned { sys_munmap(stack, stack_size); }
1167        release_thread_slot(slot);
1168        return EAGAIN;
1169    }
1170    let tls_base = if static_mode {
1171        fs_base.sub(STATIC_TLS_TP_OFFSET)
1172    } else {
1173        fs_base.sub(__keel_tls_base_offset())
1174    };
1175    let tls_size = if tls_owned { tls_total } else { 0 };
1176    init_thread_slot(slot, 1);
1177    (*slot).user_fn = start_routine;
1178    (*slot).user_arg = arg;
1179    (*slot).stack = stack;
1180    (*slot).stack_size = stack_size;
1181    (*slot).stack_owned = stack_owned;
1182    (*slot).fs_base = fs_base;
1183    (*slot).tls_base = tls_base;
1184    (*slot).tls_size = tls_size;
1185    let tid_ptr = &raw mut (*slot).tid;
1186    let flags = CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD
1187        | CLONE_SYSVSEM | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_SETTLS;
1188    ACTIVE_THREADS.fetch_add(1, Ordering::AcqRel);
1189    let tid = __keel_clone(thread_entry as *const () as usize, stack_top, flags, slot as *mut c_void, tid_ptr, fs_base as c_ulong, tid_ptr);
1190    if tid < 0 {
1191        ACTIVE_THREADS.fetch_sub(1, Ordering::AcqRel);
1192        (*slot).tid = -1;
1193        if stack_owned { sys_munmap(stack, stack_size); }
1194        if tls_size > 0 { sys_munmap(tls_base, tls_size); }
1195        release_thread_slot(slot);
1196        return EAGAIN;
1197    }
1198    if !attr.is_null() && (*attr).__i[6] == PTHREAD_CREATE_DETACHED {
1199        (*slot).detach_state = DT_DETACHED;
1200    }
1201    *thread = slot as PthreadT;
1202    0
1203}
1204
1205/// Tear down a joined or detached thread slot. The TLS block is kept mapped:
1206/// some runtimes (notably V8) retain pointers into an exited thread's TLS
1207/// and dereference them during process teardown.
1208unsafe fn release_finished_slot(slot: *mut Thread) {
1209    let stack = (*slot).stack;
1210    let stack_size = (*slot).stack_size;
1211    let stack_owned = (*slot).stack_owned;
1212    (*slot).tid = -1;
1213    (*slot).detach_state = DT_JOINABLE;
1214    (*slot).result = core::ptr::null_mut();
1215    (*slot).stack = core::ptr::null_mut();
1216    (*slot).stack_size = 0;
1217    (*slot).stack_owned = false;
1218    (*slot).fs_base = core::ptr::null_mut();
1219    (*slot).tls_base = core::ptr::null_mut();
1220    (*slot).tls_size = 0;
1221    if stack_owned && !stack.is_null() && stack_size > 0 {
1222        sys_munmap(stack, stack_size);
1223    }
1224    release_thread_slot(slot);
1225}
1226
1227#[no_mangle]
1228pub unsafe extern "C" fn pthread_join(thread: PthreadT, retval: *mut *mut c_void) -> c_int {
1229    let slot = thread as *mut Thread;
1230    if slot.is_null() { return EINVAL; }
1231    if thread == pthread_self() { return EDEADLK; }
1232    if (*slot).detach_state == DT_DETACHED { return EINVAL; }
1233    let tid_ptr = &raw mut (*slot).tid;
1234    loop {
1235        pthread_testcancel();
1236        let tid = core::ptr::read_volatile(tid_ptr);
1237        if tid == 0 { break; }
1238        if tid < 0 { return EINVAL; }
1239        sys_futex(tid_ptr, FUTEX_WAIT, tid, null_mut(), null_mut(), 0);
1240        pthread_testcancel();
1241    }
1242    if !retval.is_null() { *retval = (*slot).result; }
1243    release_finished_slot(slot);
1244    0
1245}
1246
1247#[no_mangle]
1248pub unsafe extern "C" fn pthread_detach(thread: PthreadT) -> c_int {
1249    let slot = thread as *mut Thread;
1250    if slot.is_null() { return EINVAL; }
1251    let old = a_cas(&raw mut (*slot).detach_state, DT_JOINABLE, DT_DETACHED);
1252    if old == DT_EXITED {
1253        release_finished_slot(slot);
1254    }
1255    0
1256}
1257
1258#[no_mangle]
1259pub unsafe extern "C" fn pthread_exit(retval: *mut c_void) -> ! {
1260    if let Some(slot) = find_thread() {
1261        thread_finish(slot, retval)
1262    }
1263    sys_exit_thread(0)
1264}
1265
1266// pthread_attr_t stores a usize stack size at __i[0..2], a usize guard at
1267// __i[2..4], the stack top pointer at __i[4..6], and scalar flags after it.
1268unsafe fn attr_stack_size(attr: *const pthread_attr_t) -> usize {
1269    *((*attr).__i.as_ptr() as *const usize)
1270}
1271unsafe fn attr_set_stack_size(attr: *mut pthread_attr_t, sz: usize) {
1272    *((*attr).__i.as_mut_ptr() as *mut usize) = sz;
1273}
1274unsafe fn attr_stack_top(attr: *const pthread_attr_t) -> *mut c_void {
1275    *((*attr).__i.as_ptr().add(4) as *const *mut c_void)
1276}
1277unsafe fn attr_set_stack_top(attr: *mut pthread_attr_t, top: *mut c_void) {
1278    *((*attr).__i.as_mut_ptr().add(4) as *mut *mut c_void) = top;
1279}
1280unsafe fn attr_guard_size(attr: *const pthread_attr_t) -> usize {
1281    *((*attr).__i.as_ptr().add(2) as *const usize)
1282}
1283unsafe fn attr_set_guard_size(attr: *mut pthread_attr_t, sz: usize) {
1284    *((*attr).__i.as_mut_ptr().add(2) as *mut usize) = sz;
1285}
1286
1287// --- pthread_attr_* ---
1288#[no_mangle]
1289pub unsafe extern "C" fn pthread_attr_init(attr: *mut pthread_attr_t) -> c_int {
1290    core::ptr::write_bytes(attr, 0, 1);
1291    attr_set_stack_size(attr, STACK_SIZE);
1292    attr_set_guard_size(attr, PAGE);
1293    (*attr).__i[6] = PTHREAD_CREATE_JOINABLE;
1294    (*attr).__i[7] = PTHREAD_INHERIT_SCHED;
1295    0
1296}
1297#[no_mangle]
1298pub unsafe extern "C" fn pthread_attr_destroy(_attr: *mut pthread_attr_t) -> c_int { 0 }
1299#[no_mangle]
1300pub unsafe extern "C" fn pthread_attr_setdetachstate(attr: *mut pthread_attr_t, s: c_int) -> c_int {
1301    if s != PTHREAD_CREATE_JOINABLE && s != PTHREAD_CREATE_DETACHED { return EINVAL; }
1302    (*attr).__i[6] = s; 0
1303}
1304#[no_mangle]
1305pub unsafe extern "C" fn pthread_attr_getdetachstate(attr: *const pthread_attr_t, s: *mut c_int) -> c_int {
1306    *s = (*attr).__i[6]; 0
1307}
1308#[no_mangle]
1309pub unsafe extern "C" fn pthread_attr_setstacksize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
1310    if sz < 2048 { return EINVAL; }
1311    attr_set_stack_size(attr, sz);
1312    attr_set_stack_top(attr, core::ptr::null_mut());
1313    0
1314}
1315#[no_mangle]
1316pub unsafe extern "C" fn pthread_attr_getstacksize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
1317    *sz = attr_stack_size(attr); 0
1318}
1319#[no_mangle]
1320pub unsafe extern "C" fn pthread_attr_setstack(attr: *mut pthread_attr_t, addr: *mut c_void, sz: usize) -> c_int {
1321    if sz < 2048 { return EINVAL; }
1322    attr_set_stack_size(attr, sz);
1323    // musl stores the top of the stack, not its base.
1324    attr_set_stack_top(attr, (addr as *mut u8).add(sz) as *mut c_void);
1325    0
1326}
1327#[no_mangle]
1328pub unsafe extern "C" fn pthread_attr_getstack(attr: *const pthread_attr_t, addr: *mut *mut c_void, sz: *mut usize) -> c_int {
1329    let size = attr_stack_size(attr);
1330    *sz = size;
1331    let top = attr_stack_top(attr);
1332    *addr = if top.is_null() {
1333        core::ptr::null_mut()
1334    } else {
1335        (top as *mut u8).sub(size) as *mut c_void
1336    };
1337    0
1338}
1339#[no_mangle]
1340pub unsafe extern "C" fn pthread_attr_setguardsize(attr: *mut pthread_attr_t, sz: usize) -> c_int {
1341    attr_set_guard_size(attr, sz); 0
1342}
1343#[no_mangle]
1344pub unsafe extern "C" fn pthread_attr_getguardsize(attr: *const pthread_attr_t, sz: *mut usize) -> c_int {
1345    *sz = attr_guard_size(attr); 0
1346}
1347#[no_mangle]
1348pub unsafe extern "C" fn pthread_attr_setscope(_attr: *mut pthread_attr_t, scope: c_int) -> c_int {
1349    if scope != PTHREAD_SCOPE_SYSTEM { return EINVAL; }
1350    0
1351}
1352#[no_mangle]
1353pub unsafe extern "C" fn pthread_attr_getscope(_attr: *const pthread_attr_t, scope: *mut c_int) -> c_int {
1354    *scope = PTHREAD_SCOPE_SYSTEM; 0
1355}
1356#[no_mangle]
1357pub unsafe extern "C" fn pthread_attr_setinheritsched(attr: *mut pthread_attr_t, inh: c_int) -> c_int {
1358    if inh != PTHREAD_INHERIT_SCHED && inh != PTHREAD_EXPLICIT_SCHED { return EINVAL; }
1359    (*attr).__i[7] = inh; 0
1360}
1361#[no_mangle]
1362pub unsafe extern "C" fn pthread_attr_getinheritsched(attr: *const pthread_attr_t, inh: *mut c_int) -> c_int {
1363    *inh = (*attr).__i[7]; 0
1364}
1365#[no_mangle]
1366pub unsafe extern "C" fn pthread_attr_setschedpolicy(attr: *mut pthread_attr_t, p: c_int) -> c_int {
1367    (*attr).__i[8] = p; 0
1368}
1369#[no_mangle]
1370pub unsafe extern "C" fn pthread_attr_getschedpolicy(attr: *const pthread_attr_t, p: *mut c_int) -> c_int {
1371    *p = (*attr).__i[8]; 0
1372}
1373#[no_mangle]
1374pub unsafe extern "C" fn pthread_attr_setschedparam(attr: *mut pthread_attr_t, param: *const sched_param) -> c_int {
1375    (*attr).__i[9] = (*param).sched_priority; 0
1376}
1377#[no_mangle]
1378pub unsafe extern "C" fn pthread_attr_getschedparam(attr: *const pthread_attr_t, param: *mut sched_param) -> c_int {
1379    (*param).sched_priority = (*attr).__i[9]; 0
1380}
1381
1382// --- pthread_mutexattr_* ---
1383#[no_mangle]
1384pub unsafe extern "C" fn pthread_mutexattr_init(attr: *mut pthread_mutexattr_t) -> c_int {
1385    (*attr).__attr = 0; 0
1386}
1387#[no_mangle]
1388pub unsafe extern "C" fn pthread_mutexattr_destroy(_attr: *mut pthread_mutexattr_t) -> c_int { 0 }
1389#[no_mangle]
1390pub unsafe extern "C" fn pthread_mutexattr_settype(attr: *mut pthread_mutexattr_t, t: c_int) -> c_int {
1391    if (t as c_uint) > 2 { return EINVAL; }
1392    (*attr).__attr = ((*attr).__attr & !3) | t as c_uint; 0
1393}
1394#[no_mangle]
1395pub unsafe extern "C" fn pthread_mutexattr_gettype(attr: *const pthread_mutexattr_t, t: *mut c_int) -> c_int {
1396    *t = ((*attr).__attr & 3) as c_int; 0
1397}
1398#[no_mangle]
1399pub unsafe extern "C" fn pthread_mutexattr_setpshared(attr: *mut pthread_mutexattr_t, p: c_int) -> c_int {
1400    if (p as c_uint) > 1 { return EINVAL; }
1401    (*attr).__attr = ((*attr).__attr & !(MUTEX_PSHARED as c_uint)) | ((p as c_uint) << 7); 0
1402}
1403#[no_mangle]
1404pub unsafe extern "C" fn pthread_mutexattr_getpshared(attr: *const pthread_mutexattr_t, p: *mut c_int) -> c_int {
1405    *p = (((*attr).__attr >> 7) & 1) as c_int; 0
1406}
1407
1408#[no_mangle]
1409pub unsafe extern "C" fn pthread_mutexattr_setprotocol(attr: *mut pthread_mutexattr_t, protocol: c_int) -> c_int {
1410    match protocol {
1411        0 => { (*attr).__attr &= !(MUTEX_PI as c_uint); 0 }
1412        1 => {
1413            let mut lk: c_int = 0;
1414            let r = sys_futex(&raw mut lk, FUTEX_LOCK_PI, 0, null_mut(), null_mut(), 0);
1415            if r < 0 { return (-r) as c_int; }
1416            sys_futex(&raw mut lk, FUTEX_UNLOCK_PI, 0, null_mut(), null_mut(), 0);
1417            (*attr).__attr |= MUTEX_PI as c_uint;
1418            0
1419        }
1420        2 => ENOTSUP,
1421        _ => EINVAL,
1422    }
1423}
1424#[no_mangle]
1425pub unsafe extern "C" fn pthread_mutexattr_getprotocol(attr: *const pthread_mutexattr_t, protocol: *mut c_int) -> c_int {
1426    *protocol = (((*attr).__attr >> 3) & 3) as c_int; 0
1427}
1428
1429
1430#[no_mangle]
1431pub unsafe extern "C" fn pthread_mutexattr_setrobust(attr: *mut pthread_mutexattr_t, robust: c_int) -> c_int {
1432    if (robust as c_uint) > 1 { return EINVAL; }
1433    if robust != 0 {
1434        (*attr).__attr |= MUTEX_ROBUST as c_uint;
1435    } else {
1436        (*attr).__attr &= !(MUTEX_ROBUST as c_uint);
1437    }
1438    0
1439}
1440#[no_mangle]
1441pub unsafe extern "C" fn pthread_mutexattr_getrobust(attr: *const pthread_mutexattr_t, robust: *mut c_int) -> c_int {
1442    *robust = (((*attr).__attr >> 2) & 1) as c_int; 0
1443}
1444
1445#[no_mangle]
1446pub unsafe extern "C" fn pthread_mutex_consistent(m: *mut pthread_mutex_t) -> c_int {
1447    let old = a_load(&raw const (*m).__i[1]);
1448    let own = old & MUTEX_OWNER_MASK;
1449    if ((*m).__i[0] & MUTEX_ROBUST) == 0 || own == 0 || (old & MUTEX_ROBUST_PENDING) == 0 {
1450        return EINVAL;
1451    }
1452    let self_tid = sys_gettid() as c_int;
1453    if own != self_tid { return EPERM; }
1454    a_and(&raw mut (*m).__i[1], !(MUTEX_ROBUST_PENDING));
1455    0
1456}
1457
1458unsafe fn a_and(addr: *mut c_int, val: c_int) {
1459    let a = &*(addr as *const AtomicI32);
1460    a.fetch_and(val, Ordering::AcqRel);
1461}
1462
1463// --- pthread_mutex_* ---
1464const MUTEX_TYPE_MASK: c_int = 3;
1465const MUTEX_ROBUST: c_int = 4;
1466const MUTEX_PI: c_int = 8;
1467const MUTEX_PSHARED: c_int = 128;
1468const MUTEX_OWNER_MASK: c_int = 0x3fff_ffff;
1469const MUTEX_ROBUST_PENDING: c_int = 0x4000_0000;
1470const FUTEX_WAITER_BIT: c_int = 1i32 << 31;
1471
1472unsafe fn ensure_robust_list(slot: &mut Thread) {
1473    if slot.robust_list.futex_offset == 0 {
1474        slot.robust_list.futex_offset = -28;
1475        slot.robust_list.pending = core::ptr::null_mut();
1476        sys_set_robust_list(&mut slot.robust_list, 24);
1477    }
1478}
1479
1480unsafe fn mutex_trylock(m: *mut pthread_mutex_t) -> c_int {
1481    let type_ = (*m).__i[0];
1482    // Fast path: plain NORMAL only (no PI, no robust, no pshared).
1483    // A failed CAS must report EBUSY unconditionally: the old value may be
1484    // the waiter bit (0x80000000), whose low bits are zero, and masking it
1485    // with EBUSY would falsely report that the lock was acquired.
1486    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL {
1487        let old = a_cas(&raw mut (*m).__i[1], 0, EBUSY);
1488        return if old == 0 { 0 } else { EBUSY };
1489    }
1490    let base_type = type_ & MUTEX_TYPE_MASK;
1491    let self_tid = sys_gettid() as c_int;
1492    let old = a_load(&raw const (*m).__i[1]);
1493    let own = old & MUTEX_OWNER_MASK;
1494    if own == self_tid {
1495        if (type_ & MUTEX_PI) != 0 && (*m).__i[5] < 0 {
1496            (*m).__i[5] = 0;
1497            return 0;
1498        }
1499        if base_type == PTHREAD_MUTEX_RECURSIVE {
1500            if (*m).__i[5] >= c_int::MAX { return EAGAIN; }
1501            (*m).__i[5] += 1;
1502            return 0;
1503        }
1504        if base_type == PTHREAD_MUTEX_ERRORCHECK { return EDEADLK; }
1505        return EBUSY;
1506    }
1507    if own == MUTEX_OWNER_MASK { return ENOTRECOVERABLE; }
1508    if own != 0 || (old != 0 && (type_ & MUTEX_ROBUST) == 0) { return EBUSY; }
1509    let mut newtid = self_tid;
1510    if (type_ & MUTEX_ROBUST) != 0 {
1511        if (*m).__i[2] != 0 { newtid |= FUTEX_WAITER_BIT; }
1512        newtid |= old & MUTEX_ROBUST_PENDING;
1513    }
1514    if a_cas(&raw mut (*m).__i[1], old, newtid) == old {
1515        (*m).__i[5] = 0;
1516        if (type_ & MUTEX_ROBUST) != 0 {
1517            if let Some(slot) = find_thread() {
1518                ensure_robust_list(slot);
1519                let m_next = &raw mut (*m).__i[8] as *mut robust_list;
1520                let head = &mut slot.robust_list.list;
1521                (*m_next).next = head.next;
1522                head.next = m_next;
1523            }
1524        }
1525        if old != 0 { return EOWNERDEAD; }
1526        0
1527    } else { EBUSY }
1528}
1529
1530unsafe fn mutex_lock_internal(m: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
1531    let type_ = (*m).__i[0];
1532    if (type_ & 0x8f) == PTHREAD_MUTEX_NORMAL && a_cas(&raw mut (*m).__i[1], 0, EBUSY) == 0 {
1533        return 0;
1534    }
1535    let r = mutex_trylock(m);
1536    if r != EBUSY { return r; }
1537    if (type_ & MUTEX_PI) != 0 {
1538        let timeout_ptr = if abs_timeout.is_null() { core::ptr::null() } else { abs_timeout };
1539        loop {
1540            let e = futex_lock_pi(&raw mut (*m).__i[1], timeout_ptr);
1541            match e {
1542                0 => {
1543                    if (type_ & MUTEX_ROBUST) != 0 && (((*m).__i[1] & MUTEX_ROBUST_PENDING) != 0 || (*m).__i[2] != 0) {
1544                        (*m).__i[5] = -1;
1545                        let _ = mutex_trylock(m);
1546                        return EOWNERDEAD;
1547                    }
1548                    if (type_ & MUTEX_ROBUST) == 0 && (((*m).__i[1] & MUTEX_ROBUST_PENDING) != 0 || (*m).__i[2] != 0) {
1549                        (*m).__i[2] = -1;
1550                        futex_unlock_pi(&raw mut (*m).__i[1]);
1551                        return EBUSY;
1552                    }
1553                    (*m).__i[5] = -1;
1554                    let r2 = mutex_trylock(m);
1555                    if r2 == 0 { return 0; }
1556                    return r2;
1557                }
1558                EINTR => continue,
1559                EDEADLK => {
1560                    if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK { return e; }
1561                    loop { pause(); }
1562                }
1563                EOWNERDEAD => {
1564                    (*m).__i[5] = -1;
1565                    let _ = mutex_trylock(m);
1566                    return EOWNERDEAD;
1567                }
1568                _ => return e,
1569            }
1570        }
1571    }
1572    let mut spins = 100;
1573    while spins > 0 {
1574        let r = mutex_trylock(m);
1575        if r != EBUSY { return r; }
1576        core::hint::spin_loop();
1577        spins -= 1;
1578    }
1579    loop {
1580        let r = mutex_trylock(m);
1581        if r != EBUSY { return r; }
1582        if (type_ & MUTEX_TYPE_MASK) == PTHREAD_MUTEX_ERRORCHECK {
1583            let self_tid = sys_gettid() as c_int;
1584            if (a_load(&raw const (*m).__i[1]) & MUTEX_OWNER_MASK) == self_tid { return EDEADLK; }
1585        }
1586        a_fetch_add(&raw mut (*m).__i[2], 1);
1587        let val = a_load(&raw const (*m).__i[1]);
1588        // If the previous owner released the lock between trylock() and the
1589        // load above, retry instead of publishing a waiter-only lock word
1590        // (0x80000000) that no thread owns.
1591        if val == 0 {
1592            a_fetch_sub(&raw mut (*m).__i[2], 1);
1593            continue;
1594        }
1595        a_cas(&raw mut (*m).__i[1], val, val | FUTEX_WAITER_BIT);
1596        let e = futex_timedwait(&raw mut (*m).__i[1], val | FUTEX_WAITER_BIT, abs_timeout);
1597        a_fetch_sub(&raw mut (*m).__i[2], 1);
1598        if e != 0 && e != EINTR { return e; }
1599    }
1600}
1601
1602#[no_mangle]
1603pub unsafe extern "C" fn pthread_mutex_init(mutex: *mut pthread_mutex_t, attr: *const pthread_mutexattr_t) -> c_int {
1604    core::ptr::write_bytes(mutex, 0, 1);
1605    if !attr.is_null() { (*mutex).__i[0] = (*attr).__attr as c_int; }
1606    0
1607}
1608#[no_mangle]
1609pub unsafe extern "C" fn pthread_mutex_destroy(_mutex: *mut pthread_mutex_t) -> c_int { 0 }
1610#[no_mangle]
1611pub unsafe extern "C" fn pthread_mutex_lock(mutex: *mut pthread_mutex_t) -> c_int {
1612    mutex_lock_internal(mutex, core::ptr::null())
1613}
1614#[no_mangle]
1615pub unsafe extern "C" fn pthread_mutex_trylock(mutex: *mut pthread_mutex_t) -> c_int {
1616    mutex_trylock(mutex)
1617}
1618#[no_mangle]
1619pub unsafe extern "C" fn pthread_mutex_timedlock(mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
1620    mutex_lock_internal(mutex, abs_timeout)
1621}
1622#[no_mangle]
1623pub unsafe extern "C" fn pthread_mutex_unlock(mutex: *mut pthread_mutex_t) -> c_int {
1624    let type_ = (*mutex).__i[0];
1625    let base_type = type_ & MUTEX_TYPE_MASK;
1626    let old = a_load(&raw const (*mutex).__i[1]);
1627    if base_type != PTHREAD_MUTEX_NORMAL {
1628        let self_tid = sys_gettid() as c_int;
1629        if (old & MUTEX_OWNER_MASK) != self_tid { return EPERM; }
1630        if base_type == PTHREAD_MUTEX_RECURSIVE && (*mutex).__i[5] > 0 {
1631            (*mutex).__i[5] -= 1;
1632            return 0;
1633        }
1634    }
1635    let mut new = 0;
1636    if (type_ & MUTEX_ROBUST) != 0 && (old & MUTEX_ROBUST_PENDING) != 0 {
1637        new = 0x7fffffff;
1638    }
1639    if (type_ & MUTEX_PI) != 0 {
1640        if old < 0 || a_cas(&raw mut (*mutex).__i[1], old, new) != old {
1641            if new != 0 { a_store(&raw mut (*mutex).__i[2], -1); }
1642            return futex_unlock_pi(&raw mut (*mutex).__i[1]);
1643        }
1644        return 0;
1645    }
1646    a_store(&raw mut (*mutex).__i[1], new);
1647    if new == 0 && (a_load(&raw const (*mutex).__i[2]) > 0 || old < 0) {
1648        futex_wake(&raw mut (*mutex).__i[1], 1);
1649    }
1650    0
1651}
1652
1653// --- pthread_condattr_* ---
1654#[no_mangle]
1655pub unsafe extern "C" fn pthread_condattr_init(attr: *mut pthread_condattr_t) -> c_int {
1656    (*attr).__attr = 0; 0
1657}
1658#[no_mangle]
1659pub unsafe extern "C" fn pthread_condattr_destroy(_attr: *mut pthread_condattr_t) -> c_int { 0 }
1660#[no_mangle]
1661pub unsafe extern "C" fn pthread_condattr_setclock(attr: *mut pthread_condattr_t, clk: c_int) -> c_int {
1662    if clk != CLOCK_REALTIME && clk != CLOCK_MONOTONIC { return EINVAL; }
1663    (*attr).__attr = ((*attr).__attr & 0x80000000) | clk as c_uint; 0
1664}
1665#[no_mangle]
1666pub unsafe extern "C" fn pthread_condattr_getclock(attr: *const pthread_condattr_t, clk: *mut c_int) -> c_int {
1667    *clk = ((*attr).__attr & 0x7fffffff) as c_int; 0
1668}
1669#[no_mangle]
1670pub unsafe extern "C" fn pthread_condattr_setpshared(attr: *mut pthread_condattr_t, p: c_int) -> c_int {
1671    if (p as c_uint) > 1 { return EINVAL; }
1672    (*attr).__attr = ((*attr).__attr & 0x7fffffff) | ((p as c_uint) << 31); 0
1673}
1674#[no_mangle]
1675pub unsafe extern "C" fn pthread_condattr_getpshared(attr: *const pthread_condattr_t, p: *mut c_int) -> c_int {
1676    *p = ((*attr).__attr >> 31) as c_int; 0
1677}
1678
1679// --- pthread_cond_* ---
1680#[no_mangle]
1681pub unsafe extern "C" fn pthread_cond_init(cond: *mut pthread_cond_t, attr: *const pthread_condattr_t) -> c_int {
1682    core::ptr::write_bytes(cond, 0, 1);
1683    if !attr.is_null() {
1684        (*cond).__i[4] = ((*attr).__attr & 0x7fffffff) as c_int;
1685    }
1686    0
1687}
1688#[no_mangle]
1689pub unsafe extern "C" fn pthread_cond_destroy(_cond: *mut pthread_cond_t) -> c_int { 0 }
1690#[no_mangle]
1691pub unsafe extern "C" fn pthread_cond_wait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t) -> c_int {
1692    pthread_cond_timedwait(cond, mutex, core::ptr::null())
1693}
1694
1695
1696#[no_mangle]
1697pub unsafe extern "C" fn pthread_cond_timedwait(cond: *mut pthread_cond_t, mutex: *mut pthread_mutex_t, abs_timeout: *const timespec) -> c_int {
1698    pthread_testcancel();
1699    let seq_ptr = &raw mut (*cond).__i[2];
1700    let waiters_ptr = &raw mut (*cond).__i[3];
1701    let seq = a_load(seq_ptr);
1702    a_fetch_add(waiters_ptr, 1);
1703    pthread_mutex_unlock(mutex);
1704    let e = futex_timedwait(seq_ptr, seq, abs_timeout);
1705    a_fetch_sub(waiters_ptr, 1);
1706    let r = pthread_mutex_lock(mutex);
1707    if r != 0 { return r; }
1708    if e == EINTR {
1709        pthread_testcancel();
1710    }
1711    if e != 0 && e != EINTR { return e; }
1712    0
1713}
1714#[no_mangle]
1715pub unsafe extern "C" fn pthread_cond_signal(cond: *mut pthread_cond_t) -> c_int {
1716    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
1717    a_fetch_add(&raw mut (*cond).__i[2], 1);
1718    futex_wake(&raw mut (*cond).__i[2], 1);
1719    0
1720}
1721#[no_mangle]
1722pub unsafe extern "C" fn pthread_cond_broadcast(cond: *mut pthread_cond_t) -> c_int {
1723    if a_load(&raw const (*cond).__i[3]) == 0 { return 0; }
1724    a_fetch_add(&raw mut (*cond).__i[2], 1);
1725    futex_wake(&raw mut (*cond).__i[2], -1);
1726    0
1727}
1728
1729// --- pthread_rwlockattr_* ---
1730#[no_mangle]
1731pub unsafe extern "C" fn pthread_rwlockattr_init(attr: *mut pthread_rwlockattr_t) -> c_int {
1732    (*attr).__attr = [0; 2]; 0
1733}
1734#[no_mangle]
1735pub unsafe extern "C" fn pthread_rwlockattr_destroy(_attr: *mut pthread_rwlockattr_t) -> c_int { 0 }
1736#[no_mangle]
1737pub unsafe extern "C" fn pthread_rwlockattr_setpshared(attr: *mut pthread_rwlockattr_t, p: c_int) -> c_int {
1738    if (p as c_uint) > 1 { return EINVAL; }
1739    (*attr).__attr[0] = ((*attr).__attr[0] & !128) | ((p as c_uint) << 7); 0
1740}
1741#[no_mangle]
1742pub unsafe extern "C" fn pthread_rwlockattr_getpshared(attr: *const pthread_rwlockattr_t, p: *mut c_int) -> c_int {
1743    *p = (((*attr).__attr[0] >> 7) & 1) as c_int; 0
1744}
1745
1746// --- pthread_rwlock_* ---
1747unsafe fn rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int {
1748    loop {
1749        let val = a_load(&raw const (*rw).__i[0]);
1750        let cnt = val & 0x7fffffff;
1751        if cnt == 0x7fffffff { return EBUSY; }
1752        if cnt == 0x7ffffffe { return EAGAIN; }
1753        if a_cas(&raw mut (*rw).__i[0], val, val + 1) == val { return 0; }
1754    }
1755}
1756unsafe fn rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int {
1757    if a_cas(&raw mut (*rw).__i[0], 0, 0x7fffffff) == 0 { 0 } else { EBUSY }
1758}
1759unsafe fn rwlock_timedrdlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
1760    let r = rwlock_tryrdlock(rw);
1761    if r != EBUSY { return r; }
1762    let mut spins = 100;
1763    while spins > 0 { let r = rwlock_tryrdlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
1764    loop {
1765        let r = rwlock_tryrdlock(rw);
1766        if r != EBUSY { return r; }
1767        let val = a_load(&raw const (*rw).__i[0]);
1768        if val & 0x7fffffff != 0x7fffffff { continue; }
1769        a_fetch_add(&raw mut (*rw).__i[1], 1);
1770        a_cas(&raw mut (*rw).__i[0], val, val | FUTEX_WAITER_BIT);
1771        let e = futex_timedwait(&raw mut (*rw).__i[0], val | FUTEX_WAITER_BIT, abs_timeout);
1772        a_fetch_sub(&raw mut (*rw).__i[1], 1);
1773        if e != 0 && e != EINTR { return e; }
1774    }
1775}
1776unsafe fn rwlock_timedwrlock(rw: *mut pthread_rwlock_t, abs_timeout: *const timespec) -> c_int {
1777    let r = rwlock_trywrlock(rw);
1778    if r != EBUSY { return r; }
1779    let mut spins = 100;
1780    while spins > 0 { let r = rwlock_trywrlock(rw); if r != EBUSY { return r; } core::hint::spin_loop(); spins -= 1; }
1781    loop {
1782        let r = rwlock_trywrlock(rw);
1783        if r != EBUSY { return r; }
1784        let val = a_load(&raw const (*rw).__i[0]);
1785        if val == 0 { continue; }
1786        a_fetch_add(&raw mut (*rw).__i[1], 1);
1787        a_cas(&raw mut (*rw).__i[0], val, val | FUTEX_WAITER_BIT);
1788        let e = futex_timedwait(&raw mut (*rw).__i[0], val | FUTEX_WAITER_BIT, abs_timeout);
1789        a_fetch_sub(&raw mut (*rw).__i[1], 1);
1790        if e != 0 && e != EINTR { return e; }
1791    }
1792}
1793
1794#[no_mangle]
1795pub unsafe extern "C" fn pthread_rwlock_init(rw: *mut pthread_rwlock_t, attr: *const pthread_rwlockattr_t) -> c_int {
1796    core::ptr::write_bytes(rw, 0, 1);
1797    if !attr.is_null() { (*rw).__i[2] = (*attr).__attr[0] as c_int & 128; }
1798    0
1799}
1800#[no_mangle]
1801pub unsafe extern "C" fn pthread_rwlock_destroy(_rw: *mut pthread_rwlock_t) -> c_int { 0 }
1802#[no_mangle]
1803pub unsafe extern "C" fn pthread_rwlock_rdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedrdlock(rw, core::ptr::null()) }
1804#[no_mangle]
1805pub unsafe extern "C" fn pthread_rwlock_tryrdlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_tryrdlock(rw) }
1806#[no_mangle]
1807pub unsafe extern "C" fn pthread_rwlock_timedrdlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedrdlock(rw, t) }
1808#[no_mangle]
1809pub unsafe extern "C" fn pthread_rwlock_wrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_timedwrlock(rw, core::ptr::null()) }
1810#[no_mangle]
1811pub unsafe extern "C" fn pthread_rwlock_trywrlock(rw: *mut pthread_rwlock_t) -> c_int { rwlock_trywrlock(rw) }
1812#[no_mangle]
1813pub unsafe extern "C" fn pthread_rwlock_timedwrlock(rw: *mut pthread_rwlock_t, t: *const timespec) -> c_int { rwlock_timedwrlock(rw, t) }
1814#[no_mangle]
1815pub unsafe extern "C" fn pthread_rwlock_unlock(rw: *mut pthread_rwlock_t) -> c_int {
1816    loop {
1817        let val = a_load(&raw const (*rw).__i[0]);
1818        let cnt = val & 0x7fffffff;
1819        let new_val = if cnt == 0x7fffffff || cnt == 1 { 0 } else { val - 1 };
1820        if a_cas(&raw mut (*rw).__i[0], val, new_val) == val {
1821            if new_val == 0 && (a_load(&raw const (*rw).__i[1]) > 0 || val < 0) {
1822                futex_wake(&raw mut (*rw).__i[0], cnt);
1823            }
1824            return 0;
1825        }
1826    }
1827}
1828
1829// --- pthread_barrierattr_* ---
1830#[no_mangle]
1831pub unsafe extern "C" fn pthread_barrierattr_init(attr: *mut pthread_barrierattr_t) -> c_int { (*attr).__attr = 0; 0 }
1832#[no_mangle]
1833pub unsafe extern "C" fn pthread_barrierattr_destroy(_attr: *mut pthread_barrierattr_t) -> c_int { 0 }
1834#[no_mangle]
1835pub unsafe extern "C" fn pthread_barrierattr_setpshared(attr: *mut pthread_barrierattr_t, p: c_int) -> c_int {
1836    if (p as c_uint) > 1 { return EINVAL; }
1837    (*attr).__attr = p as c_uint; 0
1838}
1839#[no_mangle]
1840pub unsafe extern "C" fn pthread_barrierattr_getpshared(attr: *const pthread_barrierattr_t, p: *mut c_int) -> c_int {
1841    *p = (*attr).__attr as c_int; 0
1842}
1843
1844// --- pthread_barrier_* ---
1845#[no_mangle]
1846pub unsafe extern "C" fn pthread_barrier_init(b: *mut pthread_barrier_t, _attr: *const pthread_barrierattr_t, count: c_uint) -> c_int {
1847    if count == 0 { return EINVAL; }
1848    core::ptr::write_bytes(b, 0, 1);
1849    (*b).__i[2] = count as c_int - 1;
1850    0
1851}
1852#[no_mangle]
1853pub unsafe extern "C" fn pthread_barrier_destroy(_b: *mut pthread_barrier_t) -> c_int { 0 }
1854#[no_mangle]
1855pub unsafe extern "C" fn pthread_barrier_wait(b: *mut pthread_barrier_t) -> c_int {
1856    let limit = (*b).__i[2];
1857    if limit == 0 { return PTHREAD_BARRIER_SERIAL_THREAD; }
1858    spinlock_lock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
1859    let arrived = a_load(&raw const (*b).__i[3]) + 1;
1860    a_store(&raw mut (*b).__i[3], arrived);
1861    if arrived > limit {
1862        a_store(&raw mut (*b).__i[3], 0);
1863        let gen = a_load(&raw const (*b).__i[4]);
1864        a_store(&raw mut (*b).__i[4], gen + 1);
1865        spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
1866        futex_wake(&raw mut (*b).__i[4], -1);
1867        return PTHREAD_BARRIER_SERIAL_THREAD;
1868    }
1869    let gen = a_load(&raw const (*b).__i[4]);
1870    spinlock_unlock(&raw mut (*b).__i[0], &raw mut (*b).__i[1]);
1871    while a_load(&raw const (*b).__i[4]) == gen {
1872        futex_wait(&raw mut (*b).__i[4], gen);
1873    }
1874    0
1875}
1876
1877// --- pthread_spin_* ---
1878#[no_mangle]
1879pub unsafe extern "C" fn pthread_spin_init(s: *mut pthread_spinlock_t, _pshared: c_int) -> c_int { a_store(s, 0); 0 }
1880#[no_mangle]
1881pub unsafe extern "C" fn pthread_spin_destroy(_s: *mut pthread_spinlock_t) -> c_int { 0 }
1882#[no_mangle]
1883pub unsafe extern "C" fn pthread_spin_lock(s: *mut pthread_spinlock_t) -> c_int {
1884    while a_load(s) != 0 || a_cas(s, 0, EBUSY) != 0 { core::hint::spin_loop(); }
1885    0
1886}
1887#[no_mangle]
1888pub unsafe extern "C" fn pthread_spin_trylock(s: *mut pthread_spinlock_t) -> c_int { a_cas(s, 0, EBUSY) }
1889#[no_mangle]
1890pub unsafe extern "C" fn pthread_spin_unlock(s: *mut pthread_spinlock_t) -> c_int { a_store(s, 0); 0 }
1891
1892// --- sem_* ---
1893#[no_mangle]
1894pub unsafe extern "C" fn sem_init(sem: *mut sem_t, pshared: c_int, value: c_uint) -> c_int {
1895    if value > SEM_VALUE_MAX as c_uint { return EINVAL; }
1896    (*sem).__val[0] = value as c_int;
1897    (*sem).__val[1] = 0;
1898    (*sem).__val[2] = if pshared != 0 { 0 } else { 128 };
1899    0
1900}
1901#[no_mangle]
1902pub unsafe extern "C" fn sem_destroy(_sem: *mut sem_t) -> c_int { 0 }
1903
1904unsafe fn sem_trywait_internal(sem: *mut sem_t) -> c_int {
1905    loop {
1906        let val = a_load(&raw const (*sem).__val[0]);
1907        if val & SEM_VALUE_MAX == 0 { return EAGAIN; }
1908        if a_cas(&raw mut (*sem).__val[0], val, val - 1) == val { return 0; }
1909    }
1910}
1911
1912#[no_mangle]
1913pub unsafe extern "C" fn sem_trywait(sem: *mut sem_t) -> c_int {
1914    if sem_trywait_internal(sem) == 0 { 0 } else { ERRNO!() = EAGAIN; -1 }
1915}
1916unsafe fn sem_wait_common(sem: *mut sem_t, abs_timeout: *const timespec) -> c_int {
1917    pthread_testcancel();
1918    if sem_trywait_internal(sem) == 0 { return 0; }
1919    let mut spins = 100;
1920    while spins > 0 {
1921        if sem_trywait_internal(sem) == 0 { return 0; }
1922        core::hint::spin_loop();
1923        spins -= 1;
1924    }
1925    loop {
1926        pthread_testcancel();
1927        if sem_trywait_internal(sem) == 0 { return 0; }
1928        let val = a_load(&raw const (*sem).__val[0]);
1929        if val & SEM_VALUE_MAX != 0 { continue; }
1930        a_cas(&raw mut (*sem).__val[0], val, val | FUTEX_WAITER_BIT);
1931        a_fetch_add(&raw mut (*sem).__val[1], 1);
1932        let e = if abs_timeout.is_null() {
1933            futex_wait(&raw mut (*sem).__val[0], FUTEX_WAITER_BIT);
1934            0
1935        } else {
1936            futex_timedwait(&raw mut (*sem).__val[0], FUTEX_WAITER_BIT, abs_timeout)
1937        };
1938        a_fetch_sub(&raw mut (*sem).__val[1], 1);
1939        if e != 0 && e != EINTR { ERRNO!() = e; return -1; }
1940    }
1941}
1942
1943#[no_mangle]
1944pub unsafe extern "C" fn sem_wait(sem: *mut sem_t) -> c_int {
1945    sem_wait_common(sem, core::ptr::null())
1946}
1947
1948#[no_mangle]
1949pub unsafe extern "C" fn sem_timedwait(sem: *mut sem_t, abs_timeout: *const timespec) -> c_int {
1950    sem_wait_common(sem, abs_timeout)
1951}
1952
1953#[no_mangle]
1954pub unsafe extern "C" fn sem_post(sem: *mut sem_t) -> c_int {
1955    loop {
1956        let val = a_load(&raw const (*sem).__val[0]);
1957        if (val & SEM_VALUE_MAX) == SEM_VALUE_MAX { ERRNO!() = EOVERFLOW; return -1; }
1958        let mut new = val + 1;
1959        let waiters = a_load(&raw const (*sem).__val[1]);
1960        if waiters <= 1 { new &= !FUTEX_WAITER_BIT; }
1961        if a_cas(&raw mut (*sem).__val[0], val, new) == val {
1962            if val < 0 || waiters > 0 {
1963                futex_wake(&raw mut (*sem).__val[0], if waiters > 1 { 1 } else { -1 });
1964            }
1965            return 0;
1966        }
1967    }
1968}
1969#[no_mangle]
1970pub unsafe extern "C" fn sem_getvalue(sem: *mut sem_t, sval: *mut c_int) -> c_int {
1971    *sval = a_load(&raw const (*sem).__val[0]) & SEM_VALUE_MAX;
1972    0
1973}
1974