2 * libev event processing core, watcher management
4 * Copyright (c) 2007 Marc Alexander Lehmann <libev@schmorp.de>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are
11 * * Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
14 * * Redistributions in binary form must reproduce the above
15 * copyright notice, this list of conditions and the following
16 * disclaimer in the documentation and/or other materials provided
17 * with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46 #include <sys/types.h>
51 #ifndef EV_USE_MONOTONIC
52 # ifdef CLOCK_MONOTONIC
53 # define EV_USE_MONOTONIC 1
58 # define EV_USE_SELECT 1
62 # define EV_USE_EPOLL 0
65 #ifndef CLOCK_REALTIME
66 # define EV_USE_REALTIME 0
68 #ifndef EV_USE_REALTIME
69 # define EV_USE_REALTIME 1 /* posix requirement, but might be slower */
72 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
73 #define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detetc time jumps) */
74 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
75 #define CLEANUP_INTERVAL (MAX_BLOCKTIME * 5.) /* how often to try to free memory and re-check fds */
79 typedef struct ev_watcher *W;
80 typedef struct ev_watcher_list *WL;
81 typedef struct ev_watcher_time *WT;
83 static ev_tstamp now, diff; /* monotonic clock */
87 static int have_monotonic; /* runtime */
89 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
90 static void (*method_modify)(int fd, int oev, int nev);
91 static void (*method_poll)(ev_tstamp timeout);
93 /*****************************************************************************/
100 clock_gettime (CLOCK_REALTIME, &ts);
101 return ts.tv_sec + ts.tv_nsec * 1e-9;
104 gettimeofday (&tv, 0);
105 return tv.tv_sec + tv.tv_usec * 1e-6;
116 clock_gettime (CLOCK_MONOTONIC, &ts);
117 return ts.tv_sec + ts.tv_nsec * 1e-9;
124 #define array_roundsize(base,n) ((n) | 4 & ~3)
126 #define array_needsize(base,cur,cnt,init) \
132 newcnt = array_roundsize (base, newcnt << 1); \
134 while ((cnt) > newcnt); \
136 base = realloc (base, sizeof (*base) * (newcnt)); \
137 init (base + cur, newcnt - cur); \
141 /*****************************************************************************/
146 unsigned char events;
154 anfds_init (ANFD *base, int count)
159 base->events = EV_NONE;
172 static ANPENDING *pendings;
173 static int pendingmax, pendingcnt;
176 event (W w, int events)
180 pendings [w->pending - 1].events |= events;
184 w->pending = ++pendingcnt;
185 array_needsize (pendings, pendingmax, pendingcnt, );
186 pendings [pendingcnt - 1].w = w;
187 pendings [pendingcnt - 1].events = events;
191 queue_events (W *events, int eventcnt, int type)
195 for (i = 0; i < eventcnt; ++i)
196 event (events [i], type);
200 fd_event (int fd, int events)
202 ANFD *anfd = anfds + fd;
205 for (w = anfd->head; w; w = w->next)
207 int ev = w->events & events;
214 /*****************************************************************************/
216 static int *fdchanges;
217 static int fdchangemax, fdchangecnt;
224 for (i = 0; i < fdchangecnt; ++i)
226 int fd = fdchanges [i];
227 ANFD *anfd = anfds + fd;
232 for (w = anfd->head; w; w = w->next)
237 if (anfd->events != events)
239 method_modify (fd, anfd->events, events);
240 anfd->events = events;
250 if (anfds [fd].reify || fdchangecnt < 0)
253 anfds [fd].reify = 1;
256 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
257 fdchanges [fdchangecnt - 1] = fd;
260 /* called on EBADF to verify fds */
266 for (fd = 0; fd < anfdmax; ++fd)
267 if (anfds [fd].events)
268 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
269 while (anfds [fd].head)
271 ev_io_stop (anfds [fd].head);
272 event ((W)anfds [fd].head, EV_ERROR | EV_READ | EV_WRITE);
276 /*****************************************************************************/
278 static struct ev_timer **timers;
279 static int timermax, timercnt;
281 static struct ev_periodic **periodics;
282 static int periodicmax, periodiccnt;
285 upheap (WT *timers, int k)
289 while (k && timers [k >> 1]->at > w->at)
291 timers [k] = timers [k >> 1];
292 timers [k]->active = k + 1;
297 timers [k]->active = k + 1;
302 downheap (WT *timers, int N, int k)
310 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
313 if (w->at <= timers [j]->at)
316 timers [k] = timers [j];
317 timers [k]->active = k + 1;
322 timers [k]->active = k + 1;
325 /*****************************************************************************/
329 struct ev_signal *head;
330 sig_atomic_t volatile gotsig;
333 static ANSIG *signals;
334 static int signalmax;
336 static int sigpipe [2];
337 static sig_atomic_t volatile gotsig;
338 static struct ev_io sigev;
341 signals_init (ANSIG *base, int count)
353 sighandler (int signum)
355 signals [signum - 1].gotsig = 1;
360 write (sigpipe [1], &signum, 1);
365 sigcb (struct ev_io *iow, int revents)
370 read (sigpipe [0], &revents, 1);
373 for (sig = signalmax; sig--; )
374 if (signals [sig].gotsig)
376 signals [sig].gotsig = 0;
378 for (w = signals [sig].head; w; w = w->next)
379 event ((W)w, EV_SIGNAL);
386 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
387 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
389 /* rather than sort out wether we really need nb, set it */
390 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
391 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
393 ev_io_set (&sigev, sigpipe [0], EV_READ);
394 ev_io_start (&sigev);
397 /*****************************************************************************/
399 static struct ev_idle **idles;
400 static int idlemax, idlecnt;
402 static struct ev_prepare **prepares;
403 static int preparemax, preparecnt;
405 static struct ev_check **checks;
406 static int checkmax, checkcnt;
408 /*****************************************************************************/
410 static struct ev_child *childs [PID_HASHSIZE];
411 static struct ev_signal childev;
414 # define WCONTINUED 0
418 childcb (struct ev_signal *sw, int revents)
423 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
424 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
425 if (w->pid == pid || w->pid == -1)
428 event ((W)w, EV_CHILD);
432 /*****************************************************************************/
435 # include "ev_epoll.c"
438 # include "ev_select.c"
442 ev_version_major (void)
444 return EV_VERSION_MAJOR;
448 ev_version_minor (void)
450 return EV_VERSION_MINOR;
453 int ev_init (int flags)
460 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
472 ev_method = EVMETHOD_NONE;
474 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
477 if (ev_method == EVMETHOD_NONE) select_init (flags);
482 ev_watcher_init (&sigev, sigcb);
485 ev_signal_init (&childev, childcb, SIGCHLD);
486 ev_signal_start (&childev);
493 /*****************************************************************************/
496 ev_fork_prepare (void)
502 ev_fork_parent (void)
511 if (ev_method == EVMETHOD_EPOLL)
512 epoll_postfork_child ();
522 /*****************************************************************************/
529 ANPENDING *p = pendings + --pendingcnt;
534 p->w->cb (p->w, p->events);
542 while (timercnt && timers [0]->at <= now)
544 struct ev_timer *w = timers [0];
546 /* first reschedule or stop timer */
549 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
550 w->at = now + w->repeat;
551 downheap ((WT *)timers, timercnt, 0);
554 ev_timer_stop (w); /* nonrepeating: stop timer */
556 event ((W)w, EV_TIMEOUT);
561 periodics_reify (void)
563 while (periodiccnt && periodics [0]->at <= ev_now)
565 struct ev_periodic *w = periodics [0];
567 /* first reschedule or stop timer */
570 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
571 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", w->at > ev_now));
572 downheap ((WT *)periodics, periodiccnt, 0);
575 ev_periodic_stop (w); /* nonrepeating: stop timer */
577 event ((W)w, EV_PERIODIC);
582 periodics_reschedule (ev_tstamp diff)
586 /* adjust periodics after time jump */
587 for (i = 0; i < periodiccnt; ++i)
589 struct ev_periodic *w = periodics [i];
593 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
595 if (fabs (diff) >= 1e-4)
597 ev_periodic_stop (w);
598 ev_periodic_start (w);
600 i = 0; /* restart loop, inefficient, but time jumps should be rare */
615 ev_tstamp odiff = diff;
617 for (i = 4; --i; ) /* loop a few times, before making important decisions */
622 if (fabs (odiff - diff) < MIN_TIMEJUMP)
623 return; /* all is well */
628 periodics_reschedule (diff - odiff);
629 /* no timer adjustment, as the monotonic clock doesn't jump */
633 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
635 periodics_reschedule (ev_now - now);
637 /* adjust timers. this is easy, as the offset is the same for all */
638 for (i = 0; i < timercnt; ++i)
639 timers [i]->at += diff;
648 void ev_loop (int flags)
651 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
655 /* queue check watchers (and execute them) */
658 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
662 /* update fd-related kernel structures */
665 /* calculate blocking time */
667 /* we only need this for !monotonic clockor timers, but as we basically
668 always have timers, we just calculate it always */
671 if (flags & EVLOOP_NONBLOCK || idlecnt)
675 block = MAX_BLOCKTIME;
679 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
680 if (block > to) block = to;
685 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
686 if (block > to) block = to;
689 if (block < 0.) block = 0.;
694 /* update ev_now, do magic */
697 /* queue pending timers and reschedule them */
698 timers_reify (); /* relative timers called last */
699 periodics_reify (); /* absolute timers called first */
701 /* queue idle watchers unless io or timers are pending */
703 queue_events ((W *)idles, idlecnt, EV_IDLE);
705 /* queue check watchers, to be executed first */
707 queue_events ((W *)checks, checkcnt, EV_CHECK);
711 while (!ev_loop_done);
713 if (ev_loop_done != 2)
717 /*****************************************************************************/
720 wlist_add (WL *head, WL elem)
727 wlist_del (WL *head, WL elem)
737 head = &(*head)->next;
742 ev_clear_pending (W w)
746 pendings [w->pending - 1].w = 0;
752 ev_start (W w, int active)
763 /*****************************************************************************/
766 ev_io_start (struct ev_io *w)
768 if (ev_is_active (w))
773 assert (("ev_io_start called with negative fd", fd >= 0));
776 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
777 wlist_add ((WL *)&anfds[fd].head, (WL)w);
783 ev_io_stop (struct ev_io *w)
785 ev_clear_pending ((W)w);
786 if (!ev_is_active (w))
789 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
796 ev_timer_start (struct ev_timer *w)
798 if (ev_is_active (w))
803 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
805 ev_start ((W)w, ++timercnt);
806 array_needsize (timers, timermax, timercnt, );
807 timers [timercnt - 1] = w;
808 upheap ((WT *)timers, timercnt - 1);
812 ev_timer_stop (struct ev_timer *w)
814 ev_clear_pending ((W)w);
815 if (!ev_is_active (w))
818 if (w->active < timercnt--)
820 timers [w->active - 1] = timers [timercnt];
821 downheap ((WT *)timers, timercnt, w->active - 1);
830 ev_timer_again (struct ev_timer *w)
832 if (ev_is_active (w))
836 w->at = now + w->repeat;
837 downheap ((WT *)timers, timercnt, w->active - 1);
847 ev_periodic_start (struct ev_periodic *w)
849 if (ev_is_active (w))
852 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
854 /* this formula differs from the one in periodic_reify because we do not always round up */
856 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
858 ev_start ((W)w, ++periodiccnt);
859 array_needsize (periodics, periodicmax, periodiccnt, );
860 periodics [periodiccnt - 1] = w;
861 upheap ((WT *)periodics, periodiccnt - 1);
865 ev_periodic_stop (struct ev_periodic *w)
867 ev_clear_pending ((W)w);
868 if (!ev_is_active (w))
871 if (w->active < periodiccnt--)
873 periodics [w->active - 1] = periodics [periodiccnt];
874 downheap ((WT *)periodics, periodiccnt, w->active - 1);
881 ev_signal_start (struct ev_signal *w)
883 if (ev_is_active (w))
886 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
889 array_needsize (signals, signalmax, w->signum, signals_init);
890 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
895 sa.sa_handler = sighandler;
896 sigfillset (&sa.sa_mask);
898 sigaction (w->signum, &sa, 0);
903 ev_signal_stop (struct ev_signal *w)
905 ev_clear_pending ((W)w);
906 if (!ev_is_active (w))
909 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
912 if (!signals [w->signum - 1].head)
913 signal (w->signum, SIG_DFL);
917 ev_idle_start (struct ev_idle *w)
919 if (ev_is_active (w))
922 ev_start ((W)w, ++idlecnt);
923 array_needsize (idles, idlemax, idlecnt, );
924 idles [idlecnt - 1] = w;
928 ev_idle_stop (struct ev_idle *w)
930 ev_clear_pending ((W)w);
931 if (ev_is_active (w))
934 idles [w->active - 1] = idles [--idlecnt];
939 ev_prepare_start (struct ev_prepare *w)
941 if (ev_is_active (w))
944 ev_start ((W)w, ++preparecnt);
945 array_needsize (prepares, preparemax, preparecnt, );
946 prepares [preparecnt - 1] = w;
950 ev_prepare_stop (struct ev_prepare *w)
952 ev_clear_pending ((W)w);
953 if (ev_is_active (w))
956 prepares [w->active - 1] = prepares [--preparecnt];
961 ev_check_start (struct ev_check *w)
963 if (ev_is_active (w))
966 ev_start ((W)w, ++checkcnt);
967 array_needsize (checks, checkmax, checkcnt, );
968 checks [checkcnt - 1] = w;
972 ev_check_stop (struct ev_check *w)
974 ev_clear_pending ((W)w);
975 if (ev_is_active (w))
978 checks [w->active - 1] = checks [--checkcnt];
983 ev_child_start (struct ev_child *w)
985 if (ev_is_active (w))
989 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
993 ev_child_stop (struct ev_child *w)
995 ev_clear_pending ((W)w);
996 if (ev_is_active (w))
999 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1003 /*****************************************************************************/
1009 void (*cb)(int revents, void *arg);
1014 once_cb (struct ev_once *once, int revents)
1016 void (*cb)(int revents, void *arg) = once->cb;
1017 void *arg = once->arg;
1019 ev_io_stop (&once->io);
1020 ev_timer_stop (&once->to);
1027 once_cb_io (struct ev_io *w, int revents)
1029 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1033 once_cb_to (struct ev_timer *w, int revents)
1035 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1039 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1041 struct ev_once *once = malloc (sizeof (struct ev_once));
1044 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1050 ev_watcher_init (&once->io, once_cb_io);
1053 ev_io_set (&once->io, fd, events);
1054 ev_io_start (&once->io);
1057 ev_watcher_init (&once->to, once_cb_to);
1060 ev_timer_set (&once->to, timeout, 0.);
1061 ev_timer_start (&once->to);
1066 /*****************************************************************************/
1073 sin_cb (struct ev_io *w, int revents)
1075 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1079 ocb (struct ev_timer *w, int revents)
1081 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1087 scb (struct ev_signal *w, int revents)
1089 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1095 gcb (struct ev_signal *w, int revents)
1097 fprintf (stderr, "generic %x\n", revents);
1105 ev_io_init (&wio, sin_cb, 0, EV_READ);
1108 struct ev_timer t[10000];
1112 for (i = 0; i < 10000; ++i)
1114 struct ev_timer *w = t + i;
1115 ev_watcher_init (w, ocb, i);
1116 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1118 if (drand48 () < 0.5)
1124 ev_timer_init (&t1, ocb, 5, 10);
1125 ev_timer_start (&t1);
1127 struct ev_signal sig;
1128 ev_signal_init (&sig, scb, SIGQUIT);
1129 ev_signal_start (&sig);
1132 ev_check_init (&cw, gcb);
1133 ev_check_start (&cw);
1136 ev_idle_init (&iw, gcb);
1137 ev_idle_start (&iw);