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