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 /*****************************************************************************/
144 unsigned char events;
152 anfds_init (ANFD *base, int count)
157 base->events = EV_NONE;
170 static ANPENDING *pendings;
171 static int pendingmax, pendingcnt;
174 event (W w, int events)
178 pendings [w->pending - 1].events |= events;
182 w->pending = ++pendingcnt;
183 array_needsize (pendings, pendingmax, pendingcnt, );
184 pendings [pendingcnt - 1].w = w;
185 pendings [pendingcnt - 1].events = events;
189 queue_events (W *events, int eventcnt, int type)
193 for (i = 0; i < eventcnt; ++i)
194 event (events [i], type);
198 fd_event (int fd, int events)
200 ANFD *anfd = anfds + fd;
203 for (w = anfd->head; w; w = w->next)
205 int ev = w->events & events;
212 /*****************************************************************************/
214 static int *fdchanges;
215 static int fdchangemax, fdchangecnt;
222 for (i = 0; i < fdchangecnt; ++i)
224 int fd = fdchanges [i];
225 ANFD *anfd = anfds + fd;
230 for (w = anfd->head; w; w = w->next)
235 if (anfd->events != events)
237 method_modify (fd, anfd->events, events);
238 anfd->events = events;
248 if (anfds [fd].reify || fdchangecnt < 0)
251 anfds [fd].reify = 1;
254 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
255 fdchanges [fdchangecnt - 1] = fd;
258 /* called on EBADF to verify fds */
264 for (fd = 0; fd < anfdmax; ++fd)
265 if (anfds [fd].events)
266 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
267 while (anfds [fd].head)
269 ev_io_stop (anfds [fd].head);
270 event ((W)anfds [fd].head, EV_ERROR | EV_READ | EV_WRITE);
274 /*****************************************************************************/
276 static struct ev_timer **timers;
277 static int timermax, timercnt;
279 static struct ev_periodic **periodics;
280 static int periodicmax, periodiccnt;
283 upheap (WT *timers, int k)
287 while (k && timers [k >> 1]->at > w->at)
289 timers [k] = timers [k >> 1];
290 timers [k]->active = k + 1;
295 timers [k]->active = k + 1;
300 downheap (WT *timers, int N, int k)
308 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
311 if (w->at <= timers [j]->at)
314 timers [k] = timers [j];
315 timers [k]->active = k + 1;
320 timers [k]->active = k + 1;
323 /*****************************************************************************/
327 struct ev_signal *head;
331 static ANSIG *signals;
332 static int signalmax;
334 static int sigpipe [2];
335 static sig_atomic_t gotsig;
336 static struct ev_io sigev;
339 signals_init (ANSIG *base, int count)
351 sighandler (int signum)
353 signals [signum - 1].gotsig = 1;
358 write (sigpipe [1], &gotsig, 1);
363 sigcb (struct ev_io *iow, int revents)
369 read (sigpipe [0], &revents, 1);
371 for (sig = signalmax; sig--; )
372 if (signals [sig].gotsig)
374 signals [sig].gotsig = 0;
376 for (w = signals [sig].head; w; w = w->next)
377 event ((W)w, EV_SIGNAL);
384 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
385 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
387 /* rather than sort out wether we really need nb, set it */
388 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
389 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
391 ev_io_set (&sigev, sigpipe [0], EV_READ);
392 ev_io_start (&sigev);
395 /*****************************************************************************/
397 static struct ev_idle **idles;
398 static int idlemax, idlecnt;
400 static struct ev_prepare **prepares;
401 static int preparemax, preparecnt;
403 static struct ev_check **checks;
404 static int checkmax, checkcnt;
406 /*****************************************************************************/
408 static struct ev_child *childs [PID_HASHSIZE];
409 static struct ev_signal childev;
412 # define WCONTINUED 0
416 childcb (struct ev_signal *sw, int revents)
421 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
422 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
423 if (w->pid == pid || w->pid == -1)
426 event ((W)w, EV_CHILD);
430 /*****************************************************************************/
433 # include "ev_epoll.c"
436 # include "ev_select.c"
440 ev_version_major (void)
442 return EV_VERSION_MAJOR;
446 ev_version_minor (void)
448 return EV_VERSION_MINOR;
451 int ev_init (int flags)
458 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
470 ev_method = EVMETHOD_NONE;
472 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
475 if (ev_method == EVMETHOD_NONE) select_init (flags);
480 ev_watcher_init (&sigev, sigcb);
483 ev_signal_init (&childev, childcb, SIGCHLD);
484 ev_signal_start (&childev);
491 /*****************************************************************************/
500 ev_postfork_parent (void)
506 ev_postfork_child (void)
509 if (ev_method == EVMETHOD_EPOLL)
510 epoll_postfork_child ();
520 /*****************************************************************************/
527 ANPENDING *p = pendings + --pendingcnt;
532 p->w->cb (p->w, p->events);
540 while (timercnt && timers [0]->at <= now)
542 struct ev_timer *w = timers [0];
544 /* first reschedule or stop timer */
547 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
548 w->at = now + w->repeat;
549 downheap ((WT *)timers, timercnt, 0);
552 ev_timer_stop (w); /* nonrepeating: stop timer */
554 event ((W)w, EV_TIMEOUT);
559 periodics_reify (void)
561 while (periodiccnt && periodics [0]->at <= ev_now)
563 struct ev_periodic *w = periodics [0];
565 /* first reschedule or stop timer */
568 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
569 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", w->at > ev_now));
570 downheap ((WT *)periodics, periodiccnt, 0);
573 ev_periodic_stop (w); /* nonrepeating: stop timer */
575 event ((W)w, EV_PERIODIC);
580 periodics_reschedule (ev_tstamp diff)
584 /* adjust periodics after time jump */
585 for (i = 0; i < periodiccnt; ++i)
587 struct ev_periodic *w = periodics [i];
591 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
593 if (fabs (diff) >= 1e-4)
595 ev_periodic_stop (w);
596 ev_periodic_start (w);
598 i = 0; /* restart loop, inefficient, but time jumps should be rare */
613 ev_tstamp odiff = diff;
615 for (i = 4; --i; ) /* loop a few times, before making important decisions */
620 if (fabs (odiff - diff) < MIN_TIMEJUMP)
621 return; /* all is well */
626 periodics_reschedule (diff - odiff);
627 /* no timer adjustment, as the monotonic clock doesn't jump */
631 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
633 periodics_reschedule (ev_now - now);
635 /* adjust timers. this is easy, as the offset is the same for all */
636 for (i = 0; i < timercnt; ++i)
637 timers [i]->at += diff;
646 void ev_loop (int flags)
649 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
653 /* queue check watchers (and execute them) */
656 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
660 /* update fd-related kernel structures */
663 /* calculate blocking time */
665 /* we only need this for !monotonic clockor timers, but as we basically
666 always have timers, we just calculate it always */
669 if (flags & EVLOOP_NONBLOCK || idlecnt)
673 block = MAX_BLOCKTIME;
677 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
678 if (block > to) block = to;
683 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
684 if (block > to) block = to;
687 if (block < 0.) block = 0.;
692 /* update ev_now, do magic */
695 /* queue pending timers and reschedule them */
696 timers_reify (); /* relative timers called last */
697 periodics_reify (); /* absolute timers called first */
699 /* queue idle watchers unless io or timers are pending */
701 queue_events ((W *)idles, idlecnt, EV_IDLE);
703 /* queue check watchers, to be executed first */
705 queue_events ((W *)checks, checkcnt, EV_CHECK);
709 while (!ev_loop_done);
711 if (ev_loop_done != 2)
715 /*****************************************************************************/
718 wlist_add (WL *head, WL elem)
725 wlist_del (WL *head, WL elem)
735 head = &(*head)->next;
740 ev_clear_pending (W w)
744 pendings [w->pending - 1].w = 0;
750 ev_start (W w, int active)
761 /*****************************************************************************/
764 ev_io_start (struct ev_io *w)
766 if (ev_is_active (w))
771 assert (("ev_io_start called with negative fd", fd >= 0));
774 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
775 wlist_add ((WL *)&anfds[fd].head, (WL)w);
781 ev_io_stop (struct ev_io *w)
783 ev_clear_pending ((W)w);
784 if (!ev_is_active (w))
787 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
794 ev_timer_start (struct ev_timer *w)
796 if (ev_is_active (w))
801 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
803 ev_start ((W)w, ++timercnt);
804 array_needsize (timers, timermax, timercnt, );
805 timers [timercnt - 1] = w;
806 upheap ((WT *)timers, timercnt - 1);
810 ev_timer_stop (struct ev_timer *w)
812 ev_clear_pending ((W)w);
813 if (!ev_is_active (w))
816 if (w->active < timercnt--)
818 timers [w->active - 1] = timers [timercnt];
819 downheap ((WT *)timers, timercnt, w->active - 1);
828 ev_timer_again (struct ev_timer *w)
830 if (ev_is_active (w))
834 w->at = now + w->repeat;
835 downheap ((WT *)timers, timercnt, w->active - 1);
845 ev_periodic_start (struct ev_periodic *w)
847 if (ev_is_active (w))
850 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
852 /* this formula differs from the one in periodic_reify because we do not always round up */
854 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
856 ev_start ((W)w, ++periodiccnt);
857 array_needsize (periodics, periodicmax, periodiccnt, );
858 periodics [periodiccnt - 1] = w;
859 upheap ((WT *)periodics, periodiccnt - 1);
863 ev_periodic_stop (struct ev_periodic *w)
865 ev_clear_pending ((W)w);
866 if (!ev_is_active (w))
869 if (w->active < periodiccnt--)
871 periodics [w->active - 1] = periodics [periodiccnt];
872 downheap ((WT *)periodics, periodiccnt, w->active - 1);
879 ev_signal_start (struct ev_signal *w)
881 if (ev_is_active (w))
884 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
887 array_needsize (signals, signalmax, w->signum, signals_init);
888 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
893 sa.sa_handler = sighandler;
894 sigfillset (&sa.sa_mask);
896 sigaction (w->signum, &sa, 0);
901 ev_signal_stop (struct ev_signal *w)
903 ev_clear_pending ((W)w);
904 if (!ev_is_active (w))
907 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
910 if (!signals [w->signum - 1].head)
911 signal (w->signum, SIG_DFL);
915 ev_idle_start (struct ev_idle *w)
917 if (ev_is_active (w))
920 ev_start ((W)w, ++idlecnt);
921 array_needsize (idles, idlemax, idlecnt, );
922 idles [idlecnt - 1] = w;
926 ev_idle_stop (struct ev_idle *w)
928 ev_clear_pending ((W)w);
929 if (ev_is_active (w))
932 idles [w->active - 1] = idles [--idlecnt];
937 ev_prepare_start (struct ev_prepare *w)
939 if (ev_is_active (w))
942 ev_start ((W)w, ++preparecnt);
943 array_needsize (prepares, preparemax, preparecnt, );
944 prepares [preparecnt - 1] = w;
948 ev_prepare_stop (struct ev_prepare *w)
950 ev_clear_pending ((W)w);
951 if (ev_is_active (w))
954 prepares [w->active - 1] = prepares [--preparecnt];
959 ev_check_start (struct ev_check *w)
961 if (ev_is_active (w))
964 ev_start ((W)w, ++checkcnt);
965 array_needsize (checks, checkmax, checkcnt, );
966 checks [checkcnt - 1] = w;
970 ev_check_stop (struct ev_check *w)
972 ev_clear_pending ((W)w);
973 if (ev_is_active (w))
976 checks [w->active - 1] = checks [--checkcnt];
981 ev_child_start (struct ev_child *w)
983 if (ev_is_active (w))
987 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
991 ev_child_stop (struct ev_child *w)
993 ev_clear_pending ((W)w);
994 if (ev_is_active (w))
997 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1001 /*****************************************************************************/
1007 void (*cb)(int revents, void *arg);
1012 once_cb (struct ev_once *once, int revents)
1014 void (*cb)(int revents, void *arg) = once->cb;
1015 void *arg = once->arg;
1017 ev_io_stop (&once->io);
1018 ev_timer_stop (&once->to);
1025 once_cb_io (struct ev_io *w, int revents)
1027 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1031 once_cb_to (struct ev_timer *w, int revents)
1033 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1037 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1039 struct ev_once *once = malloc (sizeof (struct ev_once));
1042 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1048 ev_watcher_init (&once->io, once_cb_io);
1051 ev_io_set (&once->io, fd, events);
1052 ev_io_start (&once->io);
1055 ev_watcher_init (&once->to, once_cb_to);
1058 ev_timer_set (&once->to, timeout, 0.);
1059 ev_timer_start (&once->to);
1064 /*****************************************************************************/
1071 sin_cb (struct ev_io *w, int revents)
1073 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1077 ocb (struct ev_timer *w, int revents)
1079 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1085 scb (struct ev_signal *w, int revents)
1087 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1093 gcb (struct ev_signal *w, int revents)
1095 fprintf (stderr, "generic %x\n", revents);
1103 ev_io_init (&wio, sin_cb, 0, EV_READ);
1106 struct ev_timer t[10000];
1110 for (i = 0; i < 10000; ++i)
1112 struct ev_timer *w = t + i;
1113 ev_watcher_init (w, ocb, i);
1114 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1116 if (drand48 () < 0.5)
1122 ev_timer_init (&t1, ocb, 5, 10);
1123 ev_timer_start (&t1);
1125 struct ev_signal sig;
1126 ev_signal_init (&sig, scb, SIGQUIT);
1127 ev_signal_start (&sig);
1130 ev_check_init (&cw, gcb);
1131 ev_check_start (&cw);
1134 ev_idle_init (&iw, gcb);
1135 ev_idle_start (&iw);