uloop: Add flag to allow callback to be called on error conditions.
[project/libubox.git] / uloop.c
1 /*
2  * uloop - event loop implementation
3  *
4  * Copyright (C) 2010-2013 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 bool uloop_handle_sigchld = true;
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
67 #ifdef USE_KQUEUE
68
69 int uloop_init(void)
70 {
71         struct timespec timeout = { 0, 0 };
72         struct kevent ev = {};
73
74         if (poll_fd >= 0)
75                 return 0;
76
77         poll_fd = kqueue();
78         if (poll_fd < 0)
79                 return -1;
80
81         EV_SET(&ev, SIGCHLD, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
82         kevent(poll_fd, &ev, 1, NULL, 0, &timeout);
83
84         return 0;
85 }
86
87
88 static uint16_t get_flags(unsigned int flags, unsigned int mask)
89 {
90         uint16_t kflags = 0;
91
92         if (!(flags & mask))
93                 return EV_DELETE;
94
95         kflags = EV_ADD;
96         if (flags & ULOOP_EDGE_TRIGGER)
97                 kflags |= EV_CLEAR;
98
99         return kflags;
100 }
101
102 static struct kevent events[ULOOP_MAX_EVENTS];
103
104 static int register_kevent(struct uloop_fd *fd, unsigned int flags)
105 {
106         struct timespec timeout = { 0, 0 };
107         struct kevent ev[2];
108         int nev = 0;
109         unsigned int fl = 0;
110         unsigned int changed;
111         uint16_t kflags;
112
113         if (flags & ULOOP_EDGE_DEFER)
114                 flags &= ~ULOOP_EDGE_TRIGGER;
115
116         changed = flags ^ fd->flags;
117         if (changed & ULOOP_EDGE_TRIGGER)
118                 changed |= flags;
119
120         if (changed & ULOOP_READ) {
121                 kflags = get_flags(flags, ULOOP_READ);
122                 EV_SET(&ev[nev++], fd->fd, EVFILT_READ, kflags, 0, 0, fd);
123         }
124
125         if (changed & ULOOP_WRITE) {
126                 kflags = get_flags(flags, ULOOP_WRITE);
127                 EV_SET(&ev[nev++], fd->fd, EVFILT_WRITE, kflags, 0, 0, fd);
128         }
129
130         if (!flags)
131                 fl |= EV_DELETE;
132
133         fd->flags = flags;
134         if (kevent(poll_fd, ev, nev, NULL, fl, &timeout) == -1)
135                 return -1;
136
137         return 0;
138 }
139
140 static int register_poll(struct uloop_fd *fd, unsigned int flags)
141 {
142         if (flags & ULOOP_EDGE_TRIGGER)
143                 flags |= ULOOP_EDGE_DEFER;
144         else
145                 flags &= ~ULOOP_EDGE_DEFER;
146
147         return register_kevent(fd, flags);
148 }
149
150 static int __uloop_fd_delete(struct uloop_fd *fd)
151 {
152         return register_poll(fd, 0);
153 }
154
155 static int uloop_fetch_events(int timeout)
156 {
157         struct timespec ts;
158         int nfds, n;
159
160         if (timeout >= 0) {
161                 ts.tv_sec = timeout / 1000;
162                 ts.tv_nsec = (timeout % 1000) * 1000000;
163         }
164
165         nfds = kevent(poll_fd, NULL, 0, events, ARRAY_SIZE(events), timeout >= 0 ? &ts : NULL);
166         for (n = 0; n < nfds; n++) {
167                 struct uloop_fd_event *cur = &cur_fds[n];
168                 struct uloop_fd *u = events[n].udata;
169                 unsigned int ev = 0;
170
171                 cur->fd = u;
172                 if (!u)
173                         continue;
174
175                 if (events[n].flags & EV_ERROR) {
176                         u->error = true;
177                         if (!(u->flags & ULOOP_ERROR_CB))
178                                 uloop_fd_delete(u);
179                 }
180
181                 if(events[n].filter == EVFILT_READ)
182                         ev |= ULOOP_READ;
183                 else if (events[n].filter == EVFILT_WRITE)
184                         ev |= ULOOP_WRITE;
185
186                 if (events[n].flags & EV_EOF)
187                         u->eof = true;
188                 else if (!ev)
189                         cur->fd = NULL;
190
191                 cur->events = ev;
192                 if (u->flags & ULOOP_EDGE_DEFER) {
193                         u->flags &= ~ULOOP_EDGE_DEFER;
194                         u->flags |= ULOOP_EDGE_TRIGGER;
195                         register_kevent(u, u->flags);
196                 }
197         }
198         return nfds;
199 }
200
201 #endif
202
203 #ifdef USE_EPOLL
204
205 /**
206  * FIXME: uClibc < 0.9.30.3 does not define EPOLLRDHUP for Linux >= 2.6.17
207  */
208 #ifndef EPOLLRDHUP
209 #define EPOLLRDHUP 0x2000
210 #endif
211
212 int uloop_init(void)
213 {
214         if (poll_fd >= 0)
215                 return 0;
216
217         poll_fd = epoll_create(32);
218         if (poll_fd < 0)
219                 return -1;
220
221         fcntl(poll_fd, F_SETFD, fcntl(poll_fd, F_GETFD) | FD_CLOEXEC);
222         return 0;
223 }
224
225 static int register_poll(struct uloop_fd *fd, unsigned int flags)
226 {
227         struct epoll_event ev;
228         int op = fd->registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD;
229
230         memset(&ev, 0, sizeof(struct epoll_event));
231
232         if (flags & ULOOP_READ)
233                 ev.events |= EPOLLIN | EPOLLRDHUP;
234
235         if (flags & ULOOP_WRITE)
236                 ev.events |= EPOLLOUT;
237
238         if (flags & ULOOP_EDGE_TRIGGER)
239                 ev.events |= EPOLLET;
240
241         ev.data.fd = fd->fd;
242         ev.data.ptr = fd;
243         fd->flags = flags;
244
245         return epoll_ctl(poll_fd, op, fd->fd, &ev);
246 }
247
248 static struct epoll_event events[ULOOP_MAX_EVENTS];
249
250 static int __uloop_fd_delete(struct uloop_fd *sock)
251 {
252         sock->flags = 0;
253         return epoll_ctl(poll_fd, EPOLL_CTL_DEL, sock->fd, 0);
254 }
255
256 static int uloop_fetch_events(int timeout)
257 {
258         int n, nfds;
259
260         nfds = epoll_wait(poll_fd, events, ARRAY_SIZE(events), timeout);
261         for (n = 0; n < nfds; ++n) {
262                 struct uloop_fd_event *cur = &cur_fds[n];
263                 struct uloop_fd *u = events[n].data.ptr;
264                 unsigned int ev = 0;
265
266                 cur->fd = u;
267                 if (!u)
268                         continue;
269
270                 if (events[n].events & (EPOLLERR|EPOLLHUP)) {
271                         u->error = true;
272                         if (!(u->flags & ULOOP_ERROR_CB))
273                                 uloop_fd_delete(u);
274                 }
275
276                 if(!(events[n].events & (EPOLLRDHUP|EPOLLIN|EPOLLOUT|EPOLLERR|EPOLLHUP))) {
277                         cur->fd = NULL;
278                         continue;
279                 }
280
281                 if(events[n].events & EPOLLRDHUP)
282                         u->eof = true;
283
284                 if(events[n].events & EPOLLIN)
285                         ev |= ULOOP_READ;
286
287                 if(events[n].events & EPOLLOUT)
288                         ev |= ULOOP_WRITE;
289
290                 cur->events = ev;
291         }
292
293         return nfds;
294 }
295
296 #endif
297
298 static bool uloop_fd_stack_event(struct uloop_fd *fd, int events)
299 {
300         struct uloop_fd_stack *cur;
301
302         /*
303          * Do not buffer events for level-triggered fds, they will keep firing.
304          * Caller needs to take care of recursion issues.
305          */
306         if (!(fd->flags & ULOOP_EDGE_TRIGGER))
307                 return false;
308
309         for (cur = fd_stack; cur; cur = cur->next) {
310                 if (cur->fd != fd)
311                         continue;
312
313                 if (events < 0)
314                         cur->fd = NULL;
315                 else
316                         cur->events |= events | ULOOP_EVENT_BUFFERED;
317
318                 return true;
319         }
320
321         return false;
322 }
323
324 static void uloop_run_events(int timeout)
325 {
326         struct uloop_fd_event *cur;
327         struct uloop_fd *fd;
328
329         if (!cur_nfds) {
330                 cur_fd = 0;
331                 cur_nfds = uloop_fetch_events(timeout);
332                 if (cur_nfds < 0)
333                         cur_nfds = 0;
334         }
335
336         while (cur_nfds > 0) {
337                 struct uloop_fd_stack stack_cur;
338                 unsigned int events;
339
340                 cur = &cur_fds[cur_fd++];
341                 cur_nfds--;
342
343                 fd = cur->fd;
344                 events = cur->events;
345                 if (!fd)
346                         continue;
347
348                 if (!fd->cb)
349                         continue;
350
351                 if (uloop_fd_stack_event(fd, cur->events))
352                         continue;
353
354                 stack_cur.next = fd_stack;
355                 stack_cur.fd = fd;
356                 fd_stack = &stack_cur;
357                 do {
358                         stack_cur.events = 0;
359                         fd->cb(fd, events);
360                         events = stack_cur.events & ULOOP_EVENT_MASK;
361                 } while (stack_cur.fd && events);
362                 fd_stack = stack_cur.next;
363
364                 return;
365         }
366 }
367
368 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags)
369 {
370         unsigned int fl;
371         int ret;
372
373         if (!(flags & (ULOOP_READ | ULOOP_WRITE)))
374                 return uloop_fd_delete(sock);
375
376         if (!sock->registered && !(flags & ULOOP_BLOCKING)) {
377                 fl = fcntl(sock->fd, F_GETFL, 0);
378                 fl |= O_NONBLOCK;
379                 fcntl(sock->fd, F_SETFL, fl);
380         }
381
382         ret = register_poll(sock, flags);
383         if (ret < 0)
384                 goto out;
385
386         sock->registered = true;
387         sock->eof = false;
388
389 out:
390         return ret;
391 }
392
393 int uloop_fd_delete(struct uloop_fd *fd)
394 {
395         int i;
396
397         for (i = 0; i < cur_nfds; i++) {
398                 if (cur_fds[cur_fd + i].fd != fd)
399                         continue;
400
401                 cur_fds[cur_fd + i].fd = NULL;
402         }
403
404         if (!fd->registered)
405                 return 0;
406
407         fd->registered = false;
408         uloop_fd_stack_event(fd, -1);
409         return __uloop_fd_delete(fd);
410 }
411
412 static int tv_diff(struct timeval *t1, struct timeval *t2)
413 {
414         return
415                 (t1->tv_sec - t2->tv_sec) * 1000 +
416                 (t1->tv_usec - t2->tv_usec) / 1000;
417 }
418
419 int uloop_timeout_add(struct uloop_timeout *timeout)
420 {
421         struct uloop_timeout *tmp;
422         struct list_head *h = &timeouts;
423
424         if (timeout->pending)
425                 return -1;
426
427         list_for_each_entry(tmp, &timeouts, list) {
428                 if (tv_diff(&tmp->time, &timeout->time) > 0) {
429                         h = &tmp->list;
430                         break;
431                 }
432         }
433
434         list_add_tail(&timeout->list, h);
435         timeout->pending = true;
436
437         return 0;
438 }
439
440 static void uloop_gettime(struct timeval *tv)
441 {
442         struct timespec ts;
443
444         clock_gettime(CLOCK_MONOTONIC, &ts);
445         tv->tv_sec = ts.tv_sec;
446         tv->tv_usec = ts.tv_nsec / 1000;
447 }
448
449 int uloop_timeout_set(struct uloop_timeout *timeout, int msecs)
450 {
451         struct timeval *time = &timeout->time;
452
453         if (timeout->pending)
454                 uloop_timeout_cancel(timeout);
455
456         uloop_gettime(&timeout->time);
457
458         time->tv_sec += msecs / 1000;
459         time->tv_usec += (msecs % 1000) * 1000;
460
461         if (time->tv_usec > 1000000) {
462                 time->tv_sec++;
463                 time->tv_usec %= 1000000;
464         }
465
466         return uloop_timeout_add(timeout);
467 }
468
469 int uloop_timeout_cancel(struct uloop_timeout *timeout)
470 {
471         if (!timeout->pending)
472                 return -1;
473
474         list_del(&timeout->list);
475         timeout->pending = false;
476
477         return 0;
478 }
479
480 int uloop_timeout_remaining(struct uloop_timeout *timeout)
481 {
482         struct timeval now;
483
484         if (!timeout->pending)
485                 return -1;
486
487         uloop_gettime(&now);
488
489         return tv_diff(&timeout->time, &now);
490 }
491
492 int uloop_process_add(struct uloop_process *p)
493 {
494         struct uloop_process *tmp;
495         struct list_head *h = &processes;
496
497         if (p->pending)
498                 return -1;
499
500         list_for_each_entry(tmp, &processes, list) {
501                 if (tmp->pid > p->pid) {
502                         h = &tmp->list;
503                         break;
504                 }
505         }
506
507         list_add_tail(&p->list, h);
508         p->pending = true;
509
510         return 0;
511 }
512
513 int uloop_process_delete(struct uloop_process *p)
514 {
515         if (!p->pending)
516                 return -1;
517
518         list_del(&p->list);
519         p->pending = false;
520
521         return 0;
522 }
523
524 static void uloop_handle_processes(void)
525 {
526         struct uloop_process *p, *tmp;
527         pid_t pid;
528         int ret;
529
530         do_sigchld = false;
531
532         while (1) {
533                 pid = waitpid(-1, &ret, WNOHANG);
534                 if (pid <= 0)
535                         return;
536
537                 list_for_each_entry_safe(p, tmp, &processes, list) {
538                         if (p->pid < pid)
539                                 continue;
540
541                         if (p->pid > pid)
542                                 break;
543
544                         uloop_process_delete(p);
545                         p->cb(p, ret);
546                 }
547         }
548
549 }
550
551 static void uloop_handle_sigint(int signo)
552 {
553         uloop_cancelled = true;
554 }
555
556 static void uloop_sigchld(int signo)
557 {
558         do_sigchld = true;
559 }
560
561 static void uloop_setup_signals(bool add)
562 {
563         static struct sigaction old_sigint, old_sigchld;
564         struct sigaction s;
565
566         memset(&s, 0, sizeof(struct sigaction));
567
568         if (add) {
569                 s.sa_handler = uloop_handle_sigint;
570                 s.sa_flags = 0;
571         } else {
572                 s = old_sigint;
573         }
574
575         sigaction(SIGINT, &s, &old_sigint);
576
577         if (!uloop_handle_sigchld)
578                 return;
579
580         if (add)
581                 s.sa_handler = uloop_sigchld;
582         else
583                 s = old_sigchld;
584
585         sigaction(SIGCHLD, &s, &old_sigchld);
586 }
587
588 static int uloop_get_next_timeout(struct timeval *tv)
589 {
590         struct uloop_timeout *timeout;
591         int diff;
592
593         if (list_empty(&timeouts))
594                 return -1;
595
596         timeout = list_first_entry(&timeouts, struct uloop_timeout, list);
597         diff = tv_diff(&timeout->time, tv);
598         if (diff < 0)
599                 return 0;
600
601         return diff;
602 }
603
604 static void uloop_process_timeouts(struct timeval *tv)
605 {
606         struct uloop_timeout *t;
607
608         while (!list_empty(&timeouts)) {
609                 t = list_first_entry(&timeouts, struct uloop_timeout, list);
610
611                 if (tv_diff(&t->time, tv) > 0)
612                         break;
613
614                 uloop_timeout_cancel(t);
615                 if (t->cb)
616                         t->cb(t);
617         }
618 }
619
620 static void uloop_clear_timeouts(void)
621 {
622         struct uloop_timeout *t, *tmp;
623
624         list_for_each_entry_safe(t, tmp, &timeouts, list)
625                 uloop_timeout_cancel(t);
626 }
627
628 static void uloop_clear_processes(void)
629 {
630         struct uloop_process *p, *tmp;
631
632         list_for_each_entry_safe(p, tmp, &processes, list)
633                 uloop_process_delete(p);
634 }
635
636 void uloop_run(void)
637 {
638         static int recursive_calls = 0;
639         struct timeval tv;
640
641         /*
642          * Handlers are only updated for the first call to uloop_run() (and restored
643          * when this call is done).
644          */
645         if (!recursive_calls++)
646                 uloop_setup_signals(true);
647
648         while(!uloop_cancelled)
649         {
650                 uloop_gettime(&tv);
651                 uloop_process_timeouts(&tv);
652                 if (uloop_cancelled)
653                         break;
654
655                 if (do_sigchld)
656                         uloop_handle_processes();
657                 uloop_gettime(&tv);
658                 uloop_run_events(uloop_get_next_timeout(&tv));
659         }
660
661         if (!--recursive_calls)
662                 uloop_setup_signals(false);
663 }
664
665 void uloop_done(void)
666 {
667         if (poll_fd < 0)
668                 return;
669
670         close(poll_fd);
671         poll_fd = -1;
672
673         uloop_clear_timeouts();
674         uloop_clear_processes();
675 }