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>
53 #ifndef EV_USE_MONOTONIC
54 # define EV_USE_MONOTONIC 1
58 # define EV_USE_SELECT 1
62 # define EV_USE_EPOLL 0
65 #ifndef EV_USE_REALTIME
66 # define EV_USE_REALTIME 1
71 #ifndef CLOCK_MONOTONIC
72 # undef EV_USE_MONOTONIC
73 # define EV_USE_MONOTONIC 0
76 #ifndef CLOCK_REALTIME
77 # undef EV_USE_REALTIME
78 # define EV_USE_REALTIME 0
83 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
84 #define MAX_BLOCKTIME 59.731 /* never wait longer than this time (to detect time jumps) */
85 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
86 /*#define CLEANUP_INTERVAL 300. /* how often to try to free memory and re-check fds */
91 # define expect(expr,value) __builtin_expect ((expr),(value))
92 # define inline inline
94 # define expect(expr,value) (expr)
95 # define inline static
98 #define expect_false(expr) expect ((expr) != 0, 0)
99 #define expect_true(expr) expect ((expr) != 0, 1)
101 typedef struct ev_watcher *W;
102 typedef struct ev_watcher_list *WL;
103 typedef struct ev_watcher_time *WT;
105 static ev_tstamp now_floor, now, diff; /* monotonic clock */
109 static int have_monotonic; /* runtime */
111 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
112 static void (*method_modify)(int fd, int oev, int nev);
113 static void (*method_poll)(ev_tstamp timeout);
115 /*****************************************************************************/
122 clock_gettime (CLOCK_REALTIME, &ts);
123 return ts.tv_sec + ts.tv_nsec * 1e-9;
126 gettimeofday (&tv, 0);
127 return tv.tv_sec + tv.tv_usec * 1e-6;
135 if (expect_true (have_monotonic))
138 clock_gettime (CLOCK_MONOTONIC, &ts);
139 return ts.tv_sec + ts.tv_nsec * 1e-9;
146 #define array_roundsize(base,n) ((n) | 4 & ~3)
148 #define array_needsize(base,cur,cnt,init) \
149 if (expect_false ((cnt) > cur)) \
154 newcnt = array_roundsize (base, newcnt << 1); \
156 while ((cnt) > newcnt); \
158 base = realloc (base, sizeof (*base) * (newcnt)); \
159 init (base + cur, newcnt - cur); \
163 /*****************************************************************************/
168 unsigned char events;
176 anfds_init (ANFD *base, int count)
181 base->events = EV_NONE;
194 static ANPENDING *pendings;
195 static int pendingmax, pendingcnt;
198 event (W w, int events)
202 pendings [w->pending - 1].events |= events;
206 w->pending = ++pendingcnt;
207 array_needsize (pendings, pendingmax, pendingcnt, );
208 pendings [pendingcnt - 1].w = w;
209 pendings [pendingcnt - 1].events = events;
213 queue_events (W *events, int eventcnt, int type)
217 for (i = 0; i < eventcnt; ++i)
218 event (events [i], type);
222 fd_event (int fd, int events)
224 ANFD *anfd = anfds + fd;
227 for (w = anfd->head; w; w = w->next)
229 int ev = w->events & events;
236 /*****************************************************************************/
238 static int *fdchanges;
239 static int fdchangemax, fdchangecnt;
246 for (i = 0; i < fdchangecnt; ++i)
248 int fd = fdchanges [i];
249 ANFD *anfd = anfds + fd;
254 for (w = anfd->head; w; w = w->next)
259 if (anfd->events != events)
261 method_modify (fd, anfd->events, events);
262 anfd->events = events;
272 if (anfds [fd].reify || fdchangecnt < 0)
275 anfds [fd].reify = 1;
278 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
279 fdchanges [fdchangecnt - 1] = fd;
282 /* called on EBADF to verify fds */
288 for (fd = 0; fd < anfdmax; ++fd)
289 if (anfds [fd].events)
290 if (fcntl (fd, F_GETFD) == -1 && errno == EBADF)
291 while (anfds [fd].head)
293 ev_io_stop (anfds [fd].head);
294 event ((W)anfds [fd].head, EV_ERROR | EV_READ | EV_WRITE);
298 /*****************************************************************************/
300 static struct ev_timer **timers;
301 static int timermax, timercnt;
303 static struct ev_periodic **periodics;
304 static int periodicmax, periodiccnt;
307 upheap (WT *timers, int k)
311 while (k && timers [k >> 1]->at > w->at)
313 timers [k] = timers [k >> 1];
314 timers [k]->active = k + 1;
319 timers [k]->active = k + 1;
324 downheap (WT *timers, int N, int k)
332 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
335 if (w->at <= timers [j]->at)
338 timers [k] = timers [j];
339 timers [k]->active = k + 1;
344 timers [k]->active = k + 1;
347 /*****************************************************************************/
351 struct ev_signal *head;
352 sig_atomic_t volatile gotsig;
355 static ANSIG *signals;
356 static int signalmax;
358 static int sigpipe [2];
359 static sig_atomic_t volatile gotsig;
360 static struct ev_io sigev;
363 signals_init (ANSIG *base, int count)
375 sighandler (int signum)
377 signals [signum - 1].gotsig = 1;
382 write (sigpipe [1], &signum, 1);
387 sigcb (struct ev_io *iow, int revents)
392 read (sigpipe [0], &revents, 1);
395 for (signum = signalmax; signum--; )
396 if (signals [signum].gotsig)
398 signals [signum].gotsig = 0;
400 for (w = signals [signum].head; w; w = w->next)
401 event ((W)w, EV_SIGNAL);
408 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
409 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
411 /* rather than sort out wether we really need nb, set it */
412 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
413 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
415 ev_io_set (&sigev, sigpipe [0], EV_READ);
416 ev_io_start (&sigev);
419 /*****************************************************************************/
421 static struct ev_idle **idles;
422 static int idlemax, idlecnt;
424 static struct ev_prepare **prepares;
425 static int preparemax, preparecnt;
427 static struct ev_check **checks;
428 static int checkmax, checkcnt;
430 /*****************************************************************************/
432 static struct ev_child *childs [PID_HASHSIZE];
433 static struct ev_signal childev;
436 # define WCONTINUED 0
440 childcb (struct ev_signal *sw, int revents)
445 while ((pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)) != -1)
446 for (w = childs [pid & (PID_HASHSIZE - 1)]; w; w = w->next)
447 if (w->pid == pid || !w->pid)
450 event ((W)w, EV_CHILD);
454 /*****************************************************************************/
457 # include "ev_epoll.c"
460 # include "ev_select.c"
464 ev_version_major (void)
466 return EV_VERSION_MAJOR;
470 ev_version_minor (void)
472 return EV_VERSION_MINOR;
475 int ev_init (int flags)
482 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
495 ev_method = EVMETHOD_NONE;
497 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
500 if (ev_method == EVMETHOD_NONE) select_init (flags);
505 ev_watcher_init (&sigev, sigcb);
508 ev_signal_init (&childev, childcb, SIGCHLD);
509 ev_signal_start (&childev);
516 /*****************************************************************************/
519 ev_fork_prepare (void)
525 ev_fork_parent (void)
534 if (ev_method == EVMETHOD_EPOLL)
535 epoll_postfork_child ();
545 /*****************************************************************************/
552 ANPENDING *p = pendings + --pendingcnt;
557 p->w->cb (p->w, p->events);
565 while (timercnt && timers [0]->at <= now)
567 struct ev_timer *w = timers [0];
569 /* first reschedule or stop timer */
572 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
573 w->at = now + w->repeat;
574 downheap ((WT *)timers, timercnt, 0);
577 ev_timer_stop (w); /* nonrepeating: stop timer */
579 event ((W)w, EV_TIMEOUT);
584 periodics_reify (void)
586 while (periodiccnt && periodics [0]->at <= ev_now)
588 struct ev_periodic *w = periodics [0];
590 /* first reschedule or stop timer */
593 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
594 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", w->at > ev_now));
595 downheap ((WT *)periodics, periodiccnt, 0);
598 ev_periodic_stop (w); /* nonrepeating: stop timer */
600 event ((W)w, EV_PERIODIC);
605 periodics_reschedule (ev_tstamp diff)
609 /* adjust periodics after time jump */
610 for (i = 0; i < periodiccnt; ++i)
612 struct ev_periodic *w = periodics [i];
616 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
618 if (fabs (diff) >= 1e-4)
620 ev_periodic_stop (w);
621 ev_periodic_start (w);
623 i = 0; /* restart loop, inefficient, but time jumps should be rare */
630 time_update_monotonic (void)
634 if (expect_true (now - now_floor < MIN_TIMEJUMP * .5))
653 if (expect_true (have_monotonic))
655 if (time_update_monotonic ())
657 ev_tstamp odiff = diff;
659 for (i = 4; --i; ) /* loop a few times, before making important decisions */
663 if (fabs (odiff - diff) < MIN_TIMEJUMP)
664 return; /* all is well */
671 periodics_reschedule (diff - odiff);
672 /* no timer adjustment, as the monotonic clock doesn't jump */
680 if (expect_false (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
682 periodics_reschedule (ev_now - now);
684 /* adjust timers. this is easy, as the offset is the same for all */
685 for (i = 0; i < timercnt; ++i)
686 timers [i]->at += diff;
695 void ev_loop (int flags)
698 ev_loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
702 /* queue check watchers (and execute them) */
703 if (expect_false (preparecnt))
705 queue_events ((W *)prepares, preparecnt, EV_PREPARE);
709 /* update fd-related kernel structures */
712 /* calculate blocking time */
714 /* we only need this for !monotonic clockor timers, but as we basically
715 always have timers, we just calculate it always */
717 if (expect_true (have_monotonic))
718 time_update_monotonic ();
726 if (flags & EVLOOP_NONBLOCK || idlecnt)
730 block = MAX_BLOCKTIME;
734 ev_tstamp to = timers [0]->at - now + method_fudge;
735 if (block > to) block = to;
740 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
741 if (block > to) block = to;
744 if (block < 0.) block = 0.;
749 /* update ev_now, do magic */
752 /* queue pending timers and reschedule them */
753 timers_reify (); /* relative timers called last */
754 periodics_reify (); /* absolute timers called first */
756 /* queue idle watchers unless io or timers are pending */
758 queue_events ((W *)idles, idlecnt, EV_IDLE);
760 /* queue check watchers, to be executed first */
762 queue_events ((W *)checks, checkcnt, EV_CHECK);
766 while (!ev_loop_done);
768 if (ev_loop_done != 2)
772 /*****************************************************************************/
775 wlist_add (WL *head, WL elem)
782 wlist_del (WL *head, WL elem)
792 head = &(*head)->next;
797 ev_clear_pending (W w)
801 pendings [w->pending - 1].w = 0;
807 ev_start (W w, int active)
818 /*****************************************************************************/
821 ev_io_start (struct ev_io *w)
825 if (ev_is_active (w))
828 assert (("ev_io_start called with negative fd", fd >= 0));
831 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
832 wlist_add ((WL *)&anfds[fd].head, (WL)w);
838 ev_io_stop (struct ev_io *w)
840 ev_clear_pending ((W)w);
841 if (!ev_is_active (w))
844 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
851 ev_timer_start (struct ev_timer *w)
853 if (ev_is_active (w))
858 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
860 ev_start ((W)w, ++timercnt);
861 array_needsize (timers, timermax, timercnt, );
862 timers [timercnt - 1] = w;
863 upheap ((WT *)timers, timercnt - 1);
867 ev_timer_stop (struct ev_timer *w)
869 ev_clear_pending ((W)w);
870 if (!ev_is_active (w))
873 if (w->active < timercnt--)
875 timers [w->active - 1] = timers [timercnt];
876 downheap ((WT *)timers, timercnt, w->active - 1);
885 ev_timer_again (struct ev_timer *w)
887 if (ev_is_active (w))
891 w->at = now + w->repeat;
892 downheap ((WT *)timers, timercnt, w->active - 1);
902 ev_periodic_start (struct ev_periodic *w)
904 if (ev_is_active (w))
907 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
909 /* this formula differs from the one in periodic_reify because we do not always round up */
911 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
913 ev_start ((W)w, ++periodiccnt);
914 array_needsize (periodics, periodicmax, periodiccnt, );
915 periodics [periodiccnt - 1] = w;
916 upheap ((WT *)periodics, periodiccnt - 1);
920 ev_periodic_stop (struct ev_periodic *w)
922 ev_clear_pending ((W)w);
923 if (!ev_is_active (w))
926 if (w->active < periodiccnt--)
928 periodics [w->active - 1] = periodics [periodiccnt];
929 downheap ((WT *)periodics, periodiccnt, w->active - 1);
936 ev_signal_start (struct ev_signal *w)
938 if (ev_is_active (w))
941 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
944 array_needsize (signals, signalmax, w->signum, signals_init);
945 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
950 sa.sa_handler = sighandler;
951 sigfillset (&sa.sa_mask);
953 sigaction (w->signum, &sa, 0);
958 ev_signal_stop (struct ev_signal *w)
960 ev_clear_pending ((W)w);
961 if (!ev_is_active (w))
964 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
967 if (!signals [w->signum - 1].head)
968 signal (w->signum, SIG_DFL);
972 ev_idle_start (struct ev_idle *w)
974 if (ev_is_active (w))
977 ev_start ((W)w, ++idlecnt);
978 array_needsize (idles, idlemax, idlecnt, );
979 idles [idlecnt - 1] = w;
983 ev_idle_stop (struct ev_idle *w)
985 ev_clear_pending ((W)w);
986 if (ev_is_active (w))
989 idles [w->active - 1] = idles [--idlecnt];
994 ev_prepare_start (struct ev_prepare *w)
996 if (ev_is_active (w))
999 ev_start ((W)w, ++preparecnt);
1000 array_needsize (prepares, preparemax, preparecnt, );
1001 prepares [preparecnt - 1] = w;
1005 ev_prepare_stop (struct ev_prepare *w)
1007 ev_clear_pending ((W)w);
1008 if (ev_is_active (w))
1011 prepares [w->active - 1] = prepares [--preparecnt];
1016 ev_check_start (struct ev_check *w)
1018 if (ev_is_active (w))
1021 ev_start ((W)w, ++checkcnt);
1022 array_needsize (checks, checkmax, checkcnt, );
1023 checks [checkcnt - 1] = w;
1027 ev_check_stop (struct ev_check *w)
1029 ev_clear_pending ((W)w);
1030 if (ev_is_active (w))
1033 checks [w->active - 1] = checks [--checkcnt];
1038 ev_child_start (struct ev_child *w)
1040 if (ev_is_active (w))
1044 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1048 ev_child_stop (struct ev_child *w)
1050 ev_clear_pending ((W)w);
1051 if (ev_is_active (w))
1054 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1058 /*****************************************************************************/
1064 void (*cb)(int revents, void *arg);
1069 once_cb (struct ev_once *once, int revents)
1071 void (*cb)(int revents, void *arg) = once->cb;
1072 void *arg = once->arg;
1074 ev_io_stop (&once->io);
1075 ev_timer_stop (&once->to);
1082 once_cb_io (struct ev_io *w, int revents)
1084 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1088 once_cb_to (struct ev_timer *w, int revents)
1090 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1094 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1096 struct ev_once *once = malloc (sizeof (struct ev_once));
1099 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1105 ev_watcher_init (&once->io, once_cb_io);
1108 ev_io_set (&once->io, fd, events);
1109 ev_io_start (&once->io);
1112 ev_watcher_init (&once->to, once_cb_to);
1115 ev_timer_set (&once->to, timeout, 0.);
1116 ev_timer_start (&once->to);
1121 /*****************************************************************************/
1128 sin_cb (struct ev_io *w, int revents)
1130 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
1134 ocb (struct ev_timer *w, int revents)
1136 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
1142 scb (struct ev_signal *w, int revents)
1144 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
1150 gcb (struct ev_signal *w, int revents)
1152 fprintf (stderr, "generic %x\n", revents);
1160 ev_io_init (&wio, sin_cb, 0, EV_READ);
1163 struct ev_timer t[10000];
1167 for (i = 0; i < 10000; ++i)
1169 struct ev_timer *w = t + i;
1170 ev_watcher_init (w, ocb, i);
1171 ev_timer_init_abs (w, ocb, drand48 (), 0.99775533);
1173 if (drand48 () < 0.5)
1179 ev_timer_init (&t1, ocb, 5, 10);
1180 ev_timer_start (&t1);
1182 struct ev_signal sig;
1183 ev_signal_init (&sig, scb, SIGQUIT);
1184 ev_signal_start (&sig);
1187 ev_check_init (&cw, gcb);
1188 ev_check_start (&cw);
1191 ev_idle_init (&iw, gcb);
1192 ev_idle_start (&iw);