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.
41 #include <sys/types.h>
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.
66 #define PID_HASHSIZE 16 /* size of pid hahs table, must be power of two */
70 typedef struct ev_watcher *W;
71 typedef struct ev_watcher_list *WL;
72 typedef struct ev_watcher_time *WT;
74 static ev_tstamp now, diff; /* monotonic clock */
78 static int have_monotonic; /* runtime */
80 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
81 static void (*method_modify)(int fd, int oev, int nev);
82 static void (*method_poll)(ev_tstamp timeout);
84 /*****************************************************************************/
91 clock_gettime (CLOCK_REALTIME, &ts);
92 return ts.tv_sec + ts.tv_nsec * 1e-9;
95 gettimeofday (&tv, 0);
96 return tv.tv_sec + tv.tv_usec * 1e-6;
107 clock_gettime (CLOCK_MONOTONIC, &ts);
108 return ts.tv_sec + ts.tv_nsec * 1e-9;
115 #define array_needsize(base,cur,cnt,init) \
121 newcnt = (newcnt << 1) | 4 & ~3; \
123 while ((cnt) > newcnt); \
125 base = realloc (base, sizeof (*base) * (newcnt)); \
126 init (base + cur, newcnt - cur); \
130 /*****************************************************************************/
135 unsigned char wev, rev; /* want, received event set */
141 static int *fdchanges;
142 static int fdchangemax, fdchangecnt;
145 anfds_init (ANFD *base, int count)
150 base->wev = base->rev = EV_NONE;
161 static ANPENDING *pendings;
162 static int pendingmax, pendingcnt;
165 event (W w, int events)
169 w->pending = ++pendingcnt;
170 array_needsize (pendings, pendingmax, pendingcnt, );
171 pendings [pendingcnt - 1].w = w;
172 pendings [pendingcnt - 1].events = events;
177 fd_event (int fd, int events)
179 ANFD *anfd = anfds + fd;
182 for (w = anfd->head; w; w = w->next)
184 int ev = w->events & events;
192 queue_events (W *events, int eventcnt, int type)
196 for (i = 0; i < eventcnt; ++i)
197 event (events [i], type);
200 /* called on EBADF to verify fds */
206 for (fd = 0; fd < anfdmax; ++fd)
208 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
209 while (anfds [fd].head)
210 evio_stop (anfds [fd].head);
213 /*****************************************************************************/
215 static struct ev_timer **timers;
216 static int timermax, timercnt;
218 static struct ev_periodic **periodics;
219 static int periodicmax, periodiccnt;
222 upheap (WT *timers, int k)
226 while (k && timers [k >> 1]->at > w->at)
228 timers [k] = timers [k >> 1];
229 timers [k]->active = k + 1;
234 timers [k]->active = k + 1;
239 downheap (WT *timers, int N, int k)
247 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
250 if (w->at <= timers [j]->at)
253 timers [k] = timers [j];
254 timers [k]->active = k + 1;
259 timers [k]->active = k + 1;
262 /*****************************************************************************/
266 struct ev_signal *head;
270 static ANSIG *signals;
271 static int signalmax;
273 static int sigpipe [2];
274 static sig_atomic_t gotsig;
275 static struct ev_io sigev;
278 signals_init (ANSIG *base, int count)
289 sighandler (int signum)
291 signals [signum - 1].gotsig = 1;
296 write (sigpipe [1], &gotsig, 1);
301 sigcb (struct ev_io *iow, int revents)
307 read (sigpipe [0], &revents, 1);
309 for (sig = signalmax; sig--; )
310 if (signals [sig].gotsig)
312 signals [sig].gotsig = 0;
314 for (w = signals [sig].head; w; w = w->next)
315 event ((W)w, EV_SIGNAL);
322 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
323 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
325 /* rather than sort out wether we really need nb, set it */
326 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
327 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
329 evio_set (&sigev, sigpipe [0], EV_READ);
333 /*****************************************************************************/
335 static struct ev_idle **idles;
336 static int idlemax, idlecnt;
338 static struct ev_prepare **prepares;
339 static int preparemax, preparecnt;
341 static struct ev_check **checks;
342 static int checkmax, checkcnt;
344 /*****************************************************************************/
346 static struct ev_child *childs [PID_HASHSIZE];
347 static struct ev_signal childev;
350 # define WCONTINUED 0
354 childcb (struct ev_signal *sw, int revents)
359 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
360 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
361 if (w->pid == pid || w->pid == -1)
364 event ((W)w, EV_CHILD);
368 /*****************************************************************************/
371 # include "ev_epoll.c"
374 # include "ev_select.c"
377 int ev_init (int flags)
384 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
396 ev_method = EVMETHOD_NONE;
398 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
401 if (ev_method == EVMETHOD_NONE) select_init (flags);
406 evw_init (&sigev, sigcb);
409 evsignal_init (&childev, childcb, SIGCHLD);
410 evsignal_start (&childev);
417 /*****************************************************************************/
419 void ev_prefork (void)
424 void ev_postfork_parent (void)
429 void ev_postfork_child (void)
432 if (ev_method == EVMETHOD_EPOLL)
433 epoll_postfork_child ();
443 /*****************************************************************************/
450 for (i = 0; i < fdchangecnt; ++i)
452 int fd = fdchanges [i];
453 ANFD *anfd = anfds + fd;
458 for (w = anfd->head; w; w = w->next)
461 if (anfd->wev != wev)
463 method_modify (fd, anfd->wev, wev);
476 ANPENDING *p = pendings + --pendingcnt;
481 p->w->cb (p->w, p->events);
489 while (timercnt && timers [0]->at <= now)
491 struct ev_timer *w = timers [0];
493 event ((W)w, EV_TIMEOUT);
495 /* first reschedule or stop timer */
498 w->at = now + w->repeat;
499 assert (("timer timeout in the past, negative repeat?", w->at > now));
500 downheap ((WT *)timers, timercnt, 0);
503 evtimer_stop (w); /* nonrepeating: stop timer */
510 while (periodiccnt && periodics [0]->at <= ev_now)
512 struct ev_periodic *w = periodics [0];
514 /* first reschedule or stop timer */
517 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
518 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
519 downheap ((WT *)periodics, periodiccnt, 0);
522 evperiodic_stop (w); /* nonrepeating: stop timer */
524 event ((W)w, EV_TIMEOUT);
529 periodics_reschedule (ev_tstamp diff)
533 /* adjust periodics after time jump */
534 for (i = 0; i < periodiccnt; ++i)
536 struct ev_periodic *w = periodics [i];
540 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
542 if (fabs (diff) >= 1e-4)
545 evperiodic_start (w);
547 i = 0; /* restart loop, inefficient, but time jumps should be rare */
562 ev_tstamp odiff = diff;
564 for (i = 4; --i; ) /* loop a few times, before making important decisions */
569 if (fabs (odiff - diff) < MIN_TIMEJUMP)
570 return; /* all is well */
575 periodics_reschedule (diff - odiff);
576 /* no timer adjustment, as the monotonic clock doesn't jump */
580 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
582 periodics_reschedule (ev_now - now);
584 /* adjust timers. this is easy, as the offset is the same for all */
585 for (i = 0; i < timercnt; ++i)
586 timers [i]->at += diff;
595 void ev_loop (int flags)
598 ev_loop_done = flags & EVLOOP_ONESHOT ? 1 : 0;
602 /* queue check watchers (and execute them) */
605 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
609 /* update fd-related kernel structures */
612 /* calculate blocking time */
614 /* we only need this for !monotonic clockor timers, but as we basically
615 always have timers, we just calculate it always */
618 if (flags & EVLOOP_NONBLOCK || idlecnt)
622 block = MAX_BLOCKTIME;
626 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
627 if (block > to) block = to;
632 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
633 if (block > to) block = to;
636 if (block < 0.) block = 0.;
641 /* update ev_now, do magic */
644 /* queue pending timers and reschedule them */
645 timers_reify (); /* relative timers called last */
646 periodics_reify (); /* absolute timers called first */
648 /* queue idle watchers unless io or timers are pending */
650 queue_events ((W *)idles, idlecnt, EV_IDLE);
652 /* queue check watchers, to be executed first */
654 queue_events ((W *)checks, checkcnt, EV_CHECK);
658 while (!ev_loop_done);
660 if (ev_loop_done != 2)
664 /*****************************************************************************/
667 wlist_add (WL *head, WL elem)
674 wlist_del (WL *head, WL elem)
684 head = &(*head)->next;
693 pendings [w->pending - 1].w = 0;
699 ev_start (W w, int active)
710 /*****************************************************************************/
713 evio_start (struct ev_io *w)
715 if (ev_is_active (w))
721 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
722 wlist_add ((WL *)&anfds[fd].head, (WL)w);
725 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
726 fdchanges [fdchangecnt - 1] = fd;
730 evio_stop (struct ev_io *w)
733 if (!ev_is_active (w))
736 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
740 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
741 fdchanges [fdchangecnt - 1] = w->fd;
745 evtimer_start (struct ev_timer *w)
747 if (ev_is_active (w))
752 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
754 ev_start ((W)w, ++timercnt);
755 array_needsize (timers, timermax, timercnt, );
756 timers [timercnt - 1] = w;
757 upheap ((WT *)timers, timercnt - 1);
761 evtimer_stop (struct ev_timer *w)
764 if (!ev_is_active (w))
767 if (w->active < timercnt--)
769 timers [w->active - 1] = timers [timercnt];
770 downheap ((WT *)timers, timercnt, w->active - 1);
779 evtimer_again (struct ev_timer *w)
781 if (ev_is_active (w))
785 w->at = now + w->repeat;
786 downheap ((WT *)timers, timercnt, w->active - 1);
796 evperiodic_start (struct ev_periodic *w)
798 if (ev_is_active (w))
801 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
803 /* this formula differs from the one in periodic_reify because we do not always round up */
805 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
807 ev_start ((W)w, ++periodiccnt);
808 array_needsize (periodics, periodicmax, periodiccnt, );
809 periodics [periodiccnt - 1] = w;
810 upheap ((WT *)periodics, periodiccnt - 1);
814 evperiodic_stop (struct ev_periodic *w)
817 if (!ev_is_active (w))
820 if (w->active < periodiccnt--)
822 periodics [w->active - 1] = periodics [periodiccnt];
823 downheap ((WT *)periodics, periodiccnt, w->active - 1);
830 evsignal_start (struct ev_signal *w)
832 if (ev_is_active (w))
836 array_needsize (signals, signalmax, w->signum, signals_init);
837 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
842 sa.sa_handler = sighandler;
843 sigfillset (&sa.sa_mask);
845 sigaction (w->signum, &sa, 0);
850 evsignal_stop (struct ev_signal *w)
853 if (!ev_is_active (w))
856 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
859 if (!signals [w->signum - 1].head)
860 signal (w->signum, SIG_DFL);
863 void evidle_start (struct ev_idle *w)
865 if (ev_is_active (w))
868 ev_start ((W)w, ++idlecnt);
869 array_needsize (idles, idlemax, idlecnt, );
870 idles [idlecnt - 1] = w;
873 void evidle_stop (struct ev_idle *w)
876 if (ev_is_active (w))
879 idles [w->active - 1] = idles [--idlecnt];
883 void evprepare_start (struct ev_prepare *w)
885 if (ev_is_active (w))
888 ev_start ((W)w, ++preparecnt);
889 array_needsize (prepares, preparemax, preparecnt, );
890 prepares [preparecnt - 1] = w;
893 void evprepare_stop (struct ev_prepare *w)
896 if (ev_is_active (w))
899 prepares [w->active - 1] = prepares [--preparecnt];
903 void evcheck_start (struct ev_check *w)
905 if (ev_is_active (w))
908 ev_start ((W)w, ++checkcnt);
909 array_needsize (checks, checkmax, checkcnt, );
910 checks [checkcnt - 1] = w;
913 void evcheck_stop (struct ev_check *w)
916 if (ev_is_active (w))
919 checks [w->active - 1] = checks [--checkcnt];
923 void evchild_start (struct ev_child *w)
925 if (ev_is_active (w))
929 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
932 void evchild_stop (struct ev_child *w)
935 if (ev_is_active (w))
938 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
942 /*****************************************************************************/
948 void (*cb)(int revents, void *arg);
953 once_cb (struct ev_once *once, int revents)
955 void (*cb)(int revents, void *arg) = once->cb;
956 void *arg = once->arg;
958 evio_stop (&once->io);
959 evtimer_stop (&once->to);
966 once_cb_io (struct ev_io *w, int revents)
968 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
972 once_cb_to (struct ev_timer *w, int revents)
974 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
978 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
980 struct ev_once *once = malloc (sizeof (struct ev_once));
989 evw_init (&once->io, once_cb_io);
993 evio_set (&once->io, fd, events);
994 evio_start (&once->io);
997 evw_init (&once->to, once_cb_to);
1001 evtimer_set (&once->to, timeout, 0.);
1002 evtimer_start (&once->to);
1007 /*****************************************************************************/
1014 sin_cb (struct ev_io *w, int revents)
1016 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1020 ocb (struct ev_timer *w, int revents)
1022 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1028 scb (struct ev_signal *w, int revents)
1030 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1036 gcb (struct ev_signal *w, int revents)
1038 fprintf (stderr, "generic %x\n", revents);
1046 evio_init (&wio, sin_cb, 0, EV_READ);
1049 struct ev_timer t[10000];
1053 for (i = 0; i < 10000; ++i)
1055 struct ev_timer *w = t + i;
1056 evw_init (w, ocb, i);
1057 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
1059 if (drand48 () < 0.5)
1065 evtimer_init (&t1, ocb, 5, 10);
1066 evtimer_start (&t1);
1068 struct ev_signal sig;
1069 evsignal_init (&sig, scb, SIGQUIT);
1070 evsignal_start (&sig);
1073 evcheck_init (&cw, gcb);
1074 evcheck_start (&cw);
1077 evidle_init (&iw, gcb);