ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/libev/ev.c
Revision: 1.16
Committed: Wed Oct 31 13:57:34 2007 UTC (16 years, 6 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.15: +97 -11 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 #include <math.h>
2 #include <stdlib.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <signal.h>
6 #include <stddef.h>
7
8 #include <stdio.h>
9
10 #include <assert.h>
11 #include <errno.h>
12 #include <sys/time.h>
13 #include <time.h>
14
15 #define HAVE_EPOLL 1
16
17 #ifndef HAVE_MONOTONIC
18 # ifdef CLOCK_MONOTONIC
19 # define HAVE_MONOTONIC 1
20 # endif
21 #endif
22
23 #ifndef HAVE_SELECT
24 # define HAVE_SELECT 1
25 #endif
26
27 #ifndef HAVE_EPOLL
28 # define HAVE_EPOLL 0
29 #endif
30
31 #ifndef HAVE_REALTIME
32 # define HAVE_REALTIME 1 /* posix requirement, but might be slower */
33 #endif
34
35 #define MIN_TIMEJUMP 1. /* minimum timejump that gets detected (if monotonic clock available) */
36 #define MAX_BLOCKTIME 60.
37
38 #include "ev.h"
39
40 typedef struct ev_watcher *W;
41 typedef struct ev_watcher_list *WL;
42 typedef struct ev_watcher_time *WT;
43
44 static ev_tstamp now, diff; /* monotonic clock */
45 ev_tstamp ev_now;
46 int ev_method;
47
48 static int have_monotonic; /* runtime */
49
50 static ev_tstamp method_fudge; /* stupid epoll-returns-early bug */
51 static void (*method_modify)(int fd, int oev, int nev);
52 static void (*method_poll)(ev_tstamp timeout);
53
54 /*****************************************************************************/
55
56 ev_tstamp
57 ev_time (void)
58 {
59 #if HAVE_REALTIME
60 struct timespec ts;
61 clock_gettime (CLOCK_REALTIME, &ts);
62 return ts.tv_sec + ts.tv_nsec * 1e-9;
63 #else
64 struct timeval tv;
65 gettimeofday (&tv, 0);
66 return tv.tv_sec + tv.tv_usec * 1e-6;
67 #endif
68 }
69
70 static ev_tstamp
71 get_clock (void)
72 {
73 #if HAVE_MONOTONIC
74 if (have_monotonic)
75 {
76 struct timespec ts;
77 clock_gettime (CLOCK_MONOTONIC, &ts);
78 return ts.tv_sec + ts.tv_nsec * 1e-9;
79 }
80 #endif
81
82 return ev_time ();
83 }
84
85 #define array_needsize(base,cur,cnt,init) \
86 if ((cnt) > cur) \
87 { \
88 int newcnt = cur ? cur << 1 : 16; \
89 base = realloc (base, sizeof (*base) * (newcnt)); \
90 init (base + cur, newcnt - cur); \
91 cur = newcnt; \
92 }
93
94 /*****************************************************************************/
95
96 typedef struct
97 {
98 struct ev_io *head;
99 unsigned char wev, rev; /* want, received event set */
100 } ANFD;
101
102 static ANFD *anfds;
103 static int anfdmax;
104
105 static int *fdchanges;
106 static int fdchangemax, fdchangecnt;
107
108 static void
109 anfds_init (ANFD *base, int count)
110 {
111 while (count--)
112 {
113 base->head = 0;
114 base->wev = base->rev = EV_NONE;
115 ++base;
116 }
117 }
118
119 typedef struct
120 {
121 W w;
122 int events;
123 } ANPENDING;
124
125 static ANPENDING *pendings;
126 static int pendingmax, pendingcnt;
127
128 static void
129 event (W w, int events)
130 {
131 if (w->active)
132 {
133 w->pending = ++pendingcnt;
134 array_needsize (pendings, pendingmax, pendingcnt, );
135 pendings [pendingcnt - 1].w = w;
136 pendings [pendingcnt - 1].events = events;
137 }
138 }
139
140 static void
141 fd_event (int fd, int events)
142 {
143 ANFD *anfd = anfds + fd;
144 struct ev_io *w;
145
146 for (w = anfd->head; w; w = w->next)
147 {
148 int ev = w->events & events;
149
150 if (ev)
151 event ((W)w, ev);
152 }
153 }
154
155 static void
156 queue_events (W *events, int eventcnt, int type)
157 {
158 int i;
159
160 for (i = 0; i < eventcnt; ++i)
161 event (events [i], type);
162 }
163
164 /*****************************************************************************/
165
166 static struct ev_timer **timers;
167 static int timermax, timercnt;
168
169 static struct ev_periodic **periodics;
170 static int periodicmax, periodiccnt;
171
172 static void
173 upheap (WT *timers, int k)
174 {
175 WT w = timers [k];
176
177 while (k && timers [k >> 1]->at > w->at)
178 {
179 timers [k] = timers [k >> 1];
180 timers [k]->active = k + 1;
181 k >>= 1;
182 }
183
184 timers [k] = w;
185 timers [k]->active = k + 1;
186
187 }
188
189 static void
190 downheap (WT *timers, int N, int k)
191 {
192 WT w = timers [k];
193
194 while (k < (N >> 1))
195 {
196 int j = k << 1;
197
198 if (j + 1 < N && timers [j]->at > timers [j + 1]->at)
199 ++j;
200
201 if (w->at <= timers [j]->at)
202 break;
203
204 timers [k] = timers [j];
205 timers [k]->active = k + 1;
206 k = j;
207 }
208
209 timers [k] = w;
210 timers [k]->active = k + 1;
211 }
212
213 /*****************************************************************************/
214
215 typedef struct
216 {
217 struct ev_signal *head;
218 sig_atomic_t gotsig;
219 } ANSIG;
220
221 static ANSIG *signals;
222 static int signalmax;
223
224 static int sigpipe [2];
225 static sig_atomic_t gotsig;
226 static struct ev_io sigev;
227
228 static void
229 signals_init (ANSIG *base, int count)
230 {
231 while (count--)
232 {
233 base->head = 0;
234 base->gotsig = 0;
235 ++base;
236 }
237 }
238
239 static void
240 sighandler (int signum)
241 {
242 signals [signum - 1].gotsig = 1;
243
244 if (!gotsig)
245 {
246 gotsig = 1;
247 write (sigpipe [1], &gotsig, 1);
248 }
249 }
250
251 static void
252 sigcb (struct ev_io *iow, int revents)
253 {
254 struct ev_signal *w;
255 int sig;
256
257 gotsig = 0;
258 read (sigpipe [0], &revents, 1);
259
260 for (sig = signalmax; sig--; )
261 if (signals [sig].gotsig)
262 {
263 signals [sig].gotsig = 0;
264
265 for (w = signals [sig].head; w; w = w->next)
266 event ((W)w, EV_SIGNAL);
267 }
268 }
269
270 static void
271 siginit (void)
272 {
273 fcntl (sigpipe [0], F_SETFD, FD_CLOEXEC);
274 fcntl (sigpipe [1], F_SETFD, FD_CLOEXEC);
275
276 /* rather than sort out wether we really need nb, set it */
277 fcntl (sigpipe [0], F_SETFL, O_NONBLOCK);
278 fcntl (sigpipe [1], F_SETFL, O_NONBLOCK);
279
280 evio_set (&sigev, sigpipe [0], EV_READ);
281 evio_start (&sigev);
282 }
283
284 /*****************************************************************************/
285
286 static struct ev_idle **idles;
287 static int idlemax, idlecnt;
288
289 static struct ev_check **checks;
290 static int checkmax, checkcnt;
291
292 /*****************************************************************************/
293
294 #if HAVE_EPOLL
295 # include "ev_epoll.c"
296 #endif
297 #if HAVE_SELECT
298 # include "ev_select.c"
299 #endif
300
301 int ev_init (int flags)
302 {
303 #if HAVE_MONOTONIC
304 {
305 struct timespec ts;
306 if (!clock_gettime (CLOCK_MONOTONIC, &ts))
307 have_monotonic = 1;
308 }
309 #endif
310
311 ev_now = ev_time ();
312 now = get_clock ();
313 diff = ev_now - now;
314
315 if (pipe (sigpipe))
316 return 0;
317
318 ev_method = EVMETHOD_NONE;
319 #if HAVE_EPOLL
320 if (ev_method == EVMETHOD_NONE) epoll_init (flags);
321 #endif
322 #if HAVE_SELECT
323 if (ev_method == EVMETHOD_NONE) select_init (flags);
324 #endif
325
326 if (ev_method)
327 {
328 evw_init (&sigev, sigcb);
329 siginit ();
330 }
331
332 return ev_method;
333 }
334
335 /*****************************************************************************/
336
337 void ev_prefork (void)
338 {
339 /* nop */
340 }
341
342 void ev_postfork_parent (void)
343 {
344 /* nop */
345 }
346
347 void ev_postfork_child (void)
348 {
349 #if HAVE_EPOLL
350 if (ev_method == EVMETHOD_EPOLL)
351 epoll_postfork_child ();
352 #endif
353
354 evio_stop (&sigev);
355 close (sigpipe [0]);
356 close (sigpipe [1]);
357 pipe (sigpipe);
358 siginit ();
359 }
360
361 /*****************************************************************************/
362
363 static void
364 fd_reify (void)
365 {
366 int i;
367
368 for (i = 0; i < fdchangecnt; ++i)
369 {
370 int fd = fdchanges [i];
371 ANFD *anfd = anfds + fd;
372 struct ev_io *w;
373
374 int wev = 0;
375
376 for (w = anfd->head; w; w = w->next)
377 wev |= w->events;
378
379 if (anfd->wev != wev)
380 {
381 method_modify (fd, anfd->wev, wev);
382 anfd->wev = wev;
383 }
384 }
385
386 fdchangecnt = 0;
387 }
388
389 static void
390 call_pending ()
391 {
392 int i;
393
394 for (i = 0; i < pendingcnt; ++i)
395 {
396 ANPENDING *p = pendings + i;
397
398 if (p->w)
399 {
400 p->w->pending = 0;
401 p->w->cb (p->w, p->events);
402 }
403 }
404
405 pendingcnt = 0;
406 }
407
408 static void
409 timers_reify ()
410 {
411 while (timercnt && timers [0]->at <= now)
412 {
413 struct ev_timer *w = timers [0];
414
415 event ((W)w, EV_TIMEOUT);
416
417 /* first reschedule or stop timer */
418 if (w->repeat)
419 {
420 w->at = now + w->repeat;
421 assert (("timer timeout in the past, negative repeat?", w->at > now));
422 downheap ((WT *)timers, timercnt, 0);
423 }
424 else
425 evtimer_stop (w); /* nonrepeating: stop timer */
426 }
427 }
428
429 static void
430 periodics_reify ()
431 {
432 while (periodiccnt && periodics [0]->at <= ev_now)
433 {
434 struct ev_periodic *w = periodics [0];
435
436 /* first reschedule or stop timer */
437 if (w->interval)
438 {
439 w->at += floor ((ev_now - w->at) / w->interval + 1.) * w->interval;
440 assert (("periodic timeout in the past, negative interval?", w->at > ev_now));
441 downheap ((WT *)periodics, periodiccnt, 0);
442 }
443 else
444 evperiodic_stop (w); /* nonrepeating: stop timer */
445
446 event ((W)w, EV_TIMEOUT);
447 }
448 }
449
450 static void
451 periodics_reschedule (ev_tstamp diff)
452 {
453 int i;
454
455 /* adjust periodics after time jump */
456 for (i = 0; i < periodiccnt; ++i)
457 {
458 struct ev_periodic *w = periodics [i];
459
460 if (w->interval)
461 {
462 ev_tstamp diff = ceil ((ev_now - w->at) / w->interval) * w->interval;
463
464 if (fabs (diff) >= 1e-4)
465 {
466 evperiodic_stop (w);
467 evperiodic_start (w);
468
469 i = 0; /* restart loop, inefficient, but time jumps should be rare */
470 }
471 }
472 }
473 }
474
475 static void
476 time_update ()
477 {
478 int i;
479
480 ev_now = ev_time ();
481
482 if (have_monotonic)
483 {
484 ev_tstamp odiff = diff;
485
486 for (i = 4; --i; ) /* loop a few times, before making important decisions */
487 {
488 now = get_clock ();
489 diff = ev_now - now;
490
491 if (fabs (odiff - diff) < MIN_TIMEJUMP)
492 return; /* all is well */
493
494 ev_now = ev_time ();
495 }
496
497 periodics_reschedule (diff - odiff);
498 /* no timer adjustment, as the monotonic clock doesn't jump */
499 }
500 else
501 {
502 if (now > ev_now || now < ev_now - MAX_BLOCKTIME - MIN_TIMEJUMP)
503 {
504 periodics_reschedule (ev_now - now);
505
506 /* adjust timers. this is easy, as the offset is the same for all */
507 for (i = 0; i < timercnt; ++i)
508 timers [i]->at += diff;
509 }
510
511 now = ev_now;
512 }
513 }
514
515 int ev_loop_done;
516
517 void ev_loop (int flags)
518 {
519 double block;
520 ev_loop_done = flags & EVLOOP_ONESHOT ? 1 : 0;
521
522 if (checkcnt)
523 {
524 queue_events ((W *)checks, checkcnt, EV_CHECK);
525 call_pending ();
526 }
527
528 do
529 {
530 /* update fd-related kernel structures */
531 fd_reify ();
532
533 /* calculate blocking time */
534
535 /* we only need this for !monotonic clock, but as we always have timers, we just calculate it every time */
536 ev_now = ev_time ();
537
538 if (flags & EVLOOP_NONBLOCK || idlecnt)
539 block = 0.;
540 else
541 {
542 block = MAX_BLOCKTIME;
543
544 if (timercnt)
545 {
546 ev_tstamp to = timers [0]->at - (have_monotonic ? get_clock () : ev_now) + method_fudge;
547 if (block > to) block = to;
548 }
549
550 if (periodiccnt)
551 {
552 ev_tstamp to = periodics [0]->at - ev_now + method_fudge;
553 if (block > to) block = to;
554 }
555
556 if (block < 0.) block = 0.;
557 }
558
559 method_poll (block);
560
561 /* update ev_now, do magic */
562 time_update ();
563
564 /* queue pending timers and reschedule them */
565 periodics_reify (); /* absolute timers first */
566 timers_reify (); /* relative timers second */
567
568 /* queue idle watchers unless io or timers are pending */
569 if (!pendingcnt)
570 queue_events ((W *)idles, idlecnt, EV_IDLE);
571
572 /* queue check and possibly idle watchers */
573 queue_events ((W *)checks, checkcnt, EV_CHECK);
574
575 call_pending ();
576 }
577 while (!ev_loop_done);
578
579 if (ev_loop_done != 2)
580 ev_loop_done = 0;
581 }
582
583 /*****************************************************************************/
584
585 static void
586 wlist_add (WL *head, WL elem)
587 {
588 elem->next = *head;
589 *head = elem;
590 }
591
592 static void
593 wlist_del (WL *head, WL elem)
594 {
595 while (*head)
596 {
597 if (*head == elem)
598 {
599 *head = elem->next;
600 return;
601 }
602
603 head = &(*head)->next;
604 }
605 }
606
607 static void
608 ev_clear (W w)
609 {
610 if (w->pending)
611 {
612 pendings [w->pending - 1].w = 0;
613 w->pending = 0;
614 }
615 }
616
617 static void
618 ev_start (W w, int active)
619 {
620 w->active = active;
621 }
622
623 static void
624 ev_stop (W w)
625 {
626 w->active = 0;
627 }
628
629 /*****************************************************************************/
630
631 void
632 evio_start (struct ev_io *w)
633 {
634 if (ev_is_active (w))
635 return;
636
637 int fd = w->fd;
638
639 ev_start ((W)w, 1);
640 array_needsize (anfds, anfdmax, fd + 1, anfds_init);
641 wlist_add ((WL *)&anfds[fd].head, (WL)w);
642
643 ++fdchangecnt;
644 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
645 fdchanges [fdchangecnt - 1] = fd;
646 }
647
648 void
649 evio_stop (struct ev_io *w)
650 {
651 ev_clear ((W)w);
652 if (!ev_is_active (w))
653 return;
654
655 wlist_del ((WL *)&anfds[w->fd].head, (WL)w);
656 ev_stop ((W)w);
657
658 ++fdchangecnt;
659 array_needsize (fdchanges, fdchangemax, fdchangecnt, );
660 fdchanges [fdchangecnt - 1] = w->fd;
661 }
662
663 void
664 evtimer_start (struct ev_timer *w)
665 {
666 if (ev_is_active (w))
667 return;
668
669 w->at += now;
670
671 assert (("timer repeat value less than zero not allowed", w->repeat >= 0.));
672
673 ev_start ((W)w, ++timercnt);
674 array_needsize (timers, timermax, timercnt, );
675 timers [timercnt - 1] = w;
676 upheap ((WT *)timers, timercnt - 1);
677 }
678
679 void
680 evtimer_stop (struct ev_timer *w)
681 {
682 ev_clear ((W)w);
683 if (!ev_is_active (w))
684 return;
685
686 if (w->active < timercnt--)
687 {
688 timers [w->active - 1] = timers [timercnt];
689 downheap ((WT *)timers, timercnt, w->active - 1);
690 }
691
692 w->at = w->repeat;
693
694 ev_stop ((W)w);
695 }
696
697 void
698 evtimer_again (struct ev_timer *w)
699 {
700 if (ev_is_active (w))
701 {
702 if (w->repeat)
703 {
704 w->at = now + w->repeat;
705 downheap ((WT *)timers, timercnt, w->active - 1);
706 }
707 else
708 evtimer_stop (w);
709 }
710 else if (w->repeat)
711 evtimer_start (w);
712 }
713
714 void
715 evperiodic_start (struct ev_periodic *w)
716 {
717 if (ev_is_active (w))
718 return;
719
720 assert (("periodic interval value less than zero not allowed", w->interval >= 0.));
721
722 /* this formula differs from the one in periodic_reify because we do not always round up */
723 if (w->interval)
724 w->at += ceil ((ev_now - w->at) / w->interval) * w->interval;
725
726 ev_start ((W)w, ++periodiccnt);
727 array_needsize (periodics, periodicmax, periodiccnt, );
728 periodics [periodiccnt - 1] = w;
729 upheap ((WT *)periodics, periodiccnt - 1);
730 }
731
732 void
733 evperiodic_stop (struct ev_periodic *w)
734 {
735 ev_clear ((W)w);
736 if (!ev_is_active (w))
737 return;
738
739 if (w->active < periodiccnt--)
740 {
741 periodics [w->active - 1] = periodics [periodiccnt];
742 downheap ((WT *)periodics, periodiccnt, w->active - 1);
743 }
744
745 ev_stop ((W)w);
746 }
747
748 void
749 evsignal_start (struct ev_signal *w)
750 {
751 if (ev_is_active (w))
752 return;
753
754 ev_start ((W)w, 1);
755 array_needsize (signals, signalmax, w->signum, signals_init);
756 wlist_add ((WL *)&signals [w->signum - 1].head, (WL)w);
757
758 if (!w->next)
759 {
760 struct sigaction sa;
761 sa.sa_handler = sighandler;
762 sigfillset (&sa.sa_mask);
763 sa.sa_flags = 0;
764 sigaction (w->signum, &sa, 0);
765 }
766 }
767
768 void
769 evsignal_stop (struct ev_signal *w)
770 {
771 ev_clear ((W)w);
772 if (!ev_is_active (w))
773 return;
774
775 wlist_del ((WL *)&signals [w->signum - 1].head, (WL)w);
776 ev_stop ((W)w);
777
778 if (!signals [w->signum - 1].head)
779 signal (w->signum, SIG_DFL);
780 }
781
782 void evidle_start (struct ev_idle *w)
783 {
784 if (ev_is_active (w))
785 return;
786
787 ev_start ((W)w, ++idlecnt);
788 array_needsize (idles, idlemax, idlecnt, );
789 idles [idlecnt - 1] = w;
790 }
791
792 void evidle_stop (struct ev_idle *w)
793 {
794 ev_clear ((W)w);
795 if (ev_is_active (w))
796 return;
797
798 idles [w->active - 1] = idles [--idlecnt];
799 ev_stop ((W)w);
800 }
801
802 void evcheck_start (struct ev_check *w)
803 {
804 if (ev_is_active (w))
805 return;
806
807 ev_start ((W)w, ++checkcnt);
808 array_needsize (checks, checkmax, checkcnt, );
809 checks [checkcnt - 1] = w;
810 }
811
812 void evcheck_stop (struct ev_check *w)
813 {
814 ev_clear ((W)w);
815 if (ev_is_active (w))
816 return;
817
818 checks [w->active - 1] = checks [--checkcnt];
819 ev_stop ((W)w);
820 }
821
822 /*****************************************************************************/
823
824 struct ev_once
825 {
826 struct ev_io io;
827 struct ev_timer to;
828 void (*cb)(int revents, void *arg);
829 void *arg;
830 };
831
832 static void
833 once_cb (struct ev_once *once, int revents)
834 {
835 void (*cb)(int revents, void *arg) = once->cb;
836 void *arg = once->arg;
837
838 evio_stop (&once->io);
839 evtimer_stop (&once->to);
840 free (once);
841
842 cb (revents, arg);
843 }
844
845 static void
846 once_cb_io (struct ev_io *w, int revents)
847 {
848 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, io)), revents);
849 }
850
851 static void
852 once_cb_to (struct ev_timer *w, int revents)
853 {
854 once_cb ((struct ev_once *)(((char *)w) - offsetof (struct ev_once, to)), revents);
855 }
856
857 void
858 ev_once (int fd, int events, ev_tstamp timeout, void (*cb)(int revents, void *arg), void *arg)
859 {
860 struct ev_once *once = malloc (sizeof (struct ev_once));
861
862 if (!once)
863 cb (EV_ERROR, arg);
864 else
865 {
866 once->cb = cb;
867 once->arg = arg;
868
869 evw_init (&once->io, once_cb_io);
870
871 if (fd >= 0)
872 {
873 evio_set (&once->io, fd, events);
874 evio_start (&once->io);
875 }
876
877 evw_init (&once->to, once_cb_to);
878
879 if (timeout >= 0.)
880 {
881 evtimer_set (&once->to, timeout, 0.);
882 evtimer_start (&once->to);
883 }
884 }
885 }
886
887 /*****************************************************************************/
888
889 #if 0
890
891 struct ev_io wio;
892
893 static void
894 sin_cb (struct ev_io *w, int revents)
895 {
896 fprintf (stderr, "sin %d, revents %d\n", w->fd, revents);
897 }
898
899 static void
900 ocb (struct ev_timer *w, int revents)
901 {
902 //fprintf (stderr, "timer %f,%f (%x) (%f) d%p\n", w->at, w->repeat, revents, w->at - ev_time (), w->data);
903 evtimer_stop (w);
904 evtimer_start (w);
905 }
906
907 static void
908 scb (struct ev_signal *w, int revents)
909 {
910 fprintf (stderr, "signal %x,%d\n", revents, w->signum);
911 evio_stop (&wio);
912 evio_start (&wio);
913 }
914
915 static void
916 gcb (struct ev_signal *w, int revents)
917 {
918 fprintf (stderr, "generic %x\n", revents);
919
920 }
921
922 int main (void)
923 {
924 ev_init (0);
925
926 evio_init (&wio, sin_cb, 0, EV_READ);
927 evio_start (&wio);
928
929 struct ev_timer t[10000];
930
931 #if 0
932 int i;
933 for (i = 0; i < 10000; ++i)
934 {
935 struct ev_timer *w = t + i;
936 evw_init (w, ocb, i);
937 evtimer_init_abs (w, ocb, drand48 (), 0.99775533);
938 evtimer_start (w);
939 if (drand48 () < 0.5)
940 evtimer_stop (w);
941 }
942 #endif
943
944 struct ev_timer t1;
945 evtimer_init (&t1, ocb, 5, 10);
946 evtimer_start (&t1);
947
948 struct ev_signal sig;
949 evsignal_init (&sig, scb, SIGQUIT);
950 evsignal_start (&sig);
951
952 struct ev_check cw;
953 evcheck_init (&cw, gcb);
954 evcheck_start (&cw);
955
956 struct ev_idle iw;
957 evidle_init (&iw, gcb);
958 evidle_start (&iw);
959
960 ev_loop (0);
961
962 return 0;
963 }
964
965 #endif
966
967
968
969