2612fbdbc8ee4e9a6bce75bca8bb52f74199e6a1
[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 bool do_sigchld = false;
62
63 static struct uloop_fd_event cur_fds[ULOOP_MAX_EVENTS];
64 static int cur_fd, cur_nfds;
65
66 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags);
67
68 #ifdef USE_KQUEUE
69 #include "uloop-kqueue.c"
70 #endif
71
72 #ifdef USE_EPOLL
73 #include "uloop-epoll.c"
74 #endif
75
76 static void waker_consume(struct uloop_fd *fd, unsigned int events)
77 {
78         char buf[4];
79
80         while (read(fd->fd, buf, 4) > 0)
81                 ;
82 }
83
84 static int waker_pipe = -1;
85 static struct uloop_fd waker_fd = {
86         .fd = -1,
87         .cb = waker_consume,
88 };
89
90 static void waker_init_fd(int fd)
91 {
92         fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
93         fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
94 }
95
96 static int waker_init(void)
97 {
98         int fds[2];
99
100         if (waker_pipe >= 0)
101                 return 0;
102
103         if (pipe(fds) < 0)
104                 return -1;
105
106         waker_init_fd(fds[0]);
107         waker_init_fd(fds[1]);
108
109         waker_fd.fd = fds[0];
110         waker_fd.cb = waker_consume;
111         uloop_fd_add(&waker_fd, ULOOP_READ);
112
113         return 0;
114 }
115
116 int uloop_init(void)
117 {
118         if (uloop_init_pollfd() < 0)
119                 return -1;
120
121         if (waker_init() < 0) {
122                 uloop_done();
123                 return -1;
124         }
125
126         return 0;
127 }
128
129 static bool uloop_fd_stack_event(struct uloop_fd *fd, int events)
130 {
131         struct uloop_fd_stack *cur;
132
133         /*
134          * Do not buffer events for level-triggered fds, they will keep firing.
135          * Caller needs to take care of recursion issues.
136          */
137         if (!(fd->flags & ULOOP_EDGE_TRIGGER))
138                 return false;
139
140         for (cur = fd_stack; cur; cur = cur->next) {
141                 if (cur->fd != fd)
142                         continue;
143
144                 if (events < 0)
145                         cur->fd = NULL;
146                 else
147                         cur->events |= events | ULOOP_EVENT_BUFFERED;
148
149                 return true;
150         }
151
152         return false;
153 }
154
155 static void uloop_run_events(int timeout)
156 {
157         struct uloop_fd_event *cur;
158         struct uloop_fd *fd;
159
160         if (!cur_nfds) {
161                 cur_fd = 0;
162                 cur_nfds = uloop_fetch_events(timeout);
163                 if (cur_nfds < 0)
164                         cur_nfds = 0;
165         }
166
167         while (cur_nfds > 0) {
168                 struct uloop_fd_stack stack_cur;
169                 unsigned int events;
170
171                 cur = &cur_fds[cur_fd++];
172                 cur_nfds--;
173
174                 fd = cur->fd;
175                 events = cur->events;
176                 if (!fd)
177                         continue;
178
179                 if (!fd->cb)
180                         continue;
181
182                 if (uloop_fd_stack_event(fd, cur->events))
183                         continue;
184
185                 stack_cur.next = fd_stack;
186                 stack_cur.fd = fd;
187                 fd_stack = &stack_cur;
188                 do {
189                         stack_cur.events = 0;
190                         fd->cb(fd, events);
191                         events = stack_cur.events & ULOOP_EVENT_MASK;
192                 } while (stack_cur.fd && events);
193                 fd_stack = stack_cur.next;
194
195                 return;
196         }
197 }
198
199 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags)
200 {
201         unsigned int fl;
202         int ret;
203
204         if (!(flags & (ULOOP_READ | ULOOP_WRITE)))
205                 return uloop_fd_delete(sock);
206
207         if (!sock->registered && !(flags & ULOOP_BLOCKING)) {
208                 fl = fcntl(sock->fd, F_GETFL, 0);
209                 fl |= O_NONBLOCK;
210                 fcntl(sock->fd, F_SETFL, fl);
211         }
212
213         ret = register_poll(sock, flags);
214         if (ret < 0)
215                 goto out;
216
217         sock->registered = true;
218         sock->eof = false;
219         sock->error = false;
220
221 out:
222         return ret;
223 }
224
225 int uloop_fd_delete(struct uloop_fd *fd)
226 {
227         int i;
228
229         for (i = 0; i < cur_nfds; i++) {
230                 if (cur_fds[cur_fd + i].fd != fd)
231                         continue;
232
233                 cur_fds[cur_fd + i].fd = NULL;
234         }
235
236         if (!fd->registered)
237                 return 0;
238
239         fd->registered = false;
240         uloop_fd_stack_event(fd, -1);
241         return __uloop_fd_delete(fd);
242 }
243
244 static int tv_diff(struct timeval *t1, struct timeval *t2)
245 {
246         return
247                 (t1->tv_sec - t2->tv_sec) * 1000 +
248                 (t1->tv_usec - t2->tv_usec) / 1000;
249 }
250
251 int uloop_timeout_add(struct uloop_timeout *timeout)
252 {
253         struct uloop_timeout *tmp;
254         struct list_head *h = &timeouts;
255
256         if (timeout->pending)
257                 return -1;
258
259         list_for_each_entry(tmp, &timeouts, list) {
260                 if (tv_diff(&tmp->time, &timeout->time) > 0) {
261                         h = &tmp->list;
262                         break;
263                 }
264         }
265
266         list_add_tail(&timeout->list, h);
267         timeout->pending = true;
268
269         return 0;
270 }
271
272 static void uloop_gettime(struct timeval *tv)
273 {
274         struct timespec ts;
275
276         clock_gettime(CLOCK_MONOTONIC, &ts);
277         tv->tv_sec = ts.tv_sec;
278         tv->tv_usec = ts.tv_nsec / 1000;
279 }
280
281 int uloop_timeout_set(struct uloop_timeout *timeout, int msecs)
282 {
283         struct timeval *time = &timeout->time;
284
285         if (timeout->pending)
286                 uloop_timeout_cancel(timeout);
287
288         uloop_gettime(time);
289
290         time->tv_sec += msecs / 1000;
291         time->tv_usec += (msecs % 1000) * 1000;
292
293         if (time->tv_usec > 1000000) {
294                 time->tv_sec++;
295                 time->tv_usec -= 1000000;
296         }
297
298         return uloop_timeout_add(timeout);
299 }
300
301 int uloop_timeout_cancel(struct uloop_timeout *timeout)
302 {
303         if (!timeout->pending)
304                 return -1;
305
306         list_del(&timeout->list);
307         timeout->pending = false;
308
309         return 0;
310 }
311
312 int uloop_timeout_remaining(struct uloop_timeout *timeout)
313 {
314         struct timeval now;
315
316         if (!timeout->pending)
317                 return -1;
318
319         uloop_gettime(&now);
320
321         return tv_diff(&timeout->time, &now);
322 }
323
324 int uloop_process_add(struct uloop_process *p)
325 {
326         struct uloop_process *tmp;
327         struct list_head *h = &processes;
328
329         if (p->pending)
330                 return -1;
331
332         list_for_each_entry(tmp, &processes, list) {
333                 if (tmp->pid > p->pid) {
334                         h = &tmp->list;
335                         break;
336                 }
337         }
338
339         list_add_tail(&p->list, h);
340         p->pending = true;
341
342         return 0;
343 }
344
345 int uloop_process_delete(struct uloop_process *p)
346 {
347         if (!p->pending)
348                 return -1;
349
350         list_del(&p->list);
351         p->pending = false;
352
353         return 0;
354 }
355
356 static void uloop_handle_processes(void)
357 {
358         struct uloop_process *p, *tmp;
359         pid_t pid;
360         int ret;
361
362         do_sigchld = false;
363
364         while (1) {
365                 pid = waitpid(-1, &ret, WNOHANG);
366                 if (pid < 0 && errno == EINTR)
367                         continue;
368
369                 if (pid <= 0)
370                         return;
371
372                 list_for_each_entry_safe(p, tmp, &processes, list) {
373                         if (p->pid < pid)
374                                 continue;
375
376                         if (p->pid > pid)
377                                 break;
378
379                         uloop_process_delete(p);
380                         p->cb(p, ret);
381                 }
382         }
383
384 }
385
386 static void uloop_signal_wake(void)
387 {
388         write(waker_pipe, "w", 1);
389 }
390
391 static void uloop_handle_sigint(int signo)
392 {
393         uloop_cancelled = true;
394         uloop_signal_wake();
395 }
396
397 static void uloop_sigchld(int signo)
398 {
399         do_sigchld = true;
400         uloop_signal_wake();
401 }
402
403 static void uloop_install_handler(int signum, void (*handler)(int), struct sigaction* old, bool add)
404 {
405         struct sigaction s;
406         struct sigaction *act;
407
408         act = NULL;
409         sigaction(signum, NULL, &s);
410
411         if (add) {
412                 if (s.sa_handler == SIG_DFL) { /* Do not override existing custom signal handlers */
413                         memcpy(old, &s, sizeof(struct sigaction));
414                         s.sa_handler = handler;
415                         s.sa_flags = 0;
416                         act = &s;
417                 }
418         }
419         else if (s.sa_handler == handler) { /* Do not restore if someone modified our handler */
420                         act = old;
421         }
422
423         if (act != NULL)
424                 sigaction(signum, act, NULL);
425 }
426
427 static void uloop_ignore_signal(int signum, bool ignore)
428 {
429         struct sigaction s;
430         void *new_handler = NULL;
431
432         sigaction(signum, NULL, &s);
433
434         if (ignore) {
435                 if (s.sa_handler == SIG_DFL) /* Ignore only if there isn't any custom handler */
436                         new_handler = SIG_IGN;
437         } else {
438                 if (s.sa_handler == SIG_IGN) /* Restore only if noone modified our SIG_IGN */
439                         new_handler = SIG_DFL;
440         }
441
442         if (new_handler) {
443                 s.sa_handler = new_handler;
444                 s.sa_flags = 0;
445                 sigaction(signum, &s, NULL);
446         }
447 }
448
449 static void uloop_setup_signals(bool add)
450 {
451         static struct sigaction old_sigint, old_sigchld, old_sigterm;
452
453         uloop_install_handler(SIGINT, uloop_handle_sigint, &old_sigint, add);
454         uloop_install_handler(SIGTERM, uloop_handle_sigint, &old_sigterm, add);
455         uloop_install_handler(SIGCHLD, uloop_sigchld, &old_sigchld, add);
456
457         uloop_ignore_signal(SIGPIPE, add);
458 }
459
460 static int uloop_get_next_timeout(struct timeval *tv)
461 {
462         struct uloop_timeout *timeout;
463         int diff;
464
465         if (list_empty(&timeouts))
466                 return -1;
467
468         timeout = list_first_entry(&timeouts, struct uloop_timeout, list);
469         diff = tv_diff(&timeout->time, tv);
470         if (diff < 0)
471                 return 0;
472
473         return diff;
474 }
475
476 static void uloop_process_timeouts(struct timeval *tv)
477 {
478         struct uloop_timeout *t;
479
480         while (!list_empty(&timeouts)) {
481                 t = list_first_entry(&timeouts, struct uloop_timeout, list);
482
483                 if (tv_diff(&t->time, tv) > 0)
484                         break;
485
486                 uloop_timeout_cancel(t);
487                 if (t->cb)
488                         t->cb(t);
489         }
490 }
491
492 static void uloop_clear_timeouts(void)
493 {
494         struct uloop_timeout *t, *tmp;
495
496         list_for_each_entry_safe(t, tmp, &timeouts, list)
497                 uloop_timeout_cancel(t);
498 }
499
500 static void uloop_clear_processes(void)
501 {
502         struct uloop_process *p, *tmp;
503
504         list_for_each_entry_safe(p, tmp, &processes, list)
505                 uloop_process_delete(p);
506 }
507
508 void uloop_run(void)
509 {
510         static int recursive_calls = 0;
511         struct timeval tv;
512
513         /*
514          * Handlers are only updated for the first call to uloop_run() (and restored
515          * when this call is done).
516          */
517         if (!recursive_calls++)
518                 uloop_setup_signals(true);
519
520         uloop_cancelled = false;
521         while(!uloop_cancelled)
522         {
523                 uloop_gettime(&tv);
524                 uloop_process_timeouts(&tv);
525
526                 if (do_sigchld)
527                         uloop_handle_processes();
528
529                 if (uloop_cancelled)
530                         break;
531
532                 uloop_gettime(&tv);
533                 uloop_run_events(uloop_get_next_timeout(&tv));
534         }
535
536         if (!--recursive_calls)
537                 uloop_setup_signals(false);
538 }
539
540 void uloop_done(void)
541 {
542         if (poll_fd >= 0) {
543                 close(poll_fd);
544                 poll_fd = -1;
545         }
546
547         if (waker_pipe >= 0) {
548                 uloop_fd_delete(&waker_fd);
549                 close(waker_pipe);
550                 close(waker_fd.fd);
551                 waker_pipe = -1;
552         }
553
554         uloop_clear_timeouts();
555         uloop_clear_processes();
556 }