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.
41 #include <sys/types.h>
46 #ifndef HAVE_MONOTONIC
47 # ifdef CLOCK_MONOTONIC
48 # define HAVE_MONOTONIC 1
53 # define HAVE_SELECT 1
61 # define HAVE_REALTIME 1 /* posix requirement, but might be slower */
64 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
65 #define MAX_BLOCKTIME 60.
66 #define PID_HASHSIZE 16 /* size of pid hahs table, must be power of two */
70 typedef struct ev_watcher *W;
71 typedef struct ev_watcher_list *WL;
72 typedef struct ev_watcher_time *WT;
74 static ev_tstamp now, diff; /* monotonic clock */
78 static int have_monotonic; /* runtime */
80 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
81 static void (*method_modify)(int fd, int oev, int nev);
82 static void (*method_poll)(ev_tstamp timeout);
84 /*****************************************************************************/
91 clock_gettime (CLOCK_REALTIME, &ts);
92 return ts.tv_sec + ts.tv_nsec * 1e-9;
95 gettimeofday (&tv, 0);
96 return tv.tv_sec + tv.tv_usec * 1e-6;
107 clock_gettime (CLOCK_MONOTONIC, &ts);
108 return ts.tv_sec + ts.tv_nsec * 1e-9;
115 #define array_needsize(base,cur,cnt,init) \
121 newcnt = (newcnt << 1) | 4 & ~3; \
123 while ((cnt) > newcnt); \
125 base = realloc (base, sizeof (*base) * (newcnt)); \
126 init (base + cur, newcnt - cur); \
130 /*****************************************************************************/
142 anfds_init (ANFD *base, int count)
147 base->events = EV_NONE;
158 static ANPENDING *pendings;
159 static int pendingmax, pendingcnt;
162 event (W w, int events)
166 w->pending = ++pendingcnt;
167 array_needsize (pendings, pendingmax, pendingcnt, );
168 pendings [pendingcnt - 1].w = w;
169 pendings [pendingcnt - 1].events = events;
174 queue_events (W *events, int eventcnt, int type)
178 for (i = 0; i < eventcnt; ++i)
179 event (events [i], type);
183 fd_event (int fd, int events)
185 ANFD *anfd = anfds + fd;
188 for (w = anfd->head; w; w = w->next)
190 int ev = w->events & events;
197 /*****************************************************************************/
199 static int *fdchanges;
200 static int fdchangemax, fdchangecnt;
207 for (i = 0; i < fdchangecnt; ++i)
209 int fd = fdchanges [i];
210 ANFD *anfd = anfds + fd;
215 for (w = anfd->head; w; w = w->next)
218 anfd->events &= ~EV_REIFY;
220 if (anfd->events != events)
222 method_modify (fd, anfd->events, events);
223 anfd->events = events;
233 if (anfds [fd].events & EV_REIFY)
236 anfds [fd].events |= EV_REIFY;
239 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
240 fdchanges [fdchangecnt - 1] = fd;
243 /* called on EBADF to verify fds */
249 for (fd = 0; fd < anfdmax; ++fd)
250 if (anfds [fd].events)
251 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
252 while (anfds [fd].head)
254 event ((W)anfds [fd].head, EV_ERROR);
255 evio_stop (anfds [fd].head);
259 /*****************************************************************************/
261 static struct ev_timer **timers;
262 static int timermax, timercnt;
264 static struct ev_periodic **periodics;
265 static int periodicmax, periodiccnt;
268 upheap (WT *timers, int k)
272 while (k && timers [k >> 1]->at > w->at)
274 timers [k] = timers [k >> 1];
275 timers [k]->active = k + 1;
280 timers [k]->active = k + 1;
285 downheap (WT *timers, int N, int k)
293 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
296 if (w->at <= timers [j]->at)
299 timers [k] = timers [j];
300 timers [k]->active = k + 1;
305 timers [k]->active = k + 1;
308 /*****************************************************************************/
312 struct ev_signal *head;
316 static ANSIG *signals;
317 static int signalmax;
319 static int sigpipe [2];
320 static sig_atomic_t gotsig;
321 static struct ev_io sigev;
324 signals_init (ANSIG *base, int count)
335 sighandler (int signum)
337 signals [signum - 1].gotsig = 1;
342 write (sigpipe [1], &gotsig, 1);
347 sigcb (struct ev_io *iow, int revents)
353 read (sigpipe [0], &revents, 1);
355 for (sig = signalmax; sig--; )
356 if (signals [sig].gotsig)
358 signals [sig].gotsig = 0;
360 for (w = signals [sig].head; w; w = w->next)
361 event ((W)w, EV_SIGNAL);
368 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
369 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
371 /* rather than sort out wether we really need nb, set it */
372 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
373 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
375 evio_set (&sigev, sigpipe [0], EV_READ);
379 /*****************************************************************************/
381 static struct ev_idle **idles;
382 static int idlemax, idlecnt;
384 static struct ev_prepare **prepares;
385 static int preparemax, preparecnt;
387 static struct ev_check **checks;
388 static int checkmax, checkcnt;
390 /*****************************************************************************/
392 static struct ev_child *childs [PID_HASHSIZE];
393 static struct ev_signal childev;
396 # define WCONTINUED 0
400 childcb (struct ev_signal *sw, int revents)
405 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
406 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
407 if (w->pid == pid || w->pid == -1)
410 event ((W)w, EV_CHILD);
414 /*****************************************************************************/
417 # include "ev_epoll.c"
420 # include "ev_select.c"
424 ev_version_major (void)
426 return EV_VERSION_MAJOR;
430 ev_version_minor (void)
432 return EV_VERSION_MINOR;
435 int ev_init (int flags)
442 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
454 ev_method = EVMETHOD_NONE;
456 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
459 if (ev_method == EVMETHOD_NONE) select_init (flags);
464 evw_init (&sigev, sigcb);
467 evsignal_init (&childev, childcb, SIGCHLD);
468 evsignal_start (&childev);
475 /*****************************************************************************/
484 ev_postfork_parent (void)
490 ev_postfork_child (void)
493 if (ev_method == EVMETHOD_EPOLL)
494 epoll_postfork_child ();
504 /*****************************************************************************/
511 ANPENDING *p = pendings + --pendingcnt;
516 p->w->cb (p->w, p->events);
524 while (timercnt && timers [0]->at <= now)
526 struct ev_timer *w = timers [0];
528 event ((W)w, EV_TIMEOUT);
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 evtimer_stop (w); /* nonrepeating: stop timer */
543 periodics_reify (void)
545 while (periodiccnt && periodics [0]->at <= ev_now)
547 struct ev_periodic *w = periodics [0];
549 /* first reschedule or stop timer */
552 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
553 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
554 downheap ((WT *)periodics, periodiccnt, 0);
557 evperiodic_stop (w); /* nonrepeating: stop timer */
559 event ((W)w, EV_TIMEOUT);
564 periodics_reschedule (ev_tstamp diff)
568 /* adjust periodics after time jump */
569 for (i = 0; i < periodiccnt; ++i)
571 struct ev_periodic *w = periodics [i];
575 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
577 if (fabs (diff) >= 1e-4)
580 evperiodic_start (w);
582 i = 0; /* restart loop, inefficient, but time jumps should be rare */
597 ev_tstamp odiff = diff;
599 for (i = 4; --i; ) /* loop a few times, before making important decisions */
604 if (fabs (odiff - diff) < MIN_TIMEJUMP)
605 return; /* all is well */
610 periodics_reschedule (diff - odiff);
611 /* no timer adjustment, as the monotonic clock doesn't jump */
615 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
617 periodics_reschedule (ev_now - now);
619 /* adjust timers. this is easy, as the offset is the same for all */
620 for (i = 0; i < timercnt; ++i)
621 timers [i]->at += diff;
630 void ev_loop (int flags)
633 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
637 /* queue check watchers (and execute them) */
640 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
644 /* update fd-related kernel structures */
647 /* calculate blocking time */
649 /* we only need this for !monotonic clockor timers, but as we basically
650 always have timers, we just calculate it always */
653 if (flags & EVLOOP_NONBLOCK || idlecnt)
657 block = MAX_BLOCKTIME;
661 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
662 if (block > to) block = to;
667 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
668 if (block > to) block = to;
671 if (block < 0.) block = 0.;
676 /* update ev_now, do magic */
679 /* queue pending timers and reschedule them */
680 timers_reify (); /* relative timers called last */
681 periodics_reify (); /* absolute timers called first */
683 /* queue idle watchers unless io or timers are pending */
685 queue_events ((W *)idles, idlecnt, EV_IDLE);
687 /* queue check watchers, to be executed first */
689 queue_events ((W *)checks, checkcnt, EV_CHECK);
693 while (!ev_loop_done);
695 if (ev_loop_done != 2)
699 /*****************************************************************************/
702 wlist_add (WL *head, WL elem)
709 wlist_del (WL *head, WL elem)
719 head = &(*head)->next;
728 pendings [w->pending - 1].w = 0;
734 ev_start (W w, int active)
745 /*****************************************************************************/
748 evio_start (struct ev_io *w)
750 if (ev_is_active (w))
756 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
757 wlist_add ((WL *)&anfds[fd].head, (WL)w);
763 evio_stop (struct ev_io *w)
766 if (!ev_is_active (w))
769 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
776 evtimer_start (struct ev_timer *w)
778 if (ev_is_active (w))
783 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
785 ev_start ((W)w, ++timercnt);
786 array_needsize (timers, timermax, timercnt, );
787 timers [timercnt - 1] = w;
788 upheap ((WT *)timers, timercnt - 1);
792 evtimer_stop (struct ev_timer *w)
795 if (!ev_is_active (w))
798 if (w->active < timercnt--)
800 timers [w->active - 1] = timers [timercnt];
801 downheap ((WT *)timers, timercnt, w->active - 1);
810 evtimer_again (struct ev_timer *w)
812 if (ev_is_active (w))
816 w->at = now + w->repeat;
817 downheap ((WT *)timers, timercnt, w->active - 1);
827 evperiodic_start (struct ev_periodic *w)
829 if (ev_is_active (w))
832 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
834 /* this formula differs from the one in periodic_reify because we do not always round up */
836 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
838 ev_start ((W)w, ++periodiccnt);
839 array_needsize (periodics, periodicmax, periodiccnt, );
840 periodics [periodiccnt - 1] = w;
841 upheap ((WT *)periodics, periodiccnt - 1);
845 evperiodic_stop (struct ev_periodic *w)
848 if (!ev_is_active (w))
851 if (w->active < periodiccnt--)
853 periodics [w->active - 1] = periodics [periodiccnt];
854 downheap ((WT *)periodics, periodiccnt, w->active - 1);
861 evsignal_start (struct ev_signal *w)
863 if (ev_is_active (w))
867 array_needsize (signals, signalmax, w->signum, signals_init);
868 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
873 sa.sa_handler = sighandler;
874 sigfillset (&sa.sa_mask);
876 sigaction (w->signum, &sa, 0);
881 evsignal_stop (struct ev_signal *w)
884 if (!ev_is_active (w))
887 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
890 if (!signals [w->signum - 1].head)
891 signal (w->signum, SIG_DFL);
894 void evidle_start (struct ev_idle *w)
896 if (ev_is_active (w))
899 ev_start ((W)w, ++idlecnt);
900 array_needsize (idles, idlemax, idlecnt, );
901 idles [idlecnt - 1] = w;
904 void evidle_stop (struct ev_idle *w)
907 if (ev_is_active (w))
910 idles [w->active - 1] = idles [--idlecnt];
914 void evprepare_start (struct ev_prepare *w)
916 if (ev_is_active (w))
919 ev_start ((W)w, ++preparecnt);
920 array_needsize (prepares, preparemax, preparecnt, );
921 prepares [preparecnt - 1] = w;
924 void evprepare_stop (struct ev_prepare *w)
927 if (ev_is_active (w))
930 prepares [w->active - 1] = prepares [--preparecnt];
934 void evcheck_start (struct ev_check *w)
936 if (ev_is_active (w))
939 ev_start ((W)w, ++checkcnt);
940 array_needsize (checks, checkmax, checkcnt, );
941 checks [checkcnt - 1] = w;
944 void evcheck_stop (struct ev_check *w)
947 if (ev_is_active (w))
950 checks [w->active - 1] = checks [--checkcnt];
954 void evchild_start (struct ev_child *w)
956 if (ev_is_active (w))
960 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
963 void evchild_stop (struct ev_child *w)
966 if (ev_is_active (w))
969 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
973 /*****************************************************************************/
979 void (*cb)(int revents, void *arg);
984 once_cb (struct ev_once *once, int revents)
986 void (*cb)(int revents, void *arg) = once->cb;
987 void *arg = once->arg;
989 evio_stop (&once->io);
990 evtimer_stop (&once->to);
997 once_cb_io (struct ev_io *w, int revents)
999 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1003 once_cb_to (struct ev_timer *w, int revents)
1005 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1009 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1011 struct ev_once *once = malloc (sizeof (struct ev_once));
1020 evw_init (&once->io, once_cb_io);
1024 evio_set (&once->io, fd, events);
1025 evio_start (&once->io);
1028 evw_init (&once->to, once_cb_to);
1032 evtimer_set (&once->to, timeout, 0.);
1033 evtimer_start (&once->to);
1038 /*****************************************************************************/
1045 sin_cb (struct ev_io *w, int revents)
1047 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1051 ocb (struct ev_timer *w, int revents)
1053 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1059 scb (struct ev_signal *w, int revents)
1061 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1067 gcb (struct ev_signal *w, int revents)
1069 fprintf (stderr, "generic %x\n", revents);
1077 evio_init (&wio, sin_cb, 0, EV_READ);
1080 struct ev_timer t[10000];
1084 for (i = 0; i < 10000; ++i)
1086 struct ev_timer *w = t + i;
1087 evw_init (w, ocb, i);
1088 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
1090 if (drand48 () < 0.5)
1096 evtimer_init (&t1, ocb, 5, 10);
1097 evtimer_start (&t1);
1099 struct ev_signal sig;
1100 evsignal_init (&sig, scb, SIGQUIT);
1101 evsignal_start (&sig);
1104 evcheck_init (&cw, gcb);
1105 evcheck_start (&cw);
1108 evidle_init (&iw, gcb);