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 for (i = 0; i < pendingcnt; ++i)
425 ANPENDING *p = pendings + i;
430 p->w->cb (p->w, p->events);
440 while (timercnt && timers [0]->at <= now)
442 struct ev_timer *w = timers [0];
444 event ((W)w, EV_TIMEOUT);
446 /* first reschedule or stop timer */
449 w->at = now + w->repeat;
450 assert (("timer timeout in the past, negative repeat?", w->at > now));
451 downheap ((WT *)timers, timercnt, 0);
454 evtimer_stop (w); /* nonrepeating: stop timer */
461 while (periodiccnt && periodics [0]->at <= ev_now)
463 struct ev_periodic *w = periodics [0];
465 /* first reschedule or stop timer */
468 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
469 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
470 downheap ((WT *)periodics, periodiccnt, 0);
473 evperiodic_stop (w); /* nonrepeating: stop timer */
475 event ((W)w, EV_TIMEOUT);
480 periodics_reschedule (ev_tstamp diff)
484 /* adjust periodics after time jump */
485 for (i = 0; i < periodiccnt; ++i)
487 struct ev_periodic *w = periodics [i];
491 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
493 if (fabs (diff) >= 1e-4)
496 evperiodic_start (w);
498 i = 0; /* restart loop, inefficient, but time jumps should be rare */
513 ev_tstamp odiff = diff;
515 for (i = 4; --i; ) /* loop a few times, before making important decisions */
520 if (fabs (odiff - diff) < MIN_TIMEJUMP)
521 return; /* all is well */
526 periodics_reschedule (diff - odiff);
527 /* no timer adjustment, as the monotonic clock doesn't jump */
531 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
533 periodics_reschedule (ev_now - now);
535 /* adjust timers. this is easy, as the offset is the same for all */
536 for (i = 0; i < timercnt; ++i)
537 timers [i]->at += diff;
546 void ev_loop (int flags)
549 ev_loop_done = flags & EVLOOP_ONESHOT ? 1 : 0;
553 queue_events ((W *)checks, checkcnt, EV_CHECK);
559 /* update fd-related kernel structures */
562 /* calculate blocking time */
564 /* we only need this for !monotonic clock, but as we always have timers, we just calculate it every time */
567 if (flags & EVLOOP_NONBLOCK || idlecnt)
571 block = MAX_BLOCKTIME;
575 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
576 if (block > to) block = to;
581 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
582 if (block > to) block = to;
585 if (block < 0.) block = 0.;
590 /* update ev_now, do magic */
593 /* queue pending timers and reschedule them */
594 periodics_reify (); /* absolute timers first */
595 timers_reify (); /* relative timers second */
597 /* queue idle watchers unless io or timers are pending */
599 queue_events ((W *)idles, idlecnt, EV_IDLE);
601 /* queue check and possibly idle watchers */
602 queue_events ((W *)checks, checkcnt, EV_CHECK);
606 while (!ev_loop_done);
608 if (ev_loop_done != 2)
612 /*****************************************************************************/
615 wlist_add (WL *head, WL elem)
622 wlist_del (WL *head, WL elem)
632 head = &(*head)->next;
641 pendings [w->pending - 1].w = 0;
647 ev_start (W w, int active)
658 /*****************************************************************************/
661 evio_start (struct ev_io *w)
663 if (ev_is_active (w))
669 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
670 wlist_add ((WL *)&anfds[fd].head, (WL)w);
673 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
674 fdchanges [fdchangecnt - 1] = fd;
678 evio_stop (struct ev_io *w)
681 if (!ev_is_active (w))
684 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
688 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
689 fdchanges [fdchangecnt - 1] = w->fd;
693 evtimer_start (struct ev_timer *w)
695 if (ev_is_active (w))
700 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
702 ev_start ((W)w, ++timercnt);
703 array_needsize (timers, timermax, timercnt, );
704 timers [timercnt - 1] = w;
705 upheap ((WT *)timers, timercnt - 1);
709 evtimer_stop (struct ev_timer *w)
712 if (!ev_is_active (w))
715 if (w->active < timercnt--)
717 timers [w->active - 1] = timers [timercnt];
718 downheap ((WT *)timers, timercnt, w->active - 1);
727 evtimer_again (struct ev_timer *w)
729 if (ev_is_active (w))
733 w->at = now + w->repeat;
734 downheap ((WT *)timers, timercnt, w->active - 1);
744 evperiodic_start (struct ev_periodic *w)
746 if (ev_is_active (w))
749 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
751 /* this formula differs from the one in periodic_reify because we do not always round up */
753 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
755 ev_start ((W)w, ++periodiccnt);
756 array_needsize (periodics, periodicmax, periodiccnt, );
757 periodics [periodiccnt - 1] = w;
758 upheap ((WT *)periodics, periodiccnt - 1);
762 evperiodic_stop (struct ev_periodic *w)
765 if (!ev_is_active (w))
768 if (w->active < periodiccnt--)
770 periodics [w->active - 1] = periodics [periodiccnt];
771 downheap ((WT *)periodics, periodiccnt, w->active - 1);
778 evsignal_start (struct ev_signal *w)
780 if (ev_is_active (w))
784 array_needsize (signals, signalmax, w->signum, signals_init);
785 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
790 sa.sa_handler = sighandler;
791 sigfillset (&sa.sa_mask);
793 sigaction (w->signum, &sa, 0);
798 evsignal_stop (struct ev_signal *w)
801 if (!ev_is_active (w))
804 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
807 if (!signals [w->signum - 1].head)
808 signal (w->signum, SIG_DFL);
811 void evidle_start (struct ev_idle *w)
813 if (ev_is_active (w))
816 ev_start ((W)w, ++idlecnt);
817 array_needsize (idles, idlemax, idlecnt, );
818 idles [idlecnt - 1] = w;
821 void evidle_stop (struct ev_idle *w)
824 if (ev_is_active (w))
827 idles [w->active - 1] = idles [--idlecnt];
831 void evcheck_start (struct ev_check *w)
833 if (ev_is_active (w))
836 ev_start ((W)w, ++checkcnt);
837 array_needsize (checks, checkmax, checkcnt, );
838 checks [checkcnt - 1] = w;
841 void evcheck_stop (struct ev_check *w)
844 if (ev_is_active (w))
847 checks [w->active - 1] = checks [--checkcnt];
851 /*****************************************************************************/
857 void (*cb)(int revents, void *arg);
862 once_cb (struct ev_once *once, int revents)
864 void (*cb)(int revents, void *arg) = once->cb;
865 void *arg = once->arg;
867 evio_stop (&once->io);
868 evtimer_stop (&once->to);
875 once_cb_io (struct ev_io *w, int revents)
877 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
881 once_cb_to (struct ev_timer *w, int revents)
883 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
887 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
889 struct ev_once *once = malloc (sizeof (struct ev_once));
898 evw_init (&once->io, once_cb_io);
902 evio_set (&once->io, fd, events);
903 evio_start (&once->io);
906 evw_init (&once->to, once_cb_to);
910 evtimer_set (&once->to, timeout, 0.);
911 evtimer_start (&once->to);
916 /*****************************************************************************/
923 sin_cb (struct ev_io *w, int revents)
925 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
929 ocb (struct ev_timer *w, int revents)
931 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
937 scb (struct ev_signal *w, int revents)
939 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
945 gcb (struct ev_signal *w, int revents)
947 fprintf (stderr, "generic %x\n", revents);
955 evio_init (&wio, sin_cb, 0, EV_READ);
958 struct ev_timer t[10000];
962 for (i = 0; i < 10000; ++i)
964 struct ev_timer *w = t + i;
965 evw_init (w, ocb, i);
966 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
968 if (drand48 () < 0.5)
974 evtimer_init (&t1, ocb, 5, 10);
977 struct ev_signal sig;
978 evsignal_init (&sig, scb, SIGQUIT);
979 evsignal_start (&sig);
982 evcheck_init (&cw, gcb);
986 evidle_init (&iw, gcb);