uloop: fix a regression in timeout handling
[project/libubox.git] / uloop.c
1 /*
2  * uloop - event loop implementation
3  *
4  * Copyright (C) 2010-2016 Felix Fietkau <nbd@openwrt.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #include <sys/time.h>
19 #include <sys/types.h>
20
21 #include <unistd.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <errno.h>
25 #include <poll.h>
26 #include <string.h>
27 #include <fcntl.h>
28 #include <stdbool.h>
29
30 #include "uloop.h"
31 #include "utils.h"
32
33 #ifdef USE_KQUEUE
34 #include <sys/event.h>
35 #endif
36 #ifdef USE_EPOLL
37 #include <sys/epoll.h>
38 #endif
39 #include <sys/wait.h>
40
41 struct uloop_fd_event {
42         struct uloop_fd *fd;
43         unsigned int events;
44 };
45
46 struct uloop_fd_stack {
47         struct uloop_fd_stack *next;
48         struct uloop_fd *fd;
49         unsigned int events;
50 };
51
52 static struct uloop_fd_stack *fd_stack = NULL;
53
54 #define ULOOP_MAX_EVENTS 10
55
56 static struct list_head timeouts = LIST_HEAD_INIT(timeouts);
57 static struct list_head processes = LIST_HEAD_INIT(processes);
58
59 static int poll_fd = -1;
60 bool uloop_cancelled = false;
61 static int uloop_status = 0;
62 static bool do_sigchld = false;
63
64 static struct uloop_fd_event cur_fds[ULOOP_MAX_EVENTS];
65 static int cur_fd, cur_nfds;
66 static int uloop_run_depth = 0;
67
68 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags);
69
70 #ifdef USE_KQUEUE
71 #include "uloop-kqueue.c"
72 #endif
73
74 #ifdef USE_EPOLL
75 #include "uloop-epoll.c"
76 #endif
77
78 static void waker_consume(struct uloop_fd *fd, unsigned int events)
79 {
80         char buf[4];
81
82         while (read(fd->fd, buf, 4) > 0)
83                 ;
84 }
85
86 static int waker_pipe = -1;
87 static struct uloop_fd waker_fd = {
88         .fd = -1,
89         .cb = waker_consume,
90 };
91
92 static void waker_init_fd(int fd)
93 {
94         fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
95         fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
96 }
97
98 static int waker_init(void)
99 {
100         int fds[2];
101
102         if (waker_pipe >= 0)
103                 return 0;
104
105         if (pipe(fds) < 0)
106                 return -1;
107
108         waker_init_fd(fds[0]);
109         waker_init_fd(fds[1]);
110         waker_pipe = fds[1];
111
112         waker_fd.fd = fds[0];
113         waker_fd.cb = waker_consume;
114         uloop_fd_add(&waker_fd, ULOOP_READ);
115
116         return 0;
117 }
118
119 int uloop_init(void)
120 {
121         if (uloop_init_pollfd() < 0)
122                 return -1;
123
124         if (waker_init() < 0) {
125                 uloop_done();
126                 return -1;
127         }
128
129         return 0;
130 }
131
132 static bool uloop_fd_stack_event(struct uloop_fd *fd, int events)
133 {
134         struct uloop_fd_stack *cur;
135
136         /*
137          * Do not buffer events for level-triggered fds, they will keep firing.
138          * Caller needs to take care of recursion issues.
139          */
140         if (!(fd->flags & ULOOP_EDGE_TRIGGER))
141                 return false;
142
143         for (cur = fd_stack; cur; cur = cur->next) {
144                 if (cur->fd != fd)
145                         continue;
146
147                 if (events < 0)
148                         cur->fd = NULL;
149                 else
150                         cur->events |= events | ULOOP_EVENT_BUFFERED;
151
152                 return true;
153         }
154
155         return false;
156 }
157
158 static void uloop_run_events(int timeout)
159 {
160         struct uloop_fd_event *cur;
161         struct uloop_fd *fd;
162
163         if (!cur_nfds) {
164                 cur_fd = 0;
165                 cur_nfds = uloop_fetch_events(timeout);
166                 if (cur_nfds < 0)
167                         cur_nfds = 0;
168         }
169
170         while (cur_nfds > 0) {
171                 struct uloop_fd_stack stack_cur;
172                 unsigned int events;
173
174                 cur = &cur_fds[cur_fd++];
175                 cur_nfds--;
176
177                 fd = cur->fd;
178                 events = cur->events;
179                 if (!fd)
180                         continue;
181
182                 if (!fd->cb)
183                         continue;
184
185                 if (uloop_fd_stack_event(fd, cur->events))
186                         continue;
187
188                 stack_cur.next = fd_stack;
189                 stack_cur.fd = fd;
190                 fd_stack = &stack_cur;
191                 do {
192                         stack_cur.events = 0;
193                         fd->cb(fd, events);
194                         events = stack_cur.events & ULOOP_EVENT_MASK;
195                 } while (stack_cur.fd && events);
196                 fd_stack = stack_cur.next;
197
198                 return;
199         }
200 }
201
202 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags)
203 {
204         unsigned int fl;
205         int ret;
206
207         if (!(flags & (ULOOP_READ | ULOOP_WRITE)))
208                 return uloop_fd_delete(sock);
209
210         if (!sock->registered && !(flags & ULOOP_BLOCKING)) {
211                 fl = fcntl(sock->fd, F_GETFL, 0);
212                 fl |= O_NONBLOCK;
213                 fcntl(sock->fd, F_SETFL, fl);
214         }
215
216         ret = register_poll(sock, flags);
217         if (ret < 0)
218                 goto out;
219
220         sock->registered = true;
221         sock->eof = false;
222         sock->error = false;
223
224 out:
225         return ret;
226 }
227
228 int uloop_fd_delete(struct uloop_fd *fd)
229 {
230         int i;
231
232         for (i = 0; i < cur_nfds; i++) {
233                 if (cur_fds[cur_fd + i].fd != fd)
234                         continue;
235
236                 cur_fds[cur_fd + i].fd = NULL;
237         }
238
239         if (!fd->registered)
240                 return 0;
241
242         fd->registered = false;
243         uloop_fd_stack_event(fd, -1);
244         return __uloop_fd_delete(fd);
245 }
246
247 static int tv_diff(struct timeval *t1, struct timeval *t2)
248 {
249         return
250                 (t1->tv_sec - t2->tv_sec) * 1000 +
251                 (t1->tv_usec - t2->tv_usec) / 1000;
252 }
253
254 int uloop_timeout_add(struct uloop_timeout *timeout)
255 {
256         struct uloop_timeout *tmp;
257         struct list_head *h = &timeouts;
258
259         if (timeout->pending)
260                 return -1;
261
262         list_for_each_entry(tmp, &timeouts, list) {
263                 if (tv_diff(&tmp->time, &timeout->time) > 0) {
264                         h = &tmp->list;
265                         break;
266                 }
267         }
268
269         list_add_tail(&timeout->list, h);
270         timeout->pending = true;
271
272         return 0;
273 }
274
275 static void uloop_gettime(struct timeval *tv)
276 {
277         struct timespec ts;
278
279         clock_gettime(CLOCK_MONOTONIC, &ts);
280         tv->tv_sec = ts.tv_sec;
281         tv->tv_usec = ts.tv_nsec / 1000;
282 }
283
284 int uloop_timeout_set(struct uloop_timeout *timeout, int msecs)
285 {
286         struct timeval *time = &timeout->time;
287
288         if (timeout->pending)
289                 uloop_timeout_cancel(timeout);
290
291         uloop_gettime(time);
292
293         time->tv_sec += msecs / 1000;
294         time->tv_usec += (msecs % 1000) * 1000;
295
296         if (time->tv_usec > 1000000) {
297                 time->tv_sec++;
298                 time->tv_usec -= 1000000;
299         }
300
301         return uloop_timeout_add(timeout);
302 }
303
304 int uloop_timeout_cancel(struct uloop_timeout *timeout)
305 {
306         if (!timeout->pending)
307                 return -1;
308
309         list_del(&timeout->list);
310         timeout->pending = false;
311
312         return 0;
313 }
314
315 int uloop_timeout_remaining(struct uloop_timeout *timeout)
316 {
317         struct timeval now;
318
319         if (!timeout->pending)
320                 return -1;
321
322         uloop_gettime(&now);
323
324         return tv_diff(&timeout->time, &now);
325 }
326
327 int uloop_process_add(struct uloop_process *p)
328 {
329         struct uloop_process *tmp;
330         struct list_head *h = &processes;
331
332         if (p->pending)
333                 return -1;
334
335         list_for_each_entry(tmp, &processes, list) {
336                 if (tmp->pid > p->pid) {
337                         h = &tmp->list;
338                         break;
339                 }
340         }
341
342         list_add_tail(&p->list, h);
343         p->pending = true;
344
345         return 0;
346 }
347
348 int uloop_process_delete(struct uloop_process *p)
349 {
350         if (!p->pending)
351                 return -1;
352
353         list_del(&p->list);
354         p->pending = false;
355
356         return 0;
357 }
358
359 static void uloop_handle_processes(void)
360 {
361         struct uloop_process *p, *tmp;
362         pid_t pid;
363         int ret;
364
365         do_sigchld = false;
366
367         while (1) {
368                 pid = waitpid(-1, &ret, WNOHANG);
369                 if (pid < 0 && errno == EINTR)
370                         continue;
371
372                 if (pid <= 0)
373                         return;
374
375                 list_for_each_entry_safe(p, tmp, &processes, list) {
376                         if (p->pid < pid)
377                                 continue;
378
379                         if (p->pid > pid)
380                                 break;
381
382                         uloop_process_delete(p);
383                         p->cb(p, ret);
384                 }
385         }
386
387 }
388
389 static void uloop_signal_wake(void)
390 {
391         do {
392                 if (write(waker_pipe, "w", 1) < 0) {
393                         if (errno == EINTR)
394                                 continue;
395                 }
396                 break;
397         } while (1);
398 }
399
400 static void uloop_handle_sigint(int signo)
401 {
402         uloop_status = signo;
403         uloop_cancelled = true;
404         uloop_signal_wake();
405 }
406
407 static void uloop_sigchld(int signo)
408 {
409         do_sigchld = true;
410         uloop_signal_wake();
411 }
412
413 static void uloop_install_handler(int signum, void (*handler)(int), struct sigaction* old, bool add)
414 {
415         struct sigaction s;
416         struct sigaction *act;
417
418         act = NULL;
419         sigaction(signum, NULL, &s);
420
421         if (add) {
422                 if (s.sa_handler == SIG_DFL) { /* Do not override existing custom signal handlers */
423                         memcpy(old, &s, sizeof(struct sigaction));
424                         s.sa_handler = handler;
425                         s.sa_flags = 0;
426                         act = &s;
427                 }
428         }
429         else if (s.sa_handler == handler) { /* Do not restore if someone modified our handler */
430                         act = old;
431         }
432
433         if (act != NULL)
434                 sigaction(signum, act, NULL);
435 }
436
437 static void uloop_ignore_signal(int signum, bool ignore)
438 {
439         struct sigaction s;
440         void *new_handler = NULL;
441
442         sigaction(signum, NULL, &s);
443
444         if (ignore) {
445                 if (s.sa_handler == SIG_DFL) /* Ignore only if there isn't any custom handler */
446                         new_handler = SIG_IGN;
447         } else {
448                 if (s.sa_handler == SIG_IGN) /* Restore only if noone modified our SIG_IGN */
449                         new_handler = SIG_DFL;
450         }
451
452         if (new_handler) {
453                 s.sa_handler = new_handler;
454                 s.sa_flags = 0;
455                 sigaction(signum, &s, NULL);
456         }
457 }
458
459 static void uloop_setup_signals(bool add)
460 {
461         static struct sigaction old_sigint, old_sigchld, old_sigterm;
462
463         uloop_install_handler(SIGINT, uloop_handle_sigint, &old_sigint, add);
464         uloop_install_handler(SIGTERM, uloop_handle_sigint, &old_sigterm, add);
465         uloop_install_handler(SIGCHLD, uloop_sigchld, &old_sigchld, add);
466
467         uloop_ignore_signal(SIGPIPE, add);
468 }
469
470 static int uloop_get_next_timeout(struct timeval *tv)
471 {
472         struct uloop_timeout *timeout;
473         int diff;
474
475         if (list_empty(&timeouts))
476                 return -1;
477
478         timeout = list_first_entry(&timeouts, struct uloop_timeout, list);
479         diff = tv_diff(&timeout->time, tv);
480         if (diff < 0)
481                 return 0;
482
483         return diff;
484 }
485
486 static void uloop_process_timeouts(struct timeval *tv)
487 {
488         struct uloop_timeout *t;
489
490         while (!list_empty(&timeouts)) {
491                 t = list_first_entry(&timeouts, struct uloop_timeout, list);
492
493                 if (tv_diff(&t->time, tv) > 0)
494                         break;
495
496                 uloop_timeout_cancel(t);
497                 if (t->cb)
498                         t->cb(t);
499         }
500 }
501
502 static void uloop_clear_timeouts(void)
503 {
504         struct uloop_timeout *t, *tmp;
505
506         list_for_each_entry_safe(t, tmp, &timeouts, list)
507                 uloop_timeout_cancel(t);
508 }
509
510 static void uloop_clear_processes(void)
511 {
512         struct uloop_process *p, *tmp;
513
514         list_for_each_entry_safe(p, tmp, &processes, list)
515                 uloop_process_delete(p);
516 }
517
518 bool uloop_cancelling(void)
519 {
520         return uloop_run_depth > 0 && uloop_cancelled;
521 }
522
523 int uloop_run_timeout(int timeout)
524 {
525         int next_time = 0;
526         struct timeval tv;
527
528         /*
529          * Handlers are only updated for the first call to uloop_run() (and restored
530          * when this call is done).
531          */
532         if (!uloop_run_depth++)
533                 uloop_setup_signals(true);
534
535         uloop_status = 0;
536         uloop_cancelled = false;
537         while (!uloop_cancelled)
538         {
539                 uloop_gettime(&tv);
540                 uloop_process_timeouts(&tv);
541
542                 if (do_sigchld)
543                         uloop_handle_processes();
544
545                 if (uloop_cancelled)
546                         break;
547
548                 uloop_gettime(&tv);
549
550                 next_time = uloop_get_next_timeout(&tv);
551                 if (timeout > 0 && timeout < next_time)
552                         next_time = timeout;
553                 uloop_run_events(next_time);
554         }
555
556         if (!--uloop_run_depth)
557                 uloop_setup_signals(false);
558
559         return uloop_status;
560 }
561
562 void uloop_done(void)
563 {
564         if (poll_fd >= 0) {
565                 close(poll_fd);
566                 poll_fd = -1;
567         }
568
569         if (waker_pipe >= 0) {
570                 uloop_fd_delete(&waker_fd);
571                 close(waker_pipe);
572                 close(waker_fd.fd);
573                 waker_pipe = -1;
574         }
575
576         uloop_clear_timeouts();
577         uloop_clear_processes();
578 }