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 clockor timers, but as we basically
576 always have timers, we just calculate it always */
579 if (flags & EVLOOP_NONBLOCK || idlecnt)
583 block = MAX_BLOCKTIME;
587 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
588 if (block > to) block = to;
593 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
594 if (block > to) block = to;
597 if (block < 0.) block = 0.;
602 /* update ev_now, do magic */
605 /* queue pending timers and reschedule them */
606 timers_reify (); /* relative timers called last */
607 periodics_reify (); /* absolute timers called first */
609 /* queue idle watchers unless io or timers are pending */
611 queue_events ((W *)idles, idlecnt, EV_IDLE);
613 /* queue check watchers, to be executed first */
615 queue_events ((W *)checks, checkcnt, EV_CHECK);
619 while (!ev_loop_done);
621 if (ev_loop_done != 2)
625 /*****************************************************************************/
628 wlist_add (WL *head, WL elem)
635 wlist_del (WL *head, WL elem)
645 head = &(*head)->next;
654 pendings [w->pending - 1].w = 0;
660 ev_start (W w, int active)
671 /*****************************************************************************/
674 evio_start (struct ev_io *w)
676 if (ev_is_active (w))
682 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
683 wlist_add ((WL *)&anfds[fd].head, (WL)w);
686 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
687 fdchanges [fdchangecnt - 1] = fd;
691 evio_stop (struct ev_io *w)
694 if (!ev_is_active (w))
697 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
701 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
702 fdchanges [fdchangecnt - 1] = w->fd;
706 evtimer_start (struct ev_timer *w)
708 if (ev_is_active (w))
713 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
715 ev_start ((W)w, ++timercnt);
716 array_needsize (timers, timermax, timercnt, );
717 timers [timercnt - 1] = w;
718 upheap ((WT *)timers, timercnt - 1);
722 evtimer_stop (struct ev_timer *w)
725 if (!ev_is_active (w))
728 if (w->active < timercnt--)
730 timers [w->active - 1] = timers [timercnt];
731 downheap ((WT *)timers, timercnt, w->active - 1);
740 evtimer_again (struct ev_timer *w)
742 if (ev_is_active (w))
746 w->at = now + w->repeat;
747 downheap ((WT *)timers, timercnt, w->active - 1);
757 evperiodic_start (struct ev_periodic *w)
759 if (ev_is_active (w))
762 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
764 /* this formula differs from the one in periodic_reify because we do not always round up */
766 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
768 ev_start ((W)w, ++periodiccnt);
769 array_needsize (periodics, periodicmax, periodiccnt, );
770 periodics [periodiccnt - 1] = w;
771 upheap ((WT *)periodics, periodiccnt - 1);
775 evperiodic_stop (struct ev_periodic *w)
778 if (!ev_is_active (w))
781 if (w->active < periodiccnt--)
783 periodics [w->active - 1] = periodics [periodiccnt];
784 downheap ((WT *)periodics, periodiccnt, w->active - 1);
791 evsignal_start (struct ev_signal *w)
793 if (ev_is_active (w))
797 array_needsize (signals, signalmax, w->signum, signals_init);
798 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
803 sa.sa_handler = sighandler;
804 sigfillset (&sa.sa_mask);
806 sigaction (w->signum, &sa, 0);
811 evsignal_stop (struct ev_signal *w)
814 if (!ev_is_active (w))
817 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
820 if (!signals [w->signum - 1].head)
821 signal (w->signum, SIG_DFL);
824 void evidle_start (struct ev_idle *w)
826 if (ev_is_active (w))
829 ev_start ((W)w, ++idlecnt);
830 array_needsize (idles, idlemax, idlecnt, );
831 idles [idlecnt - 1] = w;
834 void evidle_stop (struct ev_idle *w)
837 if (ev_is_active (w))
840 idles [w->active - 1] = idles [--idlecnt];
844 void evprepare_start (struct ev_prepare *w)
846 if (ev_is_active (w))
849 ev_start ((W)w, ++preparecnt);
850 array_needsize (prepares, preparemax, preparecnt, );
851 prepares [preparecnt - 1] = w;
854 void evprepare_stop (struct ev_prepare *w)
857 if (ev_is_active (w))
860 prepares [w->active - 1] = prepares [--preparecnt];
864 void evcheck_start (struct ev_check *w)
866 if (ev_is_active (w))
869 ev_start ((W)w, ++checkcnt);
870 array_needsize (checks, checkmax, checkcnt, );
871 checks [checkcnt - 1] = w;
874 void evcheck_stop (struct ev_check *w)
877 if (ev_is_active (w))
880 checks [w->active - 1] = checks [--checkcnt];
884 /*****************************************************************************/
890 void (*cb)(int revents, void *arg);
895 once_cb (struct ev_once *once, int revents)
897 void (*cb)(int revents, void *arg) = once->cb;
898 void *arg = once->arg;
900 evio_stop (&once->io);
901 evtimer_stop (&once->to);
908 once_cb_io (struct ev_io *w, int revents)
910 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
914 once_cb_to (struct ev_timer *w, int revents)
916 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
920 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
922 struct ev_once *once = malloc (sizeof (struct ev_once));
931 evw_init (&once->io, once_cb_io);
935 evio_set (&once->io, fd, events);
936 evio_start (&once->io);
939 evw_init (&once->to, once_cb_to);
943 evtimer_set (&once->to, timeout, 0.);
944 evtimer_start (&once->to);
949 /*****************************************************************************/
956 sin_cb (struct ev_io *w, int revents)
958 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
962 ocb (struct ev_timer *w, int revents)
964 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
970 scb (struct ev_signal *w, int revents)
972 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
978 gcb (struct ev_signal *w, int revents)
980 fprintf (stderr, "generic %x\n", revents);
988 evio_init (&wio, sin_cb, 0, EV_READ);
991 struct ev_timer t[10000];
995 for (i = 0; i < 10000; ++i)
997 struct ev_timer *w = t + i;
998 evw_init (w, ocb, i);
999 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
1001 if (drand48 () < 0.5)
1007 evtimer_init (&t1, ocb, 5, 10);
1008 evtimer_start (&t1);
1010 struct ev_signal sig;
1011 evsignal_init (&sig, scb, SIGQUIT);
1012 evsignal_start (&sig);
1015 evcheck_init (&cw, gcb);
1016 evcheck_start (&cw);
1019 evidle_init (&iw, gcb);