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