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_check **checks;
330 static int checkmax, checkcnt;
332 /*****************************************************************************/
335 # include "ev_epoll.c"
338 # include "ev_select.c"
341 int ev_init (int flags)
346 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
358 ev_method = EVMETHOD_NONE;
360 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
363 if (ev_method == EVMETHOD_NONE) select_init (flags);
368 evw_init (&sigev, sigcb);
375 /*****************************************************************************/
377 void ev_prefork (void)
382 void ev_postfork_parent (void)
387 void ev_postfork_child (void)
390 if (ev_method == EVMETHOD_EPOLL)
391 epoll_postfork_child ();
401 /*****************************************************************************/
408 for (i = 0; i < fdchangecnt; ++i)
410 int fd = fdchanges [i];
411 ANFD *anfd = anfds + fd;
416 for (w = anfd->head; w; w = w->next)
419 if (anfd->wev != wev)
421 method_modify (fd, anfd->wev, wev);
434 ANPENDING *p = pendings + --pendingcnt;
439 p->w->cb (p->w, p->events);
447 while (timercnt && timers [0]->at <= now)
449 struct ev_timer *w = timers [0];
451 event ((W)w, EV_TIMEOUT);
453 /* first reschedule or stop timer */
456 w->at = now + w->repeat;
457 assert (("timer timeout in the past, negative repeat?", w->at > now));
458 downheap ((WT *)timers, timercnt, 0);
461 evtimer_stop (w); /* nonrepeating: stop timer */
468 while (periodiccnt && periodics [0]->at <= ev_now)
470 struct ev_periodic *w = periodics [0];
472 /* first reschedule or stop timer */
475 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
476 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
477 downheap ((WT *)periodics, periodiccnt, 0);
480 evperiodic_stop (w); /* nonrepeating: stop timer */
482 event ((W)w, EV_TIMEOUT);
487 periodics_reschedule (ev_tstamp diff)
491 /* adjust periodics after time jump */
492 for (i = 0; i < periodiccnt; ++i)
494 struct ev_periodic *w = periodics [i];
498 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
500 if (fabs (diff) >= 1e-4)
503 evperiodic_start (w);
505 i = 0; /* restart loop, inefficient, but time jumps should be rare */
520 ev_tstamp odiff = diff;
522 for (i = 4; --i; ) /* loop a few times, before making important decisions */
527 if (fabs (odiff - diff) < MIN_TIMEJUMP)
528 return; /* all is well */
533 periodics_reschedule (diff - odiff);
534 /* no timer adjustment, as the monotonic clock doesn't jump */
538 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
540 periodics_reschedule (ev_now - now);
542 /* adjust timers. this is easy, as the offset is the same for all */
543 for (i = 0; i < timercnt; ++i)
544 timers [i]->at += diff;
553 void ev_loop (int flags)
556 ev_loop_done = flags & EVLOOP_ONESHOT ? 1 : 0;
560 queue_events ((W *)checks, checkcnt, EV_CHECK);
566 /* update fd-related kernel structures */
569 /* calculate blocking time */
571 /* we only need this for !monotonic clock, but as we always have timers, we just calculate it every time */
574 if (flags & EVLOOP_NONBLOCK || idlecnt)
578 block = MAX_BLOCKTIME;
582 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
583 if (block > to) block = to;
588 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
589 if (block > to) block = to;
592 if (block < 0.) block = 0.;
597 /* update ev_now, do magic */
600 /* queue pending timers and reschedule them */
601 periodics_reify (); /* absolute timers first */
602 timers_reify (); /* relative timers second */
604 /* queue idle watchers unless io or timers are pending */
606 queue_events ((W *)idles, idlecnt, EV_IDLE);
608 /* queue check and possibly idle watchers */
609 queue_events ((W *)checks, checkcnt, EV_CHECK);
613 while (!ev_loop_done);
615 if (ev_loop_done != 2)
619 /*****************************************************************************/
622 wlist_add (WL *head, WL elem)
629 wlist_del (WL *head, WL elem)
639 head = &(*head)->next;
648 pendings [w->pending - 1].w = 0;
654 ev_start (W w, int active)
665 /*****************************************************************************/
668 evio_start (struct ev_io *w)
670 if (ev_is_active (w))
676 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
677 wlist_add ((WL *)&anfds[fd].head, (WL)w);
680 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
681 fdchanges [fdchangecnt - 1] = fd;
685 evio_stop (struct ev_io *w)
688 if (!ev_is_active (w))
691 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
695 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
696 fdchanges [fdchangecnt - 1] = w->fd;
700 evtimer_start (struct ev_timer *w)
702 if (ev_is_active (w))
707 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
709 ev_start ((W)w, ++timercnt);
710 array_needsize (timers, timermax, timercnt, );
711 timers [timercnt - 1] = w;
712 upheap ((WT *)timers, timercnt - 1);
716 evtimer_stop (struct ev_timer *w)
719 if (!ev_is_active (w))
722 if (w->active < timercnt--)
724 timers [w->active - 1] = timers [timercnt];
725 downheap ((WT *)timers, timercnt, w->active - 1);
734 evtimer_again (struct ev_timer *w)
736 if (ev_is_active (w))
740 w->at = now + w->repeat;
741 downheap ((WT *)timers, timercnt, w->active - 1);
751 evperiodic_start (struct ev_periodic *w)
753 if (ev_is_active (w))
756 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
758 /* this formula differs from the one in periodic_reify because we do not always round up */
760 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
762 ev_start ((W)w, ++periodiccnt);
763 array_needsize (periodics, periodicmax, periodiccnt, );
764 periodics [periodiccnt - 1] = w;
765 upheap ((WT *)periodics, periodiccnt - 1);
769 evperiodic_stop (struct ev_periodic *w)
772 if (!ev_is_active (w))
775 if (w->active < periodiccnt--)
777 periodics [w->active - 1] = periodics [periodiccnt];
778 downheap ((WT *)periodics, periodiccnt, w->active - 1);
785 evsignal_start (struct ev_signal *w)
787 if (ev_is_active (w))
791 array_needsize (signals, signalmax, w->signum, signals_init);
792 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
797 sa.sa_handler = sighandler;
798 sigfillset (&sa.sa_mask);
800 sigaction (w->signum, &sa, 0);
805 evsignal_stop (struct ev_signal *w)
808 if (!ev_is_active (w))
811 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
814 if (!signals [w->signum - 1].head)
815 signal (w->signum, SIG_DFL);
818 void evidle_start (struct ev_idle *w)
820 if (ev_is_active (w))
823 ev_start ((W)w, ++idlecnt);
824 array_needsize (idles, idlemax, idlecnt, );
825 idles [idlecnt - 1] = w;
828 void evidle_stop (struct ev_idle *w)
831 if (ev_is_active (w))
834 idles [w->active - 1] = idles [--idlecnt];
838 void evcheck_start (struct ev_check *w)
840 if (ev_is_active (w))
843 ev_start ((W)w, ++checkcnt);
844 array_needsize (checks, checkmax, checkcnt, );
845 checks [checkcnt - 1] = w;
848 void evcheck_stop (struct ev_check *w)
851 if (ev_is_active (w))
854 checks [w->active - 1] = checks [--checkcnt];
858 /*****************************************************************************/
864 void (*cb)(int revents, void *arg);
869 once_cb (struct ev_once *once, int revents)
871 void (*cb)(int revents, void *arg) = once->cb;
872 void *arg = once->arg;
874 evio_stop (&once->io);
875 evtimer_stop (&once->to);
882 once_cb_io (struct ev_io *w, int revents)
884 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
888 once_cb_to (struct ev_timer *w, int revents)
890 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
894 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
896 struct ev_once *once = malloc (sizeof (struct ev_once));
905 evw_init (&once->io, once_cb_io);
909 evio_set (&once->io, fd, events);
910 evio_start (&once->io);
913 evw_init (&once->to, once_cb_to);
917 evtimer_set (&once->to, timeout, 0.);
918 evtimer_start (&once->to);
923 /*****************************************************************************/
930 sin_cb (struct ev_io *w, int revents)
932 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
936 ocb (struct ev_timer *w, int revents)
938 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
944 scb (struct ev_signal *w, int revents)
946 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
952 gcb (struct ev_signal *w, int revents)
954 fprintf (stderr, "generic %x\n", revents);
962 evio_init (&wio, sin_cb, 0, EV_READ);
965 struct ev_timer t[10000];
969 for (i = 0; i < 10000; ++i)
971 struct ev_timer *w = t + i;
972 evw_init (w, ocb, i);
973 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
975 if (drand48 () < 0.5)
981 evtimer_init (&t1, ocb, 5, 10);
984 struct ev_signal sig;
985 evsignal_init (&sig, scb, SIGQUIT);
986 evsignal_start (&sig);
989 evcheck_init (&cw, gcb);
993 evidle_init (&iw, gcb);