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.
39 # if HAVE_CLOCK_GETTIME
40 # ifndef EV_USE_MONOTONIC
41 # define EV_USE_MONOTONIC 1
43 # ifndef EV_USE_REALTIME
44 # define EV_USE_REALTIME 1
47 # ifndef EV_USE_MONOTONIC
48 # define EV_USE_MONOTONIC 0
50 # ifndef EV_USE_REALTIME
51 # define EV_USE_REALTIME 0
55 # ifndef EV_USE_SELECT
56 # if HAVE_SELECT && HAVE_SYS_SELECT_H
57 # define EV_USE_SELECT 1
59 # define EV_USE_SELECT 0
64 # if HAVE_POLL && HAVE_POLL_H
65 # define EV_USE_POLL 1
67 # define EV_USE_POLL 0
72 # if HAVE_EPOLL_CTL && HAVE_SYS_EPOLL_H
73 # define EV_USE_EPOLL 1
75 # define EV_USE_EPOLL 0
79 # ifndef EV_USE_KQUEUE
80 # if HAVE_KQUEUE && HAVE_SYS_EVENT_H && HAVE_SYS_QUEUE_H
81 # define EV_USE_KQUEUE 1
83 # define EV_USE_KQUEUE 0
88 # if HAVE_PORT_H && HAVE_PORT_CREATE
89 # define EV_USE_PORT 1
91 # define EV_USE_PORT 0
106 #include <sys/types.h>
113 # include <sys/time.h>
114 # include <sys/wait.h>
116 # define WIN32_LEAN_AND_MEAN
117 # include <windows.h>
118 # ifndef EV_SELECT_IS_WINSOCKET
119 # define EV_SELECT_IS_WINSOCKET 1
125 #ifndef EV_USE_MONOTONIC
126 # define EV_USE_MONOTONIC 0
129 #ifndef EV_USE_REALTIME
130 # define EV_USE_REALTIME 0
133 #ifndef EV_USE_SELECT
134 # define EV_USE_SELECT 1
139 # define EV_USE_POLL 0
141 # define EV_USE_POLL 1
146 # define EV_USE_EPOLL 0
149 #ifndef EV_USE_KQUEUE
150 # define EV_USE_KQUEUE 0
154 # define EV_USE_PORT 0
159 #ifndef CLOCK_MONOTONIC
160 # undef EV_USE_MONOTONIC
161 # define EV_USE_MONOTONIC 0
164 #ifndef CLOCK_REALTIME
165 # undef EV_USE_REALTIME
166 # define EV_USE_REALTIME 0
169 #if EV_SELECT_IS_WINSOCKET
170 # include <winsock.h>
175 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
176 #define MAX_BLOCKTIME 59.743 /* never wait longer than this time (to detect time jumps) */
177 #define PID_HASHSIZE 16 /* size of pid hash table, must be power of two */
178 /*#define CLEANUP_INTERVAL (MAX_BLOCKTIME * 5.) /* how often to try to free memory and re-check fds */
187 # define expect(expr,value) __builtin_expect ((expr),(value))
188 # define inline static inline
190 # define expect(expr,value) (expr)
191 # define inline static
194 #define expect_false(expr) expect ((expr) != 0, 0)
195 #define expect_true(expr) expect ((expr) != 0, 1)
197 #define NUMPRI (EV_MAXPRI - EV_MINPRI + 1)
198 #define ABSPRI(w) ((w)->priority - EV_MINPRI)
200 #define EMPTY0 /* required for microsofts broken pseudo-c compiler */
201 #define EMPTY2(a,b) /* used to suppress some warnings */
203 typedef struct ev_watcher *W;
204 typedef struct ev_watcher_list *WL;
205 typedef struct ev_watcher_time *WT;
207 static int have_monotonic; /* did clock_gettime (CLOCK_MONOTONIC) work? */
210 # include "ev_win32.c"
213 /*****************************************************************************/
215 static void (*syserr_cb)(const char *msg);
217 void ev_set_syserr_cb (void (*cb)(const char *msg))
223 syserr (const char *msg)
226 msg = "(libev) system error";
237 static void *(*alloc)(void *ptr, long size);
239 void ev_set_allocator (void *(*cb)(void *ptr, long size))
245 ev_realloc (void *ptr, long size)
247 ptr = alloc ? alloc (ptr, size) : realloc (ptr, size);
251 fprintf (stderr, "libev: cannot allocate %ld bytes, aborting.", size);
258 #define ev_malloc(size) ev_realloc (0, (size))
259 #define ev_free(ptr) ev_realloc ((ptr), 0)
261 /*****************************************************************************/
266 unsigned char events;
268 #if EV_SELECT_IS_WINSOCKET
284 #define ev_rt_now ((loop)->ev_rt_now)
285 #define VAR(name,decl) decl;
291 static struct ev_loop default_loop_struct;
292 struct ev_loop *ev_default_loop_ptr;
297 #define VAR(name,decl) static decl;
301 static int ev_default_loop_ptr;
305 /*****************************************************************************/
312 clock_gettime (CLOCK_REALTIME, &ts);
313 return ts.tv_sec + ts.tv_nsec * 1e-9;
316 gettimeofday (&tv, 0);
317 return tv.tv_sec + tv.tv_usec * 1e-6;
325 if (expect_true (have_monotonic))
328 clock_gettime (CLOCK_MONOTONIC, &ts);
329 return ts.tv_sec + ts.tv_nsec * 1e-9;
344 #define array_roundsize(type,n) (((n) | 4) & ~3)
346 #define array_needsize(type,base,cur,cnt,init) \
347 if (expect_false ((cnt) > cur)) \
352 newcnt = array_roundsize (type, newcnt << 1); \
354 while ((cnt) > newcnt); \
356 base = (type *)ev_realloc (base, sizeof (type) * (newcnt));\
357 init (base + cur, newcnt - cur); \
361 #define array_slim(type,stem) \
362 if (stem ## max < array_roundsize (stem ## cnt >> 2)) \
364 stem ## max = array_roundsize (stem ## cnt >> 1); \
365 base = (type *)ev_realloc (base, sizeof (type) * (stem ## max));\
366 fprintf (stderr, "slimmed down " # stem " to %d\n", stem ## max);/*D*/\
369 #define array_free(stem, idx) \
370 ev_free (stem ## s idx); stem ## cnt idx = stem ## max idx = 0;
372 /*****************************************************************************/
375 anfds_init (ANFD *base, int count)
380 base->events = EV_NONE;
388 ev_feed_event (EV_P_ void *w, int revents)
392 if (expect_false (w_->pending))
394 pendings [ABSPRI (w_)][w_->pending - 1].events |= revents;
398 w_->pending = ++pendingcnt [ABSPRI (w_)];
399 array_needsize (ANPENDING, pendings [ABSPRI (w_)], pendingmax [ABSPRI (w_)], pendingcnt [ABSPRI (w_)], EMPTY2);
400 pendings [ABSPRI (w_)][w_->pending - 1].w = w_;
401 pendings [ABSPRI (w_)][w_->pending - 1].events = revents;
405 queue_events (EV_P_ W *events, int eventcnt, int type)
409 for (i = 0; i < eventcnt; ++i)
410 ev_feed_event (EV_A_ events [i], type);
414 fd_event (EV_P_ int fd, int revents)
416 ANFD *anfd = anfds + fd;
419 for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
421 int ev = w->events & revents;
424 ev_feed_event (EV_A_ (W)w, ev);
429 ev_feed_fd_event (EV_P_ int fd, int revents)
431 fd_event (EV_A_ fd, revents);
434 /*****************************************************************************/
441 for (i = 0; i < fdchangecnt; ++i)
443 int fd = fdchanges [i];
444 ANFD *anfd = anfds + fd;
449 for (w = (struct ev_io *)anfd->head; w; w = (struct ev_io *)((WL)w)->next)
452 #if EV_SELECT_IS_WINSOCKET
456 anfd->handle = _get_osfhandle (fd);
457 assert (("libev only supports socket fds in this configuration", ioctlsocket (anfd->handle, FIONREAD, &argp) == 0));
463 backend_modify (EV_A_ fd, anfd->events, events);
464 anfd->events = events;
471 fd_change (EV_P_ int fd)
473 if (expect_false (anfds [fd].reify))
476 anfds [fd].reify = 1;
479 array_needsize (int, fdchanges, fdchangemax, fdchangecnt, EMPTY2);
480 fdchanges [fdchangecnt - 1] = fd;
484 fd_kill (EV_P_ int fd)
488 while ((w = (struct ev_io *)anfds [fd].head))
490 ev_io_stop (EV_A_ w);
491 ev_feed_event (EV_A_ (W)w, EV_ERROR | EV_READ | EV_WRITE);
499 return _get_osfhandle (fd) != -1;
501 return fcntl (fd, F_GETFD) != -1;
505 /* called on EBADF to verify fds */
511 for (fd = 0; fd < anfdmax; ++fd)
512 if (anfds [fd].events)
513 if (!fd_valid (fd) == -1 && errno == EBADF)
517 /* called on ENOMEM in select/poll to kill some fds and retry */
523 for (fd = anfdmax; fd--; )
524 if (anfds [fd].events)
531 /* usually called after fork if backend needs to re-arm all fds from scratch */
537 /* this should be highly optimised to not do anything but set a flag */
538 for (fd = 0; fd < anfdmax; ++fd)
539 if (anfds [fd].events)
541 anfds [fd].events = 0;
542 fd_change (EV_A_ fd);
546 /*****************************************************************************/
549 upheap (WT *heap, int k)
553 while (k && heap [k >> 1]->at > w->at)
555 heap [k] = heap [k >> 1];
556 ((W)heap [k])->active = k + 1;
561 ((W)heap [k])->active = k + 1;
566 downheap (WT *heap, int N, int k)
574 if (j + 1 < N && heap [j]->at > heap [j + 1]->at)
577 if (w->at <= heap [j]->at)
581 ((W)heap [k])->active = k + 1;
586 ((W)heap [k])->active = k + 1;
590 adjustheap (WT *heap, int N, int k)
593 downheap (heap, N, k);
596 /*****************************************************************************/
601 sig_atomic_t volatile gotsig;
604 static ANSIG *signals;
605 static int signalmax;
607 static int sigpipe [2];
608 static sig_atomic_t volatile gotsig;
609 static struct ev_io sigev;
612 signals_init (ANSIG *base, int count)
624 sighandler (int signum)
627 signal (signum, sighandler);
630 signals [signum - 1].gotsig = 1;
634 int old_errno = errno;
636 write (sigpipe [1], &signum, 1);
642 ev_feed_signal_event (EV_P_ int signum)
647 assert (("feeding signal events is only supported in the default loop", loop == ev_default_loop_ptr));
652 if (signum < 0 || signum >= signalmax)
655 signals [signum].gotsig = 0;
657 for (w = signals [signum].head; w; w = w->next)
658 ev_feed_event (EV_A_ (W)w, EV_SIGNAL);
662 sigcb (EV_P_ struct ev_io *iow, int revents)
666 read (sigpipe [0], &revents, 1);
669 for (signum = signalmax; signum--; )
670 if (signals [signum].gotsig)
671 ev_feed_signal_event (EV_A_ signum + 1);
679 ioctlsocket (_get_osfhandle (fd), FIONBIO, &arg);
681 fcntl (fd, F_SETFD, FD_CLOEXEC);
682 fcntl (fd, F_SETFL, O_NONBLOCK);
689 fd_intern (sigpipe [0]);
690 fd_intern (sigpipe [1]);
692 ev_io_set (&sigev, sigpipe [0], EV_READ);
693 ev_io_start (EV_A_ &sigev);
694 ev_unref (EV_A); /* child watcher should not keep loop alive */
697 /*****************************************************************************/
699 static struct ev_child *childs [PID_HASHSIZE];
703 static struct ev_signal childev;
706 # define WCONTINUED 0
710 child_reap (EV_P_ struct ev_signal *sw, int chain, int pid, int status)
714 for (w = (struct ev_child *)childs [chain & (PID_HASHSIZE - 1)]; w; w = (struct ev_child *)((WL)w)->next)
715 if (w->pid == pid || !w->pid)
717 ev_priority (w) = ev_priority (sw); /* need to do it *now* */
720 ev_feed_event (EV_A_ (W)w, EV_CHILD);
725 childcb (EV_P_ struct ev_signal *sw, int revents)
729 if (0 < (pid = waitpid (-1, &status, WNOHANG | WUNTRACED | WCONTINUED)))
731 /* make sure we are called again until all childs have been reaped */
732 ev_feed_event (EV_A_ (W)sw, EV_SIGNAL);
734 child_reap (EV_A_ sw, pid, pid, status);
735 child_reap (EV_A_ sw, 0, pid, status); /* this might trigger a watcher twice, but event catches that */
741 /*****************************************************************************/
744 # include "ev_port.c"
747 # include "ev_kqueue.c"
750 # include "ev_epoll.c"
753 # include "ev_poll.c"
756 # include "ev_select.c"
760 ev_version_major (void)
762 return EV_VERSION_MAJOR;
766 ev_version_minor (void)
768 return EV_VERSION_MINOR;
771 /* return true if we are running with elevated privileges and should ignore env variables */
778 return getuid () != geteuid ()
779 || getgid () != getegid ();
784 ev_supported_backends (void)
786 unsigned int flags = 0;
788 if (EV_USE_PORT ) flags |= EVBACKEND_PORT;
789 if (EV_USE_KQUEUE) flags |= EVBACKEND_KQUEUE;
790 if (EV_USE_EPOLL ) flags |= EVBACKEND_EPOLL;
791 if (EV_USE_POLL ) flags |= EVBACKEND_POLL;
792 if (EV_USE_SELECT) flags |= EVBACKEND_SELECT;
798 ev_recommended_backends (void)
800 unsigned int flags = ev_recommended_backends ();
803 /* kqueue is borked on everything but netbsd apparently */
804 /* it usually doesn't work correctly on anything but sockets and pipes */
805 flags &= ~EVBACKEND_KQUEUE;
808 // flags &= ~EVBACKEND_KQUEUE; for documentation
809 flags &= ~EVBACKEND_POLL;
822 loop_init (EV_P_ unsigned int flags)
829 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
834 ev_rt_now = ev_time ();
835 mn_now = get_clock ();
837 rtmn_diff = ev_rt_now - mn_now;
839 if (!(flags & EVFLAG_NOENV)
841 && getenv ("LIBEV_FLAGS"))
842 flags = atoi (getenv ("LIBEV_FLAGS"));
844 if (!(flags & 0x0000ffffUL))
845 flags |= ev_recommended_backends ();
849 if (!backend && (flags & EVBACKEND_PORT )) backend = port_init (EV_A_ flags);
852 if (!backend && (flags & EVBACKEND_KQUEUE)) backend = kqueue_init (EV_A_ flags);
855 if (!backend && (flags & EVBACKEND_EPOLL )) backend = epoll_init (EV_A_ flags);
858 if (!backend && (flags & EVBACKEND_POLL )) backend = poll_init (EV_A_ flags);
861 if (!backend && (flags & EVBACKEND_SELECT)) backend = select_init (EV_A_ flags);
864 ev_init (&sigev, sigcb);
865 ev_set_priority (&sigev, EV_MAXPRI);
875 if (backend == EVBACKEND_PORT ) port_destroy (EV_A);
878 if (backend == EVBACKEND_KQUEUE) kqueue_destroy (EV_A);
881 if (backend == EVBACKEND_EPOLL ) epoll_destroy (EV_A);
884 if (backend == EVBACKEND_POLL ) poll_destroy (EV_A);
887 if (backend == EVBACKEND_SELECT) select_destroy (EV_A);
890 for (i = NUMPRI; i--; )
891 array_free (pending, [i]);
893 /* have to use the microsoft-never-gets-it-right macro */
894 array_free (fdchange, EMPTY0);
895 array_free (timer, EMPTY0);
897 array_free (periodic, EMPTY0);
899 array_free (idle, EMPTY0);
900 array_free (prepare, EMPTY0);
901 array_free (check, EMPTY0);
910 if (backend == EVBACKEND_PORT ) port_fork (EV_A);
913 if (backend == EVBACKEND_KQUEUE) kqueue_fork (EV_A);
916 if (backend == EVBACKEND_EPOLL ) epoll_fork (EV_A);
919 if (ev_is_active (&sigev))
924 ev_io_stop (EV_A_ &sigev);
928 while (pipe (sigpipe))
929 syserr ("(libev) error creating pipe");
939 ev_loop_new (unsigned int flags)
941 struct ev_loop *loop = (struct ev_loop *)ev_malloc (sizeof (struct ev_loop));
943 memset (loop, 0, sizeof (struct ev_loop));
945 loop_init (EV_A_ flags);
947 if (ev_backend (EV_A))
954 ev_loop_destroy (EV_P)
970 ev_default_loop_init (unsigned int flags)
973 ev_default_loop (unsigned int flags)
976 if (sigpipe [0] == sigpipe [1])
980 if (!ev_default_loop_ptr)
983 struct ev_loop *loop = ev_default_loop_ptr = &default_loop_struct;
985 ev_default_loop_ptr = 1;
988 loop_init (EV_A_ flags);
990 if (ev_backend (EV_A))
995 ev_signal_init (&childev, childcb, SIGCHLD);
996 ev_set_priority (&childev, EV_MAXPRI);
997 ev_signal_start (EV_A_ &childev);
998 ev_unref (EV_A); /* child watcher should not keep loop alive */
1002 ev_default_loop_ptr = 0;
1005 return ev_default_loop_ptr;
1009 ev_default_destroy (void)
1012 struct ev_loop *loop = ev_default_loop_ptr;
1016 ev_ref (EV_A); /* child watcher */
1017 ev_signal_stop (EV_A_ &childev);
1020 ev_ref (EV_A); /* signal watcher */
1021 ev_io_stop (EV_A_ &sigev);
1023 close (sigpipe [0]); sigpipe [0] = 0;
1024 close (sigpipe [1]); sigpipe [1] = 0;
1026 loop_destroy (EV_A);
1030 ev_default_fork (void)
1033 struct ev_loop *loop = ev_default_loop_ptr;
1040 /*****************************************************************************/
1047 for (pri = NUMPRI; pri--; )
1048 if (pendingcnt [pri])
1059 for (pri = NUMPRI; pri--; )
1060 while (pendingcnt [pri])
1062 ANPENDING *p = pendings [pri] + --pendingcnt [pri];
1064 if (expect_true (p->w))
1067 EV_CB_INVOKE (p->w, p->events);
1075 while (timercnt && ((WT)timers [0])->at <= mn_now)
1077 struct ev_timer *w = timers [0];
1079 assert (("inactive timer on timer heap detected", ev_is_active (w)));
1081 /* first reschedule or stop timer */
1084 assert (("negative ev_timer repeat value found while processing timers", w->repeat > 0.));
1086 ((WT)w)->at += w->repeat;
1087 if (((WT)w)->at < mn_now)
1088 ((WT)w)->at = mn_now;
1090 downheap ((WT *)timers, timercnt, 0);
1093 ev_timer_stop (EV_A_ w); /* nonrepeating: stop timer */
1095 ev_feed_event (EV_A_ (W)w, EV_TIMEOUT);
1101 periodics_reify (EV_P)
1103 while (periodiccnt && ((WT)periodics [0])->at <= ev_rt_now)
1105 struct ev_periodic *w = periodics [0];
1107 assert (("inactive timer on periodic heap detected", ev_is_active (w)));
1109 /* first reschedule or stop timer */
1110 if (w->reschedule_cb)
1112 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now + 0.0001);
1113 assert (("ev_periodic reschedule callback returned time in the past", ((WT)w)->at > ev_rt_now));
1114 downheap ((WT *)periodics, periodiccnt, 0);
1116 else if (w->interval)
1118 ((WT)w)->at += floor ((ev_rt_now - ((WT)w)->at) / w->interval + 1.) * w->interval;
1119 assert (("ev_periodic timeout in the past detected while processing timers, negative interval?", ((WT)w)->at > ev_rt_now));
1120 downheap ((WT *)periodics, periodiccnt, 0);
1123 ev_periodic_stop (EV_A_ w); /* nonrepeating: stop timer */
1125 ev_feed_event (EV_A_ (W)w, EV_PERIODIC);
1130 periodics_reschedule (EV_P)
1134 /* adjust periodics after time jump */
1135 for (i = 0; i < periodiccnt; ++i)
1137 struct ev_periodic *w = periodics [i];
1139 if (w->reschedule_cb)
1140 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now);
1141 else if (w->interval)
1142 ((WT)w)->at += ceil ((ev_rt_now - ((WT)w)->at) / w->interval) * w->interval;
1145 /* now rebuild the heap */
1146 for (i = periodiccnt >> 1; i--; )
1147 downheap ((WT *)periodics, periodiccnt, i);
1152 time_update_monotonic (EV_P)
1154 mn_now = get_clock ();
1156 if (expect_true (mn_now - now_floor < MIN_TIMEJUMP * .5))
1158 ev_rt_now = rtmn_diff + mn_now;
1164 ev_rt_now = ev_time ();
1174 #if EV_USE_MONOTONIC
1175 if (expect_true (have_monotonic))
1177 if (time_update_monotonic (EV_A))
1179 ev_tstamp odiff = rtmn_diff;
1181 for (i = 4; --i; ) /* loop a few times, before making important decisions */
1183 rtmn_diff = ev_rt_now - mn_now;
1185 if (fabs (odiff - rtmn_diff) < MIN_TIMEJUMP)
1186 return; /* all is well */
1188 ev_rt_now = ev_time ();
1189 mn_now = get_clock ();
1194 periodics_reschedule (EV_A);
1196 /* no timer adjustment, as the monotonic clock doesn't jump */
1197 /* timers_reschedule (EV_A_ rtmn_diff - odiff) */
1203 ev_rt_now = ev_time ();
1205 if (expect_false (mn_now > ev_rt_now || mn_now < ev_rt_now - MAX_BLOCKTIME - MIN_TIMEJUMP))
1208 periodics_reschedule (EV_A);
1211 /* adjust timers. this is easy, as the offset is the same for all */
1212 for (i = 0; i < timercnt; ++i)
1213 ((WT)timers [i])->at += ev_rt_now - mn_now;
1232 static int loop_done;
1235 ev_loop (EV_P_ int flags)
1238 loop_done = flags & (EVLOOP_ONESHOT | EVLOOP_NONBLOCK) ? 1 : 0;
1242 /* queue check watchers (and execute them) */
1243 if (expect_false (preparecnt))
1245 queue_events (EV_A_ (W *)prepares, preparecnt, EV_PREPARE);
1246 call_pending (EV_A);
1249 /* we might have forked, so reify kernel state if necessary */
1250 if (expect_false (postfork))
1253 /* update fd-related kernel structures */
1256 /* calculate blocking time */
1258 /* we only need this for !monotonic clock or timers, but as we basically
1259 always have timers, we just calculate it always */
1260 #if EV_USE_MONOTONIC
1261 if (expect_true (have_monotonic))
1262 time_update_monotonic (EV_A);
1266 ev_rt_now = ev_time ();
1270 if (flags & EVLOOP_NONBLOCK || idlecnt)
1274 block = MAX_BLOCKTIME;
1278 ev_tstamp to = ((WT)timers [0])->at - mn_now + backend_fudge;
1279 if (block > to) block = to;
1285 ev_tstamp to = ((WT)periodics [0])->at - ev_rt_now + backend_fudge;
1286 if (block > to) block = to;
1290 if (expect_false (block < 0.)) block = 0.;
1293 backend_poll (EV_A_ block);
1295 /* update ev_rt_now, do magic */
1298 /* queue pending timers and reschedule them */
1299 timers_reify (EV_A); /* relative timers called last */
1301 periodics_reify (EV_A); /* absolute timers called first */
1304 /* queue idle watchers unless io or timers are pending */
1305 if (idlecnt && !any_pending (EV_A))
1306 queue_events (EV_A_ (W *)idles, idlecnt, EV_IDLE);
1308 /* queue check watchers, to be executed first */
1309 if (expect_false (checkcnt))
1310 queue_events (EV_A_ (W *)checks, checkcnt, EV_CHECK);
1312 call_pending (EV_A);
1314 if (expect_false (loop_done))
1323 ev_unloop (EV_P_ int how)
1328 /*****************************************************************************/
1331 wlist_add (WL *head, WL elem)
1338 wlist_del (WL *head, WL elem)
1348 head = &(*head)->next;
1353 ev_clear_pending (EV_P_ W w)
1357 pendings [ABSPRI (w)][w->pending - 1].w = 0;
1363 ev_start (EV_P_ W w, int active)
1365 if (w->priority < EV_MINPRI) w->priority = EV_MINPRI;
1366 if (w->priority > EV_MAXPRI) w->priority = EV_MAXPRI;
1379 /*****************************************************************************/
1382 ev_io_start (EV_P_ struct ev_io *w)
1386 if (expect_false (ev_is_active (w)))
1389 assert (("ev_io_start called with negative fd", fd >= 0));
1391 ev_start (EV_A_ (W)w, 1);
1392 array_needsize (ANFD, anfds, anfdmax, fd + 1, anfds_init);
1393 wlist_add ((WL *)&anfds[fd].head, (WL)w);
1395 fd_change (EV_A_ fd);
1399 ev_io_stop (EV_P_ struct ev_io *w)
1401 ev_clear_pending (EV_A_ (W)w);
1402 if (expect_false (!ev_is_active (w)))
1405 assert (("ev_io_start called with illegal fd (must stay constant after start!)", w->fd >= 0 && w->fd < anfdmax));
1407 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
1408 ev_stop (EV_A_ (W)w);
1410 fd_change (EV_A_ w->fd);
1414 ev_timer_start (EV_P_ struct ev_timer *w)
1416 if (expect_false (ev_is_active (w)))
1419 ((WT)w)->at += mn_now;
1421 assert (("ev_timer_start called with negative timer repeat value", w->repeat >= 0.));
1423 ev_start (EV_A_ (W)w, ++timercnt);
1424 array_needsize (struct ev_timer *, timers, timermax, timercnt, EMPTY2);
1425 timers [timercnt - 1] = w;
1426 upheap ((WT *)timers, timercnt - 1);
1428 assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
1432 ev_timer_stop (EV_P_ struct ev_timer *w)
1434 ev_clear_pending (EV_A_ (W)w);
1435 if (expect_false (!ev_is_active (w)))
1438 assert (("internal timer heap corruption", timers [((W)w)->active - 1] == w));
1440 if (expect_true (((W)w)->active < timercnt--))
1442 timers [((W)w)->active - 1] = timers [timercnt];
1443 adjustheap ((WT *)timers, timercnt, ((W)w)->active - 1);
1446 ((WT)w)->at -= mn_now;
1448 ev_stop (EV_A_ (W)w);
1452 ev_timer_again (EV_P_ struct ev_timer *w)
1454 if (ev_is_active (w))
1458 ((WT)w)->at = mn_now + w->repeat;
1459 adjustheap ((WT *)timers, timercnt, ((W)w)->active - 1);
1462 ev_timer_stop (EV_A_ w);
1467 ev_timer_start (EV_A_ w);
1473 ev_periodic_start (EV_P_ struct ev_periodic *w)
1475 if (expect_false (ev_is_active (w)))
1478 if (w->reschedule_cb)
1479 ((WT)w)->at = w->reschedule_cb (w, ev_rt_now);
1480 else if (w->interval)
1482 assert (("ev_periodic_start called with negative interval value", w->interval >= 0.));
1483 /* this formula differs from the one in periodic_reify because we do not always round up */
1484 ((WT)w)->at += ceil ((ev_rt_now - ((WT)w)->at) / w->interval) * w->interval;
1487 ev_start (EV_A_ (W)w, ++periodiccnt);
1488 array_needsize (struct ev_periodic *, periodics, periodicmax, periodiccnt, EMPTY2);
1489 periodics [periodiccnt - 1] = w;
1490 upheap ((WT *)periodics, periodiccnt - 1);
1492 assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
1496 ev_periodic_stop (EV_P_ struct ev_periodic *w)
1498 ev_clear_pending (EV_A_ (W)w);
1499 if (expect_false (!ev_is_active (w)))
1502 assert (("internal periodic heap corruption", periodics [((W)w)->active - 1] == w));
1504 if (expect_true (((W)w)->active < periodiccnt--))
1506 periodics [((W)w)->active - 1] = periodics [periodiccnt];
1507 adjustheap ((WT *)periodics, periodiccnt, ((W)w)->active - 1);
1510 ev_stop (EV_A_ (W)w);
1514 ev_periodic_again (EV_P_ struct ev_periodic *w)
1516 /* TODO: use adjustheap and recalculation */
1517 ev_periodic_stop (EV_A_ w);
1518 ev_periodic_start (EV_A_ w);
1523 ev_idle_start (EV_P_ struct ev_idle *w)
1525 if (expect_false (ev_is_active (w)))
1528 ev_start (EV_A_ (W)w, ++idlecnt);
1529 array_needsize (struct ev_idle *, idles, idlemax, idlecnt, EMPTY2);
1530 idles [idlecnt - 1] = w;
1534 ev_idle_stop (EV_P_ struct ev_idle *w)
1536 ev_clear_pending (EV_A_ (W)w);
1537 if (expect_false (!ev_is_active (w)))
1540 idles [((W)w)->active - 1] = idles [--idlecnt];
1541 ev_stop (EV_A_ (W)w);
1545 ev_prepare_start (EV_P_ struct ev_prepare *w)
1547 if (expect_false (ev_is_active (w)))
1550 ev_start (EV_A_ (W)w, ++preparecnt);
1551 array_needsize (struct ev_prepare *, prepares, preparemax, preparecnt, EMPTY2);
1552 prepares [preparecnt - 1] = w;
1556 ev_prepare_stop (EV_P_ struct ev_prepare *w)
1558 ev_clear_pending (EV_A_ (W)w);
1559 if (expect_false (!ev_is_active (w)))
1562 prepares [((W)w)->active - 1] = prepares [--preparecnt];
1563 ev_stop (EV_A_ (W)w);
1567 ev_check_start (EV_P_ struct ev_check *w)
1569 if (expect_false (ev_is_active (w)))
1572 ev_start (EV_A_ (W)w, ++checkcnt);
1573 array_needsize (struct ev_check *, checks, checkmax, checkcnt, EMPTY2);
1574 checks [checkcnt - 1] = w;
1578 ev_check_stop (EV_P_ struct ev_check *w)
1580 ev_clear_pending (EV_A_ (W)w);
1581 if (expect_false (!ev_is_active (w)))
1584 checks [((W)w)->active - 1] = checks [--checkcnt];
1585 ev_stop (EV_A_ (W)w);
1589 # define SA_RESTART 0
1593 ev_signal_start (EV_P_ struct ev_signal *w)
1596 assert (("signal watchers are only supported in the default loop", loop == ev_default_loop_ptr));
1598 if (expect_false (ev_is_active (w)))
1601 assert (("ev_signal_start called with illegal signal number", w->signum > 0));
1603 ev_start (EV_A_ (W)w, 1);
1604 array_needsize (ANSIG, signals, signalmax, w->signum, signals_init);
1605 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
1610 signal (w->signum, sighandler);
1612 struct sigaction sa;
1613 sa.sa_handler = sighandler;
1614 sigfillset (&sa.sa_mask);
1615 sa.sa_flags = SA_RESTART; /* if restarting works we save one iteration */
1616 sigaction (w->signum, &sa, 0);
1622 ev_signal_stop (EV_P_ struct ev_signal *w)
1624 ev_clear_pending (EV_A_ (W)w);
1625 if (expect_false (!ev_is_active (w)))
1628 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
1629 ev_stop (EV_A_ (W)w);
1631 if (!signals [w->signum - 1].head)
1632 signal (w->signum, SIG_DFL);
1636 ev_child_start (EV_P_ struct ev_child *w)
1639 assert (("child watchers are only supported in the default loop", loop == ev_default_loop_ptr));
1641 if (expect_false (ev_is_active (w)))
1644 ev_start (EV_A_ (W)w, 1);
1645 wlist_add ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1649 ev_child_stop (EV_P_ struct ev_child *w)
1651 ev_clear_pending (EV_A_ (W)w);
1652 if (expect_false (!ev_is_active (w)))
1655 wlist_del ((WL *)&childs [w->pid & (PID_HASHSIZE - 1)], (WL)w);
1656 ev_stop (EV_A_ (W)w);
1659 /*****************************************************************************/
1665 void (*cb)(int revents, void *arg);
1670 once_cb (EV_P_ struct ev_once *once, int revents)
1672 void (*cb)(int revents, void *arg) = once->cb;
1673 void *arg = once->arg;
1675 ev_io_stop (EV_A_ &once->io);
1676 ev_timer_stop (EV_A_ &once->to);
1683 once_cb_io (EV_P_ struct ev_io *w, int revents)
1685 once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
1689 once_cb_to (EV_P_ struct ev_timer *w, int revents)
1691 once_cb (EV_A_ (struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
1695 ev_once (EV_P_ int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
1697 struct ev_once *once = (struct ev_once *)ev_malloc (sizeof (struct ev_once));
1699 if (expect_false (!once))
1701 cb (EV_ERROR | EV_READ | EV_WRITE | EV_TIMEOUT, arg);
1708 ev_init (&once->io, once_cb_io);
1711 ev_io_set (&once->io, fd, events);
1712 ev_io_start (EV_A_ &once->io);
1715 ev_init (&once->to, once_cb_to);
1718 ev_timer_set (&once->to, timeout, 0.);
1719 ev_timer_start (EV_A_ &once->to);