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.
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.
69 typedef struct ev_watcher *W;
70 typedef struct ev_watcher_list *WL;
71 typedef struct ev_watcher_time *WT;
73 static ev_tstamp now, diff; /* monotonic clock */
77 static int have_monotonic; /* runtime */
79 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
80 static void (*method_modify)(int fd, int oev, int nev);
81 static void (*method_poll)(ev_tstamp timeout);
83 /*****************************************************************************/
90 clock_gettime (CLOCK_REALTIME, &ts);
91 return ts.tv_sec + ts.tv_nsec * 1e-9;
94 gettimeofday (&tv, 0);
95 return tv.tv_sec + tv.tv_usec * 1e-6;
106 clock_gettime (CLOCK_MONOTONIC, &ts);
107 return ts.tv_sec + ts.tv_nsec * 1e-9;
114 #define array_needsize(base,cur,cnt,init) \
117 int newcnt = cur ? cur << 1 : 16; \
118 base = realloc (base, sizeof (*base) * (newcnt)); \
119 init (base + cur, newcnt - cur); \
123 /*****************************************************************************/
128 unsigned char wev, rev; /* want, received event set */
134 static int *fdchanges;
135 static int fdchangemax, fdchangecnt;
138 anfds_init (ANFD *base, int count)
143 base->wev = base->rev = EV_NONE;
154 static ANPENDING *pendings;
155 static int pendingmax, pendingcnt;
158 event (W w, int events)
162 w->pending = ++pendingcnt;
163 array_needsize (pendings, pendingmax, pendingcnt, );
164 pendings [pendingcnt - 1].w = w;
165 pendings [pendingcnt - 1].events = events;
170 fd_event (int fd, int events)
172 ANFD *anfd = anfds + fd;
175 for (w = anfd->head; w; w = w->next)
177 int ev = w->events & events;
185 queue_events (W *events, int eventcnt, int type)
189 for (i = 0; i < eventcnt; ++i)
190 event (events [i], type);
193 /*****************************************************************************/
195 static struct ev_timer **timers;
196 static int timermax, timercnt;
198 static struct ev_periodic **periodics;
199 static int periodicmax, periodiccnt;
202 upheap (WT *timers, int k)
206 while (k && timers [k >> 1]->at > w->at)
208 timers [k] = timers [k >> 1];
209 timers [k]->active = k + 1;
214 timers [k]->active = k + 1;
219 downheap (WT *timers, int N, int k)
227 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
230 if (w->at <= timers [j]->at)
233 timers [k] = timers [j];
234 timers [k]->active = k + 1;
239 timers [k]->active = k + 1;
242 /*****************************************************************************/
246 struct ev_signal *head;
250 static ANSIG *signals;
251 static int signalmax;
253 static int sigpipe [2];
254 static sig_atomic_t gotsig;
255 static struct ev_io sigev;
258 signals_init (ANSIG *base, int count)
269 sighandler (int signum)
271 signals [signum - 1].gotsig = 1;
276 write (sigpipe [1], &gotsig, 1);
281 sigcb (struct ev_io *iow, int revents)
287 read (sigpipe [0], &revents, 1);
289 for (sig = signalmax; sig--; )
290 if (signals [sig].gotsig)
292 signals [sig].gotsig = 0;
294 for (w = signals [sig].head; w; w = w->next)
295 event ((W)w, EV_SIGNAL);
302 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
303 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
305 /* rather than sort out wether we really need nb, set it */
306 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
307 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
309 evio_set (&sigev, sigpipe [0], EV_READ);
313 /*****************************************************************************/
315 static struct ev_idle **idles;
316 static int idlemax, idlecnt;
318 static struct ev_check **checks;
319 static int checkmax, checkcnt;
321 /*****************************************************************************/
324 # include "ev_epoll.c"
327 # include "ev_select.c"
330 int ev_init (int flags)
335 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
347 ev_method = EVMETHOD_NONE;
349 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
352 if (ev_method == EVMETHOD_NONE) select_init (flags);
357 evw_init (&sigev, sigcb);
364 /*****************************************************************************/
366 void ev_prefork (void)
371 void ev_postfork_parent (void)
376 void ev_postfork_child (void)
379 if (ev_method == EVMETHOD_EPOLL)
380 epoll_postfork_child ();
390 /*****************************************************************************/
397 for (i = 0; i < fdchangecnt; ++i)
399 int fd = fdchanges [i];
400 ANFD *anfd = anfds + fd;
405 for (w = anfd->head; w; w = w->next)
408 if (anfd->wev != wev)
410 method_modify (fd, anfd->wev, wev);
423 ANPENDING *p = pendings + --pendingcnt;
428 p->w->cb (p->w, p->events);
436 while (timercnt && timers [0]->at <= now)
438 struct ev_timer *w = timers [0];
440 event ((W)w, EV_TIMEOUT);
442 /* first reschedule or stop timer */
445 w->at = now + w->repeat;
446 assert (("timer timeout in the past, negative repeat?", w->at > now));
447 downheap ((WT *)timers, timercnt, 0);
450 evtimer_stop (w); /* nonrepeating: stop timer */
457 while (periodiccnt && periodics [0]->at <= ev_now)
459 struct ev_periodic *w = periodics [0];
461 /* first reschedule or stop timer */
464 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
465 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
466 downheap ((WT *)periodics, periodiccnt, 0);
469 evperiodic_stop (w); /* nonrepeating: stop timer */
471 event ((W)w, EV_TIMEOUT);
476 periodics_reschedule (ev_tstamp diff)
480 /* adjust periodics after time jump */
481 for (i = 0; i < periodiccnt; ++i)
483 struct ev_periodic *w = periodics [i];
487 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
489 if (fabs (diff) >= 1e-4)
492 evperiodic_start (w);
494 i = 0; /* restart loop, inefficient, but time jumps should be rare */
509 ev_tstamp odiff = diff;
511 for (i = 4; --i; ) /* loop a few times, before making important decisions */
516 if (fabs (odiff - diff) < MIN_TIMEJUMP)
517 return; /* all is well */
522 periodics_reschedule (diff - odiff);
523 /* no timer adjustment, as the monotonic clock doesn't jump */
527 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
529 periodics_reschedule (ev_now - now);
531 /* adjust timers. this is easy, as the offset is the same for all */
532 for (i = 0; i < timercnt; ++i)
533 timers [i]->at += diff;
542 void ev_loop (int flags)
545 ev_loop_done = flags & EVLOOP_ONESHOT ? 1 : 0;
549 queue_events ((W *)checks, checkcnt, EV_CHECK);
555 /* update fd-related kernel structures */
558 /* calculate blocking time */
560 /* we only need this for !monotonic clock, but as we always have timers, we just calculate it every time */
563 if (flags & EVLOOP_NONBLOCK || idlecnt)
567 block = MAX_BLOCKTIME;
571 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
572 if (block > to) block = to;
577 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
578 if (block > to) block = to;
581 if (block < 0.) block = 0.;
586 /* update ev_now, do magic */
589 /* queue pending timers and reschedule them */
590 periodics_reify (); /* absolute timers first */
591 timers_reify (); /* relative timers second */
593 /* queue idle watchers unless io or timers are pending */
595 queue_events ((W *)idles, idlecnt, EV_IDLE);
597 /* queue check and possibly idle watchers */
598 queue_events ((W *)checks, checkcnt, EV_CHECK);
602 while (!ev_loop_done);
604 if (ev_loop_done != 2)
608 /*****************************************************************************/
611 wlist_add (WL *head, WL elem)
618 wlist_del (WL *head, WL elem)
628 head = &(*head)->next;
637 pendings [w->pending - 1].w = 0;
643 ev_start (W w, int active)
654 /*****************************************************************************/
657 evio_start (struct ev_io *w)
659 if (ev_is_active (w))
665 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
666 wlist_add ((WL *)&anfds[fd].head, (WL)w);
669 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
670 fdchanges [fdchangecnt - 1] = fd;
674 evio_stop (struct ev_io *w)
677 if (!ev_is_active (w))
680 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
684 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
685 fdchanges [fdchangecnt - 1] = w->fd;
689 evtimer_start (struct ev_timer *w)
691 if (ev_is_active (w))
696 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
698 ev_start ((W)w, ++timercnt);
699 array_needsize (timers, timermax, timercnt, );
700 timers [timercnt - 1] = w;
701 upheap ((WT *)timers, timercnt - 1);
705 evtimer_stop (struct ev_timer *w)
708 if (!ev_is_active (w))
711 if (w->active < timercnt--)
713 timers [w->active - 1] = timers [timercnt];
714 downheap ((WT *)timers, timercnt, w->active - 1);
723 evtimer_again (struct ev_timer *w)
725 if (ev_is_active (w))
729 w->at = now + w->repeat;
730 downheap ((WT *)timers, timercnt, w->active - 1);
740 evperiodic_start (struct ev_periodic *w)
742 if (ev_is_active (w))
745 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
747 /* this formula differs from the one in periodic_reify because we do not always round up */
749 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
751 ev_start ((W)w, ++periodiccnt);
752 array_needsize (periodics, periodicmax, periodiccnt, );
753 periodics [periodiccnt - 1] = w;
754 upheap ((WT *)periodics, periodiccnt - 1);
758 evperiodic_stop (struct ev_periodic *w)
761 if (!ev_is_active (w))
764 if (w->active < periodiccnt--)
766 periodics [w->active - 1] = periodics [periodiccnt];
767 downheap ((WT *)periodics, periodiccnt, w->active - 1);
774 evsignal_start (struct ev_signal *w)
776 if (ev_is_active (w))
780 array_needsize (signals, signalmax, w->signum, signals_init);
781 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
786 sa.sa_handler = sighandler;
787 sigfillset (&sa.sa_mask);
789 sigaction (w->signum, &sa, 0);
794 evsignal_stop (struct ev_signal *w)
797 if (!ev_is_active (w))
800 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
803 if (!signals [w->signum - 1].head)
804 signal (w->signum, SIG_DFL);
807 void evidle_start (struct ev_idle *w)
809 if (ev_is_active (w))
812 ev_start ((W)w, ++idlecnt);
813 array_needsize (idles, idlemax, idlecnt, );
814 idles [idlecnt - 1] = w;
817 void evidle_stop (struct ev_idle *w)
820 if (ev_is_active (w))
823 idles [w->active - 1] = idles [--idlecnt];
827 void evcheck_start (struct ev_check *w)
829 if (ev_is_active (w))
832 ev_start ((W)w, ++checkcnt);
833 array_needsize (checks, checkmax, checkcnt, );
834 checks [checkcnt - 1] = w;
837 void evcheck_stop (struct ev_check *w)
840 if (ev_is_active (w))
843 checks [w->active - 1] = checks [--checkcnt];
847 /*****************************************************************************/
853 void (*cb)(int revents, void *arg);
858 once_cb (struct ev_once *once, int revents)
860 void (*cb)(int revents, void *arg) = once->cb;
861 void *arg = once->arg;
863 evio_stop (&once->io);
864 evtimer_stop (&once->to);
871 once_cb_io (struct ev_io *w, int revents)
873 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
877 once_cb_to (struct ev_timer *w, int revents)
879 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
883 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
885 struct ev_once *once = malloc (sizeof (struct ev_once));
894 evw_init (&once->io, once_cb_io);
898 evio_set (&once->io, fd, events);
899 evio_start (&once->io);
902 evw_init (&once->to, once_cb_to);
906 evtimer_set (&once->to, timeout, 0.);
907 evtimer_start (&once->to);
912 /*****************************************************************************/
919 sin_cb (struct ev_io *w, int revents)
921 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
925 ocb (struct ev_timer *w, int revents)
927 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
933 scb (struct ev_signal *w, int revents)
935 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
941 gcb (struct ev_signal *w, int revents)
943 fprintf (stderr, "generic %x\n", revents);
951 evio_init (&wio, sin_cb, 0, EV_READ);
954 struct ev_timer t[10000];
958 for (i = 0; i < 10000; ++i)
960 struct ev_timer *w = t + i;
961 evw_init (w, ocb, i);
962 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
964 if (drand48 () < 0.5)
970 evtimer_init (&t1, ocb, 5, 10);
973 struct ev_signal sig;
974 evsignal_init (&sig, scb, SIGQUIT);
975 evsignal_start (&sig);
978 evcheck_init (&cw, gcb);
982 evidle_init (&iw, gcb);