Make futexes 100x better on x86 MacOS

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
This commit is contained in:
Justine Tunney 2023-10-03 14:47:20 -07:00
parent ff250a0c10
commit 85f64f3851
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
21 changed files with 267 additions and 34 deletions

View file

@ -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"
@ -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':
@ -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:
*

View file

@ -3,7 +3,7 @@
#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 */
@ -11,7 +11,7 @@
#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_

54
libc/intrin/ulock.c Normal file
View file

@ -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
libc/intrin/ulock.h Normal file
View file

@ -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_ */