Skip to content

Commit 38bceae

Browse files
committed
Give up on making clock_nanosleep() precise
Multiple projects I care about make the assumption that this isn't a system call that sleeps for a particular number of nanonseconds, but rather a function that parks processes on kernel scheduler quantums. Anyone who wants the old behavior should use cosmo_clock_nanosleep()
1 parent 99f0491 commit 38bceae

File tree

4 files changed

+150
-109
lines changed

4 files changed

+150
-109
lines changed

libc/calls/clock_nanosleep-cosmo.c

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
2+
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
3+
╞══════════════════════════════════════════════════════════════════════════════╡
4+
│ Copyright 2024 Justine Alexandra Roberts Tunney │
5+
│ │
6+
│ Permission to use, copy, modify, and/or distribute this software for │
7+
│ any purpose with or without fee is hereby granted, provided that the │
8+
│ above copyright notice and this permission notice appear in all copies. │
9+
│ │
10+
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
11+
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
12+
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
13+
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
14+
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
15+
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
16+
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
17+
│ PERFORMANCE OF THIS SOFTWARE. │
18+
╚─────────────────────────────────────────────────────────────────────────────*/
19+
#include "libc/calls/calls.h"
20+
#include "libc/calls/internal.h"
21+
#include "libc/calls/struct/timespec.h"
22+
#include "libc/errno.h"
23+
#include "libc/runtime/clktck.h"
24+
#include "libc/runtime/runtime.h"
25+
#include "libc/sysv/consts/clock.h"
26+
#include "libc/sysv/consts/timer.h"
27+
28+
/**
29+
* Sleeps with higher accuracy at the cost of cpu.
30+
*/
31+
int cosmo_clock_nanosleep(int clock, int flags, const struct timespec *req,
32+
struct timespec *rem) {
33+
34+
// pick clocks
35+
int time_clock;
36+
int sleep_clock;
37+
if (clock == CLOCK_REALTIME || //
38+
clock == CLOCK_REALTIME_PRECISE) {
39+
time_clock = clock;
40+
sleep_clock = CLOCK_REALTIME;
41+
} else if (clock == CLOCK_MONOTONIC || //
42+
clock == CLOCK_MONOTONIC_PRECISE) {
43+
time_clock = clock;
44+
sleep_clock = CLOCK_MONOTONIC;
45+
} else if (clock == CLOCK_REALTIME_COARSE || //
46+
clock == CLOCK_REALTIME_FAST) {
47+
return sys_clock_nanosleep(CLOCK_REALTIME, flags, req, rem);
48+
} else if (clock == CLOCK_MONOTONIC_COARSE || //
49+
clock == CLOCK_MONOTONIC_FAST) {
50+
return sys_clock_nanosleep(CLOCK_MONOTONIC, flags, req, rem);
51+
} else {
52+
return sys_clock_nanosleep(clock, flags, req, rem);
53+
}
54+
55+
// sleep bulk of time in kernel
56+
struct timespec start, deadline, remain, waitfor, now;
57+
struct timespec quantum = timespec_fromnanos(1000000000 / CLK_TCK);
58+
clock_gettime(time_clock, &start);
59+
deadline = flags & TIMER_ABSTIME ? *req : timespec_add(start, *req);
60+
if (timespec_cmp(start, deadline) >= 0) return 0;
61+
remain = timespec_sub(deadline, start);
62+
if (timespec_cmp(remain, quantum) > 0) {
63+
waitfor = timespec_sub(remain, quantum);
64+
if (sys_clock_nanosleep(sleep_clock, 0, &waitfor, rem) == -1) {
65+
if (!flags && rem && errno == EINTR) {
66+
*rem = timespec_add(*rem, quantum);
67+
}
68+
return -1;
69+
}
70+
}
71+
72+
// spin through final scheduling quantum
73+
int rc = 0;
74+
ftrace_enabled(-1);
75+
do {
76+
if (_check_cancel()) {
77+
rc = -1;
78+
break;
79+
}
80+
clock_gettime(time_clock, &now);
81+
} while (timespec_cmp(now, deadline) < 0);
82+
ftrace_enabled(+1);
83+
return rc;
84+
}

libc/calls/clock_nanosleep-sys.c

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
2+
│ vi: set et ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi │
3+
╞══════════════════════════════════════════════════════════════════════════════╡
4+
│ Copyright 2024 Justine Alexandra Roberts Tunney │
5+
│ │
6+
│ Permission to use, copy, modify, and/or distribute this software for │
7+
│ any purpose with or without fee is hereby granted, provided that the │
8+
│ above copyright notice and this permission notice appear in all copies. │
9+
│ │
10+
│ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │
11+
│ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │
12+
│ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │
13+
│ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │
14+
│ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │
15+
│ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │
16+
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
17+
│ PERFORMANCE OF THIS SOFTWARE. │
18+
╚─────────────────────────────────────────────────────────────────────────────*/
19+
#include "libc/calls/calls.h"
20+
#include "libc/calls/cp.internal.h"
21+
#include "libc/calls/struct/timespec.h"
22+
#include "libc/calls/struct/timespec.internal.h"
23+
#include "libc/dce.h"
24+
#include "libc/errno.h"
25+
#include "libc/intrin/describeflags.internal.h"
26+
#include "libc/intrin/strace.internal.h"
27+
#include "libc/intrin/weaken.h"
28+
#include "libc/sysv/errfuns.h"
29+
#include "libc/thread/thread.h"
30+
31+
int sys_clock_nanosleep(int clock, int flags, //
32+
const struct timespec *req, struct timespec *rem) {
33+
int rc;
34+
BEGIN_CANCELATION_POINT;
35+
if (IsLinux() || IsFreebsd() || IsNetbsd()) {
36+
rc = __sys_clock_nanosleep(clock, flags, req, rem);
37+
} else if (IsXnu()) {
38+
rc = sys_clock_nanosleep_xnu(clock, flags, req, rem);
39+
} else if (IsOpenbsd()) {
40+
rc = sys_clock_nanosleep_openbsd(clock, flags, req, rem);
41+
} else if (IsWindows()) {
42+
rc = sys_clock_nanosleep_nt(clock, flags, req, rem);
43+
} else {
44+
rc = enosys();
45+
}
46+
if (rc > 0) {
47+
errno = rc;
48+
rc = -1;
49+
}
50+
// system call support might not detect cancelation on bsds
51+
if (rc == -1 && errno == EINTR && //
52+
_weaken(pthread_testcancel_np) && //
53+
_weaken(pthread_testcancel_np)()) {
54+
rc = ecanceled();
55+
}
56+
END_CANCELATION_POINT;
57+
STRACE("sys_clock_nanosleep(%s, %s, %s, [%s]) → %d% m",
58+
DescribeClockName(clock), DescribeSleepFlags(flags),
59+
DescribeTimespec(0, req), DescribeTimespec(rc, rem), rc);
60+
return rc;
61+
}

libc/calls/clock_nanosleep.c

Lines changed: 3 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -16,112 +16,10 @@
1616
│ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │
1717
│ PERFORMANCE OF THIS SOFTWARE. │
1818
╚─────────────────────────────────────────────────────────────────────────────*/
19-
#include "libc/assert.h"
20-
#include "libc/calls/cp.internal.h"
21-
#include "libc/calls/internal.h"
2219
#include "libc/calls/struct/timespec.h"
23-
#include "libc/calls/struct/timespec.internal.h"
2420
#include "libc/dce.h"
2521
#include "libc/errno.h"
26-
#include "libc/intrin/describeflags.internal.h"
27-
#include "libc/intrin/kprintf.h"
28-
#include "libc/intrin/strace.internal.h"
29-
#include "libc/intrin/weaken.h"
30-
#include "libc/runtime/clktck.h"
31-
#include "libc/runtime/runtime.h"
32-
#include "libc/sysv/consts/clock.h"
3322
#include "libc/sysv/consts/timer.h"
34-
#include "libc/sysv/errfuns.h"
35-
#include "libc/thread/thread.h"
36-
37-
static int sys_clock_nanosleep(int clock, int flags, //
38-
const struct timespec *req,
39-
struct timespec *rem) {
40-
int rc;
41-
BEGIN_CANCELATION_POINT;
42-
if (IsLinux() || IsFreebsd() || IsNetbsd()) {
43-
rc = __sys_clock_nanosleep(clock, flags, req, rem);
44-
} else if (IsXnu()) {
45-
rc = sys_clock_nanosleep_xnu(clock, flags, req, rem);
46-
} else if (IsOpenbsd()) {
47-
rc = sys_clock_nanosleep_openbsd(clock, flags, req, rem);
48-
} else if (IsWindows()) {
49-
rc = sys_clock_nanosleep_nt(clock, flags, req, rem);
50-
} else {
51-
rc = enosys();
52-
}
53-
if (rc > 0) {
54-
errno = rc;
55-
rc = -1;
56-
}
57-
// system call support might not detect cancelation on bsds
58-
if (rc == -1 && errno == EINTR && //
59-
_weaken(pthread_testcancel_np) && //
60-
_weaken(pthread_testcancel_np)()) {
61-
rc = ecanceled();
62-
}
63-
END_CANCELATION_POINT;
64-
STRACE("sys_clock_nanosleep(%s, %s, %s, [%s]) → %d% m",
65-
DescribeClockName(clock), DescribeSleepFlags(flags),
66-
DescribeTimespec(0, req), DescribeTimespec(rc, rem), rc);
67-
return rc;
68-
}
69-
70-
static int cosmo_clock_nanosleep(int clock, int flags,
71-
const struct timespec *req,
72-
struct timespec *rem) {
73-
74-
// pick clocks
75-
int time_clock;
76-
int sleep_clock;
77-
if (clock == CLOCK_REALTIME || //
78-
clock == CLOCK_REALTIME_PRECISE) {
79-
time_clock = clock;
80-
sleep_clock = CLOCK_REALTIME;
81-
} else if (clock == CLOCK_MONOTONIC || //
82-
clock == CLOCK_MONOTONIC_PRECISE) {
83-
time_clock = clock;
84-
sleep_clock = CLOCK_MONOTONIC;
85-
} else if (clock == CLOCK_REALTIME_COARSE || //
86-
clock == CLOCK_REALTIME_FAST) {
87-
return sys_clock_nanosleep(CLOCK_REALTIME, flags, req, rem);
88-
} else if (clock == CLOCK_MONOTONIC_COARSE || //
89-
clock == CLOCK_MONOTONIC_FAST) {
90-
return sys_clock_nanosleep(CLOCK_MONOTONIC, flags, req, rem);
91-
} else {
92-
return sys_clock_nanosleep(clock, flags, req, rem);
93-
}
94-
95-
// sleep bulk of time in kernel
96-
struct timespec start, deadline, remain, waitfor, now;
97-
struct timespec quantum = timespec_fromnanos(1000000000 / CLK_TCK);
98-
unassert(!clock_gettime(time_clock, &start));
99-
deadline = flags & TIMER_ABSTIME ? *req : timespec_add(start, *req);
100-
if (timespec_cmp(start, deadline) >= 0) return 0;
101-
remain = timespec_sub(deadline, start);
102-
if (timespec_cmp(remain, quantum) > 0) {
103-
waitfor = timespec_sub(remain, quantum);
104-
if (sys_clock_nanosleep(sleep_clock, 0, &waitfor, rem) == -1) {
105-
if (!flags && rem && errno == EINTR) {
106-
*rem = timespec_add(*rem, quantum);
107-
}
108-
return -1;
109-
}
110-
}
111-
112-
// spin through final scheduling quantum
113-
int rc = 0;
114-
ftrace_enabled(-1);
115-
do {
116-
if (_check_cancel()) {
117-
rc = -1;
118-
break;
119-
}
120-
unassert(!clock_gettime(time_clock, &now));
121-
} while (timespec_cmp(now, deadline) < 0);
122-
ftrace_enabled(+1);
123-
return rc;
124-
}
12523

12624
/**
12725
* Sleeps for particular amount of time.
@@ -157,10 +55,8 @@ static int cosmo_clock_nanosleep(int clock, int flags,
15755
* on OpenBSD it's good; on XNU it's bad; and on Windows it's ugly.
15856
*
15957
* @param clock may be
160-
* - `CLOCK_REALTIME` to have nanosecond-accurate wall time sleeps
161-
* - `CLOCK_REALTIME_COARSE` to not spin through scheduler quantum
162-
* - `CLOCK_MONOTONIC` to base the sleep off the monotinic clock
163-
* - `CLOCK_MONOTONIC_COARSE` to once again not do userspace spin
58+
* - `CLOCK_REALTIME`
59+
* - `CLOCK_MONOTONIC`
16460
* @param flags can be 0 for relative and `TIMER_ABSTIME` for absolute
16561
* @param req can be a relative or absolute time, depending on `flags`
16662
* @param rem shall be updated with the remainder of unslept time when
@@ -193,7 +89,7 @@ errno_t clock_nanosleep(int clock, int flags, //
19389
return EINVAL;
19490
}
19591
errno_t old = errno;
196-
int rc = cosmo_clock_nanosleep(clock, flags, req, rem);
92+
int rc = sys_clock_nanosleep(clock, flags, req, rem);
19793
errno_t err = !rc ? 0 : errno;
19894
errno = old;
19995
return err;

libc/calls/struct/timespec.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ int timespec_getres(struct timespec *, int) libcesque;
1919
int timespec_get(struct timespec *, int) libcesque;
2020

2121
#ifdef _COSMO_SOURCE
22-
/* cosmopolitan libc's non-posix timespec library
23-
removed by default due to emacs codebase clash */
22+
int sys_clock_nanosleep(int, int, const struct timespec *, struct timespec *);
23+
int cosmo_clock_nanosleep(int, int, const struct timespec *, struct timespec *);
2424
#define timespec_zero ((struct timespec){0})
2525
#define timespec_max ((struct timespec){0x7fffffffffffffff, 999999999})
2626
libcesque int timespec_cmp(struct timespec, struct timespec) pureconst;

0 commit comments

Comments
 (0)