xref: /openbsd/lib/libc/thread/synch.h (revision 73471bf0)
1 /*	$OpenBSD: synch.h,v 1.7 2021/06/13 21:11:54 kettenis Exp $ */
2 /*
3  * Copyright (c) 2017 Martin Pieuchot
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16  */
17 
18 #include <sys/atomic.h>
19 #include <sys/time.h>
20 #include <sys/futex.h>
21 
22 static inline int
23 _wake(volatile uint32_t *p, int n)
24 {
25 	return futex(p, FUTEX_WAKE_PRIVATE, n, NULL, NULL);
26 }
27 
28 static inline int
29 _twait(volatile uint32_t *p, int val, clockid_t clockid, const struct timespec *abs)
30 {
31 	struct timespec rel;
32 	int saved_errno = errno;
33 	int error;
34 
35 	if (abs == NULL) {
36 		error = futex(p, FUTEX_WAIT_PRIVATE, val, NULL, NULL);
37 		if (error == -1) {
38 			error = errno;
39 			errno = saved_errno;
40 		}
41 		return error;
42 	}
43 
44 	if (abs->tv_nsec >= 1000000000 || WRAP(clock_gettime)(clockid, &rel))
45 		return EINVAL;
46 
47 	rel.tv_sec = abs->tv_sec - rel.tv_sec;
48 	if ((rel.tv_nsec = abs->tv_nsec - rel.tv_nsec) < 0) {
49 		rel.tv_sec--;
50 		rel.tv_nsec += 1000000000;
51 	}
52 	if (rel.tv_sec < 0)
53 		return ETIMEDOUT;
54 
55 	error = futex(p, FUTEX_WAIT_PRIVATE, val, &rel, NULL);
56 	if (error == -1) {
57 		error = errno;
58 		errno = saved_errno;
59 	}
60 	return error;
61 }
62 
63 static inline int
64 _requeue(volatile uint32_t *p, int n, int m, volatile uint32_t *q)
65 {
66 	return futex(p, FUTEX_REQUEUE_PRIVATE, n, (void *)(long)m, q);
67 }
68