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 #ifndef HAVE_MONOTONIC
45 # ifdef CLOCK_MONOTONIC
46 # define HAVE_MONOTONIC 1
51 # define HAVE_SELECT 1
59 # define HAVE_REALTIME 1 /* posix requirement, but might be slower */
62 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
63 #define MAX_BLOCKTIME 60.
67 typedef struct ev_watcher *W;
68 typedef struct ev_watcher_list *WL;
69 typedef struct ev_watcher_time *WT;
71 static ev_tstamp now, diff; /* monotonic clock */
75 static int have_monotonic; /* runtime */
77 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
78 static void (*method_modify)(int fd, int oev, int nev);
79 static void (*method_poll)(ev_tstamp timeout);
81 /*****************************************************************************/
88 clock_gettime (CLOCK_REALTIME, &ts);
89 return ts.tv_sec + ts.tv_nsec * 1e-9;
92 gettimeofday (&tv, 0);
93 return tv.tv_sec + tv.tv_usec * 1e-6;
104 clock_gettime (CLOCK_MONOTONIC, &ts);
105 return ts.tv_sec + ts.tv_nsec * 1e-9;
112 #define array_needsize(base,cur,cnt,init) \
115 int newcnt = cur ? cur << 1 : 16; \
116 base = realloc (base, sizeof (*base) * (newcnt)); \
117 init (base + cur, newcnt - cur); \
121 /*****************************************************************************/
126 unsigned char wev, rev; /* want, received event set */
132 static int *fdchanges;
133 static int fdchangemax, fdchangecnt;
136 anfds_init (ANFD *base, int count)
141 base->wev = base->rev = EV_NONE;
152 static ANPENDING *pendings;
153 static int pendingmax, pendingcnt;
156 event (W w, int events)
160 w->pending = ++pendingcnt;
161 array_needsize (pendings, pendingmax, pendingcnt, );
162 pendings [pendingcnt - 1].w = w;
163 pendings [pendingcnt - 1].events = events;
168 fd_event (int fd, int events)
170 ANFD *anfd = anfds + fd;
173 for (w = anfd->head; w; w = w->next)
175 int ev = w->events & events;
183 queue_events (W *events, int eventcnt, int type)
187 for (i = 0; i < eventcnt; ++i)
188 event (events [i], type);
191 /* called on EBADF to verify fds */
197 for (fd = 0; fd < anfdmax; ++fd)
199 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
200 while (anfds [fd].head)
201 evio_stop (anfds [fd].head);
204 /*****************************************************************************/
206 static struct ev_timer **timers;
207 static int timermax, timercnt;
209 static struct ev_periodic **periodics;
210 static int periodicmax, periodiccnt;
213 upheap (WT *timers, int k)
217 while (k && timers [k >> 1]->at > w->at)
219 timers [k] = timers [k >> 1];
220 timers [k]->active = k + 1;
225 timers [k]->active = k + 1;
230 downheap (WT *timers, int N, int k)
238 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
241 if (w->at <= timers [j]->at)
244 timers [k] = timers [j];
245 timers [k]->active = k + 1;
250 timers [k]->active = k + 1;
253 /*****************************************************************************/
257 struct ev_signal *head;
261 static ANSIG *signals;
262 static int signalmax;
264 static int sigpipe [2];
265 static sig_atomic_t gotsig;
266 static struct ev_io sigev;
269 signals_init (ANSIG *base, int count)
280 sighandler (int signum)
282 signals [signum - 1].gotsig = 1;
287 write (sigpipe [1], &gotsig, 1);
292 sigcb (struct ev_io *iow, int revents)
298 read (sigpipe [0], &revents, 1);
300 for (sig = signalmax; sig--; )
301 if (signals [sig].gotsig)
303 signals [sig].gotsig = 0;
305 for (w = signals [sig].head; w; w = w->next)
306 event ((W)w, EV_SIGNAL);
313 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
314 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
316 /* rather than sort out wether we really need nb, set it */
317 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
318 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
320 evio_set (&sigev, sigpipe [0], EV_READ);
324 /*****************************************************************************/
326 static struct ev_idle **idles;
327 static int idlemax, idlecnt;
329 static struct ev_prepare **prepares;
330 static int preparemax, preparecnt;
332 static struct ev_check **checks;
333 static int checkmax, checkcnt;
335 /*****************************************************************************/
338 # include "ev_epoll.c"
341 # include "ev_select.c"
344 int ev_init (int flags)
349 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
361 ev_method = EVMETHOD_NONE;
363 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
366 if (ev_method == EVMETHOD_NONE) select_init (flags);
371 evw_init (&sigev, sigcb);
378 /*****************************************************************************/
380 void ev_prefork (void)
385 void ev_postfork_parent (void)
390 void ev_postfork_child (void)
393 if (ev_method == EVMETHOD_EPOLL)
394 epoll_postfork_child ();
404 /*****************************************************************************/
411 for (i = 0; i < fdchangecnt; ++i)
413 int fd = fdchanges [i];
414 ANFD *anfd = anfds + fd;
419 for (w = anfd->head; w; w = w->next)
422 if (anfd->wev != wev)
424 method_modify (fd, anfd->wev, wev);
437 ANPENDING *p = pendings + --pendingcnt;
442 p->w->cb (p->w, p->events);
450 while (timercnt && timers [0]->at <= now)
452 struct ev_timer *w = timers [0];
454 event ((W)w, EV_TIMEOUT);
456 /* first reschedule or stop timer */
459 w->at = now + w->repeat;
460 assert (("timer timeout in the past, negative repeat?", w->at > now));
461 downheap ((WT *)timers, timercnt, 0);
464 evtimer_stop (w); /* nonrepeating: stop timer */
471 while (periodiccnt && periodics [0]->at <= ev_now)
473 struct ev_periodic *w = periodics [0];
475 /* first reschedule or stop timer */
478 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
479 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
480 downheap ((WT *)periodics, periodiccnt, 0);
483 evperiodic_stop (w); /* nonrepeating: stop timer */
485 event ((W)w, EV_TIMEOUT);
490 periodics_reschedule (ev_tstamp diff)
494 /* adjust periodics after time jump */
495 for (i = 0; i < periodiccnt; ++i)
497 struct ev_periodic *w = periodics [i];
501 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
503 if (fabs (diff) >= 1e-4)
506 evperiodic_start (w);
508 i = 0; /* restart loop, inefficient, but time jumps should be rare */
523 ev_tstamp odiff = diff;
525 for (i = 4; --i; ) /* loop a few times, before making important decisions */
530 if (fabs (odiff - diff) < MIN_TIMEJUMP)
531 return; /* all is well */
536 periodics_reschedule (diff - odiff);
537 /* no timer adjustment, as the monotonic clock doesn't jump */
541 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
543 periodics_reschedule (ev_now - now);
545 /* adjust timers. this is easy, as the offset is the same for all */
546 for (i = 0; i < timercnt; ++i)
547 timers [i]->at += diff;
556 void ev_loop (int flags)
559 ev_loop_done = flags & EVLOOP_ONESHOT ? 1 : 0;
563 /* queue check watchers (and execute them) */
566 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
570 /* update fd-related kernel structures */
573 /* calculate blocking time */
575 /* we only need this for !monotonic clock, but as we always have timers, we just calculate it every time */
578 if (flags & EVLOOP_NONBLOCK || idlecnt)
582 block = MAX_BLOCKTIME;
586 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
587 if (block > to) block = to;
592 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
593 if (block > to) block = to;
596 if (block < 0.) block = 0.;
601 /* update ev_now, do magic */
604 /* queue pending timers and reschedule them */
605 timers_reify (); /* relative timers called last */
606 periodics_reify (); /* absolute timers called first */
608 /* queue idle watchers unless io or timers are pending */
610 queue_events ((W *)idles, idlecnt, EV_IDLE);
612 /* queue check watchers, to be executed first */
614 queue_events ((W *)checks, checkcnt, EV_CHECK);
618 while (!ev_loop_done);
620 if (ev_loop_done != 2)
624 /*****************************************************************************/
627 wlist_add (WL *head, WL elem)
634 wlist_del (WL *head, WL elem)
644 head = &(*head)->next;
653 pendings [w->pending - 1].w = 0;
659 ev_start (W w, int active)
670 /*****************************************************************************/
673 evio_start (struct ev_io *w)
675 if (ev_is_active (w))
681 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
682 wlist_add ((WL *)&anfds[fd].head, (WL)w);
685 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
686 fdchanges [fdchangecnt - 1] = fd;
690 evio_stop (struct ev_io *w)
693 if (!ev_is_active (w))
696 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
700 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
701 fdchanges [fdchangecnt - 1] = w->fd;
705 evtimer_start (struct ev_timer *w)
707 if (ev_is_active (w))
712 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
714 ev_start ((W)w, ++timercnt);
715 array_needsize (timers, timermax, timercnt, );
716 timers [timercnt - 1] = w;
717 upheap ((WT *)timers, timercnt - 1);
721 evtimer_stop (struct ev_timer *w)
724 if (!ev_is_active (w))
727 if (w->active < timercnt--)
729 timers [w->active - 1] = timers [timercnt];
730 downheap ((WT *)timers, timercnt, w->active - 1);
739 evtimer_again (struct ev_timer *w)
741 if (ev_is_active (w))
745 w->at = now + w->repeat;
746 downheap ((WT *)timers, timercnt, w->active - 1);
756 evperiodic_start (struct ev_periodic *w)
758 if (ev_is_active (w))
761 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
763 /* this formula differs from the one in periodic_reify because we do not always round up */
765 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
767 ev_start ((W)w, ++periodiccnt);
768 array_needsize (periodics, periodicmax, periodiccnt, );
769 periodics [periodiccnt - 1] = w;
770 upheap ((WT *)periodics, periodiccnt - 1);
774 evperiodic_stop (struct ev_periodic *w)
777 if (!ev_is_active (w))
780 if (w->active < periodiccnt--)
782 periodics [w->active - 1] = periodics [periodiccnt];
783 downheap ((WT *)periodics, periodiccnt, w->active - 1);
790 evsignal_start (struct ev_signal *w)
792 if (ev_is_active (w))
796 array_needsize (signals, signalmax, w->signum, signals_init);
797 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
802 sa.sa_handler = sighandler;
803 sigfillset (&sa.sa_mask);
805 sigaction (w->signum, &sa, 0);
810 evsignal_stop (struct ev_signal *w)
813 if (!ev_is_active (w))
816 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
819 if (!signals [w->signum - 1].head)
820 signal (w->signum, SIG_DFL);
823 void evidle_start (struct ev_idle *w)
825 if (ev_is_active (w))
828 ev_start ((W)w, ++idlecnt);
829 array_needsize (idles, idlemax, idlecnt, );
830 idles [idlecnt - 1] = w;
833 void evidle_stop (struct ev_idle *w)
836 if (ev_is_active (w))
839 idles [w->active - 1] = idles [--idlecnt];
843 void evprepare_start (struct ev_prepare *w)
845 if (ev_is_active (w))
848 ev_start ((W)w, ++preparecnt);
849 array_needsize (prepares, preparemax, preparecnt, );
850 prepares [preparecnt - 1] = w;
853 void evprepare_stop (struct ev_prepare *w)
856 if (ev_is_active (w))
859 prepares [w->active - 1] = prepares [--preparecnt];
863 void evcheck_start (struct ev_check *w)
865 if (ev_is_active (w))
868 ev_start ((W)w, ++checkcnt);
869 array_needsize (checks, checkmax, checkcnt, );
870 checks [checkcnt - 1] = w;
873 void evcheck_stop (struct ev_check *w)
876 if (ev_is_active (w))
879 checks [w->active - 1] = checks [--checkcnt];
883 /*****************************************************************************/
889 void (*cb)(int revents, void *arg);
894 once_cb (struct ev_once *once, int revents)
896 void (*cb)(int revents, void *arg) = once->cb;
897 void *arg = once->arg;
899 evio_stop (&once->io);
900 evtimer_stop (&once->to);
907 once_cb_io (struct ev_io *w, int revents)
909 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
913 once_cb_to (struct ev_timer *w, int revents)
915 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
919 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
921 struct ev_once *once = malloc (sizeof (struct ev_once));
930 evw_init (&once->io, once_cb_io);
934 evio_set (&once->io, fd, events);
935 evio_start (&once->io);
938 evw_init (&once->to, once_cb_to);
942 evtimer_set (&once->to, timeout, 0.);
943 evtimer_start (&once->to);
948 /*****************************************************************************/
955 sin_cb (struct ev_io *w, int revents)
957 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
961 ocb (struct ev_timer *w, int revents)
963 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
969 scb (struct ev_signal *w, int revents)
971 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
977 gcb (struct ev_signal *w, int revents)
979 fprintf (stderr, "generic %x\n", revents);
987 evio_init (&wio, sin_cb, 0, EV_READ);
990 struct ev_timer t[10000];
994 for (i = 0; i < 10000; ++i)
996 struct ev_timer *w = t + i;
997 evw_init (w, ocb, i);
998 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
1000 if (drand48 () < 0.5)
1006 evtimer_init (&t1, ocb, 5, 10);
1007 evtimer_start (&t1);
1009 struct ev_signal sig;
1010 evsignal_init (&sig, scb, SIGQUIT);
1011 evsignal_start (&sig);
1014 evcheck_init (&cw, gcb);
1015 evcheck_start (&cw);
1018 evidle_init (&iw, gcb);