timer_posix.c (2219B)
1 /* see LICENSE file for copyright and license details */ 2 #include "../timer.h" 3 4 /* deadlines on the monotonic clock posix has, which may stop while the 5 * machine sleeps */ 6 #if !defined(__linux__) || defined(ARUU_FORCE_POSIX) 7 #include <errno.h> 8 #include <poll.h> 9 #include <string.h> 10 11 static struct timespec deadline[TIMER_MAX]; /* 0 0 for disarmed */ 12 static int ntimers; 13 14 static int 15 armed(int i) 16 { 17 return deadline[i].tv_sec || deadline[i].tv_nsec; 18 } 19 20 static long long 21 nsec(const struct timespec *ts) 22 { 23 return ts->tv_sec * 1000000000LL + ts->tv_nsec; 24 } 25 26 int 27 timer_init(int n) 28 { 29 if (n > TIMER_MAX) { 30 errno = EINVAL; 31 return -1; 32 } 33 ntimers = n; 34 memset(deadline, 0, sizeof(deadline)); 35 return 0; 36 } 37 38 int 39 timer_set(int i, const struct timespec *ts) 40 { 41 struct timespec now; 42 long long t; 43 44 if (!ts->tv_sec && !ts->tv_nsec) { 45 memset(&deadline[i], 0, sizeof(deadline[i])); 46 return 0; 47 } 48 if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) 49 return -1; 50 t = nsec(&now) + nsec(ts); 51 deadline[i].tv_sec = t / 1000000000LL; 52 deadline[i].tv_nsec = t % 1000000000LL; 53 return 0; 54 } 55 56 int 57 timer_left(int i, struct timespec *ts) 58 { 59 struct timespec now; 60 long long t = 0; 61 62 if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) 63 return -1; 64 if (armed(i) && (t = nsec(&deadline[i]) - nsec(&now)) < 1) 65 t = 1; 66 ts->tv_sec = t / 1000000000LL; 67 ts->tv_nsec = t % 1000000000LL; 68 return 0; 69 } 70 71 int 72 timer_wait(int fd) 73 { 74 struct pollfd pfd = {.fd = fd, .events = POLLIN}; 75 struct timespec now; 76 long long next, left; 77 int i, ms, fired; 78 79 for (;;) { 80 if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) 81 return -1; 82 fired = 0; 83 next = -1; 84 for (i = 0; i < ntimers; i++) { 85 if (!armed(i)) 86 continue; 87 left = nsec(&deadline[i]) - nsec(&now); 88 if (left <= 0) { 89 fired |= 1 << i; 90 memset(&deadline[i], 0, sizeof(deadline[i])); 91 } else if (next < 0 || left < next) { 92 next = left; 93 } 94 } 95 if (fired) 96 return fired; 97 ms = next < 0 ? -1 : (int)((next + 999999) / 1000000); 98 if (poll(&pfd, 1, ms) == -1) 99 return -1; 100 if (pfd.revents) 101 return 0; 102 } 103 } 104 #endif