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