1 /*
2  * Copyright (c) 2000-2004 Niels Provos <provos@citi.umich.edu>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 #ifdef HAVE_CONFIG_H
28 #include "config.h"
29 #endif
30 
31 #ifdef WIN32
32 #define WIN32_LEAN_AND_MEAN
33 #include <windows.h>
34 #undef WIN32_LEAN_AND_MEAN
35 #endif
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_TIME_H
38 #include <sys/time.h>
39 #else
40 #include <sys/_libevent_time.h>
41 #endif
42 #include <sys/queue.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #ifndef WIN32
46 #include <unistd.h>
47 #endif
48 #include <errno.h>
49 #include <signal.h>
50 #include <string.h>
51 #include <assert.h>
52 #include <time.h>
53 
54 #include "event.h"
55 #include "event-internal.h"
56 #include "evutil.h"
57 #include "log.h"
58 
59 #ifdef HAVE_EVENT_PORTS
60 extern const struct eventop evportops;
61 #endif
62 #ifdef HAVE_SELECT
63 extern const struct eventop selectops;
64 #endif
65 #ifdef HAVE_POLL
66 extern const struct eventop pollops;
67 #endif
68 #ifdef HAVE_EPOLL
69 extern const struct eventop epollops;
70 #endif
71 #ifdef HAVE_WORKING_KQUEUE
72 extern const struct eventop kqops;
73 #endif
74 #ifdef HAVE_DEVPOLL
75 extern const struct eventop devpollops;
76 #endif
77 #ifdef WIN32
78 extern const struct eventop win32ops;
79 #endif
80 
81 /* In order of preference */
82 static const struct eventop *eventops[] = {
83 #ifdef HAVE_EVENT_PORTS
84 	&evportops,
85 #endif
86 #ifdef HAVE_WORKING_KQUEUE
87 	&kqops,
88 #endif
89 #ifdef HAVE_EPOLL
90 	&epollops,
91 #endif
92 #ifdef HAVE_DEVPOLL
93 	&devpollops,
94 #endif
95 #ifdef HAVE_POLL
96 	&pollops,
97 #endif
98 #ifdef HAVE_SELECT
99 	&selectops,
100 #endif
101 #ifdef WIN32
102 	&win32ops,
103 #endif
104 	NULL
105 };
106 
107 /* Global state */
108 struct event_base *current_base = NULL;
109 extern struct event_base *evsignal_base;
110 static int use_monotonic = 1;
111 
112 /* Prototypes */
113 static void	event_queue_insert(struct event_base *, struct event *, int);
114 static void	event_queue_remove(struct event_base *, struct event *, int);
115 static int	event_haveevents(struct event_base *);
116 
117 static void	event_process_active(struct event_base *);
118 
119 static int	timeout_next(struct event_base *, struct timeval **);
120 static void	timeout_process(struct event_base *);
121 static void	timeout_correct(struct event_base *, struct timeval *);
122 
123 static int
gettime(struct event_base * base,struct timeval * tp)124 gettime(struct event_base *base, struct timeval *tp)
125 {
126 	if (base->tv_cache.tv_sec) {
127 		*tp = base->tv_cache;
128 		return (0);
129 	}
130 
131 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
132 	struct timespec	ts;
133 
134 	if (use_monotonic &&
135 	    clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
136 		tp->tv_sec = ts.tv_sec;
137 		tp->tv_usec = ts.tv_nsec / 1000;
138 		return (0);
139 	}
140 #endif
141 
142 	use_monotonic = 0;
143 
144 	return (evutil_gettimeofday(tp, NULL));
145 }
146 
147 struct event_base *
event_init(void)148 event_init(void)
149 {
150 	struct event_base *base = event_base_new();
151 
152 	if (base != NULL)
153 		current_base = base;
154 
155 	return (base);
156 }
157 
158 struct event_base *
event_base_new(void)159 event_base_new(void)
160 {
161 	int i;
162 	struct event_base *base;
163 
164 	if ((base = calloc(1, sizeof(struct event_base))) == NULL)
165 		event_err(1, "%s: calloc", __func__);
166 
167 	gettime(base, &base->event_tv);
168 
169 	base->is_precise = 0;
170 
171 	min_heap_ctor(&base->timeheap);
172 	TAILQ_INIT(&base->eventqueue);
173 	base->sig.ev_signal_pair[0] = -1;
174 	base->sig.ev_signal_pair[1] = -1;
175 
176 	base->evbase = NULL;
177 	for (i = 0; eventops[i] && !base->evbase; i++) {
178 		base->evsel = eventops[i];
179 
180 		base->evbase = base->evsel->init(base);
181 	}
182 
183 	if (base->evbase == NULL)
184 		event_errx(1, "%s: no event mechanism available", __func__);
185 
186 	if (evutil_getenv("EVENT_SHOW_METHOD"))
187 		event_msgx("libevent using: %s\n",
188 			   base->evsel->name);
189 
190 	/* allocate a single active event queue */
191 	event_base_priority_init(base, 1);
192 
193 	return (base);
194 }
195 
196 void
event_base_free(struct event_base * base)197 event_base_free(struct event_base *base)
198 {
199 	int i, n_deleted=0;
200 	struct event *ev;
201 
202 	if (base == NULL && current_base)
203 		base = current_base;
204 	if (base == current_base)
205 		current_base = NULL;
206 
207 	/* XXX(niels) - check for internal events first */
208 	assert(base);
209 	/* Delete all non-internal events. */
210 	for (ev = TAILQ_FIRST(&base->eventqueue); ev; ) {
211 		struct event *next = TAILQ_NEXT(ev, ev_next);
212 		if (!(ev->ev_flags & EVLIST_INTERNAL)) {
213 			event_del(ev);
214 			++n_deleted;
215 		}
216 		ev = next;
217 	}
218 	while ((ev = min_heap_top(&base->timeheap)) != NULL) {
219 		event_del(ev);
220 		++n_deleted;
221 	}
222 
223 	for (i = 0; i < base->nactivequeues; ++i) {
224 		for (ev = TAILQ_FIRST(base->activequeues[i]); ev; ) {
225 			struct event *next = TAILQ_NEXT(ev, ev_active_next);
226 			if (!(ev->ev_flags & EVLIST_INTERNAL)) {
227 				event_del(ev);
228 				++n_deleted;
229 			}
230 			ev = next;
231 		}
232 	}
233 
234 	if (n_deleted)
235 		event_debug(("%s: %d events were still set in base",
236 			__func__, n_deleted));
237 
238 	if (base->evsel->dealloc != NULL)
239 		base->evsel->dealloc(base, base->evbase);
240 
241 	for (i = 0; i < base->nactivequeues; ++i)
242 		assert(TAILQ_EMPTY(base->activequeues[i]));
243 
244 	assert(min_heap_empty(&base->timeheap));
245 	min_heap_dtor(&base->timeheap);
246 
247 	for (i = 0; i < base->nactivequeues; ++i)
248 		free(base->activequeues[i]);
249 	free(base->activequeues);
250 
251 	assert(TAILQ_EMPTY(&base->eventqueue));
252 
253 	free(base);
254 }
255 
256 /* reinitialized the event base after a fork */
257 int
event_reinit(struct event_base * base)258 event_reinit(struct event_base *base)
259 {
260 	const struct eventop *evsel = base->evsel;
261 	void *evbase = base->evbase;
262 	int res = 0;
263 	struct event *ev;
264 
265 #if 0
266 	/* Right now, reinit always takes effect, since even if the
267 	   backend doesn't require it, the signal socketpair code does.
268 	 */
269 	/* check if this event mechanism requires reinit */
270 	if (!evsel->need_reinit)
271 		return (0);
272 #endif
273 
274 	/* prevent internal delete */
275 	if (base->sig.ev_signal_added) {
276 		/* we cannot call event_del here because the base has
277 		 * not been reinitialized yet. */
278 		event_queue_remove(base, &base->sig.ev_signal,
279 		    EVLIST_INSERTED);
280 		if (base->sig.ev_signal.ev_flags & EVLIST_ACTIVE)
281 			event_queue_remove(base, &base->sig.ev_signal,
282 			    EVLIST_ACTIVE);
283 		base->sig.ev_signal_added = 0;
284 	}
285 
286 	if (base->evsel->dealloc != NULL)
287 		base->evsel->dealloc(base, base->evbase);
288 	evbase = base->evbase = evsel->init(base);
289 	if (base->evbase == NULL)
290 		event_errx(1, "%s: could not reinitialize event mechanism",
291 		    __func__);
292 
293 	TAILQ_FOREACH(ev, &base->eventqueue, ev_next) {
294 		if (evsel->add(evbase, ev) == -1)
295 			res = -1;
296 	}
297 
298 	return (res);
299 }
300 
301 int
event_priority_init(int npriorities)302 event_priority_init(int npriorities)
303 {
304   return event_base_priority_init(current_base, npriorities);
305 }
306 
307 int
event_base_priority_init(struct event_base * base,int npriorities)308 event_base_priority_init(struct event_base *base, int npriorities)
309 {
310 	int i;
311 
312 	if (base->event_count_active)
313 		return (-1);
314 
315 	if (npriorities == base->nactivequeues)
316 		return (0);
317 
318 	if (base->nactivequeues) {
319 		for (i = 0; i < base->nactivequeues; ++i) {
320 			free(base->activequeues[i]);
321 		}
322 		free(base->activequeues);
323 	}
324 
325 	/* Allocate our priority queues */
326 	base->nactivequeues = npriorities;
327 	base->activequeues = (struct event_list **)
328 	    calloc(base->nactivequeues, sizeof(struct event_list *));
329 	if (base->activequeues == NULL)
330 		event_err(1, "%s: calloc", __func__);
331 
332 	for (i = 0; i < base->nactivequeues; ++i) {
333 		base->activequeues[i] = malloc(sizeof(struct event_list));
334 		if (base->activequeues[i] == NULL)
335 			event_err(1, "%s: malloc", __func__);
336 		TAILQ_INIT(base->activequeues[i]);
337 	}
338 
339 	return (0);
340 }
341 
342 int
event_haveevents(struct event_base * base)343 event_haveevents(struct event_base *base)
344 {
345 	return (base->event_count > 0);
346 }
347 
348 /*
349  * Active events are stored in priority queues.  Lower priorities are always
350  * process before higher priorities.  Low priority events can starve high
351  * priority ones.
352  */
353 
354 static void
event_process_active(struct event_base * base)355 event_process_active(struct event_base *base)
356 {
357 	struct event *ev;
358 	struct event_list *activeq = NULL;
359 	int i;
360 	short ncalls;
361 
362 	for (i = 0; i < base->nactivequeues; ++i) {
363 		if (TAILQ_FIRST(base->activequeues[i]) != NULL) {
364 			activeq = base->activequeues[i];
365 			break;
366 		}
367 	}
368 
369 	assert(activeq != NULL);
370 
371 	for (ev = TAILQ_FIRST(activeq); ev; ev = TAILQ_FIRST(activeq)) {
372 		if (ev->ev_events & EV_PERSIST)
373 			event_queue_remove(base, ev, EVLIST_ACTIVE);
374 		else
375 			event_del(ev);
376 
377 		/* Allows deletes to work */
378 		ncalls = ev->ev_ncalls;
379 		ev->ev_pncalls = &ncalls;
380 		while (ncalls) {
381 			ncalls--;
382 			ev->ev_ncalls = ncalls;
383 			(*ev->ev_callback)((int)ev->ev_fd, ev->ev_res, ev->ev_arg);
384 			if (base->event_break)
385 				return;
386 		}
387 	}
388 }
389 
390 /*
391  * Wait continously for events.  We exit only if no events are left.
392  */
393 
394 int
event_dispatch(void)395 event_dispatch(void)
396 {
397 	return (event_loop(0));
398 }
399 
400 int
event_base_dispatch(struct event_base * event_base)401 event_base_dispatch(struct event_base *event_base)
402 {
403   return (event_base_loop(event_base, 0));
404 }
405 
406 const char *
event_base_get_method(struct event_base * base)407 event_base_get_method(struct event_base *base)
408 {
409 	assert(base);
410 	return (base->evsel->name);
411 }
412 
413 static void
event_loopexit_cb(int fd,short what,void * arg)414 event_loopexit_cb(int fd, short what, void *arg)
415 {
416 	struct event_base *base = arg;
417 	base->event_gotterm = 1;
418 }
419 
420 /* not thread safe */
421 int
event_loopexit(const struct timeval * tv)422 event_loopexit(const struct timeval *tv)
423 {
424 	return (event_once(-1, EV_TIMEOUT, event_loopexit_cb,
425 		    current_base, tv));
426 }
427 
428 int
event_base_loopexit(struct event_base * event_base,const struct timeval * tv)429 event_base_loopexit(struct event_base *event_base, const struct timeval *tv)
430 {
431 	return (event_base_once(event_base, -1, EV_TIMEOUT, event_loopexit_cb,
432 		    event_base, tv));
433 }
434 
435 /* not thread safe */
436 int
event_loopbreak(void)437 event_loopbreak(void)
438 {
439 	return (event_base_loopbreak(current_base));
440 }
441 
442 int
event_base_loopbreak(struct event_base * event_base)443 event_base_loopbreak(struct event_base *event_base)
444 {
445 	if (event_base == NULL)
446 		return (-1);
447 
448 	event_base->event_break = 1;
449 	return (0);
450 }
451 
452 
453 
454 /* not thread safe */
455 
456 int
event_loop(int flags)457 event_loop(int flags)
458 {
459 	return event_base_loop(current_base, flags);
460 }
461 
462 int
event_base_loop(struct event_base * base,int flags)463 event_base_loop(struct event_base *base, int flags)
464 {
465 	const struct eventop *evsel = base->evsel;
466 	void *evbase = base->evbase;
467 	struct timeval tv;
468 	struct timeval *tv_p;
469 	int res, done;
470 
471 	/* clear time cache */
472 	base->tv_cache.tv_sec = 0;
473 
474 	if (base->sig.ev_signal_added)
475 		evsignal_base = base;
476 	done = 0;
477 	while (!done) {
478 		/* Terminate the loop if we have been asked to */
479 		if (base->event_gotterm) {
480 			base->event_gotterm = 0;
481 			break;
482 		}
483 
484 		if (base->event_break) {
485 			base->event_break = 0;
486 			break;
487 		}
488 
489 		timeout_correct(base, &tv);
490 
491 		tv_p = &tv;
492 		if (!base->event_count_active && !(flags & EVLOOP_NONBLOCK)) {
493 			timeout_next(base, &tv_p);
494 		} else {
495 			/*
496 			 * if we have active events, we just poll new events
497 			 * without waiting.
498 			 */
499 			evutil_timerclear(&tv);
500 		}
501 
502 		/* If we have no events, we just exit */
503 		if (!event_haveevents(base)) {
504 			event_debug(("%s: no events registered.", __func__));
505 			return (1);
506 		}
507 
508 		/* update last old time */
509 		gettime(base, &base->event_tv);
510 
511 		/* clear time cache */
512 		base->tv_cache.tv_sec = 0;
513 
514 		if (flags & EVLOOP_PRECISE)
515 			base->is_precise = 1;
516 		res = evsel->dispatch(base, evbase, tv_p);
517 		if (flags & EVLOOP_PRECISE)
518 			base->is_precise = 0;
519 
520 		if (res == -1)
521 			return (-1);
522 		gettime(base, &base->tv_cache);
523 
524 		timeout_process(base);
525 
526 		if (base->event_count_active) {
527 			event_process_active(base);
528 			if (!base->event_count_active && (flags & EVLOOP_ONCE))
529 				done = 1;
530 		} else if (flags & EVLOOP_NONBLOCK)
531 			done = 1;
532 	}
533 
534 	/* clear time cache */
535 	base->tv_cache.tv_sec = 0;
536 
537 	event_debug(("%s: asked to terminate loop.", __func__));
538 	return (0);
539 }
540 
541 /* Sets up an event for processing once */
542 
543 struct event_once {
544 	struct event ev;
545 
546 	void (*cb)(int, short, void *);
547 	void *arg;
548 };
549 
550 /* One-time callback, it deletes itself */
551 
552 static void
event_once_cb(int fd,short events,void * arg)553 event_once_cb(int fd, short events, void *arg)
554 {
555 	struct event_once *eonce = arg;
556 
557 	(*eonce->cb)(fd, events, eonce->arg);
558 	free(eonce);
559 }
560 
561 /* not threadsafe, event scheduled once. */
562 int
event_once(int fd,short events,void (* callback)(int,short,void *),void * arg,const struct timeval * tv)563 event_once(int fd, short events,
564     void (*callback)(int, short, void *), void *arg, const struct timeval *tv)
565 {
566 	return event_base_once(current_base, fd, events, callback, arg, tv);
567 }
568 
569 /* Schedules an event once */
570 int
event_base_once(struct event_base * base,int fd,short events,void (* callback)(int,short,void *),void * arg,const struct timeval * tv)571 event_base_once(struct event_base *base, int fd, short events,
572     void (*callback)(int, short, void *), void *arg, const struct timeval *tv)
573 {
574 	struct event_once *eonce;
575 	struct timeval etv;
576 	int res;
577 
578 	/* We cannot support signals that just fire once */
579 	if (events & EV_SIGNAL)
580 		return (-1);
581 
582 	if ((eonce = calloc(1, sizeof(struct event_once))) == NULL)
583 		return (-1);
584 
585 	eonce->cb = callback;
586 	eonce->arg = arg;
587 
588 	if (events == EV_TIMEOUT) {
589 		if (tv == NULL) {
590 			evutil_timerclear(&etv);
591 			tv = &etv;
592 		}
593 
594 		evtimer_set(&eonce->ev, event_once_cb, eonce);
595 	} else if (events & (EV_READ|EV_WRITE)) {
596 		events &= EV_READ|EV_WRITE;
597 
598 		event_set(&eonce->ev, fd, events, event_once_cb, eonce);
599 	} else {
600 		/* Bad event combination */
601 		free(eonce);
602 		return (-1);
603 	}
604 
605 	res = event_base_set(base, &eonce->ev);
606 	if (res == 0)
607 		res = event_add(&eonce->ev, tv);
608 	if (res != 0) {
609 		free(eonce);
610 		return (res);
611 	}
612 
613 	return (0);
614 }
615 
616 void
event_set(struct event * ev,int fd,short events,void (* callback)(int,short,void *),void * arg)617 event_set(struct event *ev, int fd, short events,
618 	  void (*callback)(int, short, void *), void *arg)
619 {
620 	/* Take the current base - caller needs to set the real base later */
621 	ev->ev_base = current_base;
622 
623 	ev->ev_callback = callback;
624 	ev->ev_arg = arg;
625 	ev->ev_fd = fd;
626 	ev->ev_events = events;
627 	ev->ev_res = 0;
628 	ev->ev_flags = EVLIST_INIT;
629 	ev->ev_ncalls = 0;
630 	ev->ev_pncalls = NULL;
631 
632 	min_heap_elem_init(ev);
633 
634 	/* by default, we put new events into the middle priority */
635 	if(current_base)
636 		ev->ev_pri = current_base->nactivequeues/2;
637 }
638 
639 int
event_base_set(struct event_base * base,struct event * ev)640 event_base_set(struct event_base *base, struct event *ev)
641 {
642 	/* Only innocent events may be assigned to a different base */
643 	if (ev->ev_flags != EVLIST_INIT)
644 		return (-1);
645 
646 	ev->ev_base = base;
647 	ev->ev_pri = base->nactivequeues/2;
648 
649 	return (0);
650 }
651 
652 /*
653  * Set's the priority of an event - if an event is already scheduled
654  * changing the priority is going to fail.
655  */
656 
657 int
event_priority_set(struct event * ev,int pri)658 event_priority_set(struct event *ev, int pri)
659 {
660 	if (ev->ev_flags & EVLIST_ACTIVE)
661 		return (-1);
662 	if (pri < 0 || pri >= ev->ev_base->nactivequeues)
663 		return (-1);
664 
665 	ev->ev_pri = pri;
666 
667 	return (0);
668 }
669 
670 /*
671  * Checks if a specific event is pending or scheduled.
672  */
673 
674 int
event_pending(struct event * ev,short event,struct timeval * tv)675 event_pending(struct event *ev, short event, struct timeval *tv)
676 {
677 	struct timeval	now, res;
678 	int flags = 0;
679 
680 	if (ev->ev_flags & EVLIST_INSERTED)
681 		flags |= (ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL));
682 	if (ev->ev_flags & EVLIST_ACTIVE)
683 		flags |= ev->ev_res;
684 	if (ev->ev_flags & EVLIST_TIMEOUT)
685 		flags |= EV_TIMEOUT;
686 
687 	event &= (EV_TIMEOUT|EV_READ|EV_WRITE|EV_SIGNAL);
688 
689 	/* See if there is a timeout that we should report */
690 	if (tv != NULL && (flags & event & EV_TIMEOUT)) {
691 		gettime(ev->ev_base, &now);
692 		evutil_timersub(&ev->ev_timeout, &now, &res);
693 		/* correctly remap to real time */
694 		evutil_gettimeofday(&now, NULL);
695 		evutil_timeradd(&now, &res, tv);
696 	}
697 
698 	return (flags & event);
699 }
700 
701 int
event_add(struct event * ev,const struct timeval * tv)702 event_add(struct event *ev, const struct timeval *tv)
703 {
704 	struct event_base *base = ev->ev_base;
705 	const struct eventop *evsel = base->evsel;
706 	void *evbase = base->evbase;
707 	int res = 0;
708 
709 	event_debug((
710 		 "event_add: event: %p, %s%s%scall %p",
711 		 ev,
712 		 ev->ev_events & EV_READ ? "EV_READ " : " ",
713 		 ev->ev_events & EV_WRITE ? "EV_WRITE " : " ",
714 		 tv ? "EV_TIMEOUT " : " ",
715 		 ev->ev_callback));
716 
717 	assert(!(ev->ev_flags & ~EVLIST_ALL));
718 
719 	/*
720 	 * prepare for timeout insertion further below, if we get a
721 	 * failure on any step, we should not change any state.
722 	 */
723 	if (tv != NULL && !(ev->ev_flags & EVLIST_TIMEOUT)) {
724 		if (min_heap_reserve(&base->timeheap,
725 			1 + min_heap_size(&base->timeheap)) == -1)
726 			return (-1);  /* ENOMEM == errno */
727 	}
728 
729 	if ((ev->ev_events & (EV_READ|EV_WRITE|EV_SIGNAL)) &&
730 	    !(ev->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE))) {
731 		res = evsel->add(evbase, ev);
732 		if (res != -1)
733 			event_queue_insert(base, ev, EVLIST_INSERTED);
734 	}
735 
736 	/*
737 	 * we should change the timout state only if the previous event
738 	 * addition succeeded.
739 	 */
740 	if (res != -1 && tv != NULL) {
741 		struct timeval now;
742 
743 		/*
744 		 * we already reserved memory above for the case where we
745 		 * are not replacing an exisiting timeout.
746 		 */
747 		if (ev->ev_flags & EVLIST_TIMEOUT)
748 			event_queue_remove(base, ev, EVLIST_TIMEOUT);
749 
750 		/* Check if it is active due to a timeout.  Rescheduling
751 		 * this timeout before the callback can be executed
752 		 * removes it from the active list. */
753 		if ((ev->ev_flags & EVLIST_ACTIVE) &&
754 		    (ev->ev_res & EV_TIMEOUT)) {
755 			/* See if we are just active executing this
756 			 * event in a loop
757 			 */
758 			if (ev->ev_ncalls && ev->ev_pncalls) {
759 				/* Abort loop */
760 				*ev->ev_pncalls = 0;
761 			}
762 
763 			event_queue_remove(base, ev, EVLIST_ACTIVE);
764 		}
765 
766 		gettime(base, &now);
767 		evutil_timeradd(&now, tv, &ev->ev_timeout);
768 
769 		event_debug((
770 			 "event_add: timeout in %ld seconds, call %p",
771 			 tv->tv_sec, ev->ev_callback));
772 
773 		event_queue_insert(base, ev, EVLIST_TIMEOUT);
774 	}
775 
776 	return (res);
777 }
778 
779 int
event_del(struct event * ev)780 event_del(struct event *ev)
781 {
782 	struct event_base *base;
783 
784 	event_debug(("event_del: %p, callback %p",
785 		 ev, ev->ev_callback));
786 
787 	/* An event without a base has not been added */
788 	if (ev->ev_base == NULL)
789 		return (-1);
790 
791 	base = ev->ev_base;
792 
793 	assert(!(ev->ev_flags & ~EVLIST_ALL));
794 
795 	/* See if we are just active executing this event in a loop */
796 	if (ev->ev_ncalls && ev->ev_pncalls) {
797 		/* Abort loop */
798 		*ev->ev_pncalls = 0;
799 	}
800 
801 	if (ev->ev_flags & EVLIST_TIMEOUT)
802 		event_queue_remove(base, ev, EVLIST_TIMEOUT);
803 
804 	if (ev->ev_flags & EVLIST_ACTIVE)
805 		event_queue_remove(base, ev, EVLIST_ACTIVE);
806 
807 	if (ev->ev_flags & EVLIST_INSERTED) {
808 		event_queue_remove(base, ev, EVLIST_INSERTED);
809 		return (base->evsel->del(base->evbase, ev));
810 	}
811 
812 	return (0);
813 }
814 
815 void
event_active(struct event * ev,int res,short ncalls)816 event_active(struct event *ev, int res, short ncalls)
817 {
818 	/* We get different kinds of events, add them together */
819 	if (ev->ev_flags & EVLIST_ACTIVE) {
820 		ev->ev_res |= res;
821 		return;
822 	}
823 
824 	ev->ev_res = res;
825 	ev->ev_ncalls = ncalls;
826 	ev->ev_pncalls = NULL;
827 	event_queue_insert(ev->ev_base, ev, EVLIST_ACTIVE);
828 }
829 
830 static int
timeout_next(struct event_base * base,struct timeval ** tv_p)831 timeout_next(struct event_base *base, struct timeval **tv_p)
832 {
833 	struct timeval now;
834 	struct event *ev;
835 	struct timeval *tv = *tv_p;
836 
837 	if ((ev = min_heap_top(&base->timeheap)) == NULL) {
838 		/* if no time-based events are active wait for I/O */
839 		*tv_p = NULL;
840 		return (0);
841 	}
842 
843 	if (gettime(base, &now) == -1)
844 		return (-1);
845 
846 	if (evutil_timercmp(&ev->ev_timeout, &now, <=)) {
847 		evutil_timerclear(tv);
848 		return (0);
849 	}
850 
851 	evutil_timersub(&ev->ev_timeout, &now, tv);
852 
853 	assert(tv->tv_sec >= 0);
854 	assert(tv->tv_usec >= 0);
855 
856 	event_debug(("timeout_next: in %ld seconds", tv->tv_sec));
857 	return (0);
858 }
859 
860 /*
861  * Determines if the time is running backwards by comparing the current
862  * time against the last time we checked.  Not needed when using clock
863  * monotonic.
864  */
865 
866 static void
timeout_correct(struct event_base * base,struct timeval * tv)867 timeout_correct(struct event_base *base, struct timeval *tv)
868 {
869 	struct event **pev;
870 	unsigned int size;
871 	struct timeval off;
872 
873 	if (use_monotonic)
874 		return;
875 
876 	/* Check if time is running backwards */
877 	gettime(base, tv);
878 	if (evutil_timercmp(tv, &base->event_tv, >=)) {
879 		base->event_tv = *tv;
880 		return;
881 	}
882 
883 	event_debug(("%s: time is running backwards, corrected",
884 		    __func__));
885 	evutil_timersub(&base->event_tv, tv, &off);
886 
887 	/*
888 	 * We can modify the key element of the node without destroying
889 	 * the key, beause we apply it to all in the right order.
890 	 */
891 	pev = base->timeheap.p;
892 	size = base->timeheap.n;
893 	for (; size-- > 0; ++pev) {
894 		struct timeval *ev_tv = &(**pev).ev_timeout;
895 		evutil_timersub(ev_tv, &off, ev_tv);
896 	}
897 	/* Now remember what the new time turned out to be. */
898 	base->event_tv = *tv;
899 }
900 
901 void
timeout_process(struct event_base * base)902 timeout_process(struct event_base *base)
903 {
904 	struct timeval now;
905 	struct event *ev;
906 
907 	if (min_heap_empty(&base->timeheap))
908 		return;
909 
910 	gettime(base, &now);
911 
912 	while ((ev = min_heap_top(&base->timeheap))) {
913 		if (evutil_timercmp(&ev->ev_timeout, &now, >))
914 			break;
915 
916 		/* delete this event from the I/O queues */
917 		event_del(ev);
918 
919 		event_debug(("timeout_process: call %p",
920 			 ev->ev_callback));
921 		event_active(ev, EV_TIMEOUT, 1);
922 	}
923 }
924 
925 void
event_queue_remove(struct event_base * base,struct event * ev,int queue)926 event_queue_remove(struct event_base *base, struct event *ev, int queue)
927 {
928 	if (!(ev->ev_flags & queue))
929 		event_errx(1, "%s: %p(fd %d) not on queue %x", __func__,
930 			   ev, ev->ev_fd, queue);
931 
932 	if (~ev->ev_flags & EVLIST_INTERNAL)
933 		base->event_count--;
934 
935 	ev->ev_flags &= ~queue;
936 	switch (queue) {
937 	case EVLIST_INSERTED:
938 		TAILQ_REMOVE(&base->eventqueue, ev, ev_next);
939 		break;
940 	case EVLIST_ACTIVE:
941 		base->event_count_active--;
942 		TAILQ_REMOVE(base->activequeues[ev->ev_pri],
943 		    ev, ev_active_next);
944 		break;
945 	case EVLIST_TIMEOUT:
946 		min_heap_erase(&base->timeheap, ev);
947 		break;
948 	default:
949 		event_errx(1, "%s: unknown queue %x", __func__, queue);
950 	}
951 }
952 
953 void
event_queue_insert(struct event_base * base,struct event * ev,int queue)954 event_queue_insert(struct event_base *base, struct event *ev, int queue)
955 {
956 	if (ev->ev_flags & queue) {
957 		/* Double insertion is possible for active events */
958 		if (queue & EVLIST_ACTIVE)
959 			return;
960 
961 		event_errx(1, "%s: %p(fd %d) already on queue %x", __func__,
962 			   ev, ev->ev_fd, queue);
963 	}
964 
965 	if (~ev->ev_flags & EVLIST_INTERNAL)
966 		base->event_count++;
967 
968 	ev->ev_flags |= queue;
969 	switch (queue) {
970 	case EVLIST_INSERTED:
971 		TAILQ_INSERT_TAIL(&base->eventqueue, ev, ev_next);
972 		break;
973 	case EVLIST_ACTIVE:
974 		base->event_count_active++;
975 		TAILQ_INSERT_TAIL(base->activequeues[ev->ev_pri],
976 		    ev,ev_active_next);
977 		break;
978 	case EVLIST_TIMEOUT: {
979 		min_heap_push(&base->timeheap, ev);
980 		break;
981 	}
982 	default:
983 		event_errx(1, "%s: unknown queue %x", __func__, queue);
984 	}
985 }
986 
987 /* Functions for debugging */
988 
989 const char *
event_get_version(void)990 event_get_version(void)
991 {
992 	return (VERSION);
993 }
994 
995 /*
996  * No thread-safe interface needed - the information should be the same
997  * for all threads.
998  */
999 
1000 const char *
event_get_method(void)1001 event_get_method(void)
1002 {
1003 	return (current_base->evsel->name);
1004 }
1005