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>
53 #ifndef EV_USE_MONOTONIC
54 # define EV_USE_MONOTONIC 1
58 # define EV_USE_SELECT 1
62 # define EV_USE_POLL 0 /* poll is usually slower than select, and not as well tested */
66 # define EV_USE_EPOLL 0
69 #ifndef EV_USE_REALTIME
70 # define EV_USE_REALTIME 1
75 #ifndef CLOCK_MONOTONIC
76 # undef EV_USE_MONOTONIC
77 # define EV_USE_MONOTONIC 0
80 #ifndef CLOCK_REALTIME
81 # undef EV_USE_REALTIME
82 # define EV_USE_REALTIME 0
87 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
88 #define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detect time jumps) */
89 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
90 /*#define CLEANUP_INTERVAL 300. /* how often to try to free memory and re-check fds */
95 # define expect(expr,value) __builtin_expect ((expr),(value))
96 # define inline inline
98 # define expect(expr,value) (expr)
99 # define inline static
102 #define expect_false(expr) expect ((expr) != 0, 0)
103 #define expect_true(expr) expect ((expr) != 0, 1)
105 typedef struct ev_watcher *W;
106 typedef struct ev_watcher_list *WL;
107 typedef struct ev_watcher_time *WT;
109 static ev_tstamp now_floor, now, diff; /* monotonic clock */
113 static int have_monotonic; /* runtime */
115 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
116 static void (*method_modify)(int fd, int oev, int nev);
117 static void (*method_poll)(ev_tstamp timeout);
119 /*****************************************************************************/
126 clock_gettime (CLOCK_REALTIME, &ts);
127 return ts.tv_sec + ts.tv_nsec * 1e-9;
130 gettimeofday (&tv, 0);
131 return tv.tv_sec + tv.tv_usec * 1e-6;
139 if (expect_true (have_monotonic))
142 clock_gettime (CLOCK_MONOTONIC, &ts);
143 return ts.tv_sec + ts.tv_nsec * 1e-9;
150 #define array_roundsize(base,n) ((n) | 4 & ~3)
152 #define array_needsize(base,cur,cnt,init) \
153 if (expect_false ((cnt) > cur)) \
158 newcnt = array_roundsize (base, newcnt << 1); \
160 while ((cnt) > newcnt); \
162 base = realloc (base, sizeof (*base) * (newcnt)); \
163 init (base + cur, newcnt - cur); \
167 /*****************************************************************************/
172 unsigned char events;
180 anfds_init (ANFD *base, int count)
185 base->events = EV_NONE;
198 static ANPENDING *pendings;
199 static int pendingmax, pendingcnt;
202 event (W w, int events)
206 pendings [w->pending - 1].events |= events;
210 w->pending = ++pendingcnt;
211 array_needsize (pendings, pendingmax, pendingcnt, );
212 pendings [pendingcnt - 1].w = w;
213 pendings [pendingcnt - 1].events = events;
217 queue_events (W *events, int eventcnt, int type)
221 for (i = 0; i < eventcnt; ++i)
222 event (events [i], type);
226 fd_event (int fd, int events)
228 ANFD *anfd = anfds + fd;
231 for (w = anfd->head; w; w = w->next)
233 int ev = w->events & events;
240 /*****************************************************************************/
242 static int *fdchanges;
243 static int fdchangemax, fdchangecnt;
250 for (i = 0; i < fdchangecnt; ++i)
252 int fd = fdchanges [i];
253 ANFD *anfd = anfds + fd;
258 for (w = anfd->head; w; w = w->next)
263 if (anfd->events != events)
265 method_modify (fd, anfd->events, events);
266 anfd->events = events;
276 if (anfds [fd].reify || fdchangecnt < 0)
279 anfds [fd].reify = 1;
282 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
283 fdchanges [fdchangecnt - 1] = fd;
291 printf ("killing fd %d\n", fd);//D
292 while ((w = anfds [fd].head))
295 event ((W)w, EV_ERROR | EV_READ | EV_WRITE);
299 /* called on EBADF to verify fds */
305 for (fd = 0; fd < anfdmax; ++fd)
306 if (anfds [fd].events)
307 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
311 /* called on ENOMEM in select/poll to kill some fds and retry */
318 if (anfds [fd].events)
326 /*****************************************************************************/
328 static struct ev_timer **timers;
329 static int timermax, timercnt;
331 static struct ev_periodic **periodics;
332 static int periodicmax, periodiccnt;
335 upheap (WT *timers, int k)
339 while (k && timers [k >> 1]->at > w->at)
341 timers [k] = timers [k >> 1];
342 timers [k]->active = k + 1;
347 timers [k]->active = k + 1;
352 downheap (WT *timers, int N, int k)
360 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
363 if (w->at <= timers [j]->at)
366 timers [k] = timers [j];
367 timers [k]->active = k + 1;
372 timers [k]->active = k + 1;
375 /*****************************************************************************/
379 struct ev_signal *head;
380 sig_atomic_t volatile gotsig;
383 static ANSIG *signals;
384 static int signalmax;
386 static int sigpipe [2];
387 static sig_atomic_t volatile gotsig;
388 static struct ev_io sigev;
391 signals_init (ANSIG *base, int count)
403 sighandler (int signum)
405 signals [signum - 1].gotsig = 1;
410 write (sigpipe [1], &signum, 1);
415 sigcb (struct ev_io *iow, int revents)
420 read (sigpipe [0], &revents, 1);
423 for (signum = signalmax; signum--; )
424 if (signals [signum].gotsig)
426 signals [signum].gotsig = 0;
428 for (w = signals [signum].head; w; w = w->next)
429 event ((W)w, EV_SIGNAL);
436 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
437 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
439 /* rather than sort out wether we really need nb, set it */
440 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
441 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
443 ev_io_set (&sigev, sigpipe [0], EV_READ);
444 ev_io_start (&sigev);
447 /*****************************************************************************/
449 static struct ev_idle **idles;
450 static int idlemax, idlecnt;
452 static struct ev_prepare **prepares;
453 static int preparemax, preparecnt;
455 static struct ev_check **checks;
456 static int checkmax, checkcnt;
458 /*****************************************************************************/
460 static struct ev_child *childs [PID_HASHSIZE];
461 static struct ev_signal childev;
464 # define WCONTINUED 0
468 childcb (struct ev_signal *sw, int revents)
473 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
474 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
475 if (w->pid == pid || !w->pid)
478 event ((W)w, EV_CHILD);
482 /*****************************************************************************/
485 # include "ev_epoll.c"
488 # include "ev_poll.c"
491 # include "ev_select.c"
495 ev_version_major (void)
497 return EV_VERSION_MAJOR;
501 ev_version_minor (void)
503 return EV_VERSION_MINOR;
506 /* return true if we are running with elevated privileges and ignore env variables */
510 return getuid () != geteuid ()
511 || getgid () != getegid ();
514 int ev_init (int methods)
521 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
534 if (methods == EVMETHOD_AUTO)
535 if (!enable_secure () && getenv ("LIBEV_METHODS"))
536 methods = atoi (getenv ("LIBEV_METHODS"));
538 methods = EVMETHOD_ANY;
542 if (!ev_method && (methods & EVMETHOD_EPOLL )) epoll_init (methods);
545 if (!ev_method && (methods & EVMETHOD_POLL )) poll_init (methods);
548 if (!ev_method && (methods & EVMETHOD_SELECT)) select_init (methods);
553 ev_watcher_init (&sigev, sigcb);
556 ev_signal_init (&childev, childcb, SIGCHLD);
557 ev_signal_start (&childev);
564 /*****************************************************************************/
567 ev_fork_prepare (void)
573 ev_fork_parent (void)
582 if (ev_method == EVMETHOD_EPOLL)
583 epoll_postfork_child ();
593 /*****************************************************************************/
600 ANPENDING *p = pendings + --pendingcnt;
605 p->w->cb (p->w, p->events);
613 while (timercnt && timers [0]->at <= now)
615 struct ev_timer *w = timers [0];
617 /* first reschedule or stop timer */
620 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
621 w->at = now + w->repeat;
622 downheap ((WT *)timers, timercnt, 0);
625 ev_timer_stop (w); /* nonrepeating: stop timer */
627 event ((W)w, EV_TIMEOUT);
632 periodics_reify (void)
634 while (periodiccnt && periodics [0]->at <= ev_now)
636 struct ev_periodic *w = periodics [0];
638 /* first reschedule or stop timer */
641 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
642 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", w->at > ev_now));
643 downheap ((WT *)periodics, periodiccnt, 0);
646 ev_periodic_stop (w); /* nonrepeating: stop timer */
648 event ((W)w, EV_PERIODIC);
653 periodics_reschedule (ev_tstamp diff)
657 /* adjust periodics after time jump */
658 for (i = 0; i < periodiccnt; ++i)
660 struct ev_periodic *w = periodics [i];
664 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
666 if (fabs (diff) >= 1e-4)
668 ev_periodic_stop (w);
669 ev_periodic_start (w);
671 i = 0; /* restart loop, inefficient, but time jumps should be rare */
678 time_update_monotonic (void)
682 if (expect_true (now - now_floor < MIN_TIMEJUMP * .5))
701 if (expect_true (have_monotonic))
703 if (time_update_monotonic ())
705 ev_tstamp odiff = diff;
707 for (i = 4; --i; ) /* loop a few times, before making important decisions */
711 if (fabs (odiff - diff) < MIN_TIMEJUMP)
712 return; /* all is well */
719 periodics_reschedule (diff - odiff);
720 /* no timer adjustment, as the monotonic clock doesn't jump */
728 if (expect_false (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
730 periodics_reschedule (ev_now - now);
732 /* adjust timers. this is easy, as the offset is the same for all */
733 for (i = 0; i < timercnt; ++i)
734 timers [i]->at += diff;
743 void ev_loop (int flags)
746 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
750 /* queue check watchers (and execute them) */
751 if (expect_false (preparecnt))
753 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
757 /* update fd-related kernel structures */
760 /* calculate blocking time */
762 /* we only need this for !monotonic clockor timers, but as we basically
763 always have timers, we just calculate it always */
765 if (expect_true (have_monotonic))
766 time_update_monotonic ();
774 if (flags & EVLOOP_NONBLOCK || idlecnt)
778 block = MAX_BLOCKTIME;
782 ev_tstamp to = timers [0]->at - now + method_fudge;
783 if (block > to) block = to;
788 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
789 if (block > to) block = to;
792 if (block < 0.) block = 0.;
797 /* update ev_now, do magic */
800 /* queue pending timers and reschedule them */
801 timers_reify (); /* relative timers called last */
802 periodics_reify (); /* absolute timers called first */
804 /* queue idle watchers unless io or timers are pending */
806 queue_events ((W *)idles, idlecnt, EV_IDLE);
808 /* queue check watchers, to be executed first */
810 queue_events ((W *)checks, checkcnt, EV_CHECK);
814 while (!ev_loop_done);
816 if (ev_loop_done != 2)
820 /*****************************************************************************/
823 wlist_add (WL *head, WL elem)
830 wlist_del (WL *head, WL elem)
840 head = &(*head)->next;
845 ev_clear_pending (W w)
849 pendings [w->pending - 1].w = 0;
855 ev_start (W w, int active)
866 /*****************************************************************************/
869 ev_io_start (struct ev_io *w)
873 if (ev_is_active (w))
876 assert (("ev_io_start called with negative fd", fd >= 0));
879 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
880 wlist_add ((WL *)&anfds[fd].head, (WL)w);
886 ev_io_stop (struct ev_io *w)
888 ev_clear_pending ((W)w);
889 if (!ev_is_active (w))
892 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
899 ev_timer_start (struct ev_timer *w)
901 if (ev_is_active (w))
906 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
908 ev_start ((W)w, ++timercnt);
909 array_needsize (timers, timermax, timercnt, );
910 timers [timercnt - 1] = w;
911 upheap ((WT *)timers, timercnt - 1);
915 ev_timer_stop (struct ev_timer *w)
917 ev_clear_pending ((W)w);
918 if (!ev_is_active (w))
921 if (w->active < timercnt--)
923 timers [w->active - 1] = timers [timercnt];
924 downheap ((WT *)timers, timercnt, w->active - 1);
933 ev_timer_again (struct ev_timer *w)
935 if (ev_is_active (w))
939 w->at = now + w->repeat;
940 downheap ((WT *)timers, timercnt, w->active - 1);
950 ev_periodic_start (struct ev_periodic *w)
952 if (ev_is_active (w))
955 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
957 /* this formula differs from the one in periodic_reify because we do not always round up */
959 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
961 ev_start ((W)w, ++periodiccnt);
962 array_needsize (periodics, periodicmax, periodiccnt, );
963 periodics [periodiccnt - 1] = w;
964 upheap ((WT *)periodics, periodiccnt - 1);
968 ev_periodic_stop (struct ev_periodic *w)
970 ev_clear_pending ((W)w);
971 if (!ev_is_active (w))
974 if (w->active < periodiccnt--)
976 periodics [w->active - 1] = periodics [periodiccnt];
977 downheap ((WT *)periodics, periodiccnt, w->active - 1);
984 ev_signal_start (struct ev_signal *w)
986 if (ev_is_active (w))
989 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
992 array_needsize (signals, signalmax, w->signum, signals_init);
993 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
998 sa.sa_handler = sighandler;
999 sigfillset (&sa.sa_mask);
1001 sigaction (w->signum, &sa, 0);
1006 ev_signal_stop (struct ev_signal *w)
1008 ev_clear_pending ((W)w);
1009 if (!ev_is_active (w))
1012 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
1015 if (!signals [w->signum - 1].head)
1016 signal (w->signum, SIG_DFL);
1020 ev_idle_start (struct ev_idle *w)
1022 if (ev_is_active (w))
1025 ev_start ((W)w, ++idlecnt);
1026 array_needsize (idles, idlemax, idlecnt, );
1027 idles [idlecnt - 1] = w;
1031 ev_idle_stop (struct ev_idle *w)
1033 ev_clear_pending ((W)w);
1034 if (ev_is_active (w))
1037 idles [w->active - 1] = idles [--idlecnt];
1042 ev_prepare_start (struct ev_prepare *w)
1044 if (ev_is_active (w))
1047 ev_start ((W)w, ++preparecnt);
1048 array_needsize (prepares, preparemax, preparecnt, );
1049 prepares [preparecnt - 1] = w;
1053 ev_prepare_stop (struct ev_prepare *w)
1055 ev_clear_pending ((W)w);
1056 if (ev_is_active (w))
1059 prepares [w->active - 1] = prepares [--preparecnt];
1064 ev_check_start (struct ev_check *w)
1066 if (ev_is_active (w))
1069 ev_start ((W)w, ++checkcnt);
1070 array_needsize (checks, checkmax, checkcnt, );
1071 checks [checkcnt - 1] = w;
1075 ev_check_stop (struct ev_check *w)
1077 ev_clear_pending ((W)w);
1078 if (ev_is_active (w))
1081 checks [w->active - 1] = checks [--checkcnt];
1086 ev_child_start (struct ev_child *w)
1088 if (ev_is_active (w))
1092 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1096 ev_child_stop (struct ev_child *w)
1098 ev_clear_pending ((W)w);
1099 if (ev_is_active (w))
1102 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1106 /*****************************************************************************/
1112 void (*cb)(int revents, void *arg);
1117 once_cb (struct ev_once *once, int revents)
1119 void (*cb)(int revents, void *arg) = once->cb;
1120 void *arg = once->arg;
1122 ev_io_stop (&once->io);
1123 ev_timer_stop (&once->to);
1130 once_cb_io (struct ev_io *w, int revents)
1132 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1136 once_cb_to (struct ev_timer *w, int revents)
1138 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1142 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1144 struct ev_once *once = malloc (sizeof (struct ev_once));
1147 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1153 ev_watcher_init (&once->io, once_cb_io);
1156 ev_io_set (&once->io, fd, events);
1157 ev_io_start (&once->io);
1160 ev_watcher_init (&once->to, once_cb_to);
1163 ev_timer_set (&once->to, timeout, 0.);
1164 ev_timer_start (&once->to);
1169 /*****************************************************************************/
1176 sin_cb (struct ev_io *w, int revents)
1178 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1182 ocb (struct ev_timer *w, int revents)
1184 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1190 scb (struct ev_signal *w, int revents)
1192 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1198 gcb (struct ev_signal *w, int revents)
1200 fprintf (stderr, "generic %x\n", revents);
1208 ev_io_init (&wio, sin_cb, 0, EV_READ);
1211 struct ev_timer t[10000];
1215 for (i = 0; i < 10000; ++i)
1217 struct ev_timer *w = t + i;
1218 ev_watcher_init (w, ocb, i);
1219 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1221 if (drand48 () < 0.5)
1227 ev_timer_init (&t1, ocb, 5, 10);
1228 ev_timer_start (&t1);
1230 struct ev_signal sig;
1231 ev_signal_init (&sig, scb, SIGQUIT);
1232 ev_signal_start (&sig);
1235 ev_check_init (&cw, gcb);
1236 ev_check_start (&cw);
1239 ev_idle_init (&iw, gcb);
1240 ev_idle_start (&iw);