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)
175 pendings [w->pending - 1].events |= events;
179 w->pending = ++pendingcnt;
180 array_needsize (pendings, pendingmax, pendingcnt, );
181 pendings [pendingcnt - 1].w = w;
182 pendings [pendingcnt - 1].events = events;
186 queue_events (W *events, int eventcnt, int type)
190 for (i = 0; i < eventcnt; ++i)
191 event (events [i], type);
195 fd_event (int fd, int events)
197 ANFD *anfd = anfds + fd;
200 for (w = anfd->head; w; w = w->next)
202 int ev = w->events & events;
209 /*****************************************************************************/
211 static int *fdchanges;
212 static int fdchangemax, fdchangecnt;
219 for (i = 0; i < fdchangecnt; ++i)
221 int fd = fdchanges [i];
222 ANFD *anfd = anfds + fd;
227 for (w = anfd->head; w; w = w->next)
230 anfd->events &= ~EV_REIFY;
232 if (anfd->events != events)
234 method_modify (fd, anfd->events, events);
235 anfd->events = events;
245 if (anfds [fd].events & EV_REIFY || fdchangecnt < 0)
248 anfds [fd].events |= EV_REIFY;
251 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
252 fdchanges [fdchangecnt - 1] = fd;
255 /* called on EBADF to verify fds */
261 for (fd = 0; fd < anfdmax; ++fd)
262 if (anfds [fd].events)
263 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
264 while (anfds [fd].head)
266 ev_io_stop (anfds [fd].head);
267 event ((W)anfds [fd].head, EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT);
271 /*****************************************************************************/
273 static struct ev_timer **timers;
274 static int timermax, timercnt;
276 static struct ev_periodic **periodics;
277 static int periodicmax, periodiccnt;
280 upheap (WT *timers, int k)
284 while (k && timers [k >> 1]->at > w->at)
286 timers [k] = timers [k >> 1];
287 timers [k]->active = k + 1;
292 timers [k]->active = k + 1;
297 downheap (WT *timers, int N, int k)
305 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
308 if (w->at <= timers [j]->at)
311 timers [k] = timers [j];
312 timers [k]->active = k + 1;
317 timers [k]->active = k + 1;
320 /*****************************************************************************/
324 struct ev_signal *head;
328 static ANSIG *signals;
329 static int signalmax;
331 static int sigpipe [2];
332 static sig_atomic_t gotsig;
333 static struct ev_io sigev;
336 signals_init (ANSIG *base, int count)
347 sighandler (int signum)
349 signals [signum - 1].gotsig = 1;
354 write (sigpipe [1], &gotsig, 1);
359 sigcb (struct ev_io *iow, int revents)
365 read (sigpipe [0], &revents, 1);
367 for (sig = signalmax; sig--; )
368 if (signals [sig].gotsig)
370 signals [sig].gotsig = 0;
372 for (w = signals [sig].head; w; w = w->next)
373 event ((W)w, EV_SIGNAL);
380 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
381 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
383 /* rather than sort out wether we really need nb, set it */
384 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
385 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
387 ev_io_set (&sigev, sigpipe [0], EV_READ);
388 ev_io_start (&sigev);
391 /*****************************************************************************/
393 static struct ev_idle **idles;
394 static int idlemax, idlecnt;
396 static struct ev_prepare **prepares;
397 static int preparemax, preparecnt;
399 static struct ev_check **checks;
400 static int checkmax, checkcnt;
402 /*****************************************************************************/
404 static struct ev_child *childs [PID_HASHSIZE];
405 static struct ev_signal childev;
408 # define WCONTINUED 0
412 childcb (struct ev_signal *sw, int revents)
417 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
418 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
419 if (w->pid == pid || w->pid == -1)
422 event ((W)w, EV_CHILD);
426 /*****************************************************************************/
429 # include "ev_epoll.c"
432 # include "ev_select.c"
436 ev_version_major (void)
438 return EV_VERSION_MAJOR;
442 ev_version_minor (void)
444 return EV_VERSION_MINOR;
447 int ev_init (int flags)
454 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
466 ev_method = EVMETHOD_NONE;
468 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
471 if (ev_method == EVMETHOD_NONE) select_init (flags);
476 ev_watcher_init (&sigev, sigcb);
479 ev_signal_init (&childev, childcb, SIGCHLD);
480 ev_signal_start (&childev);
487 /*****************************************************************************/
496 ev_postfork_parent (void)
502 ev_postfork_child (void)
505 if (ev_method == EVMETHOD_EPOLL)
506 epoll_postfork_child ();
516 /*****************************************************************************/
523 ANPENDING *p = pendings + --pendingcnt;
528 p->w->cb (p->w, p->events);
536 while (timercnt && timers [0]->at <= now)
538 struct ev_timer *w = timers [0];
540 /* first reschedule or stop timer */
543 w->at = now + w->repeat;
544 assert (("timer timeout in the past, negative repeat?", w->at > now));
545 downheap ((WT *)timers, timercnt, 0);
548 ev_timer_stop (w); /* nonrepeating: stop timer */
550 event ((W)w, EV_TIMEOUT);
555 periodics_reify (void)
557 while (periodiccnt && periodics [0]->at <= ev_now)
559 struct ev_periodic *w = periodics [0];
561 /* first reschedule or stop timer */
564 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
565 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
566 downheap ((WT *)periodics, periodiccnt, 0);
569 ev_periodic_stop (w); /* nonrepeating: stop timer */
571 event ((W)w, EV_TIMEOUT);
576 periodics_reschedule (ev_tstamp diff)
580 /* adjust periodics after time jump */
581 for (i = 0; i < periodiccnt; ++i)
583 struct ev_periodic *w = periodics [i];
587 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
589 if (fabs (diff) >= 1e-4)
591 ev_periodic_stop (w);
592 ev_periodic_start (w);
594 i = 0; /* restart loop, inefficient, but time jumps should be rare */
609 ev_tstamp odiff = diff;
611 for (i = 4; --i; ) /* loop a few times, before making important decisions */
616 if (fabs (odiff - diff) < MIN_TIMEJUMP)
617 return; /* all is well */
622 periodics_reschedule (diff - odiff);
623 /* no timer adjustment, as the monotonic clock doesn't jump */
627 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
629 periodics_reschedule (ev_now - now);
631 /* adjust timers. this is easy, as the offset is the same for all */
632 for (i = 0; i < timercnt; ++i)
633 timers [i]->at += diff;
642 void ev_loop (int flags)
645 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
649 /* queue check watchers (and execute them) */
652 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
656 /* update fd-related kernel structures */
659 /* calculate blocking time */
661 /* we only need this for !monotonic clockor timers, but as we basically
662 always have timers, we just calculate it always */
665 if (flags & EVLOOP_NONBLOCK || idlecnt)
669 block = MAX_BLOCKTIME;
673 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
674 if (block > to) block = to;
679 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
680 if (block > to) block = to;
683 if (block < 0.) block = 0.;
688 /* update ev_now, do magic */
691 /* queue pending timers and reschedule them */
692 timers_reify (); /* relative timers called last */
693 periodics_reify (); /* absolute timers called first */
695 /* queue idle watchers unless io or timers are pending */
697 queue_events ((W *)idles, idlecnt, EV_IDLE);
699 /* queue check watchers, to be executed first */
701 queue_events ((W *)checks, checkcnt, EV_CHECK);
705 while (!ev_loop_done);
707 if (ev_loop_done != 2)
711 /*****************************************************************************/
714 wlist_add (WL *head, WL elem)
721 wlist_del (WL *head, WL elem)
731 head = &(*head)->next;
740 pendings [w->pending - 1].w = 0;
746 ev_start (W w, int active)
757 /*****************************************************************************/
760 ev_io_start (struct ev_io *w)
762 if (ev_is_active (w))
768 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
769 wlist_add ((WL *)&anfds[fd].head, (WL)w);
775 ev_io_stop (struct ev_io *w)
778 if (!ev_is_active (w))
781 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
788 ev_timer_start (struct ev_timer *w)
790 if (ev_is_active (w))
795 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
797 ev_start ((W)w, ++timercnt);
798 array_needsize (timers, timermax, timercnt, );
799 timers [timercnt - 1] = w;
800 upheap ((WT *)timers, timercnt - 1);
804 ev_timer_stop (struct ev_timer *w)
807 if (!ev_is_active (w))
810 if (w->active < timercnt--)
812 timers [w->active - 1] = timers [timercnt];
813 downheap ((WT *)timers, timercnt, w->active - 1);
822 ev_timer_again (struct ev_timer *w)
824 if (ev_is_active (w))
828 w->at = now + w->repeat;
829 downheap ((WT *)timers, timercnt, w->active - 1);
839 ev_periodic_start (struct ev_periodic *w)
841 if (ev_is_active (w))
844 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
846 /* this formula differs from the one in periodic_reify because we do not always round up */
848 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
850 ev_start ((W)w, ++periodiccnt);
851 array_needsize (periodics, periodicmax, periodiccnt, );
852 periodics [periodiccnt - 1] = w;
853 upheap ((WT *)periodics, periodiccnt - 1);
857 ev_periodic_stop (struct ev_periodic *w)
860 if (!ev_is_active (w))
863 if (w->active < periodiccnt--)
865 periodics [w->active - 1] = periodics [periodiccnt];
866 downheap ((WT *)periodics, periodiccnt, w->active - 1);
873 ev_signal_start (struct ev_signal *w)
875 if (ev_is_active (w))
879 array_needsize (signals, signalmax, w->signum, signals_init);
880 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
885 sa.sa_handler = sighandler;
886 sigfillset (&sa.sa_mask);
888 sigaction (w->signum, &sa, 0);
893 ev_signal_stop (struct ev_signal *w)
896 if (!ev_is_active (w))
899 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
902 if (!signals [w->signum - 1].head)
903 signal (w->signum, SIG_DFL);
907 ev_idle_start (struct ev_idle *w)
909 if (ev_is_active (w))
912 ev_start ((W)w, ++idlecnt);
913 array_needsize (idles, idlemax, idlecnt, );
914 idles [idlecnt - 1] = w;
918 ev_idle_stop (struct ev_idle *w)
921 if (ev_is_active (w))
924 idles [w->active - 1] = idles [--idlecnt];
929 ev_prepare_start (struct ev_prepare *w)
931 if (ev_is_active (w))
934 ev_start ((W)w, ++preparecnt);
935 array_needsize (prepares, preparemax, preparecnt, );
936 prepares [preparecnt - 1] = w;
940 ev_prepare_stop (struct ev_prepare *w)
943 if (ev_is_active (w))
946 prepares [w->active - 1] = prepares [--preparecnt];
951 ev_check_start (struct ev_check *w)
953 if (ev_is_active (w))
956 ev_start ((W)w, ++checkcnt);
957 array_needsize (checks, checkmax, checkcnt, );
958 checks [checkcnt - 1] = w;
962 ev_check_stop (struct ev_check *w)
965 if (ev_is_active (w))
968 checks [w->active - 1] = checks [--checkcnt];
973 ev_child_start (struct ev_child *w)
975 if (ev_is_active (w))
979 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
983 ev_child_stop (struct ev_child *w)
986 if (ev_is_active (w))
989 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
993 /*****************************************************************************/
999 void (*cb)(int revents, void *arg);
1004 once_cb (struct ev_once *once, int revents)
1006 void (*cb)(int revents, void *arg) = once->cb;
1007 void *arg = once->arg;
1009 ev_io_stop (&once->io);
1010 ev_timer_stop (&once->to);
1017 once_cb_io (struct ev_io *w, int revents)
1019 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1023 once_cb_to (struct ev_timer *w, int revents)
1025 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1029 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1031 struct ev_once *once = malloc (sizeof (struct ev_once));
1034 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1040 ev_watcher_init (&once->io, once_cb_io);
1043 ev_io_set (&once->io, fd, events);
1044 ev_io_start (&once->io);
1047 ev_watcher_init (&once->to, once_cb_to);
1050 ev_timer_set (&once->to, timeout, 0.);
1051 ev_timer_start (&once->to);
1056 /*****************************************************************************/
1063 sin_cb (struct ev_io *w, int revents)
1065 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1069 ocb (struct ev_timer *w, int revents)
1071 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1077 scb (struct ev_signal *w, int revents)
1079 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1085 gcb (struct ev_signal *w, int revents)
1087 fprintf (stderr, "generic %x\n", revents);
1095 ev_io_init (&wio, sin_cb, 0, EV_READ);
1098 struct ev_timer t[10000];
1102 for (i = 0; i < 10000; ++i)
1104 struct ev_timer *w = t + i;
1105 ev_watcher_init (w, ocb, i);
1106 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1108 if (drand48 () < 0.5)
1114 ev_timer_init (&t1, ocb, 5, 10);
1115 ev_timer_start (&t1);
1117 struct ev_signal sig;
1118 ev_signal_init (&sig, scb, SIGQUIT);
1119 ev_signal_start (&sig);
1122 ev_check_init (&cw, gcb);
1123 ev_check_start (&cw);
1126 ev_idle_init (&iw, gcb);
1127 ev_idle_start (&iw);