2 * Copyright (c) 2007 Marc Alexander Lehmann <libev@schmorp.de>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
9 * * Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
12 * * Redistributions in binary form must reproduce the above
13 * copyright notice, this list of conditions and the following
14 * disclaimer in the documentation and/or other materials provided
15 * with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44 #include <sys/types.h>
49 #ifndef EV_USE_MONOTONIC
50 # ifdef CLOCK_MONOTONIC
51 # define EV_USE_MONOTONIC 1
56 # define EV_USE_SELECT 1
60 # define EV_USE_EPOLL 0
63 #ifndef CLOCK_REALTIME
64 # define EV_USE_REALTIME 0
66 #ifndef EV_USE_REALTIME
67 # define EV_USE_REALTIME 1 /* posix requirement, but might be slower */
70 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
71 #define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detetc time jumps) */
72 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
73 #define CLEANUP_INTERVAL (MAX_BLOCKTIME * 5.) /* how often to try to free memory and re-check fds */
77 typedef struct ev_watcher *W;
78 typedef struct ev_watcher_list *WL;
79 typedef struct ev_watcher_time *WT;
81 static ev_tstamp now, diff; /* monotonic clock */
85 static int have_monotonic; /* runtime */
87 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
88 static void (*method_modify)(int fd, int oev, int nev);
89 static void (*method_poll)(ev_tstamp timeout);
91 /*****************************************************************************/
98 clock_gettime (CLOCK_REALTIME, &ts);
99 return ts.tv_sec + ts.tv_nsec * 1e-9;
102 gettimeofday (&tv, 0);
103 return tv.tv_sec + tv.tv_usec * 1e-6;
114 clock_gettime (CLOCK_MONOTONIC, &ts);
115 return ts.tv_sec + ts.tv_nsec * 1e-9;
122 #define array_roundsize(base,n) ((n) | 4 & ~3)
124 #define array_needsize(base,cur,cnt,init) \
130 newcnt = array_roundsize (base, newcnt << 1); \
132 while ((cnt) > newcnt); \
134 base = realloc (base, sizeof (*base) * (newcnt)); \
135 init (base + cur, newcnt - cur); \
139 /*****************************************************************************/
151 anfds_init (ANFD *base, int count)
156 base->events = EV_NONE;
167 static ANPENDING *pendings;
168 static int pendingmax, pendingcnt;
171 event (W w, int events)
173 w->pending = ++pendingcnt;
174 array_needsize (pendings, pendingmax, pendingcnt, );
175 pendings [pendingcnt - 1].w = w;
176 pendings [pendingcnt - 1].events = events;
180 queue_events (W *events, int eventcnt, int type)
184 for (i = 0; i < eventcnt; ++i)
185 event (events [i], type);
189 fd_event (int fd, int events)
191 ANFD *anfd = anfds + fd;
194 for (w = anfd->head; w; w = w->next)
196 int ev = w->events & events;
203 /*****************************************************************************/
205 static int *fdchanges;
206 static int fdchangemax, fdchangecnt;
213 for (i = 0; i < fdchangecnt; ++i)
215 int fd = fdchanges [i];
216 ANFD *anfd = anfds + fd;
221 for (w = anfd->head; w; w = w->next)
224 anfd->events &= ~EV_REIFY;
226 if (anfd->events != events)
228 method_modify (fd, anfd->events, events);
229 anfd->events = events;
239 if (anfds [fd].events & EV_REIFY || fdchangecnt < 0)
242 anfds [fd].events |= EV_REIFY;
245 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
246 fdchanges [fdchangecnt - 1] = fd;
249 /* called on EBADF to verify fds */
255 for (fd = 0; fd < anfdmax; ++fd)
256 if (anfds [fd].events)
257 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
258 while (anfds [fd].head)
260 event ((W)anfds [fd].head, EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT);
261 ev_io_stop (anfds [fd].head);
265 /*****************************************************************************/
267 static struct ev_timer **timers;
268 static int timermax, timercnt;
270 static struct ev_periodic **periodics;
271 static int periodicmax, periodiccnt;
274 upheap (WT *timers, int k)
278 while (k && timers [k >> 1]->at > w->at)
280 timers [k] = timers [k >> 1];
281 timers [k]->active = k + 1;
286 timers [k]->active = k + 1;
291 downheap (WT *timers, int N, int k)
299 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
302 if (w->at <= timers [j]->at)
305 timers [k] = timers [j];
306 timers [k]->active = k + 1;
311 timers [k]->active = k + 1;
314 /*****************************************************************************/
318 struct ev_signal *head;
322 static ANSIG *signals;
323 static int signalmax;
325 static int sigpipe [2];
326 static sig_atomic_t gotsig;
327 static struct ev_io sigev;
330 signals_init (ANSIG *base, int count)
341 sighandler (int signum)
343 signals [signum - 1].gotsig = 1;
348 write (sigpipe [1], &gotsig, 1);
353 sigcb (struct ev_io *iow, int revents)
359 read (sigpipe [0], &revents, 1);
361 for (sig = signalmax; sig--; )
362 if (signals [sig].gotsig)
364 signals [sig].gotsig = 0;
366 for (w = signals [sig].head; w; w = w->next)
367 event ((W)w, EV_SIGNAL);
374 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
375 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
377 /* rather than sort out wether we really need nb, set it */
378 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
379 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
381 ev_io_set (&sigev, sigpipe [0], EV_READ);
382 ev_io_start (&sigev);
385 /*****************************************************************************/
387 static struct ev_idle **idles;
388 static int idlemax, idlecnt;
390 static struct ev_prepare **prepares;
391 static int preparemax, preparecnt;
393 static struct ev_check **checks;
394 static int checkmax, checkcnt;
396 /*****************************************************************************/
398 static struct ev_child *childs [PID_HASHSIZE];
399 static struct ev_signal childev;
402 # define WCONTINUED 0
406 childcb (struct ev_signal *sw, int revents)
411 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
412 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
413 if (w->pid == pid || w->pid == -1)
416 event ((W)w, EV_CHILD);
420 /*****************************************************************************/
423 # include "ev_epoll.c"
426 # include "ev_select.c"
430 ev_version_major (void)
432 return EV_VERSION_MAJOR;
436 ev_version_minor (void)
438 return EV_VERSION_MINOR;
441 int ev_init (int flags)
448 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
460 ev_method = EVMETHOD_NONE;
462 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
465 if (ev_method == EVMETHOD_NONE) select_init (flags);
470 ev_watcher_init (&sigev, sigcb);
473 ev_signal_init (&childev, childcb, SIGCHLD);
474 ev_signal_start (&childev);
481 /*****************************************************************************/
490 ev_postfork_parent (void)
496 ev_postfork_child (void)
499 if (ev_method == EVMETHOD_EPOLL)
500 epoll_postfork_child ();
510 /*****************************************************************************/
517 ANPENDING *p = pendings + --pendingcnt;
522 p->w->cb (p->w, p->events);
530 while (timercnt && timers [0]->at <= now)
532 struct ev_timer *w = timers [0];
534 /* first reschedule or stop timer */
537 w->at = now + w->repeat;
538 assert (("timer timeout in the past, negative repeat?", w->at > now));
539 downheap ((WT *)timers, timercnt, 0);
542 ev_timer_stop (w); /* nonrepeating: stop timer */
544 event ((W)w, EV_TIMEOUT);
549 periodics_reify (void)
551 while (periodiccnt && periodics [0]->at <= ev_now)
553 struct ev_periodic *w = periodics [0];
555 /* first reschedule or stop timer */
558 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
559 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
560 downheap ((WT *)periodics, periodiccnt, 0);
563 ev_periodic_stop (w); /* nonrepeating: stop timer */
565 event ((W)w, EV_TIMEOUT);
570 periodics_reschedule (ev_tstamp diff)
574 /* adjust periodics after time jump */
575 for (i = 0; i < periodiccnt; ++i)
577 struct ev_periodic *w = periodics [i];
581 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
583 if (fabs (diff) >= 1e-4)
585 ev_periodic_stop (w);
586 ev_periodic_start (w);
588 i = 0; /* restart loop, inefficient, but time jumps should be rare */
603 ev_tstamp odiff = diff;
605 for (i = 4; --i; ) /* loop a few times, before making important decisions */
610 if (fabs (odiff - diff) < MIN_TIMEJUMP)
611 return; /* all is well */
616 periodics_reschedule (diff - odiff);
617 /* no timer adjustment, as the monotonic clock doesn't jump */
621 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
623 periodics_reschedule (ev_now - now);
625 /* adjust timers. this is easy, as the offset is the same for all */
626 for (i = 0; i < timercnt; ++i)
627 timers [i]->at += diff;
636 void ev_loop (int flags)
639 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
643 /* queue check watchers (and execute them) */
646 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
650 /* update fd-related kernel structures */
653 /* calculate blocking time */
655 /* we only need this for !monotonic clockor timers, but as we basically
656 always have timers, we just calculate it always */
659 if (flags & EVLOOP_NONBLOCK || idlecnt)
663 block = MAX_BLOCKTIME;
667 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
668 if (block > to) block = to;
673 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
674 if (block > to) block = to;
677 if (block < 0.) block = 0.;
682 /* update ev_now, do magic */
685 /* queue pending timers and reschedule them */
686 timers_reify (); /* relative timers called last */
687 periodics_reify (); /* absolute timers called first */
689 /* queue idle watchers unless io or timers are pending */
691 queue_events ((W *)idles, idlecnt, EV_IDLE);
693 /* queue check watchers, to be executed first */
695 queue_events ((W *)checks, checkcnt, EV_CHECK);
699 while (!ev_loop_done);
701 if (ev_loop_done != 2)
705 /*****************************************************************************/
708 wlist_add (WL *head, WL elem)
715 wlist_del (WL *head, WL elem)
725 head = &(*head)->next;
734 pendings [w->pending - 1].w = 0;
740 ev_start (W w, int active)
751 /*****************************************************************************/
754 ev_io_start (struct ev_io *w)
756 if (ev_is_active (w))
762 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
763 wlist_add ((WL *)&anfds[fd].head, (WL)w);
769 ev_io_stop (struct ev_io *w)
772 if (!ev_is_active (w))
775 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
782 ev_timer_start (struct ev_timer *w)
784 if (ev_is_active (w))
789 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
791 ev_start ((W)w, ++timercnt);
792 array_needsize (timers, timermax, timercnt, );
793 timers [timercnt - 1] = w;
794 upheap ((WT *)timers, timercnt - 1);
798 ev_timer_stop (struct ev_timer *w)
801 if (!ev_is_active (w))
804 if (w->active < timercnt--)
806 timers [w->active - 1] = timers [timercnt];
807 downheap ((WT *)timers, timercnt, w->active - 1);
816 ev_timer_again (struct ev_timer *w)
818 if (ev_is_active (w))
822 w->at = now + w->repeat;
823 downheap ((WT *)timers, timercnt, w->active - 1);
833 ev_periodic_start (struct ev_periodic *w)
835 if (ev_is_active (w))
838 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
840 /* this formula differs from the one in periodic_reify because we do not always round up */
842 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
844 ev_start ((W)w, ++periodiccnt);
845 array_needsize (periodics, periodicmax, periodiccnt, );
846 periodics [periodiccnt - 1] = w;
847 upheap ((WT *)periodics, periodiccnt - 1);
851 ev_periodic_stop (struct ev_periodic *w)
854 if (!ev_is_active (w))
857 if (w->active < periodiccnt--)
859 periodics [w->active - 1] = periodics [periodiccnt];
860 downheap ((WT *)periodics, periodiccnt, w->active - 1);
867 ev_signal_start (struct ev_signal *w)
869 if (ev_is_active (w))
873 array_needsize (signals, signalmax, w->signum, signals_init);
874 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
879 sa.sa_handler = sighandler;
880 sigfillset (&sa.sa_mask);
882 sigaction (w->signum, &sa, 0);
887 ev_signal_stop (struct ev_signal *w)
890 if (!ev_is_active (w))
893 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
896 if (!signals [w->signum - 1].head)
897 signal (w->signum, SIG_DFL);
901 ev_idle_start (struct ev_idle *w)
903 if (ev_is_active (w))
906 ev_start ((W)w, ++idlecnt);
907 array_needsize (idles, idlemax, idlecnt, );
908 idles [idlecnt - 1] = w;
912 ev_idle_stop (struct ev_idle *w)
915 if (ev_is_active (w))
918 idles [w->active - 1] = idles [--idlecnt];
923 ev_prepare_start (struct ev_prepare *w)
925 if (ev_is_active (w))
928 ev_start ((W)w, ++preparecnt);
929 array_needsize (prepares, preparemax, preparecnt, );
930 prepares [preparecnt - 1] = w;
934 ev_prepare_stop (struct ev_prepare *w)
937 if (ev_is_active (w))
940 prepares [w->active - 1] = prepares [--preparecnt];
945 ev_check_start (struct ev_check *w)
947 if (ev_is_active (w))
950 ev_start ((W)w, ++checkcnt);
951 array_needsize (checks, checkmax, checkcnt, );
952 checks [checkcnt - 1] = w;
956 ev_check_stop (struct ev_check *w)
959 if (ev_is_active (w))
962 checks [w->active - 1] = checks [--checkcnt];
967 ev_child_start (struct ev_child *w)
969 if (ev_is_active (w))
973 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
977 ev_child_stop (struct ev_child *w)
980 if (ev_is_active (w))
983 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
987 /*****************************************************************************/
993 void (*cb)(int revents, void *arg);
998 once_cb (struct ev_once *once, int revents)
1000 void (*cb)(int revents, void *arg) = once->cb;
1001 void *arg = once->arg;
1003 ev_io_stop (&once->io);
1004 ev_timer_stop (&once->to);
1011 once_cb_io (struct ev_io *w, int revents)
1013 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1017 once_cb_to (struct ev_timer *w, int revents)
1019 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1023 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1025 struct ev_once *once = malloc (sizeof (struct ev_once));
1028 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1034 ev_watcher_init (&once->io, once_cb_io);
1037 ev_io_set (&once->io, fd, events);
1038 ev_io_start (&once->io);
1041 ev_watcher_init (&once->to, once_cb_to);
1044 ev_timer_set (&once->to, timeout, 0.);
1045 ev_timer_start (&once->to);
1050 /*****************************************************************************/
1057 sin_cb (struct ev_io *w, int revents)
1059 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1063 ocb (struct ev_timer *w, int revents)
1065 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1071 scb (struct ev_signal *w, int revents)
1073 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1079 gcb (struct ev_signal *w, int revents)
1081 fprintf (stderr, "generic %x\n", revents);
1089 ev_io_init (&wio, sin_cb, 0, EV_READ);
1092 struct ev_timer t[10000];
1096 for (i = 0; i < 10000; ++i)
1098 struct ev_timer *w = t + i;
1099 ev_watcher_init (w, ocb, i);
1100 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1102 if (drand48 () < 0.5)
1108 ev_timer_init (&t1, ocb, 5, 10);
1109 ev_timer_start (&t1);
1111 struct ev_signal sig;
1112 ev_signal_init (&sig, scb, SIGQUIT);
1113 ev_signal_start (&sig);
1116 ev_check_init (&cw, gcb);
1117 ev_check_start (&cw);
1120 ev_idle_init (&iw, gcb);
1121 ev_idle_start (&iw);