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 #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
106 #define ABSPRI(w) ((w)->priority - EV_MINPRI)
108 typedef struct ev_watcher *W;
109 typedef struct ev_watcher_list *WL;
110 typedef struct ev_watcher_time *WT;
112 static ev_tstamp now_floor, now, diff; /* monotonic clock */
116 static int have_monotonic; /* runtime */
118 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
119 static void (*method_modify)(int fd, int oev, int nev);
120 static void (*method_poll)(ev_tstamp timeout);
122 /*****************************************************************************/
129 clock_gettime (CLOCK_REALTIME, &ts);
130 return ts.tv_sec + ts.tv_nsec * 1e-9;
133 gettimeofday (&tv, 0);
134 return tv.tv_sec + tv.tv_usec * 1e-6;
142 if (expect_true (have_monotonic))
145 clock_gettime (CLOCK_MONOTONIC, &ts);
146 return ts.tv_sec + ts.tv_nsec * 1e-9;
153 #define array_roundsize(base,n) ((n) | 4 & ~3)
155 #define array_needsize(base,cur,cnt,init) \
156 if (expect_false ((cnt) > cur)) \
161 newcnt = array_roundsize (base, newcnt << 1); \
163 while ((cnt) > newcnt); \
165 base = realloc (base, sizeof (*base) * (newcnt)); \
166 init (base + cur, newcnt - cur); \
170 /*****************************************************************************/
175 unsigned char events;
183 anfds_init (ANFD *base, int count)
188 base->events = EV_NONE;
201 static ANPENDING *pendings [NUMPRI];
202 static int pendingmax [NUMPRI], pendingcnt [NUMPRI];
205 event (W w, int events)
209 pendings [ABSPRI (w)][w->pending - 1].events |= events;
213 w->pending = ++pendingcnt [ABSPRI (w)];
214 array_needsize (pendings [ABSPRI (w)], pendingmax [ABSPRI (w)], pendingcnt [ABSPRI (w)], );
215 pendings [ABSPRI (w)][w->pending - 1].w = w;
216 pendings [ABSPRI (w)][w->pending - 1].events = events;
220 queue_events (W *events, int eventcnt, int type)
224 for (i = 0; i < eventcnt; ++i)
225 event (events [i], type);
229 fd_event (int fd, int events)
231 ANFD *anfd = anfds + fd;
234 for (w = anfd->head; w; w = w->next)
236 int ev = w->events & events;
243 /*****************************************************************************/
245 static int *fdchanges;
246 static int fdchangemax, fdchangecnt;
253 for (i = 0; i < fdchangecnt; ++i)
255 int fd = fdchanges [i];
256 ANFD *anfd = anfds + fd;
261 for (w = anfd->head; w; w = w->next)
266 if (anfd->events != events)
268 method_modify (fd, anfd->events, events);
269 anfd->events = events;
279 if (anfds [fd].reify || fdchangecnt < 0)
282 anfds [fd].reify = 1;
285 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
286 fdchanges [fdchangecnt - 1] = fd;
294 printf ("killing fd %d\n", fd);//D
295 while ((w = anfds [fd].head))
298 event ((W)w, EV_ERROR | EV_READ | EV_WRITE);
302 /* called on EBADF to verify fds */
308 for (fd = 0; fd < anfdmax; ++fd)
309 if (anfds [fd].events)
310 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
314 /* called on ENOMEM in select/poll to kill some fds and retry */
321 if (anfds [fd].events)
329 /*****************************************************************************/
331 static struct ev_timer **timers;
332 static int timermax, timercnt;
334 static struct ev_periodic **periodics;
335 static int periodicmax, periodiccnt;
338 upheap (WT *timers, int k)
342 while (k && timers [k >> 1]->at > w->at)
344 timers [k] = timers [k >> 1];
345 timers [k]->active = k + 1;
350 timers [k]->active = k + 1;
355 downheap (WT *timers, int N, int k)
363 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
366 if (w->at <= timers [j]->at)
369 timers [k] = timers [j];
370 timers [k]->active = k + 1;
375 timers [k]->active = k + 1;
378 /*****************************************************************************/
382 struct ev_signal *head;
383 sig_atomic_t volatile gotsig;
386 static ANSIG *signals;
387 static int signalmax;
389 static int sigpipe [2];
390 static sig_atomic_t volatile gotsig;
391 static struct ev_io sigev;
394 signals_init (ANSIG *base, int count)
406 sighandler (int signum)
408 signals [signum - 1].gotsig = 1;
413 write (sigpipe [1], &signum, 1);
418 sigcb (struct ev_io *iow, int revents)
423 read (sigpipe [0], &revents, 1);
426 for (signum = signalmax; signum--; )
427 if (signals [signum].gotsig)
429 signals [signum].gotsig = 0;
431 for (w = signals [signum].head; w; w = w->next)
432 event ((W)w, EV_SIGNAL);
439 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
440 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
442 /* rather than sort out wether we really need nb, set it */
443 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
444 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
446 ev_io_set (&sigev, sigpipe [0], EV_READ);
447 ev_io_start (&sigev);
450 /*****************************************************************************/
452 static struct ev_idle **idles;
453 static int idlemax, idlecnt;
455 static struct ev_prepare **prepares;
456 static int preparemax, preparecnt;
458 static struct ev_check **checks;
459 static int checkmax, checkcnt;
461 /*****************************************************************************/
463 static struct ev_child *childs [PID_HASHSIZE];
464 static struct ev_signal childev;
467 # define WCONTINUED 0
471 childcb (struct ev_signal *sw, int revents)
476 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
477 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
478 if (w->pid == pid || !w->pid)
481 event ((W)w, EV_CHILD);
485 /*****************************************************************************/
488 # include "ev_epoll.c"
491 # include "ev_poll.c"
494 # include "ev_select.c"
498 ev_version_major (void)
500 return EV_VERSION_MAJOR;
504 ev_version_minor (void)
506 return EV_VERSION_MINOR;
509 /* return true if we are running with elevated privileges and ignore env variables */
513 return getuid () != geteuid ()
514 || getgid () != getegid ();
517 int ev_init (int methods)
524 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
537 if (methods == EVMETHOD_AUTO)
538 if (!enable_secure () && getenv ("LIBEV_METHODS"))
539 methods = atoi (getenv ("LIBEV_METHODS"));
541 methods = EVMETHOD_ANY;
545 if (!ev_method && (methods & EVMETHOD_EPOLL )) epoll_init (methods);
548 if (!ev_method && (methods & EVMETHOD_POLL )) poll_init (methods);
551 if (!ev_method && (methods & EVMETHOD_SELECT)) select_init (methods);
556 ev_watcher_init (&sigev, sigcb);
559 ev_signal_init (&childev, childcb, SIGCHLD);
560 ev_signal_start (&childev);
567 /*****************************************************************************/
570 ev_fork_prepare (void)
576 ev_fork_parent (void)
585 if (ev_method == EVMETHOD_EPOLL)
586 epoll_postfork_child ();
596 /*****************************************************************************/
603 for (pri = NUMPRI; pri--; )
604 while (pendingcnt [pri])
606 ANPENDING *p = pendings [pri] + --pendingcnt [pri];
611 p->w->cb (p->w, p->events);
619 while (timercnt && timers [0]->at <= now)
621 struct ev_timer *w = timers [0];
623 /* first reschedule or stop timer */
626 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
627 w->at = now + w->repeat;
628 downheap ((WT *)timers, timercnt, 0);
631 ev_timer_stop (w); /* nonrepeating: stop timer */
633 event ((W)w, EV_TIMEOUT);
638 periodics_reify (void)
640 while (periodiccnt && periodics [0]->at <= ev_now)
642 struct ev_periodic *w = periodics [0];
644 /* first reschedule or stop timer */
647 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
648 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", w->at > ev_now));
649 downheap ((WT *)periodics, periodiccnt, 0);
652 ev_periodic_stop (w); /* nonrepeating: stop timer */
654 event ((W)w, EV_PERIODIC);
659 periodics_reschedule (ev_tstamp diff)
663 /* adjust periodics after time jump */
664 for (i = 0; i < periodiccnt; ++i)
666 struct ev_periodic *w = periodics [i];
670 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
672 if (fabs (diff) >= 1e-4)
674 ev_periodic_stop (w);
675 ev_periodic_start (w);
677 i = 0; /* restart loop, inefficient, but time jumps should be rare */
684 time_update_monotonic (void)
688 if (expect_true (now - now_floor < MIN_TIMEJUMP * .5))
707 if (expect_true (have_monotonic))
709 if (time_update_monotonic ())
711 ev_tstamp odiff = diff;
713 for (i = 4; --i; ) /* loop a few times, before making important decisions */
717 if (fabs (odiff - diff) < MIN_TIMEJUMP)
718 return; /* all is well */
725 periodics_reschedule (diff - odiff);
726 /* no timer adjustment, as the monotonic clock doesn't jump */
734 if (expect_false (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
736 periodics_reschedule (ev_now - now);
738 /* adjust timers. this is easy, as the offset is the same for all */
739 for (i = 0; i < timercnt; ++i)
740 timers [i]->at += diff;
749 void ev_loop (int flags)
752 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
756 /* queue check watchers (and execute them) */
757 if (expect_false (preparecnt))
759 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
763 /* update fd-related kernel structures */
766 /* calculate blocking time */
768 /* we only need this for !monotonic clockor timers, but as we basically
769 always have timers, we just calculate it always */
771 if (expect_true (have_monotonic))
772 time_update_monotonic ();
780 if (flags & EVLOOP_NONBLOCK || idlecnt)
784 block = MAX_BLOCKTIME;
788 ev_tstamp to = timers [0]->at - now + method_fudge;
789 if (block > to) block = to;
794 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
795 if (block > to) block = to;
798 if (block < 0.) block = 0.;
803 /* update ev_now, do magic */
806 /* queue pending timers and reschedule them */
807 timers_reify (); /* relative timers called last */
808 periodics_reify (); /* absolute timers called first */
810 /* queue idle watchers unless io or timers are pending */
812 queue_events ((W *)idles, idlecnt, EV_IDLE);
814 /* queue check watchers, to be executed first */
816 queue_events ((W *)checks, checkcnt, EV_CHECK);
820 while (!ev_loop_done);
822 if (ev_loop_done != 2)
826 /*****************************************************************************/
829 wlist_add (WL *head, WL elem)
836 wlist_del (WL *head, WL elem)
846 head = &(*head)->next;
851 ev_clear_pending (W w)
855 pendings [ABSPRI (w)][w->pending - 1].w = 0;
861 ev_start (W w, int active)
872 /*****************************************************************************/
875 ev_io_start (struct ev_io *w)
879 if (ev_is_active (w))
882 assert (("ev_io_start called with negative fd", fd >= 0));
885 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
886 wlist_add ((WL *)&anfds[fd].head, (WL)w);
892 ev_io_stop (struct ev_io *w)
894 ev_clear_pending ((W)w);
895 if (!ev_is_active (w))
898 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
905 ev_timer_start (struct ev_timer *w)
907 if (ev_is_active (w))
912 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
914 ev_start ((W)w, ++timercnt);
915 array_needsize (timers, timermax, timercnt, );
916 timers [timercnt - 1] = w;
917 upheap ((WT *)timers, timercnt - 1);
921 ev_timer_stop (struct ev_timer *w)
923 ev_clear_pending ((W)w);
924 if (!ev_is_active (w))
927 if (w->active < timercnt--)
929 timers [w->active - 1] = timers [timercnt];
930 downheap ((WT *)timers, timercnt, w->active - 1);
939 ev_timer_again (struct ev_timer *w)
941 if (ev_is_active (w))
945 w->at = now + w->repeat;
946 downheap ((WT *)timers, timercnt, w->active - 1);
956 ev_periodic_start (struct ev_periodic *w)
958 if (ev_is_active (w))
961 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
963 /* this formula differs from the one in periodic_reify because we do not always round up */
965 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
967 ev_start ((W)w, ++periodiccnt);
968 array_needsize (periodics, periodicmax, periodiccnt, );
969 periodics [periodiccnt - 1] = w;
970 upheap ((WT *)periodics, periodiccnt - 1);
974 ev_periodic_stop (struct ev_periodic *w)
976 ev_clear_pending ((W)w);
977 if (!ev_is_active (w))
980 if (w->active < periodiccnt--)
982 periodics [w->active - 1] = periodics [periodiccnt];
983 downheap ((WT *)periodics, periodiccnt, w->active - 1);
990 ev_signal_start (struct ev_signal *w)
992 if (ev_is_active (w))
995 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
998 array_needsize (signals, signalmax, w->signum, signals_init);
999 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
1003 struct sigaction sa;
1004 sa.sa_handler = sighandler;
1005 sigfillset (&sa.sa_mask);
1007 sigaction (w->signum, &sa, 0);
1012 ev_signal_stop (struct ev_signal *w)
1014 ev_clear_pending ((W)w);
1015 if (!ev_is_active (w))
1018 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
1021 if (!signals [w->signum - 1].head)
1022 signal (w->signum, SIG_DFL);
1026 ev_idle_start (struct ev_idle *w)
1028 if (ev_is_active (w))
1031 ev_start ((W)w, ++idlecnt);
1032 array_needsize (idles, idlemax, idlecnt, );
1033 idles [idlecnt - 1] = w;
1037 ev_idle_stop (struct ev_idle *w)
1039 ev_clear_pending ((W)w);
1040 if (ev_is_active (w))
1043 idles [w->active - 1] = idles [--idlecnt];
1048 ev_prepare_start (struct ev_prepare *w)
1050 if (ev_is_active (w))
1053 ev_start ((W)w, ++preparecnt);
1054 array_needsize (prepares, preparemax, preparecnt, );
1055 prepares [preparecnt - 1] = w;
1059 ev_prepare_stop (struct ev_prepare *w)
1061 ev_clear_pending ((W)w);
1062 if (ev_is_active (w))
1065 prepares [w->active - 1] = prepares [--preparecnt];
1070 ev_check_start (struct ev_check *w)
1072 if (ev_is_active (w))
1075 ev_start ((W)w, ++checkcnt);
1076 array_needsize (checks, checkmax, checkcnt, );
1077 checks [checkcnt - 1] = w;
1081 ev_check_stop (struct ev_check *w)
1083 ev_clear_pending ((W)w);
1084 if (ev_is_active (w))
1087 checks [w->active - 1] = checks [--checkcnt];
1092 ev_child_start (struct ev_child *w)
1094 if (ev_is_active (w))
1098 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1102 ev_child_stop (struct ev_child *w)
1104 ev_clear_pending ((W)w);
1105 if (ev_is_active (w))
1108 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1112 /*****************************************************************************/
1118 void (*cb)(int revents, void *arg);
1123 once_cb (struct ev_once *once, int revents)
1125 void (*cb)(int revents, void *arg) = once->cb;
1126 void *arg = once->arg;
1128 ev_io_stop (&once->io);
1129 ev_timer_stop (&once->to);
1136 once_cb_io (struct ev_io *w, int revents)
1138 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1142 once_cb_to (struct ev_timer *w, int revents)
1144 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1148 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1150 struct ev_once *once = malloc (sizeof (struct ev_once));
1153 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1159 ev_watcher_init (&once->io, once_cb_io);
1162 ev_io_set (&once->io, fd, events);
1163 ev_io_start (&once->io);
1166 ev_watcher_init (&once->to, once_cb_to);
1169 ev_timer_set (&once->to, timeout, 0.);
1170 ev_timer_start (&once->to);
1175 /*****************************************************************************/
1182 sin_cb (struct ev_io *w, int revents)
1184 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1188 ocb (struct ev_timer *w, int revents)
1190 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1196 scb (struct ev_signal *w, int revents)
1198 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1204 gcb (struct ev_signal *w, int revents)
1206 fprintf (stderr, "generic %x\n", revents);
1214 ev_io_init (&wio, sin_cb, 0, EV_READ);
1217 struct ev_timer t[10000];
1221 for (i = 0; i < 10000; ++i)
1223 struct ev_timer *w = t + i;
1224 ev_watcher_init (w, ocb, i);
1225 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1227 if (drand48 () < 0.5)
1233 ev_timer_init (&t1, ocb, 5, 10);
1234 ev_timer_start (&t1);
1236 struct ev_signal sig;
1237 ev_signal_init (&sig, scb, SIGQUIT);
1238 ev_signal_start (&sig);
1241 ev_check_init (&cw, gcb);
1242 ev_check_start (&cw);
1245 ev_idle_init (&iw, gcb);
1246 ev_idle_start (&iw);