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
70 # define EV_USE_KQUEUE 0
73 #ifndef EV_USE_REALTIME
74 # define EV_USE_REALTIME 1
79 #ifndef CLOCK_MONOTONIC
80 # undef EV_USE_MONOTONIC
81 # define EV_USE_MONOTONIC 0
84 #ifndef CLOCK_REALTIME
85 # undef EV_USE_REALTIME
86 # define EV_USE_REALTIME 0
91 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
92 #define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detect time jumps) */
93 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
94 /*#define CLEANUP_INTERVAL 300. /* how often to try to free memory and re-check fds */
99 # define expect(expr,value) __builtin_expect ((expr),(value))
100 # define inline inline
102 # define expect(expr,value) (expr)
103 # define inline static
106 #define expect_false(expr) expect ((expr) != 0, 0)
107 #define expect_true(expr) expect ((expr) != 0, 1)
109 #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
110 #define ABSPRI(w) ((w)->priority - EV_MINPRI)
112 typedef struct ev_watcher *W;
113 typedef struct ev_watcher_list *WL;
114 typedef struct ev_watcher_time *WT;
116 static ev_tstamp now_floor, now, diff; /* monotonic clock */
120 static int have_monotonic; /* runtime */
122 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
123 static void (*method_modify)(int fd, int oev, int nev);
124 static void (*method_poll)(ev_tstamp timeout);
126 /*****************************************************************************/
133 clock_gettime (CLOCK_REALTIME, &ts);
134 return ts.tv_sec + ts.tv_nsec * 1e-9;
137 gettimeofday (&tv, 0);
138 return tv.tv_sec + tv.tv_usec * 1e-6;
146 if (expect_true (have_monotonic))
149 clock_gettime (CLOCK_MONOTONIC, &ts);
150 return ts.tv_sec + ts.tv_nsec * 1e-9;
157 #define array_roundsize(base,n) ((n) | 4 & ~3)
159 #define array_needsize(base,cur,cnt,init) \
160 if (expect_false ((cnt) > cur)) \
165 newcnt = array_roundsize (base, newcnt << 1); \
167 while ((cnt) > newcnt); \
169 base = realloc (base, sizeof (*base) * (newcnt)); \
170 init (base + cur, newcnt - cur); \
174 /*****************************************************************************/
179 unsigned char events;
187 anfds_init (ANFD *base, int count)
192 base->events = EV_NONE;
205 static ANPENDING *pendings [NUMPRI];
206 static int pendingmax [NUMPRI], pendingcnt [NUMPRI];
209 event (W w, int events)
213 pendings [ABSPRI (w)][w->pending - 1].events |= events;
217 w->pending = ++pendingcnt [ABSPRI (w)];
218 array_needsize (pendings [ABSPRI (w)], pendingmax [ABSPRI (w)], pendingcnt [ABSPRI (w)], );
219 pendings [ABSPRI (w)][w->pending - 1].w = w;
220 pendings [ABSPRI (w)][w->pending - 1].events = events;
224 queue_events (W *events, int eventcnt, int type)
228 for (i = 0; i < eventcnt; ++i)
229 event (events [i], type);
233 fd_event (int fd, int events)
235 ANFD *anfd = anfds + fd;
238 for (w = anfd->head; w; w = w->next)
240 int ev = w->events & events;
247 /*****************************************************************************/
249 static int *fdchanges;
250 static int fdchangemax, fdchangecnt;
257 for (i = 0; i < fdchangecnt; ++i)
259 int fd = fdchanges [i];
260 ANFD *anfd = anfds + fd;
265 for (w = anfd->head; w; w = w->next)
270 if (anfd->events != events)
272 method_modify (fd, anfd->events, events);
273 anfd->events = events;
283 if (anfds [fd].reify || fdchangecnt < 0)
286 anfds [fd].reify = 1;
289 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
290 fdchanges [fdchangecnt - 1] = fd;
298 printf ("killing fd %d\n", fd);//D
299 while ((w = anfds [fd].head))
302 event ((W)w, EV_ERROR | EV_READ | EV_WRITE);
306 /* called on EBADF to verify fds */
312 for (fd = 0; fd < anfdmax; ++fd)
313 if (anfds [fd].events)
314 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
318 /* called on ENOMEM in select/poll to kill some fds and retry */
325 if (anfds [fd].events)
333 /*****************************************************************************/
335 static struct ev_timer **timers;
336 static int timermax, timercnt;
338 static struct ev_periodic **periodics;
339 static int periodicmax, periodiccnt;
342 upheap (WT *timers, int k)
346 while (k && timers [k >> 1]->at > w->at)
348 timers [k] = timers [k >> 1];
349 timers [k]->active = k + 1;
354 timers [k]->active = k + 1;
359 downheap (WT *timers, int N, int k)
367 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
370 if (w->at <= timers [j]->at)
373 timers [k] = timers [j];
374 timers [k]->active = k + 1;
379 timers [k]->active = k + 1;
382 /*****************************************************************************/
386 struct ev_signal *head;
387 sig_atomic_t volatile gotsig;
390 static ANSIG *signals;
391 static int signalmax;
393 static int sigpipe [2];
394 static sig_atomic_t volatile gotsig;
395 static struct ev_io sigev;
398 signals_init (ANSIG *base, int count)
410 sighandler (int signum)
412 signals [signum - 1].gotsig = 1;
417 write (sigpipe [1], &signum, 1);
422 sigcb (struct ev_io *iow, int revents)
427 read (sigpipe [0], &revents, 1);
430 for (signum = signalmax; signum--; )
431 if (signals [signum].gotsig)
433 signals [signum].gotsig = 0;
435 for (w = signals [signum].head; w; w = w->next)
436 event ((W)w, EV_SIGNAL);
443 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
444 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
446 /* rather than sort out wether we really need nb, set it */
447 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
448 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
450 ev_io_set (&sigev, sigpipe [0], EV_READ);
451 ev_io_start (&sigev);
454 /*****************************************************************************/
456 static struct ev_idle **idles;
457 static int idlemax, idlecnt;
459 static struct ev_prepare **prepares;
460 static int preparemax, preparecnt;
462 static struct ev_check **checks;
463 static int checkmax, checkcnt;
465 /*****************************************************************************/
467 static struct ev_child *childs [PID_HASHSIZE];
468 static struct ev_signal childev;
471 # define WCONTINUED 0
475 childcb (struct ev_signal *sw, int revents)
480 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
481 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
482 if (w->pid == pid || !w->pid)
485 event ((W)w, EV_CHILD);
489 /*****************************************************************************/
492 # include "ev_kqueue.c"
495 # include "ev_epoll.c"
498 # include "ev_poll.c"
501 # include "ev_select.c"
505 ev_version_major (void)
507 return EV_VERSION_MAJOR;
511 ev_version_minor (void)
513 return EV_VERSION_MINOR;
516 /* return true if we are running with elevated privileges and ignore env variables */
520 return getuid () != geteuid ()
521 || getgid () != getegid ();
524 int ev_init (int methods)
531 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
544 if (methods == EVMETHOD_AUTO)
545 if (!enable_secure () && getenv ("LIBEV_METHODS"))
546 methods = atoi (getenv ("LIBEV_METHODS"));
548 methods = EVMETHOD_ANY;
552 if (!ev_method && (methods & EVMETHOD_KQUEUE)) kqueue_init (methods);
555 if (!ev_method && (methods & EVMETHOD_EPOLL )) epoll_init (methods);
558 if (!ev_method && (methods & EVMETHOD_POLL )) poll_init (methods);
561 if (!ev_method && (methods & EVMETHOD_SELECT)) select_init (methods);
566 ev_watcher_init (&sigev, sigcb);
569 ev_signal_init (&childev, childcb, SIGCHLD);
570 ev_signal_start (&childev);
577 /*****************************************************************************/
580 ev_fork_prepare (void)
586 ev_fork_parent (void)
595 if (ev_method == EVMETHOD_EPOLL)
596 epoll_postfork_child ();
606 /*****************************************************************************/
613 for (pri = NUMPRI; pri--; )
614 while (pendingcnt [pri])
616 ANPENDING *p = pendings [pri] + --pendingcnt [pri];
621 p->w->cb (p->w, p->events);
629 while (timercnt && timers [0]->at <= now)
631 struct ev_timer *w = timers [0];
633 /* first reschedule or stop timer */
636 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
637 w->at = now + w->repeat;
638 downheap ((WT *)timers, timercnt, 0);
641 ev_timer_stop (w); /* nonrepeating: stop timer */
643 event ((W)w, EV_TIMEOUT);
648 periodics_reify (void)
650 while (periodiccnt && periodics [0]->at <= ev_now)
652 struct ev_periodic *w = periodics [0];
654 /* first reschedule or stop timer */
657 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
658 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", w->at > ev_now));
659 downheap ((WT *)periodics, periodiccnt, 0);
662 ev_periodic_stop (w); /* nonrepeating: stop timer */
664 event ((W)w, EV_PERIODIC);
669 periodics_reschedule (ev_tstamp diff)
673 /* adjust periodics after time jump */
674 for (i = 0; i < periodiccnt; ++i)
676 struct ev_periodic *w = periodics [i];
680 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
682 if (fabs (diff) >= 1e-4)
684 ev_periodic_stop (w);
685 ev_periodic_start (w);
687 i = 0; /* restart loop, inefficient, but time jumps should be rare */
694 time_update_monotonic (void)
698 if (expect_true (now - now_floor < MIN_TIMEJUMP * .5))
717 if (expect_true (have_monotonic))
719 if (time_update_monotonic ())
721 ev_tstamp odiff = diff;
723 for (i = 4; --i; ) /* loop a few times, before making important decisions */
727 if (fabs (odiff - diff) < MIN_TIMEJUMP)
728 return; /* all is well */
735 periodics_reschedule (diff - odiff);
736 /* no timer adjustment, as the monotonic clock doesn't jump */
744 if (expect_false (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
746 periodics_reschedule (ev_now - now);
748 /* adjust timers. this is easy, as the offset is the same for all */
749 for (i = 0; i < timercnt; ++i)
750 timers [i]->at += diff;
759 void ev_loop (int flags)
762 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
766 /* queue check watchers (and execute them) */
767 if (expect_false (preparecnt))
769 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
773 /* update fd-related kernel structures */
776 /* calculate blocking time */
778 /* we only need this for !monotonic clockor timers, but as we basically
779 always have timers, we just calculate it always */
781 if (expect_true (have_monotonic))
782 time_update_monotonic ();
790 if (flags & EVLOOP_NONBLOCK || idlecnt)
794 block = MAX_BLOCKTIME;
798 ev_tstamp to = timers [0]->at - now + method_fudge;
799 if (block > to) block = to;
804 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
805 if (block > to) block = to;
808 if (block < 0.) block = 0.;
813 /* update ev_now, do magic */
816 /* queue pending timers and reschedule them */
817 timers_reify (); /* relative timers called last */
818 periodics_reify (); /* absolute timers called first */
820 /* queue idle watchers unless io or timers are pending */
822 queue_events ((W *)idles, idlecnt, EV_IDLE);
824 /* queue check watchers, to be executed first */
826 queue_events ((W *)checks, checkcnt, EV_CHECK);
830 while (!ev_loop_done);
832 if (ev_loop_done != 2)
836 /*****************************************************************************/
839 wlist_add (WL *head, WL elem)
846 wlist_del (WL *head, WL elem)
856 head = &(*head)->next;
861 ev_clear_pending (W w)
865 pendings [ABSPRI (w)][w->pending - 1].w = 0;
871 ev_start (W w, int active)
873 if (w->priority < EV_MINPRI) w->priority = EV_MINPRI;
874 if (w->priority > EV_MAXPRI) w->priority = EV_MAXPRI;
885 /*****************************************************************************/
888 ev_io_start (struct ev_io *w)
892 if (ev_is_active (w))
895 assert (("ev_io_start called with negative fd", fd >= 0));
898 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
899 wlist_add ((WL *)&anfds[fd].head, (WL)w);
905 ev_io_stop (struct ev_io *w)
907 ev_clear_pending ((W)w);
908 if (!ev_is_active (w))
911 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
918 ev_timer_start (struct ev_timer *w)
920 if (ev_is_active (w))
925 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
927 ev_start ((W)w, ++timercnt);
928 array_needsize (timers, timermax, timercnt, );
929 timers [timercnt - 1] = w;
930 upheap ((WT *)timers, timercnt - 1);
934 ev_timer_stop (struct ev_timer *w)
936 ev_clear_pending ((W)w);
937 if (!ev_is_active (w))
940 if (w->active < timercnt--)
942 timers [w->active - 1] = timers [timercnt];
943 downheap ((WT *)timers, timercnt, w->active - 1);
952 ev_timer_again (struct ev_timer *w)
954 if (ev_is_active (w))
958 w->at = now + w->repeat;
959 downheap ((WT *)timers, timercnt, w->active - 1);
969 ev_periodic_start (struct ev_periodic *w)
971 if (ev_is_active (w))
974 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
976 /* this formula differs from the one in periodic_reify because we do not always round up */
978 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
980 ev_start ((W)w, ++periodiccnt);
981 array_needsize (periodics, periodicmax, periodiccnt, );
982 periodics [periodiccnt - 1] = w;
983 upheap ((WT *)periodics, periodiccnt - 1);
987 ev_periodic_stop (struct ev_periodic *w)
989 ev_clear_pending ((W)w);
990 if (!ev_is_active (w))
993 if (w->active < periodiccnt--)
995 periodics [w->active - 1] = periodics [periodiccnt];
996 downheap ((WT *)periodics, periodiccnt, w->active - 1);
1003 ev_signal_start (struct ev_signal *w)
1005 if (ev_is_active (w))
1008 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
1011 array_needsize (signals, signalmax, w->signum, signals_init);
1012 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
1016 struct sigaction sa;
1017 sa.sa_handler = sighandler;
1018 sigfillset (&sa.sa_mask);
1020 sigaction (w->signum, &sa, 0);
1025 ev_signal_stop (struct ev_signal *w)
1027 ev_clear_pending ((W)w);
1028 if (!ev_is_active (w))
1031 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
1034 if (!signals [w->signum - 1].head)
1035 signal (w->signum, SIG_DFL);
1039 ev_idle_start (struct ev_idle *w)
1041 if (ev_is_active (w))
1044 ev_start ((W)w, ++idlecnt);
1045 array_needsize (idles, idlemax, idlecnt, );
1046 idles [idlecnt - 1] = w;
1050 ev_idle_stop (struct ev_idle *w)
1052 ev_clear_pending ((W)w);
1053 if (ev_is_active (w))
1056 idles [w->active - 1] = idles [--idlecnt];
1061 ev_prepare_start (struct ev_prepare *w)
1063 if (ev_is_active (w))
1066 ev_start ((W)w, ++preparecnt);
1067 array_needsize (prepares, preparemax, preparecnt, );
1068 prepares [preparecnt - 1] = w;
1072 ev_prepare_stop (struct ev_prepare *w)
1074 ev_clear_pending ((W)w);
1075 if (ev_is_active (w))
1078 prepares [w->active - 1] = prepares [--preparecnt];
1083 ev_check_start (struct ev_check *w)
1085 if (ev_is_active (w))
1088 ev_start ((W)w, ++checkcnt);
1089 array_needsize (checks, checkmax, checkcnt, );
1090 checks [checkcnt - 1] = w;
1094 ev_check_stop (struct ev_check *w)
1096 ev_clear_pending ((W)w);
1097 if (ev_is_active (w))
1100 checks [w->active - 1] = checks [--checkcnt];
1105 ev_child_start (struct ev_child *w)
1107 if (ev_is_active (w))
1111 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1115 ev_child_stop (struct ev_child *w)
1117 ev_clear_pending ((W)w);
1118 if (ev_is_active (w))
1121 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1125 /*****************************************************************************/
1131 void (*cb)(int revents, void *arg);
1136 once_cb (struct ev_once *once, int revents)
1138 void (*cb)(int revents, void *arg) = once->cb;
1139 void *arg = once->arg;
1141 ev_io_stop (&once->io);
1142 ev_timer_stop (&once->to);
1149 once_cb_io (struct ev_io *w, int revents)
1151 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1155 once_cb_to (struct ev_timer *w, int revents)
1157 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1161 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1163 struct ev_once *once = malloc (sizeof (struct ev_once));
1166 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1172 ev_watcher_init (&once->io, once_cb_io);
1175 ev_io_set (&once->io, fd, events);
1176 ev_io_start (&once->io);
1179 ev_watcher_init (&once->to, once_cb_to);
1182 ev_timer_set (&once->to, timeout, 0.);
1183 ev_timer_start (&once->to);
1188 /*****************************************************************************/
1195 sin_cb (struct ev_io *w, int revents)
1197 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1201 ocb (struct ev_timer *w, int revents)
1203 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1209 scb (struct ev_signal *w, int revents)
1211 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1217 gcb (struct ev_signal *w, int revents)
1219 fprintf (stderr, "generic %x\n", revents);
1227 ev_io_init (&wio, sin_cb, 0, EV_READ);
1230 struct ev_timer t[10000];
1234 for (i = 0; i < 10000; ++i)
1236 struct ev_timer *w = t + i;
1237 ev_watcher_init (w, ocb, i);
1238 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1240 if (drand48 () < 0.5)
1246 ev_timer_init (&t1, ocb, 5, 10);
1247 ev_timer_start (&t1);
1249 struct ev_signal sig;
1250 ev_signal_init (&sig, scb, SIGQUIT);
1251 ev_signal_start (&sig);
1254 ev_check_init (&cw, gcb);
1255 ev_check_start (&cw);
1258 ev_idle_init (&iw, gcb);
1259 ev_idle_start (&iw);