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