Make mmap() scalable

It's now possible to create thousands of thousands of sparse independent
memory mappings, without any slowdown. The memory manager is better with
tracking memory protection now, particularly on Windows in a precise way
that can be restored during fork(). You now have the highest quality mem
manager possible. It's even better than some OSes like XNU, where mmap()
is implemented as an O(n) operation which means sadly things aren't much
improved over there. With this change the llamafile HTTP server endpoint
at /tokenize with a prompt of 50 tokens is now able to handle 2.6m r/sec
This commit is contained in:
Justine Tunney 2024-07-05 23:13:20 -07:00
parent 3756870635
commit 8c645fa1ee
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
59 changed files with 1238 additions and 1067 deletions

View file

@ -20,7 +20,6 @@
#include "libc/calls/struct/sigaction.h"
#include "libc/calls/struct/siginfo.h"
#include "libc/dce.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/sa.h"
#include "libc/sysv/consts/sicode.h"

View file

@ -118,10 +118,11 @@ TEST(setrlimit, testFileSizeLimit) {
EXPECT_EQ(0, WTERMSIG(wstatus));
}
int SetKernelEnforcedMemoryLimit(size_t n) {
struct rlimit rlim;
int SetMemoryLimit(size_t n) {
struct rlimit rlim = {0};
getrlimit(RLIMIT_AS, &rlim);
rlim.rlim_cur = n;
rlim.rlim_max = n;
return setrlimit(RLIMIT_AS, &rlim);
}
@ -129,27 +130,20 @@ TEST(setrlimit, testMemoryLimit) {
char *p;
bool gotsome;
int i, wstatus;
if (IsXnu())
return;
if (IsOpenbsd())
return; // simply too slow until mmap() becomes O(logn)
ASSERT_NE(-1, (wstatus = xspawn(0)));
if (wstatus == -2) {
ASSERT_EQ(0, SetKernelEnforcedMemoryLimit(MEM));
for (gotsome = false, i = 0; i < (MEM * 2) / __granularity(); ++i) {
p = mmap(0, __granularity(), PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE | MAP_POPULATE, -1, 0);
ASSERT_EQ(0, SetMemoryLimit(MEM));
for (gotsome = false, i = 0; i < (MEM * 2) / getpagesize(); ++i) {
p = mmap(0, getpagesize(), PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (p != MAP_FAILED) {
gotsome = true;
} else {
if (!IsNetbsd()) {
// TODO(jart): what's going on with NetBSD?
ASSERT_TRUE(gotsome);
}
ASSERT_TRUE(gotsome);
ASSERT_EQ(ENOMEM, errno);
_Exit(0);
}
rngset(p, __granularity(), _rand64, -1);
rngset(p, getpagesize(), _rand64, -1);
}
_Exit(1);
}

View file

@ -0,0 +1,76 @@
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2024 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/calls/calls.h"
#include "libc/calls/struct/timespec.h"
#include "libc/dce.h"
#include "libc/intrin/kprintf.h"
#include "libc/runtime/runtime.h"
#include "libc/sysv/consts/map.h"
#include "libc/sysv/consts/prot.h"
#define BENCH(ITERATIONS, WORK_PER_RUN, CODE) \
do { \
struct timespec start = timespec_real(); \
for (int __i = 0; __i < ITERATIONS; ++__i) { \
asm volatile("" ::: "memory"); \
CODE; \
} \
long long work = (WORK_PER_RUN) * (ITERATIONS); \
double nanos = \
(timespec_tonanos(timespec_sub(timespec_real(), start)) + work - 1) / \
(double)work; \
kprintf("%'20ld ns %2dx %s\n", (long)nanos, (ITERATIONS), #CODE); \
} while (0)
void *randaddr(void) {
static unsigned long lcg = 1;
lcg *= 6364136223846793005;
lcg += 1442695040888963407;
return (void *)(lcg >> 48 << 28);
}
void map_unmap_one_page(void) {
void *p;
if ((p = mmap(randaddr(), 1, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)) == MAP_FAILED)
__builtin_trap();
if (munmap(p, 1))
__builtin_trap();
}
int main() {
kprintf("\n");
BENCH(1000, 1, map_unmap_one_page());
// macos doesn't scale
if (IsXnu())
return 0;
// create lots of sparse mappings to put
// weight on __maps.maps. red-black tree
int n = 10000;
kprintf("%20s creating %d sparse maps...\n", "", n);
for (int i = 0; i < n; ++i) {
if (mmap(randaddr(), 1, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS,
-1, 0) == MAP_FAILED)
__builtin_trap();
}
BENCH(1000, 1, map_unmap_one_page());
}

View file

@ -461,7 +461,23 @@ void BenchUnmap(void) {
__builtin_trap();
}
void BenchBigMmap(void) {
void *p;
p = mmap(0, 101 * 1024 * 1024, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
if (p == MAP_FAILED)
__builtin_trap();
ptrs[count++] = p;
}
void BenchBigMunmap(void) {
if (munmap(ptrs[--count], 101 * 1024 * 1024))
__builtin_trap();
}
BENCH(mmap, bench) {
EZBENCH2("mmap", donothing, BenchMmapPrivate());
EZBENCH2("munmap", donothing, BenchUnmap());
// EZBENCH2("big mmap", donothing, BenchBigMmap());
// EZBENCH2("big munmap", donothing, BenchBigMunmap());
}

View file

@ -13,16 +13,18 @@
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#include "libc/intrin/rbtree.h"
#include "libc/intrin/tree.h"
#include "libc/intrin/kprintf.h"
#include "libc/intrin/maps.h"
#include "libc/macros.internal.h"
#include "libc/mem/mem.h"
#include "libc/runtime/runtime.h"
#include "libc/stdio/rand.h"
#define NUMBER_CONTAINER(e) RBTREE_CONTAINER(struct number, elem, e)
#define NUMBER_CONTAINER(e) TREE_CONTAINER(struct number, elem, e)
void rbtree_checker(const struct rbtree *node, const struct rbtree *parent,
int black_count, int *black_height, rbtree_cmp_f *cmp) {
void tree_checker(const struct Tree *node, const struct Tree *parent,
int black_count, int *black_height, tree_cmp_f *cmp) {
if (!node) {
// Leaf nodes are considered black
if (*black_height == -1) {
@ -37,89 +39,101 @@ void rbtree_checker(const struct rbtree *node, const struct rbtree *parent,
// ILLEGAL TREE: Parent link is incorrect
__builtin_trap();
if (parent) {
if (rbtree_get_left(parent) == node && cmp(parent, node) < 0)
if (tree_get_left(parent) == node && cmp(parent, node) < 0)
// ILLEGAL TREE: Binary search property violated on left child
__builtin_trap();
if (parent->right == node && cmp(node, parent) < 0)
// ILLEGAL TREE: Binary search property violated on right child
__builtin_trap();
}
if (!rbtree_get_red(node)) {
if (!tree_get_red(node)) {
black_count++;
} else if (parent && rbtree_get_red(parent)) {
} else if (parent && tree_get_red(parent)) {
// ILLEGAL TREE: Red node has red child
__builtin_trap();
}
rbtree_checker(rbtree_get_left(node), node, black_count, black_height, cmp);
rbtree_checker(node->right, node, black_count, black_height, cmp);
tree_checker(tree_get_left(node), node, black_count, black_height, cmp);
tree_checker(node->right, node, black_count, black_height, cmp);
}
void rbtree_check(struct rbtree *root, rbtree_cmp_f *cmp) {
void tree_check(struct Tree *root, tree_cmp_f *cmp) {
if (root) {
if (rbtree_get_red(root))
if (tree_get_red(root))
// ILLEGAL TREE: root node must be black
__builtin_trap();
int black_height = -1;
rbtree_checker(root, 0, 0, &black_height, cmp);
tree_checker(root, 0, 0, &black_height, cmp);
}
}
struct number {
int number;
struct rbtree elem;
long number;
struct Tree elem;
};
int number_compare(const struct rbtree *ra, const struct rbtree *rb) {
int number_search(const void *ra, const struct Tree *rb) {
long a = (long)ra;
const struct number *b = NUMBER_CONTAINER(rb);
return (a > b->number) - (a < b->number);
}
int number_compare(const struct Tree *ra, const struct Tree *rb) {
const struct number *a = NUMBER_CONTAINER(ra);
const struct number *b = NUMBER_CONTAINER(rb);
return (a->number > b->number) - (a->number < b->number);
}
struct number *number_new(int number) {
static int used;
static struct number heap[8192];
if (used == ARRAYLEN(heap))
return 0;
struct number *res = &heap[used++];
res->number = number;
struct number *res;
if ((res = malloc(sizeof(struct number))))
res->number = number;
return res;
}
struct rbtree *tree = 0;
struct Tree *tree = 0;
void print(void) {
for (struct rbtree *e = rbtree_first(tree); e; e = rbtree_next(e))
for (struct Tree *e = tree_first(tree); e; e = tree_next(e))
kprintf("%3d", NUMBER_CONTAINER(e)->number);
kprintf("\n");
}
void print_reversed(void) {
for (struct rbtree *e = rbtree_last(tree); e; e = rbtree_prev(e))
for (struct Tree *e = tree_last(tree); e; e = tree_prev(e))
kprintf("%3d", NUMBER_CONTAINER(e)->number);
kprintf("\n");
}
void simple_test(void) {
static const int kNumba[] = {74, 53, 96, 70, 34, 95, 30, 2, 89, 46,
23, 2, 52, 0, 34, 12, 90, 95, 32, 65};
static const long kNumba[] = {74, 53, 96, 70, 34, 95, 30, 2, 96, 46,
23, 2, 52, 0, 34, 94, 90, 95, 32, 65};
for (int i = 0; i < 20; ++i) {
int number = kNumba[i];
kprintf("%3d", number);
rbtree_insert(&tree, &number_new(number)->elem, number_compare);
rbtree_check(tree, number_compare);
tree_insert(&tree, &number_new(number)->elem, number_compare);
tree_check(tree, number_compare);
}
kprintf("\n");
print();
print_reversed();
for (int i = 0; i < 20; ++i) {
rbtree_remove(&tree, rbtree_get(tree, &(&(struct number){kNumba[i]})->elem,
number_compare));
rbtree_check(tree, number_compare);
tree_remove(&tree, tree_get(tree, (void *)kNumba[i], number_search));
tree_check(tree, number_compare);
print();
}
}
int main() {
ShowCrashReports();
tree_check(__maps.maps, __maps_compare);
kprintf("\n");
__print_maps(15);
kprintf("\n");
simple_test();
tree_check(__maps.maps, __maps_compare);
for (int i = 0; i < 100000; ++i)
tree_insert(&tree, &number_new(rand())->elem, number_compare);
tree_check(tree, number_compare);
tree_check(__maps.maps, __maps_compare);
__print_maps(15);
}

View file

@ -16,8 +16,11 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/atomic.h"
#include "libc/calls/calls.h"
#include "libc/dce.h"
#include "libc/intrin/atomic.h"
#include "libc/intrin/kprintf.h"
#include "libc/mem/gc.h"
#include "libc/mem/mem.h"
#include "libc/runtime/internal.h"
@ -66,7 +69,7 @@ TEST(pthread_atfork, test) {
EXITS(0);
}
pthread_mutex_t mu;
pthread_mutex_t mu = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
void mu_lock(void) {
pthread_mutex_lock(&mu);
@ -80,8 +83,12 @@ void mu_wipe(void) {
pthread_mutex_init(&mu, 0);
}
static atomic_bool once;
void *Worker(void *arg) {
for (int i = 0; i < 20; ++i) {
if (!atomic_exchange(&once, true))
__print_maps(0);
mu_lock();
usleep(20);
mu_unlock();
@ -99,14 +106,14 @@ void *Worker(void *arg) {
}
TEST(pthread_atfork, fork_exit_torture) {
if (!IsFreebsd())
return;
mu_wipe();
pthread_atfork(mu_lock, mu_unlock, mu_wipe);
int i, n = 4;
pthread_t *t = gc(malloc(sizeof(pthread_t) * n));
for (i = 0; i < n; ++i) {
for (i = 0; i < n; ++i)
ASSERT_EQ(0, pthread_create(t + i, 0, Worker, 0));
}
for (i = 0; i < n; ++i) {
for (i = 0; i < n; ++i)
ASSERT_EQ(0, pthread_join(t[i], 0));
}
}