Skip to content

Commit

Permalink
Make futexes 100x better on x86 MacOS
Browse files Browse the repository at this point in the history
Thanks to @autumnjolitz (in #876) the Cosmopolitan codebase is now
acquainted with Apple's outstanding ulock system calls which offer
something much closer to futexes than Grand Central Dispatch which
wasn't quite as good, since its wait function can't be interrupted
by signals (therefore necessitating a busy loop) and it also needs
semaphore objects to be created and freed. Even though ulock is an
internal Apple API, strictly speaking, the benefits of futexes are
so great that it's worth the risk for now especially since we have
the GCD implementation still as a quick escape hatch if it changes

Here's why this change is important for x86 XNU users. Cosmo has a
suboptimal polyfill when the operating system doesn't offer an API
that let's us implement futexes properly. Sadly we had to use that
on X86 XNU until now. The polyfill works using clock_nanosleep, to
poll the futex in a busy loop with exponential backoff. On XNU x86
clock_nanosleep suffers from us not being able to use a fast clock
gettime implementation, which had a compounding effect that's made
the polyfill function even more poorly. On X86 XNU we also need to
polyfill sched_yield() using select(), which made things even more
troublesome. Now that we have futexes we don't have any busy loops
anymore for both condition variables and thread joining so optimal
performance is attained. To demonstrate, consider these benchmarks

Before:

    $ ./lockscale_test.com -b
    consumed 38.8377   seconds real time and
              0.087131 seconds cpu time

After:

    $ ./lockscale_test.com -b
    consumed 0.007955 seconds real time and
             0.011515 seconds cpu time

Fixes #876
  • Loading branch information
jart committed Oct 3, 2023
1 parent ff250a0 commit 85f64f3
Show file tree
Hide file tree
Showing 21 changed files with 267 additions and 34 deletions.
2 changes: 2 additions & 0 deletions libc/calls/syscall_support-sysv.internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ long __syscall2(long, long, int);
int __syscall2i(long, long, int) asm("__syscall2");
long __syscall3(long, long, long, int);
int __syscall3i(long, long, long, int) asm("__syscall3");
long __syscall4(long, long, long, long, int);
int __syscall4i(long, long, long, long, int) asm("__syscall4");

bool __is_linux_2_6_23(void);
bool32 sys_isatty_metal(int);
Expand Down
52 changes: 38 additions & 14 deletions libc/intrin/kprintf.greg.c
Original file line number Diff line number Diff line change
Expand Up @@ -568,25 +568,37 @@ privileged static size_t kformat(char *b, size_t n, const char *fmt,
goto FormatUnsigned;

case 'P':
if (!(tib && (tib->tib_flags & TIB_FLAG_VFORKED))) {
x = __pid;
#ifdef __x86_64__
} else if (IsLinux()) {
asm volatile("syscall"
: "=a"(x)
: "0"(__NR_getpid)
: "rcx", "rdx", "r11", "memory");
#endif
} else {
x = 666;
}
if (!__nocolor && p + 7 <= e) {
*p++ = '\e';
*p++ = '[';
*p++ = '1';
*p++ = ';';
*p++ = '3';
*p++ = '0' + x % 8;
*p++ = 'm';
ansi = 1;
}
goto FormatDecimal;

case 'H':
if (!(tib && (tib->tib_flags & TIB_FLAG_VFORKED))) {
if (tib) {
x = atomic_load_explicit(&tib->tib_tid, memory_order_relaxed);
if (IsNetbsd() && x == 1) {
x = __pid;
}
} else {
x = __pid;
}
if (!__nocolor && p + 7 <= e) {
*p++ = '\e';
*p++ = '[';
*p++ = '1';
*p++ = ';';
*p++ = '3';
*p++ = '0' + x % 8;
*p++ = 'm';
ansi = 1;
}
#ifdef __x86_64__
} else if (IsLinux()) {
asm volatile("syscall"
Expand All @@ -597,6 +609,17 @@ privileged static size_t kformat(char *b, size_t n, const char *fmt,
} else {
x = 666;
}
if (!__nocolor && p + 7 <= e) {
// xnu thread ids are always divisible by 8
*p++ = '\e';
*p++ = '[';
*p++ = '1';
*p++ = ';';
*p++ = '3';
*p++ = '0' + x % 7;
*p++ = 'm';
ansi = 1;
}
goto FormatDecimal;

case 'u':
Expand Down Expand Up @@ -1080,7 +1103,8 @@ privileged void kvprintf(const char *fmt, va_list v) {
* - `X` uppercase
* - `T` timestamp
* - `x` hexadecimal
* - `P` PID (or TID if TLS is enabled)
* - `P` process id
* - `H` thread id
*
* Types:
*
Expand Down
4 changes: 2 additions & 2 deletions libc/intrin/strace.internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
#include "libc/intrin/likely.h"
#include "libc/runtime/runtime.h"

#define _NTTRACE 1 /* not configurable w/ flag yet */
#define _NTTRACE 0 /* not configurable w/ flag yet */
#define _POLLTRACE 0 /* not configurable w/ flag yet */
#define _DATATRACE 1 /* not configurable w/ flag yet */
#define _LOCKTRACE 0 /* not configurable w/ flag yet */
#define _STDIOTRACE 0 /* not configurable w/ flag yet */
#define _KERNTRACE 0 /* not configurable w/ flag yet */
#define _TIMETRACE 0 /* not configurable w/ flag yet */

#define STRACE_PROLOGUE "%rSYS %6P %'18T "
#define STRACE_PROLOGUE "%rSYS %6P %6H %'18T "

#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_
Expand Down
54 changes: 54 additions & 0 deletions libc/intrin/ulock.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
│vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2023 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/intrin/ulock.h"
#include "libc/assert.h"
#include "libc/calls/calls.h"
#include "libc/calls/syscall_support-sysv.internal.h"
#include "libc/dce.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"

// XNU futexes
// https://opensource.apple.com/source/xnu/xnu-7195.50.7.100.1/bsd/sys/ulock.h.auto.html
// https://opensource.apple.com/source/xnu/xnu-3789.41.3/bsd/kern/sys_ulock.c.auto.html

int sys_ulock_wait(uint32_t operation, void *addr, uint64_t value,
uint32_t timeout_micros) asm("sys_futex_cp");

// returns -1 w/ errno
int ulock_wait(uint32_t operation, void *addr, uint64_t value,
uint32_t timeout_micros) {
int rc;
operation |= ULF_WAIT_CANCEL_POINT;
STRACE("ulock_wait(%#x, %p, %lx, %u) → ...", operation, addr, value,
timeout_micros);
rc = sys_ulock_wait(operation, addr, value, timeout_micros);
STRACE("ulock_wait(%#x, %p, %lx, %u) → %d% m", operation, addr, value,
timeout_micros, rc);
return rc;
}

// returns -errno
int ulock_wake(uint32_t operation, void *addr, uint64_t wake_value) {
int rc;
rc = __syscall3i(operation, (long)addr, wake_value, 0x2000000 | 516);
STRACE("ulock_wake(%#x, %p, %lx) → %s", operation, addr, wake_value,
DescribeErrno(rc));
return rc;
}
27 changes: 27 additions & 0 deletions libc/intrin/ulock.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#ifndef COSMOPOLITAN_ULOCK_H_
#define COSMOPOLITAN_ULOCK_H_
#if !(__ASSEMBLER__ + __LINKER__ + 0)
COSMOPOLITAN_C_START_

/* both wake and wait take one of these */
#define UL_COMPARE_AND_WAIT 1 /* multi-thread */
#define UL_UNFAIR_LOCK 2
#define UL_COMPARE_AND_WAIT_SHARED 3 /* multi-thread/process */
#define UL_UNFAIR_LOCK64_SHARED 4
#define UL_COMPARE_AND_WAIT64 5
#define UL_COMPARE_AND_WAIT64_SHARED 6

#define ULF_WAKE_ALL 0x00000100
#define ULF_WAKE_THREAD 0x00000200 /* takes wake_value */
#define ULF_WAKE_ALLOW_NON_OWNER 0x00000400

#define ULF_WAIT_WORKQ_DATA_CONTENTION 0x00010000
#define ULF_WAIT_CANCEL_POINT 0x00020000 /* raises eintr */
#define ULF_WAIT_ADAPTIVE_SPIN 0x00040000

int ulock_wake(uint32_t, void *, uint64_t);
int ulock_wait(uint32_t, void *, uint64_t, uint32_t);

COSMOPOLITAN_C_END_
#endif /* !(__ASSEMBLER__ + __LINKER__ + 0) */
#endif /* COSMOPOLITAN_ULOCK_H_ */
6 changes: 6 additions & 0 deletions libc/log/oncrash_arm64.c
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,11 @@ static relegated void __oncrash_impl(int sig, struct siginfo *si,
}
Append(b, " %s %s %s %s\n", names.sysname, names.version, names.nodename,
names.release);
Append(
b, " cosmoaddr2line %s%s %lx %s\n", __argv[0],
endswith(__argv[0], ".com") ? ".dbg" : "", ctx ? ctx->uc_mcontext.PC : 0,
DescribeBacktrace(ctx ? (struct StackFrame *)ctx->uc_mcontext.BP
: (struct StackFrame *)__builtin_frame_address(0)));
if (ctx) {
long pc;
char *mem = 0;
Expand All @@ -240,6 +245,7 @@ static relegated void __oncrash_impl(int sig, struct siginfo *si,
struct StackFrame *fp;
struct SymbolTable *st;
struct fpsimd_context *vc;

st = GetSymbolTable();
debugbin = FindDebugBinary();
addr2line = GetAddr2linePath();
Expand Down
22 changes: 16 additions & 6 deletions libc/runtime/clone.c
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
#include "libc/intrin/atomic.h"
#include "libc/intrin/describeflags.internal.h"
#include "libc/intrin/strace.internal.h"
#include "libc/intrin/ulock.h"
#include "libc/intrin/weaken.h"
#include "libc/limits.h"
#include "libc/macros.internal.h"
Expand Down Expand Up @@ -197,12 +198,20 @@ XnuThreadMain(void *pthread, // rdi
// %rsi = size_t freesize,
// %rdx = uint32_t port,
// %r10 = uint32_t sem);
asm volatile("movl\t$0,%0\n\t" // *wt->ztid = 0
"xor\t%%r10d,%%r10d\n\t" // sem = 0
"syscall" // __bsdthread_terminate()
: "=m"(*wt->ztid)
: "a"(0x2000000 | 361), "D"(0), "S"(0), "d"(0L)
: "rcx", "r10", "r11", "memory");
asm volatile("movl\t$0,(%%rsi)\n\t" // *wt->ztid = 0
"mov\t$0x101,%%edi\n\t" // wake all
"xor\t%%edx,%%edx\n\t" // wake_value
"mov\t$0x02000204,%%eax\n\t" // ulock_wake()
"syscall\n\t" //
"xor\t%%edi,%%edi\n\t" // freeaddr
"xor\t%%esi,%%esi\n\t" // freesize
"xor\t%%edx,%%edx\n\t" // kport
"xor\t%%r10d,%%r10d\n\t" // joinsem
"mov\t$0x02000169,%%eax\n\t" // bsdthread_terminate()
"syscall"
: /* no outputs */
: "S"(wt->ztid)
: "rax", "rcx", "r10", "r11", "memory");
__builtin_unreachable();
}

Expand Down Expand Up @@ -443,6 +452,7 @@ static void *SiliconThreadMain(void *arg) {
*wt->ctid = wt->this;
__stack_call(wt->arg, wt->this, 0, 0, wt->func, wt);
*wt->ztid = 0;
ulock_wake(UL_COMPARE_AND_WAIT | ULF_WAKE_ALL, wt->ztid, 0);
return 0;
}

Expand Down
1 change: 1 addition & 0 deletions libc/runtime/enable_tls.c
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ textstartup void __enable_tls(void) {
tid = sys_gettid();
}
atomic_store_explicit(&tib->tib_tid, tid, memory_order_relaxed);
// TODO(jart): set_tid_address?

// initialize posix threads
_pthread_static.tib = tib;
Expand Down
2 changes: 1 addition & 1 deletion libc/sysv/calls/sys_futex.S
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
#include "libc/sysv/macros.internal.h"
.scall sys_futex,0x0a60531c6ffff0ca,98,4095,globl,hidden
.scall sys_futex,0x0a60531c622030ca,98,515,globl,hidden
2 changes: 1 addition & 1 deletion libc/sysv/calls/sys_futex_cp.S
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
#include "libc/sysv/macros.internal.h"
.scall sys_futex_cp,0x8a68539c6ffff8ca,2146,4095,globl,hidden
.scall sys_futex_cp,0x8a68539c62a038ca,2146,2563,globl,hidden
2 changes: 2 additions & 0 deletions libc/sysv/syscall2.S
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
//
// The returned value follows the Linux kernel convention ie
// errors are returned as `-errno`, rather than -1 w/ errno.
//
// This helper should not be used to do cancelation points.
__syscall2:
#ifdef __aarch64__
mov x8,x2 // syscall number (linux)
Expand Down
2 changes: 2 additions & 0 deletions libc/sysv/syscall3.S
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
//
// The return value follows the Linux Kernel (System V) ABI
// where -errno is returned, rather than doing -1 w/ errno.
//
// This helper should not be used to do cancelation points.
__syscall3:
#ifdef __aarch64__
mov x8,x3 // syscall number (linux)
Expand Down
53 changes: 53 additions & 0 deletions libc/sysv/syscall4.S
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*-*- mode:unix-assembly; indent-tabs-mode:t; tab-width:8; coding:utf-8 -*-│
│vi: set et ft=asm ts=8 tw=8 fenc=utf-8 :vi│
╞══════════════════════════════════════════════════════════════════════════════╡
│ Copyright 2023 Justine Alexandra Roberts Tunney │
│ │
│ Permission to use, copy, modify, and/or distribute this software for │
│ any purpose with or without fee is hereby granted, provided that the │
│ above copyright notice and this permission notice appear in all copies. │
│ │
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
│ PERFORMANCE OF THIS SOFTWARE. │
╚─────────────────────────────────────────────────────────────────────────────*/
#include "libc/macros.internal.h"

// Invokes system call w/ arity of four.
//
// This function takes four params. The first four, are for
// args passed along to the system call. The 5th is for the
// the magic number, indicating which system call is called
//
// The return value follows the Linux Kernel (System V) ABI
// where -errno is returned, rather than doing -1 w/ errno.
//
// This helper should not be used to do cancelation points.
__syscall4:
#ifdef __aarch64__
mov x8,x4 // syscall number (linux)
mov x16,x4 // syscall number (xnu)
mov x9,0 // clear carry flag
adds x9,x9,0 // clear carry flag
svc 0
bcs 1f
ret
1: neg x0,x0
ret
#elif defined(__x86_64__)
mov %rcx,%r10 // avoid intel cx clobber
mov %r8d,%eax // arg5 -> syscall number
clc // linux saves carry flag
syscall // bsds set carry on errs
jnc 1f
neg %rax // normalizes to system v
1: ret
#else
#error "unsupported architecture"
#endif
.endfn __syscall4,globl
4 changes: 2 additions & 2 deletions libc/sysv/syscalls.sh
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ scall sys_killpg 0x092fff092fffffff 0xfff globl hidden
scall sys_clone 0x11fffffffffff038 0x0dc globl hidden
scall sys_tkill 0x13e0771b121480c8 0x082 globl hidden # thr_kill() on FreeBSD; _lwp_kill() on NetBSD; thrkill() on OpenBSD where arg3 should be 0 or tcb; __pthread_kill() on XNU
scall sys_tgkill 0xffffff1e1ffff0ea 0x083 globl hidden # thr_kill2() on FreeBSD
scall sys_futex 0x0a60531c6ffff0ca 0x062 globl hidden # raises SIGSYS on NetBSD; _umtx_op() on FreeBSD
scall sys_futex_cp 0x8a68539c6ffff8ca 0x862 globl hidden # intended for futex wait ops
scall sys_futex 0x0a60531c622030ca 0x062 globl hidden # raises SIGSYS on NetBSD; _umtx_op() on FreeBSD
scall sys_futex_cp 0x8a68539c62a038ca 0x862 globl hidden # intended for futex wait ops
scall sys_set_robust_list 0x0a7ffffffffff111 0x063 globl # no wrapper
scall sys_get_robust_list 0x0a8ffffffffff112 0x064 globl # no wrapper
scall sys_uname 0x0a4fff0a4ffff03f 0x0a0 globl hidden
Expand Down
3 changes: 3 additions & 0 deletions libc/sysv/sysv.mk
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ LIBC_SYSV_A_FILES := \
libc/sysv/restorert.S \
libc/sysv/syscall2.S \
libc/sysv/syscall3.S \
libc/sysv/syscall4.S \
libc/sysv/systemfive.S \
libc/sysv/sysret.c \
libc/sysv/sysv.c \
Expand Down Expand Up @@ -170,6 +171,8 @@ o/$(MODE)/libc/sysv/syscall2.o: libc/sysv/syscall2.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) $<
o/$(MODE)/libc/sysv/syscall3.o: libc/sysv/syscall3.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) $<
o/$(MODE)/libc/sysv/syscall4.o: libc/sysv/syscall4.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) $<
o/$(MODE)/libc/sysv/restorert.o: libc/sysv/restorert.S
@$(COMPILE) -AOBJECTIFY.S $(OBJECTIFY.S) $(OUTPUT_OPTION) $<
o/$(MODE)/libc/sysv/calls/%.o: libc/sysv/calls/%.S
Expand Down
2 changes: 1 addition & 1 deletion libc/thread/pthread_exit.c
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ wontreturn void pthread_exit(void *rc) {
// note that the main thread is joinable by child threads
if (pt->pt_flags & PT_STATIC) {
atomic_store_explicit(&tib->tib_tid, 0, memory_order_release);
nsync_futex_wake_(&tib->tib_tid, INT_MAX, !IsWindows());
nsync_futex_wake_(&tib->tib_tid, INT_MAX, !IsWindows() && !IsXnu());
_Exit1(0);
}

Expand Down
2 changes: 1 addition & 1 deletion libc/thread/pthread_timedjoin_np.c
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ static errno_t _pthread_wait(atomic_int *ctid, struct timespec *abstime) {
if (!(rc = pthread_testcancel_np())) {
BEGIN_CANCELLATION_POINT;
while ((x = atomic_load_explicit(ctid, memory_order_acquire))) {
e = nsync_futex_wait_(ctid, x, !IsWindows(), abstime);
e = nsync_futex_wait_(ctid, x, !IsWindows() && !IsXnu(), abstime);
if (e == -ECANCELED) {
rc = ECANCELED;
break;
Expand Down
7 changes: 6 additions & 1 deletion test/libc/calls/sigbus_test.c
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,12 @@ TEST(sigbus, test) {

// verify the signal was raised
EXPECT_EQ(SIGBUS, gotsig);
EXPECT_EQ(BUS_ADRERR, gotcode);
if (IsXnuSilicon()) {
// TODO: Why does it say it's an alignment error?
EXPECT_EQ(BUS_ADRALN, gotcode);
} else {
EXPECT_EQ(BUS_ADRERR, gotcode);
}

// clean up
sigaction(SIGBUS, &oldsa, 0);
Expand Down
Loading

0 comments on commit 85f64f3

Please sign in to comment.