xref: /openbsd-src/lib/libc/thread/synch.h (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
1 /*	$OpenBSD: synch.h,v 1.5 2020/07/06 13:33:06 pirofti 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 
33 	if (abs == NULL)
34 		return futex(p, FUTEX_WAIT_PRIVATE, val, NULL, NULL);
35 
36 	if (abs->tv_nsec >= 1000000000 || WRAP(clock_gettime)(clockid, &rel))
37 		return (EINVAL);
38 
39 	rel.tv_sec = abs->tv_sec - rel.tv_sec;
40 	if ((rel.tv_nsec = abs->tv_nsec - rel.tv_nsec) < 0) {
41 		rel.tv_sec--;
42 		rel.tv_nsec += 1000000000;
43 	}
44 	if (rel.tv_sec < 0)
45 		return (ETIMEDOUT);
46 
47 	return futex(p, FUTEX_WAIT_PRIVATE, val, &rel, NULL);
48 }
49 
50 static inline int
51 _requeue(volatile uint32_t *p, int n, int m, volatile uint32_t *q)
52 {
53 	return futex(p, FUTEX_REQUEUE_PRIVATE, n, (void *)(long)m, q);
54 }
55