db8cacde28b79368468b5f3d5e7030e62e299372
[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                         register_kevent(u, u->flags);
185                 }
186         }
187         return nfds;
188 }
189
190 #endif
191
192 #ifdef USE_EPOLL
193
194 /**
195  * FIXME: uClibc < 0.9.30.3 does not define EPOLLRDHUP for Linux >= 2.6.17
196  */
197 #ifndef EPOLLRDHUP
198 #define EPOLLRDHUP 0x2000
199 #endif
200
201 int uloop_init(void)
202 {
203         if (poll_fd >= 0)
204                 return 0;
205
206         poll_fd = epoll_create(32);
207         if (poll_fd < 0)
208                 return -1;
209
210         fcntl(poll_fd, F_SETFD, fcntl(poll_fd, F_GETFD) | FD_CLOEXEC);
211         return 0;
212 }
213
214 static int register_poll(struct uloop_fd *fd, unsigned int flags)
215 {
216         struct epoll_event ev;
217         int op = fd->registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD;
218
219         memset(&ev, 0, sizeof(struct epoll_event));
220
221         if (flags & ULOOP_READ)
222                 ev.events |= EPOLLIN | EPOLLRDHUP;
223
224         if (flags & ULOOP_WRITE)
225                 ev.events |= EPOLLOUT;
226
227         if (flags & ULOOP_EDGE_TRIGGER)
228                 ev.events |= EPOLLET;
229
230         ev.data.fd = fd->fd;
231         ev.data.ptr = fd;
232
233         return epoll_ctl(poll_fd, op, fd->fd, &ev);
234 }
235
236 static struct epoll_event events[ULOOP_MAX_EVENTS];
237
238 static int __uloop_fd_delete(struct uloop_fd *sock)
239 {
240         return epoll_ctl(poll_fd, EPOLL_CTL_DEL, sock->fd, 0);
241 }
242
243 static int uloop_fetch_events(int timeout)
244 {
245         int n, nfds;
246
247         nfds = epoll_wait(poll_fd, events, ARRAY_SIZE(events), timeout);
248         for (n = 0; n < nfds; ++n) {
249                 struct uloop_fd_event *cur = &cur_fds[n];
250                 struct uloop_fd *u = events[n].data.ptr;
251                 unsigned int ev = 0;
252
253                 cur->fd = u;
254                 if (!u)
255                         continue;
256
257                 if (events[n].events & (EPOLLERR|EPOLLHUP)) {
258                         u->error = true;
259                         uloop_fd_delete(u);
260                 }
261
262                 if(!(events[n].events & (EPOLLRDHUP|EPOLLIN|EPOLLOUT|EPOLLERR|EPOLLHUP))) {
263                         cur->fd = NULL;
264                         continue;
265                 }
266
267                 if(events[n].events & EPOLLRDHUP)
268                         u->eof = true;
269
270                 if(events[n].events & EPOLLIN)
271                         ev |= ULOOP_READ;
272
273                 if(events[n].events & EPOLLOUT)
274                         ev |= ULOOP_WRITE;
275
276                 cur->events = ev;
277         }
278
279         return nfds;
280 }
281
282 #endif
283
284 static void uloop_run_events(int timeout)
285 {
286         struct uloop_fd_event *cur;
287         struct uloop_fd *fd;
288
289         if (!cur_nfds) {
290                 cur_fd = 0;
291                 cur_nfds = uloop_fetch_events(timeout);
292                 if (cur_nfds < 0)
293                         cur_nfds = 0;
294         }
295
296         while (cur_nfds > 0) {
297                 cur = &cur_fds[cur_fd++];
298                 cur_nfds--;
299
300                 fd = cur->fd;
301                 if (!fd)
302                         continue;
303
304                 if (!fd->cb)
305                         continue;
306
307                 fd->cb(fd, cur->events);
308                 return;
309         }
310 }
311
312 int uloop_fd_add(struct uloop_fd *sock, unsigned int flags)
313 {
314         unsigned int fl;
315         int ret;
316
317         if (!(flags & (ULOOP_READ | ULOOP_WRITE)))
318                 return uloop_fd_delete(sock);
319
320         if (!sock->registered && !(flags & ULOOP_BLOCKING)) {
321                 fl = fcntl(sock->fd, F_GETFL, 0);
322                 fl |= O_NONBLOCK;
323                 fcntl(sock->fd, F_SETFL, fl);
324         }
325
326         ret = register_poll(sock, flags);
327         if (ret < 0)
328                 goto out;
329
330         sock->registered = true;
331         sock->eof = false;
332
333 out:
334         return ret;
335 }
336
337 int uloop_fd_delete(struct uloop_fd *fd)
338 {
339         int i;
340
341         if (!fd->registered)
342                 return 0;
343
344         for (i = 0; i < cur_nfds; i++) {
345                 if (cur_fds[cur_fd + i].fd != fd)
346                         continue;
347
348                 cur_fds[cur_fd + i].fd = NULL;
349         }
350         fd->registered = false;
351         return __uloop_fd_delete(fd);
352 }
353
354 static int tv_diff(struct timeval *t1, struct timeval *t2)
355 {
356         return
357                 (t1->tv_sec - t2->tv_sec) * 1000 +
358                 (t1->tv_usec - t2->tv_usec) / 1000;
359 }
360
361 int uloop_timeout_add(struct uloop_timeout *timeout)
362 {
363         struct uloop_timeout *tmp;
364         struct list_head *h = &timeouts;
365
366         if (timeout->pending)
367                 return -1;
368
369         list_for_each_entry(tmp, &timeouts, list) {
370                 if (tv_diff(&tmp->time, &timeout->time) > 0) {
371                         h = &tmp->list;
372                         break;
373                 }
374         }
375
376         list_add_tail(&timeout->list, h);
377         timeout->pending = true;
378
379         return 0;
380 }
381
382 static void uloop_gettime(struct timeval *tv)
383 {
384         struct timespec ts;
385
386         clock_gettime(CLOCK_MONOTONIC, &ts);
387         tv->tv_sec = ts.tv_sec;
388         tv->tv_usec = ts.tv_nsec / 1000;
389 }
390
391 int uloop_timeout_set(struct uloop_timeout *timeout, int msecs)
392 {
393         struct timeval *time = &timeout->time;
394
395         if (timeout->pending)
396                 uloop_timeout_cancel(timeout);
397
398         uloop_gettime(&timeout->time);
399
400         time->tv_sec += msecs / 1000;
401         time->tv_usec += (msecs % 1000) * 1000;
402
403         if (time->tv_usec > 1000000) {
404                 time->tv_sec++;
405                 time->tv_usec %= 1000000;
406         }
407
408         return uloop_timeout_add(timeout);
409 }
410
411 int uloop_timeout_cancel(struct uloop_timeout *timeout)
412 {
413         if (!timeout->pending)
414                 return -1;
415
416         list_del(&timeout->list);
417         timeout->pending = false;
418
419         return 0;
420 }
421
422 int uloop_timeout_remaining(struct uloop_timeout *timeout)
423 {
424         struct timeval now;
425
426         if (!timeout->pending)
427                 return -1;
428
429         uloop_gettime(&now);
430
431         return tv_diff(&timeout->time, &now);
432 }
433
434 int uloop_process_add(struct uloop_process *p)
435 {
436         struct uloop_process *tmp;
437         struct list_head *h = &processes;
438
439         if (p->pending)
440                 return -1;
441
442         list_for_each_entry(tmp, &processes, list) {
443                 if (tmp->pid > p->pid) {
444                         h = &tmp->list;
445                         break;
446                 }
447         }
448
449         list_add_tail(&p->list, h);
450         p->pending = true;
451
452         return 0;
453 }
454
455 int uloop_process_delete(struct uloop_process *p)
456 {
457         if (!p->pending)
458                 return -1;
459
460         list_del(&p->list);
461         p->pending = false;
462
463         return 0;
464 }
465
466 static void uloop_handle_processes(void)
467 {
468         struct uloop_process *p, *tmp;
469         pid_t pid;
470         int ret;
471
472         do_sigchld = false;
473
474         while (1) {
475                 pid = waitpid(-1, &ret, WNOHANG);
476                 if (pid <= 0)
477                         return;
478
479                 list_for_each_entry_safe(p, tmp, &processes, list) {
480                         if (p->pid < pid)
481                                 continue;
482
483                         if (p->pid > pid)
484                                 break;
485
486                         uloop_process_delete(p);
487                         p->cb(p, ret);
488                 }
489         }
490
491 }
492
493 static void uloop_handle_sigint(int signo)
494 {
495         uloop_cancelled = true;
496 }
497
498 static void uloop_sigchld(int signo)
499 {
500         do_sigchld = true;
501 }
502
503 static void uloop_setup_signals(void)
504 {
505         struct sigaction s;
506
507         memset(&s, 0, sizeof(struct sigaction));
508         s.sa_handler = uloop_handle_sigint;
509         s.sa_flags = 0;
510         sigaction(SIGINT, &s, NULL);
511
512         if (uloop_handle_sigchld) {
513                 s.sa_handler = uloop_sigchld;
514                 sigaction(SIGCHLD, &s, NULL);
515         }
516 }
517
518 static int uloop_get_next_timeout(struct timeval *tv)
519 {
520         struct uloop_timeout *timeout;
521         int diff;
522
523         if (list_empty(&timeouts))
524                 return -1;
525
526         timeout = list_first_entry(&timeouts, struct uloop_timeout, list);
527         diff = tv_diff(&timeout->time, tv);
528         if (diff < 0)
529                 return 0;
530
531         return diff;
532 }
533
534 static void uloop_process_timeouts(struct timeval *tv)
535 {
536         struct uloop_timeout *t;
537
538         while (!list_empty(&timeouts)) {
539                 t = list_first_entry(&timeouts, struct uloop_timeout, list);
540
541                 if (tv_diff(&t->time, tv) > 0)
542                         break;
543
544                 uloop_timeout_cancel(t);
545                 if (t->cb)
546                         t->cb(t);
547         }
548 }
549
550 static void uloop_clear_timeouts(void)
551 {
552         struct uloop_timeout *t, *tmp;
553
554         list_for_each_entry_safe(t, tmp, &timeouts, list)
555                 uloop_timeout_cancel(t);
556 }
557
558 static void uloop_clear_processes(void)
559 {
560         struct uloop_process *p, *tmp;
561
562         list_for_each_entry_safe(p, tmp, &processes, list)
563                 uloop_process_delete(p);
564 }
565
566 void uloop_run(void)
567 {
568         struct timeval tv;
569
570         uloop_setup_signals();
571         while(!uloop_cancelled)
572         {
573                 uloop_gettime(&tv);
574                 uloop_process_timeouts(&tv);
575                 if (uloop_cancelled)
576                         break;
577
578                 if (do_sigchld)
579                         uloop_handle_processes();
580                 uloop_run_events(uloop_get_next_timeout(&tv));
581         }
582 }
583
584 void uloop_done(void)
585 {
586         if (poll_fd < 0)
587                 return;
588
589         close(poll_fd);
590         poll_fd = -1;
591
592         uloop_clear_timeouts();
593         uloop_clear_processes();
594 }