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 EV_USE_REALTIME
64 # define EV_USE_REALTIME 1 /* posix requirement, but might be slower */
67 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
68 #define MAX_BLOCKTIME 59.731
69 #define PID_HASHSIZE 16 /* size of pid hahs table, must be power of two */
73 typedef struct ev_watcher *W;
74 typedef struct ev_watcher_list *WL;
75 typedef struct ev_watcher_time *WT;
77 static ev_tstamp now, diff; /* monotonic clock */
81 static int have_monotonic; /* runtime */
83 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
84 static void (*method_modify)(int fd, int oev, int nev);
85 static void (*method_poll)(ev_tstamp timeout);
87 /*****************************************************************************/
94 clock_gettime (CLOCK_REALTIME, &ts);
95 return ts.tv_sec + ts.tv_nsec * 1e-9;
98 gettimeofday (&tv, 0);
99 return tv.tv_sec + tv.tv_usec * 1e-6;
110 clock_gettime (CLOCK_MONOTONIC, &ts);
111 return ts.tv_sec + ts.tv_nsec * 1e-9;
118 #define array_roundsize(base,n) ((n) | 4 & ~3)
120 #define array_needsize(base,cur,cnt,init) \
126 newcnt = array_roundsize (base, newcnt << 1); \
128 while ((cnt) > newcnt); \
130 base = realloc (base, sizeof (*base) * (newcnt)); \
131 init (base + cur, newcnt - cur); \
135 /*****************************************************************************/
147 anfds_init (ANFD *base, int count)
152 base->events = EV_NONE;
163 static ANPENDING *pendings;
164 static int pendingmax, pendingcnt;
167 event (W w, int events)
169 w->pending = ++pendingcnt;
170 array_needsize (pendings, pendingmax, pendingcnt, );
171 pendings [pendingcnt - 1].w = w;
172 pendings [pendingcnt - 1].events = events;
176 queue_events (W *events, int eventcnt, int type)
180 for (i = 0; i < eventcnt; ++i)
181 event (events [i], type);
185 fd_event (int fd, int events)
187 ANFD *anfd = anfds + fd;
190 for (w = anfd->head; w; w = w->next)
192 int ev = w->events & events;
199 /*****************************************************************************/
201 static int *fdchanges;
202 static int fdchangemax, fdchangecnt;
209 for (i = 0; i < fdchangecnt; ++i)
211 int fd = fdchanges [i];
212 ANFD *anfd = anfds + fd;
217 for (w = anfd->head; w; w = w->next)
220 anfd->events &= ~EV_REIFY;
222 if (anfd->events != events)
224 method_modify (fd, anfd->events, events);
225 anfd->events = events;
235 if (anfds [fd].events & EV_REIFY || fdchangecnt < 0)
238 anfds [fd].events |= EV_REIFY;
241 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
242 fdchanges [fdchangecnt - 1] = fd;
245 /* called on EBADF to verify fds */
251 for (fd = 0; fd < anfdmax; ++fd)
252 if (anfds [fd].events)
253 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
254 while (anfds [fd].head)
256 event ((W)anfds [fd].head, EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT);
257 ev_io_stop (anfds [fd].head);
261 /*****************************************************************************/
263 static struct ev_timer **timers;
264 static int timermax, timercnt;
266 static struct ev_periodic **periodics;
267 static int periodicmax, periodiccnt;
270 upheap (WT *timers, int k)
274 while (k && timers [k >> 1]->at > w->at)
276 timers [k] = timers [k >> 1];
277 timers [k]->active = k + 1;
282 timers [k]->active = k + 1;
287 downheap (WT *timers, int N, int k)
295 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
298 if (w->at <= timers [j]->at)
301 timers [k] = timers [j];
302 timers [k]->active = k + 1;
307 timers [k]->active = k + 1;
310 /*****************************************************************************/
314 struct ev_signal *head;
318 static ANSIG *signals;
319 static int signalmax;
321 static int sigpipe [2];
322 static sig_atomic_t gotsig;
323 static struct ev_io sigev;
326 signals_init (ANSIG *base, int count)
337 sighandler (int signum)
339 signals [signum - 1].gotsig = 1;
344 write (sigpipe [1], &gotsig, 1);
349 sigcb (struct ev_io *iow, int revents)
355 read (sigpipe [0], &revents, 1);
357 for (sig = signalmax; sig--; )
358 if (signals [sig].gotsig)
360 signals [sig].gotsig = 0;
362 for (w = signals [sig].head; w; w = w->next)
363 event ((W)w, EV_SIGNAL);
370 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
371 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
373 /* rather than sort out wether we really need nb, set it */
374 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
375 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
377 ev_io_set (&sigev, sigpipe [0], EV_READ);
378 ev_io_start (&sigev);
381 /*****************************************************************************/
383 static struct ev_idle **idles;
384 static int idlemax, idlecnt;
386 static struct ev_prepare **prepares;
387 static int preparemax, preparecnt;
389 static struct ev_check **checks;
390 static int checkmax, checkcnt;
392 /*****************************************************************************/
394 static struct ev_child *childs [PID_HASHSIZE];
395 static struct ev_signal childev;
398 # define WCONTINUED 0
402 childcb (struct ev_signal *sw, int revents)
407 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
408 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
409 if (w->pid == pid || w->pid == -1)
412 event ((W)w, EV_CHILD);
416 /*****************************************************************************/
419 # include "ev_epoll.c"
422 # include "ev_select.c"
426 ev_version_major (void)
428 return EV_VERSION_MAJOR;
432 ev_version_minor (void)
434 return EV_VERSION_MINOR;
437 int ev_init (int flags)
444 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
456 ev_method = EVMETHOD_NONE;
458 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
461 if (ev_method == EVMETHOD_NONE) select_init (flags);
466 ev_watcher_init (&sigev, sigcb);
469 ev_signal_init (&childev, childcb, SIGCHLD);
470 ev_signal_start (&childev);
477 /*****************************************************************************/
486 ev_postfork_parent (void)
492 ev_postfork_child (void)
495 if (ev_method == EVMETHOD_EPOLL)
496 epoll_postfork_child ();
506 /*****************************************************************************/
513 ANPENDING *p = pendings + --pendingcnt;
518 p->w->cb (p->w, p->events);
526 while (timercnt && timers [0]->at <= now)
528 struct ev_timer *w = timers [0];
530 /* first reschedule or stop timer */
533 w->at = now + w->repeat;
534 assert (("timer timeout in the past, negative repeat?", w->at > now));
535 downheap ((WT *)timers, timercnt, 0);
538 ev_timer_stop (w); /* nonrepeating: stop timer */
540 event ((W)w, EV_TIMEOUT);
545 periodics_reify (void)
547 while (periodiccnt && periodics [0]->at <= ev_now)
549 struct ev_periodic *w = periodics [0];
551 /* first reschedule or stop timer */
554 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
555 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
556 downheap ((WT *)periodics, periodiccnt, 0);
559 ev_periodic_stop (w); /* nonrepeating: stop timer */
561 event ((W)w, EV_TIMEOUT);
566 periodics_reschedule (ev_tstamp diff)
570 /* adjust periodics after time jump */
571 for (i = 0; i < periodiccnt; ++i)
573 struct ev_periodic *w = periodics [i];
577 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
579 if (fabs (diff) >= 1e-4)
581 ev_periodic_stop (w);
582 ev_periodic_start (w);
584 i = 0; /* restart loop, inefficient, but time jumps should be rare */
599 ev_tstamp odiff = diff;
601 for (i = 4; --i; ) /* loop a few times, before making important decisions */
606 if (fabs (odiff - diff) < MIN_TIMEJUMP)
607 return; /* all is well */
612 periodics_reschedule (diff - odiff);
613 /* no timer adjustment, as the monotonic clock doesn't jump */
617 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
619 periodics_reschedule (ev_now - now);
621 /* adjust timers. this is easy, as the offset is the same for all */
622 for (i = 0; i < timercnt; ++i)
623 timers [i]->at += diff;
632 void ev_loop (int flags)
635 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
639 /* queue check watchers (and execute them) */
642 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
646 /* update fd-related kernel structures */
649 /* calculate blocking time */
651 /* we only need this for !monotonic clockor timers, but as we basically
652 always have timers, we just calculate it always */
655 if (flags & EVLOOP_NONBLOCK || idlecnt)
659 block = MAX_BLOCKTIME;
663 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
664 if (block > to) block = to;
669 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
670 if (block > to) block = to;
673 if (block < 0.) block = 0.;
678 /* update ev_now, do magic */
681 /* queue pending timers and reschedule them */
682 timers_reify (); /* relative timers called last */
683 periodics_reify (); /* absolute timers called first */
685 /* queue idle watchers unless io or timers are pending */
687 queue_events ((W *)idles, idlecnt, EV_IDLE);
689 /* queue check watchers, to be executed first */
691 queue_events ((W *)checks, checkcnt, EV_CHECK);
695 while (!ev_loop_done);
697 if (ev_loop_done != 2)
701 /*****************************************************************************/
704 wlist_add (WL *head, WL elem)
711 wlist_del (WL *head, WL elem)
721 head = &(*head)->next;
730 pendings [w->pending - 1].w = 0;
736 ev_start (W w, int active)
747 /*****************************************************************************/
750 ev_io_start (struct ev_io *w)
752 if (ev_is_active (w))
758 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
759 wlist_add ((WL *)&anfds[fd].head, (WL)w);
765 ev_io_stop (struct ev_io *w)
768 if (!ev_is_active (w))
771 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
778 ev_timer_start (struct ev_timer *w)
780 if (ev_is_active (w))
785 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
787 ev_start ((W)w, ++timercnt);
788 array_needsize (timers, timermax, timercnt, );
789 timers [timercnt - 1] = w;
790 upheap ((WT *)timers, timercnt - 1);
794 ev_timer_stop (struct ev_timer *w)
797 if (!ev_is_active (w))
800 if (w->active < timercnt--)
802 timers [w->active - 1] = timers [timercnt];
803 downheap ((WT *)timers, timercnt, w->active - 1);
812 ev_timer_again (struct ev_timer *w)
814 if (ev_is_active (w))
818 w->at = now + w->repeat;
819 downheap ((WT *)timers, timercnt, w->active - 1);
829 ev_periodic_start (struct ev_periodic *w)
831 if (ev_is_active (w))
834 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
836 /* this formula differs from the one in periodic_reify because we do not always round up */
838 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
840 ev_start ((W)w, ++periodiccnt);
841 array_needsize (periodics, periodicmax, periodiccnt, );
842 periodics [periodiccnt - 1] = w;
843 upheap ((WT *)periodics, periodiccnt - 1);
847 ev_periodic_stop (struct ev_periodic *w)
850 if (!ev_is_active (w))
853 if (w->active < periodiccnt--)
855 periodics [w->active - 1] = periodics [periodiccnt];
856 downheap ((WT *)periodics, periodiccnt, w->active - 1);
863 ev_signal_start (struct ev_signal *w)
865 if (ev_is_active (w))
869 array_needsize (signals, signalmax, w->signum, signals_init);
870 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
875 sa.sa_handler = sighandler;
876 sigfillset (&sa.sa_mask);
878 sigaction (w->signum, &sa, 0);
883 ev_signal_stop (struct ev_signal *w)
886 if (!ev_is_active (w))
889 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
892 if (!signals [w->signum - 1].head)
893 signal (w->signum, SIG_DFL);
897 ev_idle_start (struct ev_idle *w)
899 if (ev_is_active (w))
902 ev_start ((W)w, ++idlecnt);
903 array_needsize (idles, idlemax, idlecnt, );
904 idles [idlecnt - 1] = w;
908 ev_idle_stop (struct ev_idle *w)
911 if (ev_is_active (w))
914 idles [w->active - 1] = idles [--idlecnt];
919 ev_prepare_start (struct ev_prepare *w)
921 if (ev_is_active (w))
924 ev_start ((W)w, ++preparecnt);
925 array_needsize (prepares, preparemax, preparecnt, );
926 prepares [preparecnt - 1] = w;
930 ev_prepare_stop (struct ev_prepare *w)
933 if (ev_is_active (w))
936 prepares [w->active - 1] = prepares [--preparecnt];
941 ev_check_start (struct ev_check *w)
943 if (ev_is_active (w))
946 ev_start ((W)w, ++checkcnt);
947 array_needsize (checks, checkmax, checkcnt, );
948 checks [checkcnt - 1] = w;
952 ev_check_stop (struct ev_check *w)
955 if (ev_is_active (w))
958 checks [w->active - 1] = checks [--checkcnt];
963 ev_child_start (struct ev_child *w)
965 if (ev_is_active (w))
969 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
973 ev_child_stop (struct ev_child *w)
976 if (ev_is_active (w))
979 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
983 /*****************************************************************************/
989 void (*cb)(int revents, void *arg);
994 once_cb (struct ev_once *once, int revents)
996 void (*cb)(int revents, void *arg) = once->cb;
997 void *arg = once->arg;
999 ev_io_stop (&once->io);
1000 ev_timer_stop (&once->to);
1007 once_cb_io (struct ev_io *w, int revents)
1009 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1013 once_cb_to (struct ev_timer *w, int revents)
1015 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1019 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1021 struct ev_once *once = malloc (sizeof (struct ev_once));
1024 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1030 ev_watcher_init (&once->io, once_cb_io);
1033 ev_io_set (&once->io, fd, events);
1034 ev_io_start (&once->io);
1037 ev_watcher_init (&once->to, once_cb_to);
1040 ev_timer_set (&once->to, timeout, 0.);
1041 ev_timer_start (&once->to);
1046 /*****************************************************************************/
1053 sin_cb (struct ev_io *w, int revents)
1055 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1059 ocb (struct ev_timer *w, int revents)
1061 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1067 scb (struct ev_signal *w, int revents)
1069 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1075 gcb (struct ev_signal *w, int revents)
1077 fprintf (stderr, "generic %x\n", revents);
1085 ev_io_init (&wio, sin_cb, 0, EV_READ);
1088 struct ev_timer t[10000];
1092 for (i = 0; i < 10000; ++i)
1094 struct ev_timer *w = t + i;
1095 ev_watcher_init (w, ocb, i);
1096 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1098 if (drand48 () < 0.5)
1104 ev_timer_init (&t1, ocb, 5, 10);
1105 ev_timer_start (&t1);
1107 struct ev_signal sig;
1108 ev_signal_init (&sig, scb, SIGQUIT);
1109 ev_signal_start (&sig);
1112 ev_check_init (&cw, gcb);
1113 ev_check_start (&cw);
1116 ev_idle_init (&iw, gcb);
1117 ev_idle_start (&iw);