2 * libev event processing core, watcher management
4 * Copyright (c) 2007 Marc Alexander Lehmann <libev@schmorp.de>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * * Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
51 #ifndef EV_USE_MONOTONIC
52 # define EV_USE_MONOTONIC 1
55 #ifndef CLOCK_MONOTONIC
56 # undef EV_USE_MONOTONIC
57 # define EV_USE_MONOTONIC 0
61 # define EV_USE_SELECT 1
65 # define EV_USE_EPOLL 0
68 #ifndef CLOCK_REALTIME
69 # define EV_USE_REALTIME 0
71 #ifndef EV_USE_REALTIME
72 # define EV_USE_REALTIME 1 /* posix requirement, but might be slower */
75 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
76 #define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detetc time jumps) */
77 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
78 #define CLEANUP_INTERVAL (MAX_BLOCKTIME * 5.) /* how often to try to free memory and re-check fds */
82 typedef struct ev_watcher *W;
83 typedef struct ev_watcher_list *WL;
84 typedef struct ev_watcher_time *WT;
86 static ev_tstamp now, diff; /* monotonic clock */
90 static int have_monotonic; /* runtime */
92 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
93 static void (*method_modify)(int fd, int oev, int nev);
94 static void (*method_poll)(ev_tstamp timeout);
96 /*****************************************************************************/
103 clock_gettime (CLOCK_REALTIME, &ts);
104 return ts.tv_sec + ts.tv_nsec * 1e-9;
107 gettimeofday (&tv, 0);
108 return tv.tv_sec + tv.tv_usec * 1e-6;
119 clock_gettime (CLOCK_MONOTONIC, &ts);
120 return ts.tv_sec + ts.tv_nsec * 1e-9;
127 #define array_roundsize(base,n) ((n) | 4 & ~3)
129 #define array_needsize(base,cur,cnt,init) \
135 newcnt = array_roundsize (base, newcnt << 1); \
137 while ((cnt) > newcnt); \
139 base = realloc (base, sizeof (*base) * (newcnt)); \
140 init (base + cur, newcnt - cur); \
144 /*****************************************************************************/
149 unsigned char events;
157 anfds_init (ANFD *base, int count)
162 base->events = EV_NONE;
175 static ANPENDING *pendings;
176 static int pendingmax, pendingcnt;
179 event (W w, int events)
183 pendings [w->pending - 1].events |= events;
187 w->pending = ++pendingcnt;
188 array_needsize (pendings, pendingmax, pendingcnt, );
189 pendings [pendingcnt - 1].w = w;
190 pendings [pendingcnt - 1].events = events;
194 queue_events (W *events, int eventcnt, int type)
198 for (i = 0; i < eventcnt; ++i)
199 event (events [i], type);
203 fd_event (int fd, int events)
205 ANFD *anfd = anfds + fd;
208 for (w = anfd->head; w; w = w->next)
210 int ev = w->events & events;
217 /*****************************************************************************/
219 static int *fdchanges;
220 static int fdchangemax, fdchangecnt;
227 for (i = 0; i < fdchangecnt; ++i)
229 int fd = fdchanges [i];
230 ANFD *anfd = anfds + fd;
235 for (w = anfd->head; w; w = w->next)
240 if (anfd->events != events)
242 method_modify (fd, anfd->events, events);
243 anfd->events = events;
253 if (anfds [fd].reify || fdchangecnt < 0)
256 anfds [fd].reify = 1;
259 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
260 fdchanges [fdchangecnt - 1] = fd;
263 /* called on EBADF to verify fds */
269 for (fd = 0; fd < anfdmax; ++fd)
270 if (anfds [fd].events)
271 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
272 while (anfds [fd].head)
274 ev_io_stop (anfds [fd].head);
275 event ((W)anfds [fd].head, EV_ERROR | EV_READ | EV_WRITE);
279 /*****************************************************************************/
281 static struct ev_timer **timers;
282 static int timermax, timercnt;
284 static struct ev_periodic **periodics;
285 static int periodicmax, periodiccnt;
288 upheap (WT *timers, int k)
292 while (k && timers [k >> 1]->at > w->at)
294 timers [k] = timers [k >> 1];
295 timers [k]->active = k + 1;
300 timers [k]->active = k + 1;
305 downheap (WT *timers, int N, int k)
313 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
316 if (w->at <= timers [j]->at)
319 timers [k] = timers [j];
320 timers [k]->active = k + 1;
325 timers [k]->active = k + 1;
328 /*****************************************************************************/
332 struct ev_signal *head;
333 sig_atomic_t volatile gotsig;
336 static ANSIG *signals;
337 static int signalmax;
339 static int sigpipe [2];
340 static sig_atomic_t volatile gotsig;
341 static struct ev_io sigev;
344 signals_init (ANSIG *base, int count)
356 sighandler (int signum)
358 signals [signum - 1].gotsig = 1;
363 write (sigpipe [1], &signum, 1);
368 sigcb (struct ev_io *iow, int revents)
373 read (sigpipe [0], &revents, 1);
376 for (signum = signalmax; signum--; )
377 if (signals [signum].gotsig)
379 signals [signum].gotsig = 0;
381 for (w = signals [signum].head; w; w = w->next)
382 event ((W)w, EV_SIGNAL);
389 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
390 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
392 /* rather than sort out wether we really need nb, set it */
393 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
394 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
396 ev_io_set (&sigev, sigpipe [0], EV_READ);
397 ev_io_start (&sigev);
400 /*****************************************************************************/
402 static struct ev_idle **idles;
403 static int idlemax, idlecnt;
405 static struct ev_prepare **prepares;
406 static int preparemax, preparecnt;
408 static struct ev_check **checks;
409 static int checkmax, checkcnt;
411 /*****************************************************************************/
413 static struct ev_child *childs [PID_HASHSIZE];
414 static struct ev_signal childev;
417 # define WCONTINUED 0
421 childcb (struct ev_signal *sw, int revents)
426 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
427 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
428 if (w->pid == pid || w->pid == -1)
431 event ((W)w, EV_CHILD);
435 /*****************************************************************************/
438 # include "ev_epoll.c"
441 # include "ev_select.c"
445 ev_version_major (void)
447 return EV_VERSION_MAJOR;
451 ev_version_minor (void)
453 return EV_VERSION_MINOR;
456 int ev_init (int flags)
463 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
475 ev_method = EVMETHOD_NONE;
477 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
480 if (ev_method == EVMETHOD_NONE) select_init (flags);
485 ev_watcher_init (&sigev, sigcb);
488 ev_signal_init (&childev, childcb, SIGCHLD);
489 ev_signal_start (&childev);
496 /*****************************************************************************/
499 ev_fork_prepare (void)
505 ev_fork_parent (void)
514 if (ev_method == EVMETHOD_EPOLL)
515 epoll_postfork_child ();
525 /*****************************************************************************/
532 ANPENDING *p = pendings + --pendingcnt;
537 p->w->cb (p->w, p->events);
545 while (timercnt && timers [0]->at <= now)
547 struct ev_timer *w = timers [0];
549 /* first reschedule or stop timer */
552 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
553 w->at = now + w->repeat;
554 downheap ((WT *)timers, timercnt, 0);
557 ev_timer_stop (w); /* nonrepeating: stop timer */
559 event ((W)w, EV_TIMEOUT);
564 periodics_reify (void)
566 while (periodiccnt && periodics [0]->at <= ev_now)
568 struct ev_periodic *w = periodics [0];
570 /* first reschedule or stop timer */
573 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
574 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", w->at > ev_now));
575 downheap ((WT *)periodics, periodiccnt, 0);
578 ev_periodic_stop (w); /* nonrepeating: stop timer */
580 event ((W)w, EV_PERIODIC);
585 periodics_reschedule (ev_tstamp diff)
589 /* adjust periodics after time jump */
590 for (i = 0; i < periodiccnt; ++i)
592 struct ev_periodic *w = periodics [i];
596 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
598 if (fabs (diff) >= 1e-4)
600 ev_periodic_stop (w);
601 ev_periodic_start (w);
603 i = 0; /* restart loop, inefficient, but time jumps should be rare */
618 ev_tstamp odiff = diff;
620 for (i = 4; --i; ) /* loop a few times, before making important decisions */
625 if (fabs (odiff - diff) < MIN_TIMEJUMP)
626 return; /* all is well */
631 periodics_reschedule (diff - odiff);
632 /* no timer adjustment, as the monotonic clock doesn't jump */
636 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
638 periodics_reschedule (ev_now - now);
640 /* adjust timers. this is easy, as the offset is the same for all */
641 for (i = 0; i < timercnt; ++i)
642 timers [i]->at += diff;
651 void ev_loop (int flags)
654 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
658 /* queue check watchers (and execute them) */
661 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
665 /* update fd-related kernel structures */
668 /* calculate blocking time */
670 /* we only need this for !monotonic clockor timers, but as we basically
671 always have timers, we just calculate it always */
674 if (flags & EVLOOP_NONBLOCK || idlecnt)
678 block = MAX_BLOCKTIME;
682 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
683 if (block > to) block = to;
688 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
689 if (block > to) block = to;
692 if (block < 0.) block = 0.;
697 /* update ev_now, do magic */
700 /* queue pending timers and reschedule them */
701 timers_reify (); /* relative timers called last */
702 periodics_reify (); /* absolute timers called first */
704 /* queue idle watchers unless io or timers are pending */
706 queue_events ((W *)idles, idlecnt, EV_IDLE);
708 /* queue check watchers, to be executed first */
710 queue_events ((W *)checks, checkcnt, EV_CHECK);
714 while (!ev_loop_done);
716 if (ev_loop_done != 2)
720 /*****************************************************************************/
723 wlist_add (WL *head, WL elem)
730 wlist_del (WL *head, WL elem)
740 head = &(*head)->next;
745 ev_clear_pending (W w)
749 pendings [w->pending - 1].w = 0;
755 ev_start (W w, int active)
766 /*****************************************************************************/
769 ev_io_start (struct ev_io *w)
773 if (ev_is_active (w))
776 assert (("ev_io_start called with negative fd", fd >= 0));
779 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
780 wlist_add ((WL *)&anfds[fd].head, (WL)w);
786 ev_io_stop (struct ev_io *w)
788 ev_clear_pending ((W)w);
789 if (!ev_is_active (w))
792 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
799 ev_timer_start (struct ev_timer *w)
801 if (ev_is_active (w))
806 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
808 ev_start ((W)w, ++timercnt);
809 array_needsize (timers, timermax, timercnt, );
810 timers [timercnt - 1] = w;
811 upheap ((WT *)timers, timercnt - 1);
815 ev_timer_stop (struct ev_timer *w)
817 ev_clear_pending ((W)w);
818 if (!ev_is_active (w))
821 if (w->active < timercnt--)
823 timers [w->active - 1] = timers [timercnt];
824 downheap ((WT *)timers, timercnt, w->active - 1);
833 ev_timer_again (struct ev_timer *w)
835 if (ev_is_active (w))
839 w->at = now + w->repeat;
840 downheap ((WT *)timers, timercnt, w->active - 1);
850 ev_periodic_start (struct ev_periodic *w)
852 if (ev_is_active (w))
855 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
857 /* this formula differs from the one in periodic_reify because we do not always round up */
859 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
861 ev_start ((W)w, ++periodiccnt);
862 array_needsize (periodics, periodicmax, periodiccnt, );
863 periodics [periodiccnt - 1] = w;
864 upheap ((WT *)periodics, periodiccnt - 1);
868 ev_periodic_stop (struct ev_periodic *w)
870 ev_clear_pending ((W)w);
871 if (!ev_is_active (w))
874 if (w->active < periodiccnt--)
876 periodics [w->active - 1] = periodics [periodiccnt];
877 downheap ((WT *)periodics, periodiccnt, w->active - 1);
884 ev_signal_start (struct ev_signal *w)
886 if (ev_is_active (w))
889 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
892 array_needsize (signals, signalmax, w->signum, signals_init);
893 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
898 sa.sa_handler = sighandler;
899 sigfillset (&sa.sa_mask);
901 sigaction (w->signum, &sa, 0);
906 ev_signal_stop (struct ev_signal *w)
908 ev_clear_pending ((W)w);
909 if (!ev_is_active (w))
912 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
915 if (!signals [w->signum - 1].head)
916 signal (w->signum, SIG_DFL);
920 ev_idle_start (struct ev_idle *w)
922 if (ev_is_active (w))
925 ev_start ((W)w, ++idlecnt);
926 array_needsize (idles, idlemax, idlecnt, );
927 idles [idlecnt - 1] = w;
931 ev_idle_stop (struct ev_idle *w)
933 ev_clear_pending ((W)w);
934 if (ev_is_active (w))
937 idles [w->active - 1] = idles [--idlecnt];
942 ev_prepare_start (struct ev_prepare *w)
944 if (ev_is_active (w))
947 ev_start ((W)w, ++preparecnt);
948 array_needsize (prepares, preparemax, preparecnt, );
949 prepares [preparecnt - 1] = w;
953 ev_prepare_stop (struct ev_prepare *w)
955 ev_clear_pending ((W)w);
956 if (ev_is_active (w))
959 prepares [w->active - 1] = prepares [--preparecnt];
964 ev_check_start (struct ev_check *w)
966 if (ev_is_active (w))
969 ev_start ((W)w, ++checkcnt);
970 array_needsize (checks, checkmax, checkcnt, );
971 checks [checkcnt - 1] = w;
975 ev_check_stop (struct ev_check *w)
977 ev_clear_pending ((W)w);
978 if (ev_is_active (w))
981 checks [w->active - 1] = checks [--checkcnt];
986 ev_child_start (struct ev_child *w)
988 if (ev_is_active (w))
992 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
996 ev_child_stop (struct ev_child *w)
998 ev_clear_pending ((W)w);
999 if (ev_is_active (w))
1002 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1006 /*****************************************************************************/
1012 void (*cb)(int revents, void *arg);
1017 once_cb (struct ev_once *once, int revents)
1019 void (*cb)(int revents, void *arg) = once->cb;
1020 void *arg = once->arg;
1022 ev_io_stop (&once->io);
1023 ev_timer_stop (&once->to);
1030 once_cb_io (struct ev_io *w, int revents)
1032 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1036 once_cb_to (struct ev_timer *w, int revents)
1038 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1042 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1044 struct ev_once *once = malloc (sizeof (struct ev_once));
1047 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1053 ev_watcher_init (&once->io, once_cb_io);
1056 ev_io_set (&once->io, fd, events);
1057 ev_io_start (&once->io);
1060 ev_watcher_init (&once->to, once_cb_to);
1063 ev_timer_set (&once->to, timeout, 0.);
1064 ev_timer_start (&once->to);
1069 /*****************************************************************************/
1076 sin_cb (struct ev_io *w, int revents)
1078 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1082 ocb (struct ev_timer *w, int revents)
1084 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1090 scb (struct ev_signal *w, int revents)
1092 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1098 gcb (struct ev_signal *w, int revents)
1100 fprintf (stderr, "generic %x\n", revents);
1108 ev_io_init (&wio, sin_cb, 0, EV_READ);
1111 struct ev_timer t[10000];
1115 for (i = 0; i < 10000; ++i)
1117 struct ev_timer *w = t + i;
1118 ev_watcher_init (w, ocb, i);
1119 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1121 if (drand48 () < 0.5)
1127 ev_timer_init (&t1, ocb, 5, 10);
1128 ev_timer_start (&t1);
1130 struct ev_signal sig;
1131 ev_signal_init (&sig, scb, SIGQUIT);
1132 ev_signal_start (&sig);
1135 ev_check_init (&cw, gcb);
1136 ev_check_start (&cw);
1139 ev_idle_init (&iw, gcb);
1140 ev_idle_start (&iw);