1 /* $OpenBSD: synch.h,v 1.9 2024/01/07 19:44:28 cheloha 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 now, 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 (!timespecisvalid(abs) || WRAP(clock_gettime)(clockid, &now)) 45 return EINVAL; 46 47 if (timespeccmp(abs, &now, <=)) 48 return ETIMEDOUT; 49 timespecsub(abs, &now, &rel); 50 51 error = futex(p, FUTEX_WAIT_PRIVATE, val, &rel, NULL); 52 if (error == -1) { 53 error = errno; 54 errno = saved_errno; 55 } 56 return error; 57 } 58 59 static inline int 60 _requeue(volatile uint32_t *p, int n, int m, volatile uint32_t *q) 61 { 62 return futex(p, FUTEX_REQUEUE_PRIVATE, n, (void *)(long)m, q); 63 } 64