xref: /libevent-2.1.12/event.c (revision 2e9ceb16)
1aa6567feSNiels Provos /*
2b85b710cSNick Mathewson  * Copyright (c) 2000-2007 Niels Provos <[email protected]>
3e49e2891SNick Mathewson  * Copyright (c) 2007-2012 Niels Provos and Nick Mathewson
4aa6567feSNiels Provos  *
5aa6567feSNiels Provos  * Redistribution and use in source and binary forms, with or without
6aa6567feSNiels Provos  * modification, are permitted provided that the following conditions
7aa6567feSNiels Provos  * are met:
8aa6567feSNiels Provos  * 1. Redistributions of source code must retain the above copyright
9aa6567feSNiels Provos  *    notice, this list of conditions and the following disclaimer.
10aa6567feSNiels Provos  * 2. Redistributions in binary form must reproduce the above copyright
11aa6567feSNiels Provos  *    notice, this list of conditions and the following disclaimer in the
12aa6567feSNiels Provos  *    documentation and/or other materials provided with the distribution.
13c3f496c7SNiels Provos  * 3. The name of the author may not be used to endorse or promote products
14aa6567feSNiels Provos  *    derived from this software without specific prior written permission.
15aa6567feSNiels Provos  *
16aa6567feSNiels Provos  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17aa6567feSNiels Provos  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18aa6567feSNiels Provos  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19aa6567feSNiels Provos  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20aa6567feSNiels Provos  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21aa6567feSNiels Provos  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22aa6567feSNiels Provos  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23aa6567feSNiels Provos  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24aa6567feSNiels Provos  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25aa6567feSNiels Provos  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26aa6567feSNiels Provos  */
27ec347b92SNick Mathewson #include "event2/event-config.h"
280915ca0aSKevin Bowling #include "evconfig-private.h"
29aa6567feSNiels Provos 
309f560bfaSNick Mathewson #ifdef _WIN32
3103fafae0SNick Mathewson #include <winsock2.h>
326ce5b876SNiels Provos #define WIN32_LEAN_AND_MEAN
336ce5b876SNiels Provos #include <windows.h>
346ce5b876SNiels Provos #undef WIN32_LEAN_AND_MEAN
356ce5b876SNiels Provos #endif
36aa6567feSNiels Provos #include <sys/types.h>
3768120d9bSNick Mathewson #if !defined(_WIN32) && defined(EVENT__HAVE_SYS_TIME_H)
38aa6567feSNiels Provos #include <sys/time.h>
3990ddd91fSNiels Provos #endif
40aa6567feSNiels Provos #include <sys/queue.h>
4168120d9bSNick Mathewson #ifdef EVENT__HAVE_SYS_SOCKET_H
42558de9b3SNiels Provos #include <sys/socket.h>
43558de9b3SNiels Provos #endif
44aa6567feSNiels Provos #include <stdio.h>
45aa6567feSNiels Provos #include <stdlib.h>
4668120d9bSNick Mathewson #ifdef EVENT__HAVE_UNISTD_H
47aa6567feSNiels Provos #include <unistd.h>
486ce5b876SNiels Provos #endif
492deb3ce0SNiels Provos #include <ctype.h>
50aa6567feSNiels Provos #include <errno.h>
517517ef2aSNiels Provos #include <signal.h>
52aa6567feSNiels Provos #include <string.h>
533ad6b47eSNiels Provos #include <time.h>
54fd4de1e7SNick Mathewson #include <limits.h>
55a39898f3SAzat Khuzhin #ifdef EVENT__HAVE_FCNTL_H
56a39898f3SAzat Khuzhin #include <fcntl.h>
57a39898f3SAzat Khuzhin #endif
58aa6567feSNiels Provos 
590ac73078SNick Mathewson #include "event2/event.h"
600ac73078SNick Mathewson #include "event2/event_struct.h"
610ac73078SNick Mathewson #include "event2/event_compat.h"
628773c4c9SNiels Provos #include "event-internal.h"
634868f4d2SNick Mathewson #include "defer-internal.h"
64558de9b3SNiels Provos #include "evthread-internal.h"
65558de9b3SNiels Provos #include "event2/thread.h"
660ac73078SNick Mathewson #include "event2/util.h"
67169321c9SNick Mathewson #include "log-internal.h"
68169321c9SNick Mathewson #include "evmap-internal.h"
69879420a7SNick Mathewson #include "iocp-internal.h"
7027308aaeSNick Mathewson #include "changelist-internal.h"
7146e5bb7bSNick Mathewson #define HT_NO_CACHE_HASH_VALUES
72cd17c3acSNick Mathewson #include "ht-internal.h"
7342a8c711SNick Mathewson #include "util-internal.h"
74aa6567feSNiels Provos 
7553a07fe2SNick Mathewson 
7653a07fe2SNick Mathewson #ifdef EVENT__HAVE_WORKING_KQUEUE
7753a07fe2SNick Mathewson #include "kqueue-internal.h"
7853a07fe2SNick Mathewson #endif
7953a07fe2SNick Mathewson 
8068120d9bSNick Mathewson #ifdef EVENT__HAVE_EVENT_PORTS
8100bc7e37SNiels Provos extern const struct eventop evportops;
8200bc7e37SNiels Provos #endif
8368120d9bSNick Mathewson #ifdef EVENT__HAVE_SELECT
84e506eaf7SNiels Provos extern const struct eventop selectops;
85aa6567feSNiels Provos #endif
8668120d9bSNick Mathewson #ifdef EVENT__HAVE_POLL
87e506eaf7SNiels Provos extern const struct eventop pollops;
88e506eaf7SNiels Provos #endif
8968120d9bSNick Mathewson #ifdef EVENT__HAVE_EPOLL
90e506eaf7SNiels Provos extern const struct eventop epollops;
913e41f17aSNiels Provos #endif
9268120d9bSNick Mathewson #ifdef EVENT__HAVE_WORKING_KQUEUE
93e506eaf7SNiels Provos extern const struct eventop kqops;
94aa6567feSNiels Provos #endif
9568120d9bSNick Mathewson #ifdef EVENT__HAVE_DEVPOLL
9606aaa92fSNiels Provos extern const struct eventop devpollops;
9706aaa92fSNiels Provos #endif
989f560bfaSNick Mathewson #ifdef _WIN32
99e506eaf7SNiels Provos extern const struct eventop win32ops;
1006ce5b876SNiels Provos #endif
101aa6567feSNiels Provos 
102cdd4c490SNick Mathewson /* Array of backends in order of preference. */
103808f00e1SNiels Provos static const struct eventop *eventops[] = {
10468120d9bSNick Mathewson #ifdef EVENT__HAVE_EVENT_PORTS
10500bc7e37SNiels Provos 	&evportops,
10600bc7e37SNiels Provos #endif
10768120d9bSNick Mathewson #ifdef EVENT__HAVE_WORKING_KQUEUE
108aa6567feSNiels Provos 	&kqops,
109aa6567feSNiels Provos #endif
11068120d9bSNick Mathewson #ifdef EVENT__HAVE_EPOLL
1113e41f17aSNiels Provos 	&epollops,
1123e41f17aSNiels Provos #endif
11368120d9bSNick Mathewson #ifdef EVENT__HAVE_DEVPOLL
11406aaa92fSNiels Provos 	&devpollops,
11506aaa92fSNiels Provos #endif
11668120d9bSNick Mathewson #ifdef EVENT__HAVE_POLL
117b3d1c6a8SNiels Provos 	&pollops,
118b3d1c6a8SNiels Provos #endif
11968120d9bSNick Mathewson #ifdef EVENT__HAVE_SELECT
120aa6567feSNiels Provos 	&selectops,
121aa6567feSNiels Provos #endif
1229f560bfaSNick Mathewson #ifdef _WIN32
1236ce5b876SNiels Provos 	&win32ops,
1246ce5b876SNiels Provos #endif
125aa6567feSNiels Provos 	NULL
126aa6567feSNiels Provos };
127aa6567feSNiels Provos 
128cdd4c490SNick Mathewson /* Global state; deprecated */
1299806b126SAzat Khuzhin EVENT2_EXPORT_SYMBOL
130c16e6844SNick Mathewson struct event_base *event_global_current_base_ = NULL;
131c16e6844SNick Mathewson #define current_base event_global_current_base_
132cdd4c490SNick Mathewson 
133cdd4c490SNick Mathewson /* Global state */
134c16e6844SNick Mathewson 
135ed36e6abSRoss Lagerwall static void *event_self_cbarg_ptr_ = NULL;
136ed36e6abSRoss Lagerwall 
137aa6567feSNiels Provos /* Prototypes */
138cba59e53SNick Mathewson static void	event_queue_insert_active(struct event_base *, struct event_callback *);
139745a63dbSNick Mathewson static void	event_queue_insert_active_later(struct event_base *, struct event_callback *);
140efc4dc50SNick Mathewson static void	event_queue_insert_timeout(struct event_base *, struct event *);
141efc4dc50SNick Mathewson static void	event_queue_insert_inserted(struct event_base *, struct event *);
142cba59e53SNick Mathewson static void	event_queue_remove_active(struct event_base *, struct event_callback *);
143745a63dbSNick Mathewson static void	event_queue_remove_active_later(struct event_base *, struct event_callback *);
144efc4dc50SNick Mathewson static void	event_queue_remove_timeout(struct event_base *, struct event *);
145efc4dc50SNick Mathewson static void	event_queue_remove_inserted(struct event_base *, struct event *);
146745a63dbSNick Mathewson static void event_queue_make_later_events_active(struct event_base *base);
147745a63dbSNick Mathewson 
1489cd5acb5SNick Mathewson static int evthread_make_base_notifiable_nolock_(struct event_base *base);
1498eedeabeSNick Mathewson static int event_del_(struct event *ev, int blocking);
1509cd5acb5SNick Mathewson 
15109cbc3dcSNick Mathewson #ifdef USE_REINSERT_TIMEOUT
15209cbc3dcSNick Mathewson /* This code seems buggy; only turn it on if we find out what the trouble is. */
1538c36acd0SNick Mathewson static void	event_queue_reinsert_timeout(struct event_base *,struct event *, int was_common, int is_common, int old_timeout_idx);
15409cbc3dcSNick Mathewson #endif
155e47042feSNick Mathewson 
1568773c4c9SNiels Provos static int	event_haveevents(struct event_base *);
157aa6567feSNiels Provos 
1580617a818SNick Mathewson static int	event_process_active(struct event_base *);
159cd699abfSNiels Provos 
1603ad6b47eSNiels Provos static int	timeout_next(struct event_base *, struct timeval **);
1618773c4c9SNiels Provos static void	timeout_process(struct event_base *);
162aa6567feSNiels Provos 
163a2a7d1d1SNick Mathewson static inline void	event_signal_closure(struct event_base *, struct event *ev);
164a2a7d1d1SNick Mathewson static inline void	event_persist_closure(struct event_base *, struct event *ev);
1658c750eafSNiels Provos 
166c3e9fcf6SNick Mathewson static int	evthread_notify_base(struct event_base *base);
167ec4cfa33SNick Mathewson 
168e47042feSNick Mathewson static void insert_common_timeout_inorder(struct common_timeout_list *ctl,
169e47042feSNick Mathewson     struct event *ev);
170e47042feSNick Mathewson 
17168120d9bSNick Mathewson #ifndef EVENT__DISABLE_DEBUG_MODE
172cd17c3acSNick Mathewson /* These functions implement a hashtable of which 'struct event *' structures
173cd17c3acSNick Mathewson  * have been setup or added.  We don't want to trust the content of the struct
174cd17c3acSNick Mathewson  * event itself, since we're trying to work through cases where an event gets
175cd17c3acSNick Mathewson  * clobbered or freed.  Instead, we keep a hashtable indexed by the pointer.
176cd17c3acSNick Mathewson  */
177cd17c3acSNick Mathewson 
178cd17c3acSNick Mathewson struct event_debug_entry {
179cd17c3acSNick Mathewson 	HT_ENTRY(event_debug_entry) node;
180cd17c3acSNick Mathewson 	const struct event *ptr;
181cd17c3acSNick Mathewson 	unsigned added : 1;
182cd17c3acSNick Mathewson };
183cd17c3acSNick Mathewson 
184cd17c3acSNick Mathewson static inline unsigned
hash_debug_entry(const struct event_debug_entry * e)185cd17c3acSNick Mathewson hash_debug_entry(const struct event_debug_entry *e)
186cd17c3acSNick Mathewson {
187137f2c60SNick Mathewson 	/* We need to do this silliness to convince compilers that we
188137f2c60SNick Mathewson 	 * honestly mean to cast e->ptr to an integer, and discard any
189137f2c60SNick Mathewson 	 * part of it that doesn't fit in an unsigned.
190137f2c60SNick Mathewson 	 */
191137f2c60SNick Mathewson 	unsigned u = (unsigned) ((ev_uintptr_t) e->ptr);
192a66e947bSNick Mathewson 	/* Our hashtable implementation is pretty sensitive to low bits,
193a66e947bSNick Mathewson 	 * and every struct event is over 64 bytes in size, so we can
194137f2c60SNick Mathewson 	 * just say >>6. */
195137f2c60SNick Mathewson 	return (u >> 6);
196cd17c3acSNick Mathewson }
197cd17c3acSNick Mathewson 
198cd17c3acSNick Mathewson static inline int
eq_debug_entry(const struct event_debug_entry * a,const struct event_debug_entry * b)199cd17c3acSNick Mathewson eq_debug_entry(const struct event_debug_entry *a,
200cd17c3acSNick Mathewson     const struct event_debug_entry *b)
201cd17c3acSNick Mathewson {
202cd17c3acSNick Mathewson 	return a->ptr == b->ptr;
203cd17c3acSNick Mathewson }
204cd17c3acSNick Mathewson 
205cb9da0bfSNick Mathewson int event_debug_mode_on_ = 0;
206dcfb19a2SMark Ellzey 
207dcfb19a2SMark Ellzey 
208a068f2e5SAzat Khuzhin #if !defined(EVENT__DISABLE_THREAD_SUPPORT) && !defined(EVENT__DISABLE_DEBUG_MODE)
209dcfb19a2SMark Ellzey /**
210dcfb19a2SMark Ellzey  * @brief debug mode variable which is set for any function/structure that needs
211dcfb19a2SMark Ellzey  *        to be shared across threads (if thread support is enabled).
212dcfb19a2SMark Ellzey  *
213dcfb19a2SMark Ellzey  *        When and if evthreads are initialized, this variable will be evaluated,
214dcfb19a2SMark Ellzey  *        and if set to something other than zero, this means the evthread setup
215dcfb19a2SMark Ellzey  *        functions were called out of order.
216dcfb19a2SMark Ellzey  *
217dcfb19a2SMark Ellzey  *        See: "Locks and threading" in the documentation.
218dcfb19a2SMark Ellzey  */
219dcfb19a2SMark Ellzey int event_debug_created_threadable_ctx_ = 0;
220a068f2e5SAzat Khuzhin #endif
221dcfb19a2SMark Ellzey 
2229ecf0d48SNick Mathewson /* Set if it's too late to enable event_debug_mode. */
2239ecf0d48SNick Mathewson static int event_debug_mode_too_late = 0;
22468120d9bSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
225cb9da0bfSNick Mathewson static void *event_debug_map_lock_ = NULL;
226b683cae3SNick Mathewson #endif
227cd17c3acSNick Mathewson static HT_HEAD(event_debug_map, event_debug_entry) global_debug_map =
228cd17c3acSNick Mathewson 	HT_INITIALIZER();
229cd17c3acSNick Mathewson 
HT_PROTOTYPE(event_debug_map,event_debug_entry,node,hash_debug_entry,eq_debug_entry)230cd17c3acSNick Mathewson HT_PROTOTYPE(event_debug_map, event_debug_entry, node, hash_debug_entry,
231e56ff65aSNick Mathewson     eq_debug_entry)
232cd17c3acSNick Mathewson HT_GENERATE(event_debug_map, event_debug_entry, node, hash_debug_entry,
233e56ff65aSNick Mathewson     eq_debug_entry, 0.5, mm_malloc, mm_realloc, mm_free)
234cd17c3acSNick Mathewson 
235f45543e2SAzat Khuzhin /* record that ev is now setup (that is, ready for an add) */
236f45543e2SAzat Khuzhin static void event_debug_note_setup_(const struct event *ev)
237f45543e2SAzat Khuzhin {
238f45543e2SAzat Khuzhin 	struct event_debug_entry *dent, find;
239f45543e2SAzat Khuzhin 
240a39898f3SAzat Khuzhin 	if (!event_debug_mode_on_)
241f45543e2SAzat Khuzhin 		goto out;
242f45543e2SAzat Khuzhin 
243f45543e2SAzat Khuzhin 	find.ptr = ev;
244f45543e2SAzat Khuzhin 	EVLOCK_LOCK(event_debug_map_lock_, 0);
245f45543e2SAzat Khuzhin 	dent = HT_FIND(event_debug_map, &global_debug_map, &find);
246f45543e2SAzat Khuzhin 	if (dent) {
247f45543e2SAzat Khuzhin 		dent->added = 0;
248f45543e2SAzat Khuzhin 	} else {
249f45543e2SAzat Khuzhin 		dent = mm_malloc(sizeof(*dent));
250f45543e2SAzat Khuzhin 		if (!dent)
251f45543e2SAzat Khuzhin 			event_err(1,
252f45543e2SAzat Khuzhin 			    "Out of memory in debugging code");
253f45543e2SAzat Khuzhin 		dent->ptr = ev;
254f45543e2SAzat Khuzhin 		dent->added = 0;
255f45543e2SAzat Khuzhin 		HT_INSERT(event_debug_map, &global_debug_map, dent);
256f45543e2SAzat Khuzhin 	}
257f45543e2SAzat Khuzhin 	EVLOCK_UNLOCK(event_debug_map_lock_, 0);
258f45543e2SAzat Khuzhin 
259f45543e2SAzat Khuzhin out:
260f45543e2SAzat Khuzhin 	event_debug_mode_too_late = 1;
261f45543e2SAzat Khuzhin }
262f45543e2SAzat Khuzhin /* record that ev is no longer setup */
event_debug_note_teardown_(const struct event * ev)263f45543e2SAzat Khuzhin static void event_debug_note_teardown_(const struct event *ev)
264f45543e2SAzat Khuzhin {
265f45543e2SAzat Khuzhin 	struct event_debug_entry *dent, find;
266f45543e2SAzat Khuzhin 
267a39898f3SAzat Khuzhin 	if (!event_debug_mode_on_)
268f45543e2SAzat Khuzhin 		goto out;
269f45543e2SAzat Khuzhin 
270f45543e2SAzat Khuzhin 	find.ptr = ev;
271f45543e2SAzat Khuzhin 	EVLOCK_LOCK(event_debug_map_lock_, 0);
272f45543e2SAzat Khuzhin 	dent = HT_REMOVE(event_debug_map, &global_debug_map, &find);
273f45543e2SAzat Khuzhin 	if (dent)
274f45543e2SAzat Khuzhin 		mm_free(dent);
275f45543e2SAzat Khuzhin 	EVLOCK_UNLOCK(event_debug_map_lock_, 0);
276f45543e2SAzat Khuzhin 
277f45543e2SAzat Khuzhin out:
278f45543e2SAzat Khuzhin 	event_debug_mode_too_late = 1;
279f45543e2SAzat Khuzhin }
280cdd4c490SNick Mathewson /* Macro: record that ev is now added */
event_debug_note_add_(const struct event * ev)281f45543e2SAzat Khuzhin static void event_debug_note_add_(const struct event *ev)
282f45543e2SAzat Khuzhin {
283f45543e2SAzat Khuzhin 	struct event_debug_entry *dent,find;
284f45543e2SAzat Khuzhin 
285a39898f3SAzat Khuzhin 	if (!event_debug_mode_on_)
286f45543e2SAzat Khuzhin 		goto out;
287f45543e2SAzat Khuzhin 
288f45543e2SAzat Khuzhin 	find.ptr = ev;
289f45543e2SAzat Khuzhin 	EVLOCK_LOCK(event_debug_map_lock_, 0);
290f45543e2SAzat Khuzhin 	dent = HT_FIND(event_debug_map, &global_debug_map, &find);
291f45543e2SAzat Khuzhin 	if (dent) {
292f45543e2SAzat Khuzhin 		dent->added = 1;
293f45543e2SAzat Khuzhin 	} else {
294f45543e2SAzat Khuzhin 		event_errx(EVENT_ERR_ABORT_,
295f45543e2SAzat Khuzhin 		    "%s: noting an add on a non-setup event %p"
296f45543e2SAzat Khuzhin 		    " (events: 0x%x, fd: "EV_SOCK_FMT
297f45543e2SAzat Khuzhin 		    ", flags: 0x%x)",
298f45543e2SAzat Khuzhin 		    __func__, ev, ev->ev_events,
299f45543e2SAzat Khuzhin 		    EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
300f45543e2SAzat Khuzhin 	}
301f45543e2SAzat Khuzhin 	EVLOCK_UNLOCK(event_debug_map_lock_, 0);
302f45543e2SAzat Khuzhin 
303f45543e2SAzat Khuzhin out:
304f45543e2SAzat Khuzhin 	event_debug_mode_too_late = 1;
305f45543e2SAzat Khuzhin }
306f45543e2SAzat Khuzhin /* record that ev is no longer added */
event_debug_note_del_(const struct event * ev)307f45543e2SAzat Khuzhin static void event_debug_note_del_(const struct event *ev)
308f45543e2SAzat Khuzhin {
309f45543e2SAzat Khuzhin 	struct event_debug_entry *dent, find;
310f45543e2SAzat Khuzhin 
311a39898f3SAzat Khuzhin 	if (!event_debug_mode_on_)
312f45543e2SAzat Khuzhin 		goto out;
313f45543e2SAzat Khuzhin 
314f45543e2SAzat Khuzhin 	find.ptr = ev;
315f45543e2SAzat Khuzhin 	EVLOCK_LOCK(event_debug_map_lock_, 0);
316f45543e2SAzat Khuzhin 	dent = HT_FIND(event_debug_map, &global_debug_map, &find);
317f45543e2SAzat Khuzhin 	if (dent) {
318f45543e2SAzat Khuzhin 		dent->added = 0;
319f45543e2SAzat Khuzhin 	} else {
320f45543e2SAzat Khuzhin 		event_errx(EVENT_ERR_ABORT_,
321f45543e2SAzat Khuzhin 		    "%s: noting a del on a non-setup event %p"
322f45543e2SAzat Khuzhin 		    " (events: 0x%x, fd: "EV_SOCK_FMT
323f45543e2SAzat Khuzhin 		    ", flags: 0x%x)",
324f45543e2SAzat Khuzhin 		    __func__, ev, ev->ev_events,
325f45543e2SAzat Khuzhin 		    EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
326f45543e2SAzat Khuzhin 	}
327f45543e2SAzat Khuzhin 	EVLOCK_UNLOCK(event_debug_map_lock_, 0);
328f45543e2SAzat Khuzhin 
329f45543e2SAzat Khuzhin out:
330f45543e2SAzat Khuzhin 	event_debug_mode_too_late = 1;
331f45543e2SAzat Khuzhin }
332f45543e2SAzat Khuzhin /* assert that ev is setup (i.e., okay to add or inspect) */
event_debug_assert_is_setup_(const struct event * ev)333f45543e2SAzat Khuzhin static void event_debug_assert_is_setup_(const struct event *ev)
334f45543e2SAzat Khuzhin {
335f45543e2SAzat Khuzhin 	struct event_debug_entry *dent, find;
336f45543e2SAzat Khuzhin 
337a39898f3SAzat Khuzhin 	if (!event_debug_mode_on_)
338f45543e2SAzat Khuzhin 		return;
339f45543e2SAzat Khuzhin 
340f45543e2SAzat Khuzhin 	find.ptr = ev;
341f45543e2SAzat Khuzhin 	EVLOCK_LOCK(event_debug_map_lock_, 0);
342f45543e2SAzat Khuzhin 	dent = HT_FIND(event_debug_map, &global_debug_map, &find);
343f45543e2SAzat Khuzhin 	if (!dent) {
344f45543e2SAzat Khuzhin 		event_errx(EVENT_ERR_ABORT_,
345f45543e2SAzat Khuzhin 		    "%s called on a non-initialized event %p"
346f45543e2SAzat Khuzhin 		    " (events: 0x%x, fd: "EV_SOCK_FMT
347f45543e2SAzat Khuzhin 		    ", flags: 0x%x)",
348f45543e2SAzat Khuzhin 		    __func__, ev, ev->ev_events,
349f45543e2SAzat Khuzhin 		    EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
350f45543e2SAzat Khuzhin 	}
351f45543e2SAzat Khuzhin 	EVLOCK_UNLOCK(event_debug_map_lock_, 0);
352f45543e2SAzat Khuzhin }
353f45543e2SAzat Khuzhin /* assert that ev is not added (i.e., okay to tear down or set up again) */
event_debug_assert_not_added_(const struct event * ev)354f45543e2SAzat Khuzhin static void event_debug_assert_not_added_(const struct event *ev)
355f45543e2SAzat Khuzhin {
356f45543e2SAzat Khuzhin 	struct event_debug_entry *dent, find;
357f45543e2SAzat Khuzhin 
358a39898f3SAzat Khuzhin 	if (!event_debug_mode_on_)
359f45543e2SAzat Khuzhin 		return;
360f45543e2SAzat Khuzhin 
361f45543e2SAzat Khuzhin 	find.ptr = ev;
362f45543e2SAzat Khuzhin 	EVLOCK_LOCK(event_debug_map_lock_, 0);
363f45543e2SAzat Khuzhin 	dent = HT_FIND(event_debug_map, &global_debug_map, &find);
364f45543e2SAzat Khuzhin 	if (dent && dent->added) {
365f45543e2SAzat Khuzhin 		event_errx(EVENT_ERR_ABORT_,
366f45543e2SAzat Khuzhin 		    "%s called on an already added event %p"
367f45543e2SAzat Khuzhin 		    " (events: 0x%x, fd: "EV_SOCK_FMT", "
368f45543e2SAzat Khuzhin 		    "flags: 0x%x)",
369f45543e2SAzat Khuzhin 		    __func__, ev, ev->ev_events,
370f45543e2SAzat Khuzhin 		    EV_SOCK_ARG(ev->ev_fd), ev->ev_flags);
371f45543e2SAzat Khuzhin 	}
372f45543e2SAzat Khuzhin 	EVLOCK_UNLOCK(event_debug_map_lock_, 0);
373f45543e2SAzat Khuzhin }
event_debug_assert_socket_nonblocking_(evutil_socket_t fd)374a39898f3SAzat Khuzhin static void event_debug_assert_socket_nonblocking_(evutil_socket_t fd)
375a39898f3SAzat Khuzhin {
376a39898f3SAzat Khuzhin 	if (!event_debug_mode_on_)
377a39898f3SAzat Khuzhin 		return;
378a8155c62SAzat Khuzhin 	if (fd < 0)
379a8155c62SAzat Khuzhin 		return;
380a39898f3SAzat Khuzhin 
381a39898f3SAzat Khuzhin #ifndef _WIN32
382a8155c62SAzat Khuzhin 	{
383a8155c62SAzat Khuzhin 		int flags;
384a39898f3SAzat Khuzhin 		if ((flags = fcntl(fd, F_GETFL, NULL)) >= 0) {
385a39898f3SAzat Khuzhin 			EVUTIL_ASSERT(flags & O_NONBLOCK);
386a39898f3SAzat Khuzhin 		}
387a8155c62SAzat Khuzhin 	}
388a39898f3SAzat Khuzhin #endif
389a39898f3SAzat Khuzhin }
390cd17c3acSNick Mathewson #else
event_debug_note_setup_(const struct event * ev)391f45543e2SAzat Khuzhin static void event_debug_note_setup_(const struct event *ev) { (void)ev; }
event_debug_note_teardown_(const struct event * ev)392f45543e2SAzat Khuzhin static void event_debug_note_teardown_(const struct event *ev) { (void)ev; }
event_debug_note_add_(const struct event * ev)393f45543e2SAzat Khuzhin static void event_debug_note_add_(const struct event *ev) { (void)ev; }
event_debug_note_del_(const struct event * ev)394f45543e2SAzat Khuzhin static void event_debug_note_del_(const struct event *ev) { (void)ev; }
event_debug_assert_is_setup_(const struct event * ev)395f45543e2SAzat Khuzhin static void event_debug_assert_is_setup_(const struct event *ev) { (void)ev; }
event_debug_assert_not_added_(const struct event * ev)396f45543e2SAzat Khuzhin static void event_debug_assert_not_added_(const struct event *ev) { (void)ev; }
event_debug_assert_socket_nonblocking_(evutil_socket_t fd)397a39898f3SAzat Khuzhin static void event_debug_assert_socket_nonblocking_(evutil_socket_t fd) { (void)fd; }
398cd17c3acSNick Mathewson #endif
399cd17c3acSNick Mathewson 
400e2642f0aSNick Mathewson #define EVENT_BASE_ASSERT_LOCKED(base)		\
401e2642f0aSNick Mathewson 	EVLOCK_ASSERT_LOCKED((base)->th_base_lock)
402e2642f0aSNick Mathewson 
403a459ef70SNick Mathewson /* How often (in seconds) do we check for changes in wall clock time relative
404a459ef70SNick Mathewson  * to monotonic time?  Set this to -1 for 'never.' */
4052a83ecc8SNick Mathewson #define CLOCK_SYNC_INTERVAL 5
406a459ef70SNick Mathewson 
407cdd4c490SNick Mathewson /** Set 'tp' to the current time according to 'base'.  We must hold the lock
408cdd4c490SNick Mathewson  * on 'base'.  If there is a cached time, return it.  Otherwise, use
409cdd4c490SNick Mathewson  * clock_gettime or gettimeofday as appropriate to find out the right time.
410cdd4c490SNick Mathewson  * Return 0 on success, -1 on failure.
411cdd4c490SNick Mathewson  */
412571ac954SNiels Provos static int
gettime(struct event_base * base,struct timeval * tp)41345e6fb0dSNiels Provos gettime(struct event_base *base, struct timeval *tp)
414571ac954SNiels Provos {
415e2642f0aSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
416e2642f0aSNick Mathewson 
41745e6fb0dSNiels Provos 	if (base->tv_cache.tv_sec) {
41845e6fb0dSNiels Provos 		*tp = base->tv_cache;
41945e6fb0dSNiels Provos 		return (0);
42045e6fb0dSNiels Provos 	}
42145e6fb0dSNiels Provos 
422f5e4eb05SNick Mathewson 	if (evutil_gettime_monotonic_(&base->monotonic_timer, tp) == -1) {
423f5e4eb05SNick Mathewson 		return -1;
424d5e1d5adSNick Mathewson 	}
425f5e4eb05SNick Mathewson 
426a459ef70SNick Mathewson 	if (base->last_updated_clock_diff + CLOCK_SYNC_INTERVAL
427b8fd6f91SNick Mathewson 	    < tp->tv_sec) {
428a459ef70SNick Mathewson 		struct timeval tv;
429a459ef70SNick Mathewson 		evutil_gettimeofday(&tv,NULL);
430a459ef70SNick Mathewson 		evutil_timersub(&tv, tp, &base->tv_clock_diff);
431b8fd6f91SNick Mathewson 		base->last_updated_clock_diff = tp->tv_sec;
432a459ef70SNick Mathewson 	}
433a459ef70SNick Mathewson 
434f5e4eb05SNick Mathewson 	return 0;
435571ac954SNiels Provos }
436571ac954SNiels Provos 
43747854a80SNick Mathewson int
event_base_gettimeofday_cached(struct event_base * base,struct timeval * tv)43847854a80SNick Mathewson event_base_gettimeofday_cached(struct event_base *base, struct timeval *tv)
43947854a80SNick Mathewson {
44047854a80SNick Mathewson 	int r;
44147854a80SNick Mathewson 	if (!base) {
44247854a80SNick Mathewson 		base = current_base;
44347854a80SNick Mathewson 		if (!current_base)
44447854a80SNick Mathewson 			return evutil_gettimeofday(tv, NULL);
44547854a80SNick Mathewson 	}
44647854a80SNick Mathewson 
44747854a80SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
448a459ef70SNick Mathewson 	if (base->tv_cache.tv_sec == 0) {
449a459ef70SNick Mathewson 		r = evutil_gettimeofday(tv, NULL);
450a459ef70SNick Mathewson 	} else {
451a459ef70SNick Mathewson 		evutil_timeradd(&base->tv_cache, &base->tv_clock_diff, tv);
452a459ef70SNick Mathewson 		r = 0;
453a459ef70SNick Mathewson 	}
45447854a80SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
45547854a80SNick Mathewson 	return r;
45647854a80SNick Mathewson }
45747854a80SNick Mathewson 
458cdd4c490SNick Mathewson /** Make 'base' have no current cached time. */
459ab96b5f3SNick Mathewson static inline void
clear_time_cache(struct event_base * base)460ab96b5f3SNick Mathewson clear_time_cache(struct event_base *base)
461ab96b5f3SNick Mathewson {
462ab96b5f3SNick Mathewson 	base->tv_cache.tv_sec = 0;
463ab96b5f3SNick Mathewson }
464ab96b5f3SNick Mathewson 
465cdd4c490SNick Mathewson /** Replace the cached time in 'base' with the current time. */
466ab96b5f3SNick Mathewson static inline void
update_time_cache(struct event_base * base)467ab96b5f3SNick Mathewson update_time_cache(struct event_base *base)
468ab96b5f3SNick Mathewson {
469ab96b5f3SNick Mathewson 	base->tv_cache.tv_sec = 0;
470ab96b5f3SNick Mathewson 	if (!(base->flags & EVENT_BASE_FLAG_NO_CACHE_TIME))
471ab96b5f3SNick Mathewson 	    gettime(base, &base->tv_cache);
472ab96b5f3SNick Mathewson }
473ab96b5f3SNick Mathewson 
474212533e4SAbel Mathew int
event_base_update_cache_time(struct event_base * base)475212533e4SAbel Mathew event_base_update_cache_time(struct event_base *base)
476212533e4SAbel Mathew {
477212533e4SAbel Mathew 
478212533e4SAbel Mathew 	if (!base) {
479212533e4SAbel Mathew 		base = current_base;
480212533e4SAbel Mathew 		if (!current_base)
481212533e4SAbel Mathew 			return -1;
482212533e4SAbel Mathew 	}
483212533e4SAbel Mathew 
484212533e4SAbel Mathew 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
4855e6fa2a3SNick Mathewson 	if (base->running_loop)
486212533e4SAbel Mathew 		update_time_cache(base);
487212533e4SAbel Mathew 	EVBASE_RELEASE_LOCK(base, th_base_lock);
488212533e4SAbel Mathew 	return 0;
489212533e4SAbel Mathew }
490212533e4SAbel Mathew 
491cba59e53SNick Mathewson static inline struct event *
event_callback_to_event(struct event_callback * evcb)492cba59e53SNick Mathewson event_callback_to_event(struct event_callback *evcb)
493cba59e53SNick Mathewson {
494cba59e53SNick Mathewson 	EVUTIL_ASSERT((evcb->evcb_flags & EVLIST_INIT));
495cba59e53SNick Mathewson 	return EVUTIL_UPCAST(evcb, struct event, ev_evcallback);
496cba59e53SNick Mathewson }
497cba59e53SNick Mathewson 
498cba59e53SNick Mathewson static inline struct event_callback *
event_to_event_callback(struct event * ev)499cba59e53SNick Mathewson event_to_event_callback(struct event *ev)
500cba59e53SNick Mathewson {
501cba59e53SNick Mathewson 	return &ev->ev_evcallback;
502cba59e53SNick Mathewson }
503cba59e53SNick Mathewson 
504a5271518SNiels Provos struct event_base *
event_init(void)505aa6567feSNiels Provos event_init(void)
506aa6567feSNiels Provos {
507904b5721SNick Mathewson 	struct event_base *base = event_base_new_with_config(NULL);
508f586f428SNiels Provos 
50991fe23fcSNick Mathewson 	if (base == NULL) {
510904b5721SNick Mathewson 		event_errx(1, "%s: Unable to construct event_base", __func__);
51191fe23fcSNick Mathewson 		return NULL;
51291fe23fcSNick Mathewson 	}
513904b5721SNick Mathewson 
514f586f428SNiels Provos 	current_base = base;
515f586f428SNiels Provos 
516f586f428SNiels Provos 	return (base);
517f586f428SNiels Provos }
518f586f428SNiels Provos 
519f586f428SNiels Provos struct event_base *
event_base_new(void)520f586f428SNiels Provos event_base_new(void)
521f586f428SNiels Provos {
522904b5721SNick Mathewson 	struct event_base *base = NULL;
523904b5721SNick Mathewson 	struct event_config *cfg = event_config_new();
524904b5721SNick Mathewson 	if (cfg) {
525904b5721SNick Mathewson 		base = event_base_new_with_config(cfg);
526904b5721SNick Mathewson 		event_config_free(cfg);
527904b5721SNick Mathewson 	}
528904b5721SNick Mathewson 	return base;
5293f56e364SNiels Provos }
5303f56e364SNiels Provos 
531cdd4c490SNick Mathewson /** Return true iff 'method' is the name of a method that 'cfg' tells us to
532cdd4c490SNick Mathewson  * avoid. */
5333f56e364SNiels Provos static int
event_config_is_avoided_method(const struct event_config * cfg,const char * method)534d38a7a19SNick Mathewson event_config_is_avoided_method(const struct event_config *cfg,
535d38a7a19SNick Mathewson     const char *method)
5363f56e364SNiels Provos {
5373f56e364SNiels Provos 	struct event_config_entry *entry;
5383f56e364SNiels Provos 
5393f56e364SNiels Provos 	TAILQ_FOREACH(entry, &cfg->entries, next) {
5403f56e364SNiels Provos 		if (entry->avoid_method != NULL &&
5413f56e364SNiels Provos 		    strcmp(entry->avoid_method, method) == 0)
5423f56e364SNiels Provos 			return (1);
5433f56e364SNiels Provos 	}
5443f56e364SNiels Provos 
5453f56e364SNiels Provos 	return (0);
5463f56e364SNiels Provos }
5473f56e364SNiels Provos 
548cdd4c490SNick Mathewson /** Return true iff 'method' is disabled according to the environment. */
5492deb3ce0SNiels Provos static int
event_is_method_disabled(const char * name)5502deb3ce0SNiels Provos event_is_method_disabled(const char *name)
5512deb3ce0SNiels Provos {
5522deb3ce0SNiels Provos 	char environment[64];
5532deb3ce0SNiels Provos 	int i;
5542deb3ce0SNiels Provos 
5552deb3ce0SNiels Provos 	evutil_snprintf(environment, sizeof(environment), "EVENT_NO%s", name);
5562deb3ce0SNiels Provos 	for (i = 8; environment[i] != '\0'; ++i)
5578ac3c4c2SNick Mathewson 		environment[i] = EVUTIL_TOUPPER_(environment[i]);
5588ac3c4c2SNick Mathewson 	/* Note that evutil_getenv_() ignores the environment entirely if
559cdd4c490SNick Mathewson 	 * we're setuid */
5608ac3c4c2SNick Mathewson 	return (evutil_getenv_(environment) != NULL);
56105965921SNick Mathewson }
5622deb3ce0SNiels Provos 
563b73ad7bcSNick Mathewson int
event_base_get_features(const struct event_base * base)564d38a7a19SNick Mathewson event_base_get_features(const struct event_base *base)
56505965921SNick Mathewson {
56605965921SNick Mathewson 	return base->evsel->features;
5672deb3ce0SNiels Provos }
5682deb3ce0SNiels Provos 
569b06b2649SNick Mathewson void
event_enable_debug_mode(void)570cd17c3acSNick Mathewson event_enable_debug_mode(void)
571cd17c3acSNick Mathewson {
57268120d9bSNick Mathewson #ifndef EVENT__DISABLE_DEBUG_MODE
573cb9da0bfSNick Mathewson 	if (event_debug_mode_on_)
574cd17c3acSNick Mathewson 		event_errx(1, "%s was called twice!", __func__);
5759ecf0d48SNick Mathewson 	if (event_debug_mode_too_late)
5769ecf0d48SNick Mathewson 		event_errx(1, "%s must be called *before* creating any events "
5779ecf0d48SNick Mathewson 		    "or event_bases",__func__);
578cd17c3acSNick Mathewson 
579cb9da0bfSNick Mathewson 	event_debug_mode_on_ = 1;
580cd17c3acSNick Mathewson 
581cd17c3acSNick Mathewson 	HT_INIT(event_debug_map, &global_debug_map);
582cd17c3acSNick Mathewson #endif
583cd17c3acSNick Mathewson }
584cd17c3acSNick Mathewson 
585cd17c3acSNick Mathewson void
event_disable_debug_mode(void)586cd17c3acSNick Mathewson event_disable_debug_mode(void)
587cd17c3acSNick Mathewson {
588941faaedSAzat Khuzhin #ifndef EVENT__DISABLE_DEBUG_MODE
589cd17c3acSNick Mathewson 	struct event_debug_entry **ent, *victim;
590cd17c3acSNick Mathewson 
591cb9da0bfSNick Mathewson 	EVLOCK_LOCK(event_debug_map_lock_, 0);
592cd17c3acSNick Mathewson 	for (ent = HT_START(event_debug_map, &global_debug_map); ent; ) {
593cd17c3acSNick Mathewson 		victim = *ent;
594cd17c3acSNick Mathewson 		ent = HT_NEXT_RMV(event_debug_map, &global_debug_map, ent);
595cd17c3acSNick Mathewson 		mm_free(victim);
596cd17c3acSNick Mathewson 	}
597cd17c3acSNick Mathewson 	HT_CLEAR(event_debug_map, &global_debug_map);
598cb9da0bfSNick Mathewson 	EVLOCK_UNLOCK(event_debug_map_lock_ , 0);
599941faaedSAzat Khuzhin 
600941faaedSAzat Khuzhin 	event_debug_mode_on_  = 0;
601cd17c3acSNick Mathewson #endif
602941faaedSAzat Khuzhin }
603cd17c3acSNick Mathewson 
6043f56e364SNiels Provos struct event_base *
event_base_new_with_config(const struct event_config * cfg)605d38a7a19SNick Mathewson event_base_new_with_config(const struct event_config *cfg)
6063f56e364SNiels Provos {
607aa6567feSNiels Provos 	int i;
60841b7cbc3SNiels Provos 	struct event_base *base;
60911ff74cfSNick Mathewson 	int should_check_environment;
610aa6567feSNiels Provos 
61168120d9bSNick Mathewson #ifndef EVENT__DISABLE_DEBUG_MODE
6129ecf0d48SNick Mathewson 	event_debug_mode_too_late = 1;
613ad85908aSNick Mathewson #endif
614cd17c3acSNick Mathewson 
615904b5721SNick Mathewson 	if ((base = mm_calloc(1, sizeof(struct event_base))) == NULL) {
616904b5721SNick Mathewson 		event_warn("%s: calloc", __func__);
617904b5721SNick Mathewson 		return NULL;
618904b5721SNick Mathewson 	}
619a2598ec6SNick Mathewson 
620630f077cSNick Mathewson 	if (cfg)
621630f077cSNick Mathewson 		base->flags = cfg->flags;
622630f077cSNick Mathewson 
623a2598ec6SNick Mathewson 	should_check_environment =
624a2598ec6SNick Mathewson 	    !(cfg && (cfg->flags & EVENT_BASE_FLAG_IGNORE_ENV));
625a2598ec6SNick Mathewson 
626f5e4eb05SNick Mathewson 	{
627f5e4eb05SNick Mathewson 		struct timeval tmp;
628a2598ec6SNick Mathewson 		int precise_time =
629a2598ec6SNick Mathewson 		    cfg && (cfg->flags & EVENT_BASE_FLAG_PRECISE_TIMER);
630630f077cSNick Mathewson 		int flags;
631630f077cSNick Mathewson 		if (should_check_environment && !precise_time) {
632a2598ec6SNick Mathewson 			precise_time = evutil_getenv_("EVENT_PRECISE_TIMER") != NULL;
63327dee54dSyongqing.jiao 			if (precise_time) {
634630f077cSNick Mathewson 				base->flags |= EVENT_BASE_FLAG_PRECISE_TIMER;
635630f077cSNick Mathewson 			}
63627dee54dSyongqing.jiao 		}
637630f077cSNick Mathewson 		flags = precise_time ? EV_MONOT_PRECISE : 0;
638630f077cSNick Mathewson 		evutil_configure_monotonic_time_(&base->monotonic_timer, flags);
639a2598ec6SNick Mathewson 
640f5e4eb05SNick Mathewson 		gettime(base, &tmp);
641f5e4eb05SNick Mathewson 	}
642aa6567feSNiels Provos 
6438ac3c4c2SNick Mathewson 	min_heap_ctor_(&base->timeheap);
644a3cec909SNick Mathewson 
64541b7cbc3SNiels Provos 	base->sig.ev_signal_pair[0] = -1;
64641b7cbc3SNiels Provos 	base->sig.ev_signal_pair[1] = -1;
6476d195109SNick Mathewson 	base->th_notify_fd[0] = -1;
6486d195109SNick Mathewson 	base->th_notify_fd[1] = -1;
649aa6567feSNiels Provos 
650745a63dbSNick Mathewson 	TAILQ_INIT(&base->active_later_queue);
651745a63dbSNick Mathewson 
6528ac3c4c2SNick Mathewson 	evmap_io_initmap_(&base->io);
6538ac3c4c2SNick Mathewson 	evmap_signal_initmap_(&base->sigmap);
6548ac3c4c2SNick Mathewson 	event_changelist_init_(&base->changelist);
6556bb2f842SNick Mathewson 
65641b7cbc3SNiels Provos 	base->evbase = NULL;
65711ff74cfSNick Mathewson 
658a37a0c0eSNick Mathewson 	if (cfg) {
659fd4de1e7SNick Mathewson 		memcpy(&base->max_dispatch_time,
660fd4de1e7SNick Mathewson 		    &cfg->max_dispatch_interval, sizeof(struct timeval));
661a37a0c0eSNick Mathewson 		base->limit_callbacks_after_prio =
662a37a0c0eSNick Mathewson 		    cfg->limit_callbacks_after_prio;
663a37a0c0eSNick Mathewson 	} else {
664fd4de1e7SNick Mathewson 		base->max_dispatch_time.tv_sec = -1;
665a37a0c0eSNick Mathewson 		base->limit_callbacks_after_prio = 1;
666a37a0c0eSNick Mathewson 	}
667fd4de1e7SNick Mathewson 	if (cfg && cfg->max_dispatch_callbacks >= 0) {
668fd4de1e7SNick Mathewson 		base->max_dispatch_callbacks = cfg->max_dispatch_callbacks;
669fd4de1e7SNick Mathewson 	} else {
670fd4de1e7SNick Mathewson 		base->max_dispatch_callbacks = INT_MAX;
671fd4de1e7SNick Mathewson 	}
672a37a0c0eSNick Mathewson 	if (base->max_dispatch_callbacks == INT_MAX &&
673a37a0c0eSNick Mathewson 	    base->max_dispatch_time.tv_sec == -1)
674a37a0c0eSNick Mathewson 		base->limit_callbacks_after_prio = INT_MAX;
675fd4de1e7SNick Mathewson 
67641b7cbc3SNiels Provos 	for (i = 0; eventops[i] && !base->evbase; i++) {
6773f56e364SNiels Provos 		if (cfg != NULL) {
6783f56e364SNiels Provos 			/* determine if this backend should be avoided */
6793f56e364SNiels Provos 			if (event_config_is_avoided_method(cfg,
6803f56e364SNiels Provos 				eventops[i]->name))
6813f56e364SNiels Provos 				continue;
68205965921SNick Mathewson 			if ((eventops[i]->features & cfg->require_features)
68305965921SNick Mathewson 			    != cfg->require_features)
68405965921SNick Mathewson 				continue;
6853f56e364SNiels Provos 		}
6863f56e364SNiels Provos 
6872deb3ce0SNiels Provos 		/* also obey the environment variables */
68811ff74cfSNick Mathewson 		if (should_check_environment &&
68911ff74cfSNick Mathewson 		    event_is_method_disabled(eventops[i]->name))
6902deb3ce0SNiels Provos 			continue;
6912deb3ce0SNiels Provos 
69241b7cbc3SNiels Provos 		base->evsel = eventops[i];
693aa6567feSNiels Provos 
69441b7cbc3SNiels Provos 		base->evbase = base->evsel->init(base);
695aa6567feSNiels Provos 	}
696aa6567feSNiels Provos 
69705965921SNick Mathewson 	if (base->evbase == NULL) {
698904b5721SNick Mathewson 		event_warnx("%s: no event mechanism available",
69902b2b4d1SNiels Provos 		    __func__);
70027ce38b6SNick Mathewson 		base->evsel = NULL;
70105965921SNick Mathewson 		event_base_free(base);
70205965921SNick Mathewson 		return NULL;
70305965921SNick Mathewson 	}
704b5b585c1SNiels Provos 
7058ac3c4c2SNick Mathewson 	if (evutil_getenv_("EVENT_SHOW_METHOD"))
7062deb3ce0SNiels Provos 		event_msgx("libevent using: %s", base->evsel->name);
707fa6c304dSNiels Provos 
708fa6c304dSNiels Provos 	/* allocate a single active event queue */
70974871cacSNick Mathewson 	if (event_base_priority_init(base, 1) < 0) {
71074871cacSNick Mathewson 		event_base_free(base);
71174871cacSNick Mathewson 		return NULL;
71274871cacSNick Mathewson 	}
7138773c4c9SNiels Provos 
714558de9b3SNiels Provos 	/* prepare for threading */
715558de9b3SNiels Provos 
716a068f2e5SAzat Khuzhin #if !defined(EVENT__DISABLE_THREAD_SUPPORT) && !defined(EVENT__DISABLE_DEBUG_MODE)
717dcfb19a2SMark Ellzey 	event_debug_created_threadable_ctx_ = 1;
718a068f2e5SAzat Khuzhin #endif
719dcfb19a2SMark Ellzey 
720f337296aSAzat Khuzhin #ifndef EVENT__DISABLE_THREAD_SUPPORT
721e7874133SNick Mathewson 	if (EVTHREAD_LOCKING_ENABLED() &&
722e7874133SNick Mathewson 	    (!cfg || !(cfg->flags & EVENT_BASE_FLAG_NOLOCK))) {
723ec35eb55SNick Mathewson 		int r;
7249cd5acb5SNick Mathewson 		EVTHREAD_ALLOC_LOCK(base->th_base_lock, 0);
725e0972c21SNick Mathewson 		EVTHREAD_ALLOC_COND(base->current_event_cond);
726ec35eb55SNick Mathewson 		r = evthread_make_base_notifiable(base);
727ec35eb55SNick Mathewson 		if (r<0) {
7284e797f38SNick Mathewson 			event_warnx("%s: Unable to make base notifiable.", __func__);
729ec35eb55SNick Mathewson 			event_base_free(base);
730ec35eb55SNick Mathewson 			return NULL;
731ec35eb55SNick Mathewson 		}
732ec35eb55SNick Mathewson 	}
733767eb70fSNick Mathewson #endif
734ec35eb55SNick Mathewson 
7359f560bfaSNick Mathewson #ifdef _WIN32
73638aec9ecSNick Mathewson 	if (cfg && (cfg->flags & EVENT_BASE_FLAG_STARTUP_IOCP))
7378ac3c4c2SNick Mathewson 		event_base_start_iocp_(base, cfg->n_cpus_hint);
738879420a7SNick Mathewson #endif
739879420a7SNick Mathewson 
74041b7cbc3SNiels Provos 	return (base);
741fa6c304dSNiels Provos }
742fa6c304dSNiels Provos 
743879420a7SNick Mathewson int
event_base_start_iocp_(struct event_base * base,int n_cpus)7448ac3c4c2SNick Mathewson event_base_start_iocp_(struct event_base *base, int n_cpus)
745879420a7SNick Mathewson {
7469f560bfaSNick Mathewson #ifdef _WIN32
747879420a7SNick Mathewson 	if (base->iocp)
748879420a7SNick Mathewson 		return 0;
7498ac3c4c2SNick Mathewson 	base->iocp = event_iocp_port_launch_(n_cpus);
750879420a7SNick Mathewson 	if (!base->iocp) {
751879420a7SNick Mathewson 		event_warnx("%s: Couldn't launch IOCP", __func__);
752879420a7SNick Mathewson 		return -1;
753879420a7SNick Mathewson 	}
754879420a7SNick Mathewson 	return 0;
755879420a7SNick Mathewson #else
756879420a7SNick Mathewson 	return -1;
757879420a7SNick Mathewson #endif
758879420a7SNick Mathewson }
759879420a7SNick Mathewson 
7602e8051f5SNiels Provos void
event_base_stop_iocp_(struct event_base * base)7618ac3c4c2SNick Mathewson event_base_stop_iocp_(struct event_base *base)
762d844242fSChristopher Davis {
7639f560bfaSNick Mathewson #ifdef _WIN32
764d844242fSChristopher Davis 	int rv;
765d844242fSChristopher Davis 
766d844242fSChristopher Davis 	if (!base->iocp)
767d844242fSChristopher Davis 		return;
7688ac3c4c2SNick Mathewson 	rv = event_iocp_shutdown_(base->iocp, -1);
769d844242fSChristopher Davis 	EVUTIL_ASSERT(rv >= 0);
770d844242fSChristopher Davis 	base->iocp = NULL;
771d844242fSChristopher Davis #endif
772d844242fSChristopher Davis }
773d844242fSChristopher Davis 
774e9ebef83SNick Mathewson static int
event_base_cancel_single_callback_(struct event_base * base,struct event_callback * evcb,int run_finalizers)775e9ebef83SNick Mathewson event_base_cancel_single_callback_(struct event_base *base,
776e9ebef83SNick Mathewson     struct event_callback *evcb,
777e9ebef83SNick Mathewson     int run_finalizers)
778e9ebef83SNick Mathewson {
779e9ebef83SNick Mathewson 	int result = 0;
780e9ebef83SNick Mathewson 
781e9ebef83SNick Mathewson 	if (evcb->evcb_flags & EVLIST_INIT) {
782e9ebef83SNick Mathewson 		struct event *ev = event_callback_to_event(evcb);
783e9ebef83SNick Mathewson 		if (!(ev->ev_flags & EVLIST_INTERNAL)) {
784e9ebef83SNick Mathewson 			event_del_(ev, EVENT_DEL_EVEN_IF_FINALIZING);
785e9ebef83SNick Mathewson 			result = 1;
786e9ebef83SNick Mathewson 		}
787e9ebef83SNick Mathewson 	} else {
788d3d999a1SAzat Khuzhin 		EVBASE_ACQUIRE_LOCK(base, th_base_lock);
789e9ebef83SNick Mathewson 		event_callback_cancel_nolock_(base, evcb, 1);
790d3d999a1SAzat Khuzhin 		EVBASE_RELEASE_LOCK(base, th_base_lock);
791e9ebef83SNick Mathewson 		result = 1;
792e9ebef83SNick Mathewson 	}
793e9ebef83SNick Mathewson 
794e9ebef83SNick Mathewson 	if (run_finalizers && (evcb->evcb_flags & EVLIST_FINALIZING)) {
795e9ebef83SNick Mathewson 		switch (evcb->evcb_closure) {
796e9ebef83SNick Mathewson 		case EV_CLOSURE_EVENT_FINALIZE:
797e9ebef83SNick Mathewson 		case EV_CLOSURE_EVENT_FINALIZE_FREE: {
798e9ebef83SNick Mathewson 			struct event *ev = event_callback_to_event(evcb);
799e9ebef83SNick Mathewson 			ev->ev_evcallback.evcb_cb_union.evcb_evfinalize(ev, ev->ev_arg);
800e9ebef83SNick Mathewson 			if (evcb->evcb_closure == EV_CLOSURE_EVENT_FINALIZE_FREE)
801e9ebef83SNick Mathewson 				mm_free(ev);
802e9ebef83SNick Mathewson 			break;
803e9ebef83SNick Mathewson 		}
804e9ebef83SNick Mathewson 		case EV_CLOSURE_CB_FINALIZE:
805e9ebef83SNick Mathewson 			evcb->evcb_cb_union.evcb_cbfinalize(evcb, evcb->evcb_arg);
806e9ebef83SNick Mathewson 			break;
807e9ebef83SNick Mathewson 		default:
808e9ebef83SNick Mathewson 			break;
809e9ebef83SNick Mathewson 		}
810e9ebef83SNick Mathewson 	}
811e9ebef83SNick Mathewson 	return result;
812e9ebef83SNick Mathewson }
813e9ebef83SNick Mathewson 
event_base_free_queues_(struct event_base * base,int run_finalizers)8147c8d0152SAzat Khuzhin static int event_base_free_queues_(struct event_base *base, int run_finalizers)
8157c8d0152SAzat Khuzhin {
8167c8d0152SAzat Khuzhin 	int deleted = 0, i;
8177c8d0152SAzat Khuzhin 
8187c8d0152SAzat Khuzhin 	for (i = 0; i < base->nactivequeues; ++i) {
8197c8d0152SAzat Khuzhin 		struct event_callback *evcb, *next;
8207c8d0152SAzat Khuzhin 		for (evcb = TAILQ_FIRST(&base->activequeues[i]); evcb; ) {
8217c8d0152SAzat Khuzhin 			next = TAILQ_NEXT(evcb, evcb_active_next);
8227c8d0152SAzat Khuzhin 			deleted += event_base_cancel_single_callback_(base, evcb, run_finalizers);
8237c8d0152SAzat Khuzhin 			evcb = next;
8247c8d0152SAzat Khuzhin 		}
8257c8d0152SAzat Khuzhin 	}
8267c8d0152SAzat Khuzhin 
8277c8d0152SAzat Khuzhin 	{
8287c8d0152SAzat Khuzhin 		struct event_callback *evcb;
8297c8d0152SAzat Khuzhin 		while ((evcb = TAILQ_FIRST(&base->active_later_queue))) {
8307c8d0152SAzat Khuzhin 			deleted += event_base_cancel_single_callback_(base, evcb, run_finalizers);
8317c8d0152SAzat Khuzhin 		}
8327c8d0152SAzat Khuzhin 	}
8337c8d0152SAzat Khuzhin 
8347c8d0152SAzat Khuzhin 	return deleted;
8357c8d0152SAzat Khuzhin }
8367c8d0152SAzat Khuzhin 
837e9ebef83SNick Mathewson static void
event_base_free_(struct event_base * base,int run_finalizers)838e9ebef83SNick Mathewson event_base_free_(struct event_base *base, int run_finalizers)
8392e8051f5SNiels Provos {
84018104973SAzat Khuzhin 	int i, n_deleted=0;
841206d4336SNick Mathewson 	struct event *ev;
842a2a7d1d1SNick Mathewson 	/* XXXX grab the lock? If there is contention when one thread frees
843a2a7d1d1SNick Mathewson 	 * the base, then the contending thread will be very sad soon. */
8442e8051f5SNiels Provos 
84509fe97daSNick Mathewson 	/* event_base_free(NULL) is how to free the current_base if we
84609fe97daSNick Mathewson 	 * made it with event_init and forgot to hold a reference to it. */
8472e8051f5SNiels Provos 	if (base == NULL && current_base)
8482e8051f5SNiels Provos 		base = current_base;
84909fe97daSNick Mathewson 	/* Don't actually free NULL. */
85009fe97daSNick Mathewson 	if (base == NULL) {
85109fe97daSNick Mathewson 		event_warnx("%s: no base to free", __func__);
85209fe97daSNick Mathewson 		return;
85309fe97daSNick Mathewson 	}
85430ae40ccSNiels Provos 	/* XXX(niels) - check for internal events first */
855558de9b3SNiels Provos 
8569f560bfaSNick Mathewson #ifdef _WIN32
8578ac3c4c2SNick Mathewson 	event_base_stop_iocp_(base);
858d844242fSChristopher Davis #endif
859d844242fSChristopher Davis 
860558de9b3SNiels Provos 	/* threading fds if we have them */
861558de9b3SNiels Provos 	if (base->th_notify_fd[0] != -1) {
862558de9b3SNiels Provos 		event_del(&base->th_notify);
863f9b4ee0aSNiels Provos 		EVUTIL_CLOSESOCKET(base->th_notify_fd[0]);
86470a44b61SNick Mathewson 		if (base->th_notify_fd[1] != -1)
865f9b4ee0aSNiels Provos 			EVUTIL_CLOSESOCKET(base->th_notify_fd[1]);
866a5901991SNick Mathewson 		base->th_notify_fd[0] = -1;
867a5901991SNick Mathewson 		base->th_notify_fd[1] = -1;
868a19b4a05SNick Mathewson 		event_debug_unassign(&base->th_notify);
869558de9b3SNiels Provos 	}
870558de9b3SNiels Provos 
871206d4336SNick Mathewson 	/* Delete all non-internal events. */
8728ac3c4c2SNick Mathewson 	evmap_delete_all_(base);
873c89b4e63SNick Mathewson 
8748ac3c4c2SNick Mathewson 	while ((ev = min_heap_top_(&base->timeheap)) != NULL) {
8758c66d4e2SNiels Provos 		event_del(ev);
8768c66d4e2SNiels Provos 		++n_deleted;
8778c66d4e2SNiels Provos 	}
878693c24efSNick Mathewson 	for (i = 0; i < base->n_common_timeouts; ++i) {
879693c24efSNick Mathewson 		struct common_timeout_list *ctl =
880693c24efSNick Mathewson 		    base->common_timeout_queues[i];
881693c24efSNick Mathewson 		event_del(&ctl->timeout_event); /* Internal; doesn't count */
882a19b4a05SNick Mathewson 		event_debug_unassign(&ctl->timeout_event);
883693c24efSNick Mathewson 		for (ev = TAILQ_FIRST(&ctl->events); ev; ) {
884693c24efSNick Mathewson 			struct event *next = TAILQ_NEXT(ev,
885693c24efSNick Mathewson 			    ev_timeout_pos.ev_next_with_common_timeout);
886693c24efSNick Mathewson 			if (!(ev->ev_flags & EVLIST_INTERNAL)) {
887693c24efSNick Mathewson 				event_del(ev);
888693c24efSNick Mathewson 				++n_deleted;
889693c24efSNick Mathewson 			}
890693c24efSNick Mathewson 			ev = next;
891693c24efSNick Mathewson 		}
892693c24efSNick Mathewson 		mm_free(ctl);
893693c24efSNick Mathewson 	}
894693c24efSNick Mathewson 	if (base->common_timeout_queues)
895693c24efSNick Mathewson 		mm_free(base->common_timeout_queues);
8968c66d4e2SNiels Provos 
8977c8d0152SAzat Khuzhin 	for (;;) {
8987c8d0152SAzat Khuzhin 		/* For finalizers we can register yet another finalizer out from
8997c8d0152SAzat Khuzhin 		 * finalizer, and iff finalizer will be in active_later_queue we can
9007c8d0152SAzat Khuzhin 		 * add finalizer to activequeues, and we will have events in
9017c8d0152SAzat Khuzhin 		 * activequeues after this function returns, which is not what we want
9027c8d0152SAzat Khuzhin 		 * (we even have an assertion for this).
9037c8d0152SAzat Khuzhin 		 *
9047c8d0152SAzat Khuzhin 		 * A simple case is bufferevent with underlying (i.e. filters).
9057c8d0152SAzat Khuzhin 		 */
9067c8d0152SAzat Khuzhin 		int i = event_base_free_queues_(base, run_finalizers);
907ca69a10fSAzat Khuzhin 		event_debug(("%s: %d events freed", __func__, i));
9087c8d0152SAzat Khuzhin 		if (!i) {
9097c8d0152SAzat Khuzhin 			break;
910e67a5ea9SNiels Provos 		}
9117c8d0152SAzat Khuzhin 		n_deleted += i;
912e67a5ea9SNiels Provos 	}
913e67a5ea9SNiels Provos 
914206d4336SNick Mathewson 	if (n_deleted)
91518104973SAzat Khuzhin 		event_debug(("%s: %d events were still set in base",
916206d4336SNick Mathewson 			__func__, n_deleted));
917206d4336SNick Mathewson 
918c17dd591SNick Mathewson 	while (LIST_FIRST(&base->once_events)) {
919c17dd591SNick Mathewson 		struct event_once *eonce = LIST_FIRST(&base->once_events);
920c17dd591SNick Mathewson 		LIST_REMOVE(eonce, next_once);
921c17dd591SNick Mathewson 		mm_free(eonce);
922c17dd591SNick Mathewson 	}
923c17dd591SNick Mathewson 
924c97ee898SNick Mathewson 	if (base->evsel != NULL && base->evsel->dealloc != NULL)
92502b2b4d1SNiels Provos 		base->evsel->dealloc(base);
926206d4336SNick Mathewson 
9272e8051f5SNiels Provos 	for (i = 0; i < base->nactivequeues; ++i)
92874871cacSNick Mathewson 		EVUTIL_ASSERT(TAILQ_EMPTY(&base->activequeues[i]));
9298c66d4e2SNiels Provos 
9308ac3c4c2SNick Mathewson 	EVUTIL_ASSERT(min_heap_empty_(&base->timeheap));
9318ac3c4c2SNick Mathewson 	min_heap_dtor_(&base->timeheap);
9322e8051f5SNiels Provos 
93349868b61SNick Mathewson 	mm_free(base->activequeues);
9342e8051f5SNiels Provos 
9358ac3c4c2SNick Mathewson 	evmap_io_clear_(&base->io);
9368ac3c4c2SNick Mathewson 	evmap_signal_clear_(&base->sigmap);
9378ac3c4c2SNick Mathewson 	event_changelist_freemem_(&base->changelist);
93802b2b4d1SNiels Provos 
9399cd5acb5SNick Mathewson 	EVTHREAD_FREE_LOCK(base->th_base_lock, 0);
940e0972c21SNick Mathewson 	EVTHREAD_FREE_COND(base->current_event_cond);
94159cd4936SNick Mathewson 
942e9ebef83SNick Mathewson 	/* If we're freeing current_base, there won't be a current_base. */
943e9ebef83SNick Mathewson 	if (base == current_base)
944e9ebef83SNick Mathewson 		current_base = NULL;
94549868b61SNick Mathewson 	mm_free(base);
9462e8051f5SNiels Provos }
9472e8051f5SNiels Provos 
948e9ebef83SNick Mathewson void
event_base_free_nofinalize(struct event_base * base)949e9ebef83SNick Mathewson event_base_free_nofinalize(struct event_base *base)
950e9ebef83SNick Mathewson {
951e9ebef83SNick Mathewson 	event_base_free_(base, 0);
952e9ebef83SNick Mathewson }
953e9ebef83SNick Mathewson 
954e9ebef83SNick Mathewson void
event_base_free(struct event_base * base)955e9ebef83SNick Mathewson event_base_free(struct event_base *base)
956e9ebef83SNick Mathewson {
957e9ebef83SNick Mathewson 	event_base_free_(base, 1);
958e9ebef83SNick Mathewson }
959e9ebef83SNick Mathewson 
960272033efSNick Mathewson /* Fake eventop; used to disable the backend temporarily inside event_reinit
961272033efSNick Mathewson  * so that we can call event_del() on an event without telling the backend.
962272033efSNick Mathewson  */
963272033efSNick Mathewson static int
nil_backend_del(struct event_base * b,evutil_socket_t fd,short old,short events,void * fdinfo)964272033efSNick Mathewson nil_backend_del(struct event_base *b, evutil_socket_t fd, short old,
965272033efSNick Mathewson     short events, void *fdinfo)
966272033efSNick Mathewson {
967272033efSNick Mathewson 	return 0;
968272033efSNick Mathewson }
969272033efSNick Mathewson const struct eventop nil_eventop = {
970272033efSNick Mathewson 	"nil",
971272033efSNick Mathewson 	NULL, /* init: unused. */
972272033efSNick Mathewson 	NULL, /* add: unused. */
973272033efSNick Mathewson 	nil_backend_del, /* del: used, so needs to be killed. */
974272033efSNick Mathewson 	NULL, /* dispatch: unused. */
975272033efSNick Mathewson 	NULL, /* dealloc: unused. */
976272033efSNick Mathewson 	0, 0, 0
977272033efSNick Mathewson };
978272033efSNick Mathewson 
979a2a7d1d1SNick Mathewson /* reinitialize the event base after a fork */
98088897852SNiels Provos int
event_reinit(struct event_base * base)98188897852SNiels Provos event_reinit(struct event_base *base)
98288897852SNiels Provos {
983e2642f0aSNick Mathewson 	const struct eventop *evsel;
98488897852SNiels Provos 	int res = 0;
985495ed667SNick Mathewson 	int was_notifiable = 0;
9862c4b5de1SNick Mathewson 	int had_signal_added = 0;
98788897852SNiels Provos 
988e2642f0aSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
989e2642f0aSNick Mathewson 
990e2642f0aSNick Mathewson 	evsel = base->evsel;
991e2642f0aSNick Mathewson 
9922c4b5de1SNick Mathewson 	/* check if this event mechanism requires reinit on the backend */
9932c4b5de1SNick Mathewson 	if (evsel->need_reinit) {
9942c4b5de1SNick Mathewson 		/* We're going to call event_del() on our notify events (the
9952c4b5de1SNick Mathewson 		 * ones that tell about signals and wakeup events).  But we
9962c4b5de1SNick Mathewson 		 * don't actually want to tell the backend to change its
9972c4b5de1SNick Mathewson 		 * state, since it might still share some resource (a kqueue,
9982c4b5de1SNick Mathewson 		 * an epoll fd) with the parent process, and we don't want to
9992c4b5de1SNick Mathewson 		 * delete the fds from _that_ backend, we temporarily stub out
10002c4b5de1SNick Mathewson 		 * the evsel with a replacement.
1001272033efSNick Mathewson 		 */
1002272033efSNick Mathewson 		base->evsel = &nil_eventop;
10032c4b5de1SNick Mathewson 	}
1004272033efSNick Mathewson 
1005272033efSNick Mathewson 	/* We need to re-create a new signal-notification fd and a new
1006272033efSNick Mathewson 	 * thread-notification fd.  Otherwise, we'll still share those with
1007272033efSNick Mathewson 	 * the parent process, which would make any notification sent to them
1008272033efSNick Mathewson 	 * get received by one or both of the event loops, more or less at
1009272033efSNick Mathewson 	 * random.
1010272033efSNick Mathewson 	 */
10113b24f4eeSNiels Provos 	if (base->sig.ev_signal_added) {
10128eedeabeSNick Mathewson 		event_del_nolock_(&base->sig.ev_signal, EVENT_DEL_AUTOBLOCK);
1013272033efSNick Mathewson 		event_debug_unassign(&base->sig.ev_signal);
1014272033efSNick Mathewson 		memset(&base->sig.ev_signal, 0, sizeof(base->sig.ev_signal));
1015ad0c237bSNicholas Marriott 		had_signal_added = 1;
1016ad0c237bSNicholas Marriott 		base->sig.ev_signal_added = 0;
1017ad0c237bSNicholas Marriott 	}
10183f18ad1bSNick Mathewson 	if (base->sig.ev_signal_pair[0] != -1)
10193f18ad1bSNick Mathewson 		EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[0]);
10203f18ad1bSNick Mathewson 	if (base->sig.ev_signal_pair[1] != -1)
10213f18ad1bSNick Mathewson 		EVUTIL_CLOSESOCKET(base->sig.ev_signal_pair[1]);
102253a07fe2SNick Mathewson 	if (base->th_notify_fn != NULL) {
1023495ed667SNick Mathewson 		was_notifiable = 1;
102453a07fe2SNick Mathewson 		base->th_notify_fn = NULL;
102553a07fe2SNick Mathewson 	}
102653a07fe2SNick Mathewson 	if (base->th_notify_fd[0] != -1) {
10278eedeabeSNick Mathewson 		event_del_nolock_(&base->th_notify, EVENT_DEL_AUTOBLOCK);
1028495ed667SNick Mathewson 		EVUTIL_CLOSESOCKET(base->th_notify_fd[0]);
1029495ed667SNick Mathewson 		if (base->th_notify_fd[1] != -1)
1030495ed667SNick Mathewson 			EVUTIL_CLOSESOCKET(base->th_notify_fd[1]);
1031495ed667SNick Mathewson 		base->th_notify_fd[0] = -1;
1032495ed667SNick Mathewson 		base->th_notify_fd[1] = -1;
1033495ed667SNick Mathewson 		event_debug_unassign(&base->th_notify);
1034495ed667SNick Mathewson 	}
10352c4b5de1SNick Mathewson 
1036272033efSNick Mathewson 	/* Replace the original evsel. */
1037272033efSNick Mathewson         base->evsel = evsel;
1038e67a5ea9SNiels Provos 
10392c4b5de1SNick Mathewson 	if (evsel->need_reinit) {
10402c4b5de1SNick Mathewson 		/* Reconstruct the backend through brute-force, so that we do
10412c4b5de1SNick Mathewson 		 * not share any structures with the parent process. For some
10422c4b5de1SNick Mathewson 		 * backends, this is necessary: epoll and kqueue, for
10432c4b5de1SNick Mathewson 		 * instance, have events associated with a kernel
10442c4b5de1SNick Mathewson 		 * structure. If didn't reinitialize, we'd share that
10452c4b5de1SNick Mathewson 		 * structure with the parent process, and any changes made by
10462c4b5de1SNick Mathewson 		 * the parent would affect our backend's behavior (and vice
10472c4b5de1SNick Mathewson 		 * versa).
1048272033efSNick Mathewson 		 */
104998b5453eSNiels Provos 		if (base->evsel->dealloc != NULL)
105002b2b4d1SNiels Provos 			base->evsel->dealloc(base);
105102b2b4d1SNiels Provos 		base->evbase = evsel->init(base);
105291fe23fcSNick Mathewson 		if (base->evbase == NULL) {
10532c4b5de1SNick Mathewson 			event_errx(1,
10542c4b5de1SNick Mathewson 			   "%s: could not reinitialize event mechanism",
105588897852SNiels Provos 			   __func__);
1056e2642f0aSNick Mathewson 			res = -1;
1057e2642f0aSNick Mathewson 			goto done;
105891fe23fcSNick Mathewson 		}
105988897852SNiels Provos 
10602c4b5de1SNick Mathewson 		/* Empty out the changelist (if any): we are starting from a
10612c4b5de1SNick Mathewson 		 * blank slate. */
10628ac3c4c2SNick Mathewson 		event_changelist_freemem_(&base->changelist);
106302b2b4d1SNiels Provos 
10642c4b5de1SNick Mathewson 		/* Tell the event maps to re-inform the backend about all
10652c4b5de1SNick Mathewson 		 * pending events. This will make the signal notification
10662c4b5de1SNick Mathewson 		 * event get re-created if necessary. */
10678ac3c4c2SNick Mathewson 		if (evmap_reinit_(base) < 0)
106802b2b4d1SNiels Provos 			res = -1;
10692c4b5de1SNick Mathewson 	} else {
10708ac3c4c2SNick Mathewson 		res = evsig_init_(base);
107188640aa1SNicholas Marriott 		if (res == 0 && had_signal_added) {
107288640aa1SNicholas Marriott 			res = event_add_nolock_(&base->sig.ev_signal, NULL, 0);
107388640aa1SNicholas Marriott 			if (res == 0)
107488640aa1SNicholas Marriott 				base->sig.ev_signal_added = 1;
107588640aa1SNicholas Marriott 		}
10762c4b5de1SNick Mathewson 	}
107788897852SNiels Provos 
1078272033efSNick Mathewson 	/* If we were notifiable before, and nothing just exploded, become
1079272033efSNick Mathewson 	 * notifiable again. */
1080495ed667SNick Mathewson 	if (was_notifiable && res == 0)
10819cd5acb5SNick Mathewson 		res = evthread_make_base_notifiable_nolock_(base);
1082495ed667SNick Mathewson 
1083e2642f0aSNick Mathewson done:
1084e2642f0aSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
108588897852SNiels Provos 	return (res);
108688897852SNiels Provos }
108788897852SNiels Provos 
1088f2645f80SAndrea Shepard /* Get the monotonic time for this event_base' timer */
1089f2645f80SAndrea Shepard int
event_gettime_monotonic(struct event_base * base,struct timeval * tv)1090f2645f80SAndrea Shepard event_gettime_monotonic(struct event_base *base, struct timeval *tv)
1091f2645f80SAndrea Shepard {
1092f2645f80SAndrea Shepard   int rv = -1;
1093f2645f80SAndrea Shepard 
1094f2645f80SAndrea Shepard   if (base && tv) {
1095f2645f80SAndrea Shepard     EVBASE_ACQUIRE_LOCK(base, th_base_lock);
1096f2645f80SAndrea Shepard     rv = evutil_gettime_monotonic_(&(base->monotonic_timer), tv);
1097f2645f80SAndrea Shepard     EVBASE_RELEASE_LOCK(base, th_base_lock);
1098f2645f80SAndrea Shepard   }
1099f2645f80SAndrea Shepard 
1100f2645f80SAndrea Shepard   return rv;
1101f2645f80SAndrea Shepard }
1102f2645f80SAndrea Shepard 
11033b2022efSNiels Provos const char **
event_get_supported_methods(void)11048acb80b4SNick Mathewson event_get_supported_methods(void)
11053b2022efSNiels Provos {
1106f8b527e6SNick Mathewson 	static const char **methods = NULL;
11073b2022efSNiels Provos 	const struct eventop **method;
11083b2022efSNiels Provos 	const char **tmp;
11093b2022efSNiels Provos 	int i = 0, k;
11103b2022efSNiels Provos 
11113b2022efSNiels Provos 	/* count all methods */
11122deb3ce0SNiels Provos 	for (method = &eventops[0]; *method != NULL; ++method) {
11133b2022efSNiels Provos 		++i;
11142deb3ce0SNiels Provos 	}
11153b2022efSNiels Provos 
11163b2022efSNiels Provos 	/* allocate one more than we need for the NULL pointer */
111718a8cfacSNick Mathewson 	tmp = mm_calloc((i + 1), sizeof(char *));
11183b2022efSNiels Provos 	if (tmp == NULL)
11193b2022efSNiels Provos 		return (NULL);
11203b2022efSNiels Provos 
11213b2022efSNiels Provos 	/* populate the array with the supported methods */
11222deb3ce0SNiels Provos 	for (k = 0, i = 0; eventops[k] != NULL; ++k) {
11232deb3ce0SNiels Provos 		tmp[i++] = eventops[k]->name;
11242deb3ce0SNiels Provos 	}
11253b2022efSNiels Provos 	tmp[i] = NULL;
11263b2022efSNiels Provos 
11272deb3ce0SNiels Provos 	if (methods != NULL)
1128ebf29455SNick Mathewson 		mm_free((char**)methods);
11292deb3ce0SNiels Provos 
11303b2022efSNiels Provos 	methods = tmp;
11313b2022efSNiels Provos 
11323b2022efSNiels Provos 	return (methods);
11333b2022efSNiels Provos }
11343b2022efSNiels Provos 
11353f56e364SNiels Provos struct event_config *
event_config_new(void)11363f56e364SNiels Provos event_config_new(void)
11373f56e364SNiels Provos {
1138faa756c7SNick Mathewson 	struct event_config *cfg = mm_calloc(1, sizeof(*cfg));
11393f56e364SNiels Provos 
11403f56e364SNiels Provos 	if (cfg == NULL)
11413f56e364SNiels Provos 		return (NULL);
11423f56e364SNiels Provos 
11433f56e364SNiels Provos 	TAILQ_INIT(&cfg->entries);
1144fd4de1e7SNick Mathewson 	cfg->max_dispatch_interval.tv_sec = -1;
11459fa56bdfSNick Mathewson 	cfg->max_dispatch_callbacks = INT_MAX;
1146a37a0c0eSNick Mathewson 	cfg->limit_callbacks_after_prio = 1;
11473f56e364SNiels Provos 
11483f56e364SNiels Provos 	return (cfg);
11493f56e364SNiels Provos }
11503f56e364SNiels Provos 
11513f56e364SNiels Provos static void
event_config_entry_free(struct event_config_entry * entry)11523f56e364SNiels Provos event_config_entry_free(struct event_config_entry *entry)
11533f56e364SNiels Provos {
11543f56e364SNiels Provos 	if (entry->avoid_method != NULL)
11553f56e364SNiels Provos 		mm_free((char *)entry->avoid_method);
11563f56e364SNiels Provos 	mm_free(entry);
11573f56e364SNiels Provos }
11583f56e364SNiels Provos 
11593f56e364SNiels Provos void
event_config_free(struct event_config * cfg)11603f56e364SNiels Provos event_config_free(struct event_config *cfg)
11613f56e364SNiels Provos {
11623f56e364SNiels Provos 	struct event_config_entry *entry;
11633f56e364SNiels Provos 
11643f56e364SNiels Provos 	while ((entry = TAILQ_FIRST(&cfg->entries)) != NULL) {
11653f56e364SNiels Provos 		TAILQ_REMOVE(&cfg->entries, entry, next);
11663f56e364SNiels Provos 		event_config_entry_free(entry);
11673f56e364SNiels Provos 	}
116877867244SNiels Provos 	mm_free(cfg);
11693f56e364SNiels Provos }
11703f56e364SNiels Provos 
11712ebfd3baSNick Mathewson int
event_config_set_flag(struct event_config * cfg,int flag)1172b73ad7bcSNick Mathewson event_config_set_flag(struct event_config *cfg, int flag)
11732ebfd3baSNick Mathewson {
11742ebfd3baSNick Mathewson 	if (!cfg)
11752ebfd3baSNick Mathewson 		return -1;
11762ebfd3baSNick Mathewson 	cfg->flags |= flag;
11772ebfd3baSNick Mathewson 	return 0;
11782ebfd3baSNick Mathewson }
11792ebfd3baSNick Mathewson 
11803f56e364SNiels Provos int
event_config_avoid_method(struct event_config * cfg,const char * method)11813f56e364SNiels Provos event_config_avoid_method(struct event_config *cfg, const char *method)
11823f56e364SNiels Provos {
11833f56e364SNiels Provos 	struct event_config_entry *entry = mm_malloc(sizeof(*entry));
11843f56e364SNiels Provos 	if (entry == NULL)
11853f56e364SNiels Provos 		return (-1);
11863f56e364SNiels Provos 
11873f56e364SNiels Provos 	if ((entry->avoid_method = mm_strdup(method)) == NULL) {
11883f56e364SNiels Provos 		mm_free(entry);
11893f56e364SNiels Provos 		return (-1);
11903f56e364SNiels Provos 	}
11913f56e364SNiels Provos 
11923f56e364SNiels Provos 	TAILQ_INSERT_TAIL(&cfg->entries, entry, next);
11933f56e364SNiels Provos 
11943f56e364SNiels Provos 	return (0);
11953f56e364SNiels Provos }
11963f56e364SNiels Provos 
1197fa6c304dSNiels Provos int
event_config_require_features(struct event_config * cfg,int features)119805965921SNick Mathewson event_config_require_features(struct event_config *cfg,
1199b73ad7bcSNick Mathewson     int features)
120005965921SNick Mathewson {
120105965921SNick Mathewson 	if (!cfg)
120205965921SNick Mathewson 		return (-1);
120305965921SNick Mathewson 	cfg->require_features = features;
120405965921SNick Mathewson 	return (0);
120505965921SNick Mathewson }
120605965921SNick Mathewson 
120705965921SNick Mathewson int
event_config_set_num_cpus_hint(struct event_config * cfg,int cpus)12082447fe88SChristopher Davis event_config_set_num_cpus_hint(struct event_config *cfg, int cpus)
12092447fe88SChristopher Davis {
12102447fe88SChristopher Davis 	if (!cfg)
12112447fe88SChristopher Davis 		return (-1);
12122447fe88SChristopher Davis 	cfg->n_cpus_hint = cpus;
12132447fe88SChristopher Davis 	return (0);
12142447fe88SChristopher Davis }
12152447fe88SChristopher Davis 
12162447fe88SChristopher Davis int
event_config_set_max_dispatch_interval(struct event_config * cfg,const struct timeval * max_interval,int max_callbacks,int min_priority)1217fd4de1e7SNick Mathewson event_config_set_max_dispatch_interval(struct event_config *cfg,
1218a37a0c0eSNick Mathewson     const struct timeval *max_interval, int max_callbacks, int min_priority)
1219fd4de1e7SNick Mathewson {
1220fd4de1e7SNick Mathewson 	if (max_interval)
1221fd4de1e7SNick Mathewson 		memcpy(&cfg->max_dispatch_interval, max_interval,
1222fd4de1e7SNick Mathewson 		    sizeof(struct timeval));
1223fd4de1e7SNick Mathewson 	else
1224fd4de1e7SNick Mathewson 		cfg->max_dispatch_interval.tv_sec = -1;
12259fa56bdfSNick Mathewson 	cfg->max_dispatch_callbacks =
12269fa56bdfSNick Mathewson 	    max_callbacks >= 0 ? max_callbacks : INT_MAX;
1227c0e425abSNick Mathewson 	if (min_priority < 0)
1228c0e425abSNick Mathewson 		min_priority = 0;
1229a37a0c0eSNick Mathewson 	cfg->limit_callbacks_after_prio = min_priority;
1230fd4de1e7SNick Mathewson 	return (0);
1231fd4de1e7SNick Mathewson }
1232fd4de1e7SNick Mathewson 
1233fd4de1e7SNick Mathewson int
event_priority_init(int npriorities)123425646045SNiels Provos event_priority_init(int npriorities)
123525646045SNiels Provos {
123625646045SNiels Provos 	return event_base_priority_init(current_base, npriorities);
123725646045SNiels Provos }
123825646045SNiels Provos 
123925646045SNiels Provos int
event_base_priority_init(struct event_base * base,int npriorities)124025646045SNiels Provos event_base_priority_init(struct event_base *base, int npriorities)
1241fa6c304dSNiels Provos {
12423c55b5eeSNick Mathewson 	int i, r;
12433c55b5eeSNick Mathewson 	r = -1;
12443c55b5eeSNick Mathewson 
12453c55b5eeSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
1246fa6c304dSNiels Provos 
1247b06b2649SNick Mathewson 	if (N_ACTIVE_CALLBACKS(base) || npriorities < 1
1248b4886ec8SNick Mathewson 	    || npriorities >= EVENT_MAX_PRIORITIES)
12493c55b5eeSNick Mathewson 		goto err;
1250fa6c304dSNiels Provos 
12511c927b7dSNiels Provos 	if (npriorities == base->nactivequeues)
12523c55b5eeSNick Mathewson 		goto ok;
12531c927b7dSNiels Provos 
12541c927b7dSNiels Provos 	if (base->nactivequeues) {
125549868b61SNick Mathewson 		mm_free(base->activequeues);
125674871cacSNick Mathewson 		base->nactivequeues = 0;
1257fa6c304dSNiels Provos 	}
1258fa6c304dSNiels Provos 
1259fa6c304dSNiels Provos 	/* Allocate our priority queues */
1260cba59e53SNick Mathewson 	base->activequeues = (struct evcallback_list *)
1261cba59e53SNick Mathewson 	  mm_calloc(npriorities, sizeof(struct evcallback_list));
126274871cacSNick Mathewson 	if (base->activequeues == NULL) {
126374871cacSNick Mathewson 		event_warn("%s: calloc", __func__);
12643c55b5eeSNick Mathewson 		goto err;
126574871cacSNick Mathewson 	}
12668773c4c9SNiels Provos 	base->nactivequeues = npriorities;
1267fa6c304dSNiels Provos 
12688773c4c9SNiels Provos 	for (i = 0; i < base->nactivequeues; ++i) {
126974871cacSNick Mathewson 		TAILQ_INIT(&base->activequeues[i]);
1270fa6c304dSNiels Provos 	}
1271fa6c304dSNiels Provos 
12723c55b5eeSNick Mathewson ok:
12733c55b5eeSNick Mathewson 	r = 0;
12743c55b5eeSNick Mathewson err:
12753c55b5eeSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
12763c55b5eeSNick Mathewson 	return (r);
1277aa6567feSNiels Provos }
1278aa6567feSNiels Provos 
1279ee3a4ee8SAlexander Drozdov int
event_base_get_npriorities(struct event_base * base)1280ee3a4ee8SAlexander Drozdov event_base_get_npriorities(struct event_base *base)
1281ee3a4ee8SAlexander Drozdov {
12823c55b5eeSNick Mathewson 
12833c55b5eeSNick Mathewson 	int n;
1284c46cb9c3SNick Mathewson 	if (base == NULL)
1285c46cb9c3SNick Mathewson 		base = current_base;
1286c46cb9c3SNick Mathewson 
12873c55b5eeSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
12883c55b5eeSNick Mathewson 	n = base->nactivequeues;
12893c55b5eeSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
12903c55b5eeSNick Mathewson 	return (n);
1291ee3a4ee8SAlexander Drozdov }
1292ee3a4ee8SAlexander Drozdov 
12930fa107d8SMobai Zhang int
event_base_get_num_events(struct event_base * base,unsigned int type)12940fa107d8SMobai Zhang event_base_get_num_events(struct event_base *base, unsigned int type)
12950fa107d8SMobai Zhang {
12960fa107d8SMobai Zhang 	int r = 0;
12970fa107d8SMobai Zhang 
12980fa107d8SMobai Zhang 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
12990fa107d8SMobai Zhang 
13000fa107d8SMobai Zhang 	if (type & EVENT_BASE_COUNT_ACTIVE)
13010fa107d8SMobai Zhang 		r += base->event_count_active;
13020fa107d8SMobai Zhang 
13030fa107d8SMobai Zhang 	if (type & EVENT_BASE_COUNT_VIRTUAL)
13040fa107d8SMobai Zhang 		r += base->virtual_event_count;
13050fa107d8SMobai Zhang 
13060fa107d8SMobai Zhang 	if (type & EVENT_BASE_COUNT_ADDED)
13070fa107d8SMobai Zhang 		r += base->event_count;
13080fa107d8SMobai Zhang 
13090fa107d8SMobai Zhang 	EVBASE_RELEASE_LOCK(base, th_base_lock);
13100fa107d8SMobai Zhang 
13110fa107d8SMobai Zhang 	return r;
13120fa107d8SMobai Zhang }
13130fa107d8SMobai Zhang 
13145173bef5SAndrew Sweeney int
event_base_get_max_events(struct event_base * base,unsigned int type,int clear)13155173bef5SAndrew Sweeney event_base_get_max_events(struct event_base *base, unsigned int type, int clear)
13165173bef5SAndrew Sweeney {
13175173bef5SAndrew Sweeney 	int r = 0;
13185173bef5SAndrew Sweeney 
13195173bef5SAndrew Sweeney 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
13205173bef5SAndrew Sweeney 
13215173bef5SAndrew Sweeney 	if (type & EVENT_BASE_COUNT_ACTIVE) {
13225173bef5SAndrew Sweeney 		r += base->event_count_active_max;
13235173bef5SAndrew Sweeney 		if (clear)
13245173bef5SAndrew Sweeney 			base->event_count_active_max = 0;
13255173bef5SAndrew Sweeney 	}
13265173bef5SAndrew Sweeney 
13275173bef5SAndrew Sweeney 	if (type & EVENT_BASE_COUNT_VIRTUAL) {
13285173bef5SAndrew Sweeney 		r += base->virtual_event_count_max;
13295173bef5SAndrew Sweeney 		if (clear)
13305173bef5SAndrew Sweeney 			base->virtual_event_count_max = 0;
13315173bef5SAndrew Sweeney 	}
13325173bef5SAndrew Sweeney 
13335173bef5SAndrew Sweeney 	if (type & EVENT_BASE_COUNT_ADDED) {
13345173bef5SAndrew Sweeney 		r += base->event_count_max;
13355173bef5SAndrew Sweeney 		if (clear)
13365173bef5SAndrew Sweeney 			base->event_count_max = 0;
13375173bef5SAndrew Sweeney 	}
13385173bef5SAndrew Sweeney 
13395173bef5SAndrew Sweeney 	EVBASE_RELEASE_LOCK(base, th_base_lock);
13405173bef5SAndrew Sweeney 
13415173bef5SAndrew Sweeney 	return r;
13425173bef5SAndrew Sweeney }
13435173bef5SAndrew Sweeney 
1344cdd4c490SNick Mathewson /* Returns true iff we're currently watching any events. */
134559e8e959SNick Mathewson static int
event_haveevents(struct event_base * base)13468773c4c9SNiels Provos event_haveevents(struct event_base *base)
1347aa6567feSNiels Provos {
13486b22e74aSNick Mathewson 	/* Caller must hold th_base_lock */
134976f7e7aeSChristopher Davis 	return (base->virtual_event_count > 0 || base->event_count > 0);
1350aa6567feSNiels Provos }
1351aa6567feSNiels Provos 
1352cdd4c490SNick Mathewson /* "closure" function called when processing active signal events */
1353a2a7d1d1SNick Mathewson static inline void
event_signal_closure(struct event_base * base,struct event * ev)13548c750eafSNiels Provos event_signal_closure(struct event_base *base, struct event *ev)
13558c750eafSNiels Provos {
13568c750eafSNiels Provos 	short ncalls;
13574e8eb6a5SNick Mathewson 	int should_break;
13588c750eafSNiels Provos 
13598c750eafSNiels Provos 	/* Allows deletes to work */
13608c750eafSNiels Provos 	ncalls = ev->ev_ncalls;
136111f36a5fSNick Mathewson 	if (ncalls != 0)
13628c750eafSNiels Provos 		ev->ev_pncalls = &ncalls;
1363e2642f0aSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
13648c750eafSNiels Provos 	while (ncalls) {
13658c750eafSNiels Provos 		ncalls--;
13668c750eafSNiels Provos 		ev->ev_ncalls = ncalls;
1367fc5e0a23SNick Mathewson 		if (ncalls == 0)
1368fc5e0a23SNick Mathewson 			ev->ev_pncalls = NULL;
1369f0325167SNick Mathewson 		(*ev->ev_callback)(ev->ev_fd, ev->ev_res, ev->ev_arg);
13704e8eb6a5SNick Mathewson 
13714e8eb6a5SNick Mathewson 		EVBASE_ACQUIRE_LOCK(base, th_base_lock);
13724e8eb6a5SNick Mathewson 		should_break = base->event_break;
13734e8eb6a5SNick Mathewson 		EVBASE_RELEASE_LOCK(base, th_base_lock);
13744e8eb6a5SNick Mathewson 
137511f36a5fSNick Mathewson 		if (should_break) {
137611f36a5fSNick Mathewson 			if (ncalls != 0)
137711f36a5fSNick Mathewson 				ev->ev_pncalls = NULL;
13788c750eafSNiels Provos 			return;
13798c750eafSNiels Provos 		}
13808c750eafSNiels Provos 	}
138111f36a5fSNick Mathewson }
13828c750eafSNiels Provos 
1383cdd4c490SNick Mathewson /* Common timeouts are special timeouts that are handled as queues rather than
1384cdd4c490SNick Mathewson  * in the minheap.  This is more efficient than the minheap if we happen to
1385cdd4c490SNick Mathewson  * know that we're going to get several thousands of timeout events all with
1386cdd4c490SNick Mathewson  * the same timeout value.
1387cdd4c490SNick Mathewson  *
1388cdd4c490SNick Mathewson  * Since all our timeout handling code assumes timevals can be copied,
1389cdd4c490SNick Mathewson  * assigned, etc, we can't use "magic pointer" to encode these common
1390cdd4c490SNick Mathewson  * timeouts.  Searching through a list to see if every timeout is common could
1391cdd4c490SNick Mathewson  * also get inefficient.  Instead, we take advantage of the fact that tv_usec
1392cdd4c490SNick Mathewson  * is 32 bits long, but only uses 20 of those bits (since it can never be over
1393cdd4c490SNick Mathewson  * 999999.)  We use the top bits to encode 4 bites of magic number, and 8 bits
1394cdd4c490SNick Mathewson  * of index into the event_base's aray of common timeouts.
1395cdd4c490SNick Mathewson  */
1396cdd4c490SNick Mathewson 
13975b18f130SNick Mathewson #define MICROSECONDS_MASK       COMMON_TIMEOUT_MICROSECONDS_MASK
1398693c24efSNick Mathewson #define COMMON_TIMEOUT_IDX_MASK 0x0ff00000
1399693c24efSNick Mathewson #define COMMON_TIMEOUT_IDX_SHIFT 20
1400693c24efSNick Mathewson #define COMMON_TIMEOUT_MASK     0xf0000000
1401693c24efSNick Mathewson #define COMMON_TIMEOUT_MAGIC    0x50000000
1402693c24efSNick Mathewson 
1403693c24efSNick Mathewson #define COMMON_TIMEOUT_IDX(tv) \
1404693c24efSNick Mathewson 	(((tv)->tv_usec & COMMON_TIMEOUT_IDX_MASK)>>COMMON_TIMEOUT_IDX_SHIFT)
1405693c24efSNick Mathewson 
1406cdd4c490SNick Mathewson /** Return true iff if 'tv' is a common timeout in 'base' */
1407693c24efSNick Mathewson static inline int
is_common_timeout(const struct timeval * tv,const struct event_base * base)1408693c24efSNick Mathewson is_common_timeout(const struct timeval *tv,
1409693c24efSNick Mathewson     const struct event_base *base)
1410693c24efSNick Mathewson {
1411693c24efSNick Mathewson 	int idx;
1412693c24efSNick Mathewson 	if ((tv->tv_usec & COMMON_TIMEOUT_MASK) != COMMON_TIMEOUT_MAGIC)
1413693c24efSNick Mathewson 		return 0;
1414693c24efSNick Mathewson 	idx = COMMON_TIMEOUT_IDX(tv);
1415693c24efSNick Mathewson 	return idx < base->n_common_timeouts;
1416693c24efSNick Mathewson }
1417693c24efSNick Mathewson 
1418e88079a8SNick Mathewson /* True iff tv1 and tv2 have the same common-timeout index, or if neither
1419e88079a8SNick Mathewson  * one is a common timeout. */
1420e88079a8SNick Mathewson static inline int
is_same_common_timeout(const struct timeval * tv1,const struct timeval * tv2)1421e88079a8SNick Mathewson is_same_common_timeout(const struct timeval *tv1, const struct timeval *tv2)
1422e88079a8SNick Mathewson {
1423e88079a8SNick Mathewson 	return (tv1->tv_usec & ~MICROSECONDS_MASK) ==
1424e88079a8SNick Mathewson 	    (tv2->tv_usec & ~MICROSECONDS_MASK);
1425e88079a8SNick Mathewson }
1426e88079a8SNick Mathewson 
1427cdd4c490SNick Mathewson /** Requires that 'tv' is a common timeout.  Return the corresponding
1428cdd4c490SNick Mathewson  * common_timeout_list. */
1429693c24efSNick Mathewson static inline struct common_timeout_list *
get_common_timeout_list(struct event_base * base,const struct timeval * tv)1430693c24efSNick Mathewson get_common_timeout_list(struct event_base *base, const struct timeval *tv)
1431693c24efSNick Mathewson {
1432693c24efSNick Mathewson 	return base->common_timeout_queues[COMMON_TIMEOUT_IDX(tv)];
1433693c24efSNick Mathewson }
1434693c24efSNick Mathewson 
1435cdd4c490SNick Mathewson #if 0
1436693c24efSNick Mathewson static inline int
1437693c24efSNick Mathewson common_timeout_ok(const struct timeval *tv,
1438693c24efSNick Mathewson     struct event_base *base)
1439693c24efSNick Mathewson {
1440693c24efSNick Mathewson 	const struct timeval *expect =
1441693c24efSNick Mathewson 	    &get_common_timeout_list(base, tv)->duration;
1442693c24efSNick Mathewson 	return tv->tv_sec == expect->tv_sec &&
1443693c24efSNick Mathewson 	    tv->tv_usec == expect->tv_usec;
1444693c24efSNick Mathewson }
1445cdd4c490SNick Mathewson #endif
1446693c24efSNick Mathewson 
1447cdd4c490SNick Mathewson /* Add the timeout for the first event in given common timeout list to the
1448cdd4c490SNick Mathewson  * event_base's minheap. */
1449693c24efSNick Mathewson static void
common_timeout_schedule(struct common_timeout_list * ctl,const struct timeval * now,struct event * head)1450693c24efSNick Mathewson common_timeout_schedule(struct common_timeout_list *ctl,
1451693c24efSNick Mathewson     const struct timeval *now, struct event *head)
1452693c24efSNick Mathewson {
1453693c24efSNick Mathewson 	struct timeval timeout = head->ev_timeout;
1454693c24efSNick Mathewson 	timeout.tv_usec &= MICROSECONDS_MASK;
14559cd5acb5SNick Mathewson 	event_add_nolock_(&ctl->timeout_event, &timeout, 1);
1456693c24efSNick Mathewson }
1457693c24efSNick Mathewson 
1458cdd4c490SNick Mathewson /* Callback: invoked when the timeout for a common timeout queue triggers.
1459cdd4c490SNick Mathewson  * This means that (at least) the first event in that queue should be run,
1460cdd4c490SNick Mathewson  * and the timeout should be rescheduled if there are more events. */
1461693c24efSNick Mathewson static void
common_timeout_callback(evutil_socket_t fd,short what,void * arg)1462693c24efSNick Mathewson common_timeout_callback(evutil_socket_t fd, short what, void *arg)
1463693c24efSNick Mathewson {
1464693c24efSNick Mathewson 	struct timeval now;
1465693c24efSNick Mathewson 	struct common_timeout_list *ctl = arg;
1466693c24efSNick Mathewson 	struct event_base *base = ctl->base;
1467693c24efSNick Mathewson 	struct event *ev = NULL;
146876cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
1469693c24efSNick Mathewson 	gettime(base, &now);
1470693c24efSNick Mathewson 	while (1) {
1471693c24efSNick Mathewson 		ev = TAILQ_FIRST(&ctl->events);
1472693c24efSNick Mathewson 		if (!ev || ev->ev_timeout.tv_sec > now.tv_sec ||
1473693c24efSNick Mathewson 		    (ev->ev_timeout.tv_sec == now.tv_sec &&
1474693c24efSNick Mathewson 			(ev->ev_timeout.tv_usec&MICROSECONDS_MASK) > now.tv_usec))
1475693c24efSNick Mathewson 			break;
14768eedeabeSNick Mathewson 		event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
14778ac3c4c2SNick Mathewson 		event_active_nolock_(ev, EV_TIMEOUT, 1);
1478693c24efSNick Mathewson 	}
1479693c24efSNick Mathewson 	if (ev)
1480693c24efSNick Mathewson 		common_timeout_schedule(ctl, &now, ev);
148176cd2b70SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
1482693c24efSNick Mathewson }
1483693c24efSNick Mathewson 
1484693c24efSNick Mathewson #define MAX_COMMON_TIMEOUTS 256
1485693c24efSNick Mathewson 
1486693c24efSNick Mathewson const struct timeval *
event_base_init_common_timeout(struct event_base * base,const struct timeval * duration)1487693c24efSNick Mathewson event_base_init_common_timeout(struct event_base *base,
1488693c24efSNick Mathewson     const struct timeval *duration)
1489693c24efSNick Mathewson {
1490693c24efSNick Mathewson 	int i;
1491693c24efSNick Mathewson 	struct timeval tv;
1492693c24efSNick Mathewson 	const struct timeval *result=NULL;
1493693c24efSNick Mathewson 	struct common_timeout_list *new_ctl;
1494693c24efSNick Mathewson 
149576cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
1496693c24efSNick Mathewson 	if (duration->tv_usec > 1000000) {
1497693c24efSNick Mathewson 		memcpy(&tv, duration, sizeof(struct timeval));
1498693c24efSNick Mathewson 		if (is_common_timeout(duration, base))
1499693c24efSNick Mathewson 			tv.tv_usec &= MICROSECONDS_MASK;
1500693c24efSNick Mathewson 		tv.tv_sec += tv.tv_usec / 1000000;
1501693c24efSNick Mathewson 		tv.tv_usec %= 1000000;
1502693c24efSNick Mathewson 		duration = &tv;
1503693c24efSNick Mathewson 	}
1504693c24efSNick Mathewson 	for (i = 0; i < base->n_common_timeouts; ++i) {
1505693c24efSNick Mathewson 		const struct common_timeout_list *ctl =
1506693c24efSNick Mathewson 		    base->common_timeout_queues[i];
1507693c24efSNick Mathewson 		if (duration->tv_sec == ctl->duration.tv_sec &&
1508693c24efSNick Mathewson 		    duration->tv_usec ==
1509693c24efSNick Mathewson 		    (ctl->duration.tv_usec & MICROSECONDS_MASK)) {
1510693c24efSNick Mathewson 			EVUTIL_ASSERT(is_common_timeout(&ctl->duration, base));
1511693c24efSNick Mathewson 			result = &ctl->duration;
1512693c24efSNick Mathewson 			goto done;
1513693c24efSNick Mathewson 		}
1514693c24efSNick Mathewson 	}
1515693c24efSNick Mathewson 	if (base->n_common_timeouts == MAX_COMMON_TIMEOUTS) {
151619c71e74SNick Mathewson 		event_warnx("%s: Too many common timeouts already in use; "
1517693c24efSNick Mathewson 		    "we only support %d per event_base", __func__,
1518693c24efSNick Mathewson 		    MAX_COMMON_TIMEOUTS);
1519693c24efSNick Mathewson 		goto done;
1520693c24efSNick Mathewson 	}
1521693c24efSNick Mathewson 	if (base->n_common_timeouts_allocated == base->n_common_timeouts) {
1522693c24efSNick Mathewson 		int n = base->n_common_timeouts < 16 ? 16 :
1523693c24efSNick Mathewson 		    base->n_common_timeouts*2;
1524693c24efSNick Mathewson 		struct common_timeout_list **newqueues =
1525693c24efSNick Mathewson 		    mm_realloc(base->common_timeout_queues,
1526693c24efSNick Mathewson 			n*sizeof(struct common_timeout_queue *));
1527693c24efSNick Mathewson 		if (!newqueues) {
1528693c24efSNick Mathewson 			event_warn("%s: realloc",__func__);
1529693c24efSNick Mathewson 			goto done;
1530693c24efSNick Mathewson 		}
1531693c24efSNick Mathewson 		base->n_common_timeouts_allocated = n;
1532693c24efSNick Mathewson 		base->common_timeout_queues = newqueues;
1533693c24efSNick Mathewson 	}
1534693c24efSNick Mathewson 	new_ctl = mm_calloc(1, sizeof(struct common_timeout_list));
1535693c24efSNick Mathewson 	if (!new_ctl) {
1536693c24efSNick Mathewson 		event_warn("%s: calloc",__func__);
1537693c24efSNick Mathewson 		goto done;
1538693c24efSNick Mathewson 	}
1539693c24efSNick Mathewson 	TAILQ_INIT(&new_ctl->events);
1540693c24efSNick Mathewson 	new_ctl->duration.tv_sec = duration->tv_sec;
1541693c24efSNick Mathewson 	new_ctl->duration.tv_usec =
1542693c24efSNick Mathewson 	    duration->tv_usec | COMMON_TIMEOUT_MAGIC |
1543693c24efSNick Mathewson 	    (base->n_common_timeouts << COMMON_TIMEOUT_IDX_SHIFT);
1544693c24efSNick Mathewson 	evtimer_assign(&new_ctl->timeout_event, base,
1545693c24efSNick Mathewson 	    common_timeout_callback, new_ctl);
1546693c24efSNick Mathewson 	new_ctl->timeout_event.ev_flags |= EVLIST_INTERNAL;
1547693c24efSNick Mathewson 	event_priority_set(&new_ctl->timeout_event, 0);
1548693c24efSNick Mathewson 	new_ctl->base = base;
1549693c24efSNick Mathewson 	base->common_timeout_queues[base->n_common_timeouts++] = new_ctl;
1550693c24efSNick Mathewson 	result = &new_ctl->duration;
1551693c24efSNick Mathewson 
1552693c24efSNick Mathewson done:
1553693c24efSNick Mathewson 	if (result)
1554693c24efSNick Mathewson 		EVUTIL_ASSERT(is_common_timeout(result, base));
1555693c24efSNick Mathewson 
155676cd2b70SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
1557693c24efSNick Mathewson 	return result;
1558693c24efSNick Mathewson }
1559693c24efSNick Mathewson 
1560cdd4c490SNick Mathewson /* Closure function invoked when we're activating a persistent event. */
1561e88079a8SNick Mathewson static inline void
event_persist_closure(struct event_base * base,struct event * ev)1562e88079a8SNick Mathewson event_persist_closure(struct event_base *base, struct event *ev)
1563e88079a8SNick Mathewson {
15642ea15ed0SJohn Ohl 	void (*evcb_callback)(evutil_socket_t, short, void *);
15652ea15ed0SJohn Ohl 
15663c7d6fcaSvjpai         // Other fields of *ev that must be stored before executing
15673c7d6fcaSvjpai         evutil_socket_t evcb_fd;
15683c7d6fcaSvjpai         short evcb_res;
15693c7d6fcaSvjpai         void *evcb_arg;
15703c7d6fcaSvjpai 
1571e88079a8SNick Mathewson 	/* reschedule the persistent event if we have a timeout. */
1572e88079a8SNick Mathewson 	if (ev->ev_io_timeout.tv_sec || ev->ev_io_timeout.tv_usec) {
157338ec0a77SNick Mathewson 		/* If there was a timeout, we want it to run at an interval of
157438ec0a77SNick Mathewson 		 * ev_io_timeout after the last time it was _scheduled_ for,
157538ec0a77SNick Mathewson 		 * not ev_io_timeout after _now_.  If it fired for another
157638ec0a77SNick Mathewson 		 * reason, though, the timeout ought to start ticking _now_. */
1577bec22b41SNick Mathewson 		struct timeval run_at, relative_to, delay, now;
1578bec22b41SNick Mathewson 		ev_uint32_t usec_mask = 0;
1579e88079a8SNick Mathewson 		EVUTIL_ASSERT(is_same_common_timeout(&ev->ev_timeout,
1580e88079a8SNick Mathewson 			&ev->ev_io_timeout));
1581bec22b41SNick Mathewson 		gettime(base, &now);
1582e88079a8SNick Mathewson 		if (is_common_timeout(&ev->ev_timeout, base)) {
1583e88079a8SNick Mathewson 			delay = ev->ev_io_timeout;
1584e88079a8SNick Mathewson 			usec_mask = delay.tv_usec & ~MICROSECONDS_MASK;
1585e88079a8SNick Mathewson 			delay.tv_usec &= MICROSECONDS_MASK;
158638ec0a77SNick Mathewson 			if (ev->ev_res & EV_TIMEOUT) {
158738ec0a77SNick Mathewson 				relative_to = ev->ev_timeout;
158838ec0a77SNick Mathewson 				relative_to.tv_usec &= MICROSECONDS_MASK;
158938ec0a77SNick Mathewson 			} else {
1590bec22b41SNick Mathewson 				relative_to = now;
159138ec0a77SNick Mathewson 			}
1592e88079a8SNick Mathewson 		} else {
1593bec22b41SNick Mathewson 			delay = ev->ev_io_timeout;
159438ec0a77SNick Mathewson 			if (ev->ev_res & EV_TIMEOUT) {
159538ec0a77SNick Mathewson 				relative_to = ev->ev_timeout;
159638ec0a77SNick Mathewson 			} else {
1597bec22b41SNick Mathewson 				relative_to = now;
159838ec0a77SNick Mathewson 			}
1599e88079a8SNick Mathewson 		}
1600bec22b41SNick Mathewson 		evutil_timeradd(&relative_to, &delay, &run_at);
1601dfd808cbSNick Mathewson 		if (evutil_timercmp(&run_at, &now, <)) {
1602dfd808cbSNick Mathewson 			/* Looks like we missed at least one invocation due to
1603dfd808cbSNick Mathewson 			 * a clock jump, not running the event loop for a
1604dfd808cbSNick Mathewson 			 * while, really slow callbacks, or
1605dfd808cbSNick Mathewson 			 * something. Reschedule relative to now.
1606dfd808cbSNick Mathewson 			 */
1607dfd808cbSNick Mathewson 			evutil_timeradd(&now, &delay, &run_at);
1608dfd808cbSNick Mathewson 		}
1609dfd808cbSNick Mathewson 		run_at.tv_usec |= usec_mask;
16109cd5acb5SNick Mathewson 		event_add_nolock_(ev, &run_at, 1);
1611e88079a8SNick Mathewson 	}
161240830f16SJohn Ohl 
16132ea15ed0SJohn Ohl 	// Save our callback before we release the lock
16143c7d6fcaSvjpai 	evcb_callback = ev->ev_callback;
16153c7d6fcaSvjpai         evcb_fd = ev->ev_fd;
16163c7d6fcaSvjpai         evcb_res = ev->ev_res;
16173c7d6fcaSvjpai         evcb_arg = ev->ev_arg;
161840830f16SJohn Ohl 
161940830f16SJohn Ohl 	// Release the lock
1620e2642f0aSNick Mathewson  	EVBASE_RELEASE_LOCK(base, th_base_lock);
162140830f16SJohn Ohl 
162240830f16SJohn Ohl 	// Execute the callback
16233c7d6fcaSvjpai         (evcb_callback)(evcb_fd, evcb_res, evcb_arg);
1624e88079a8SNick Mathewson }
1625e88079a8SNick Mathewson 
1626fa6c304dSNiels Provos /*
1627e3d82497SNick Mathewson   Helper for event_process_active to process all the events in a single queue,
1628e3d82497SNick Mathewson   releasing the lock as we go.  This function requires that the lock be held
1629e3d82497SNick Mathewson   when it's invoked.  Returns -1 if we get a signal or an event_break that
1630e3d82497SNick Mathewson   means we should stop processing any active events now.  Otherwise returns
1631cba59e53SNick Mathewson   the number of non-internal event_callbacks that we processed.
1632fa6c304dSNiels Provos */
1633e3d82497SNick Mathewson static int
event_process_active_single_queue(struct event_base * base,struct evcallback_list * activeq,int max_to_process,const struct timeval * endtime)1634e3d82497SNick Mathewson event_process_active_single_queue(struct event_base *base,
1635cba59e53SNick Mathewson     struct evcallback_list *activeq,
1636fd4de1e7SNick Mathewson     int max_to_process, const struct timeval *endtime)
1637aa6567feSNiels Provos {
1638cba59e53SNick Mathewson 	struct event_callback *evcb;
1639e3d82497SNick Mathewson 	int count = 0;
1640fa6c304dSNiels Provos 
16412e36dbe1SNick Mathewson 	EVUTIL_ASSERT(activeq != NULL);
16424922f342SNiels Provos 
1643cba59e53SNick Mathewson 	for (evcb = TAILQ_FIRST(activeq); evcb; evcb = TAILQ_FIRST(activeq)) {
1644cba59e53SNick Mathewson 		struct event *ev=NULL;
1645cba59e53SNick Mathewson 		if (evcb->evcb_flags & EVLIST_INIT) {
1646cba59e53SNick Mathewson 			ev = event_callback_to_event(evcb);
1647cba59e53SNick Mathewson 
16488eedeabeSNick Mathewson 			if (ev->ev_events & EV_PERSIST || ev->ev_flags & EVLIST_FINALIZING)
1649cba59e53SNick Mathewson 				event_queue_remove_active(base, evcb);
165003589ccbSNiels Provos 			else
16518eedeabeSNick Mathewson 				event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
165260e4c067SNiels Provos 			event_debug((
1653b1b69ac7SDiego Giagio 			    "event_process_active: event: %p, %s%s%scall %p",
165460e4c067SNiels Provos 			    ev,
165560e4c067SNiels Provos 			    ev->ev_res & EV_READ ? "EV_READ " : " ",
165660e4c067SNiels Provos 			    ev->ev_res & EV_WRITE ? "EV_WRITE " : " ",
1657b1b69ac7SDiego Giagio 			    ev->ev_res & EV_CLOSED ? "EV_CLOSED " : " ",
165860e4c067SNiels Provos 			    ev->ev_callback));
1659cba59e53SNick Mathewson 		} else {
1660cba59e53SNick Mathewson 			event_queue_remove_active(base, evcb);
1661cba59e53SNick Mathewson 			event_debug(("event_process_active: event_callback %p, "
1662cba59e53SNick Mathewson 				"closure %d, call %p",
1663ae2b84b2SNick Mathewson 				evcb, evcb->evcb_closure, evcb->evcb_cb_union.evcb_callback));
1664cba59e53SNick Mathewson 		}
166560e4c067SNiels Provos 
1666cba59e53SNick Mathewson 		if (!(evcb->evcb_flags & EVLIST_INTERNAL))
1667cba59e53SNick Mathewson 			++count;
1668cba59e53SNick Mathewson 
1669cba59e53SNick Mathewson 
1670cba59e53SNick Mathewson 		base->current_event = evcb;
167113dad99cSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
1672e0972c21SNick Mathewson 		base->current_event_waiters = 0;
1673e0972c21SNick Mathewson #endif
16746b4b77a2SNick Mathewson 
1675cba59e53SNick Mathewson 		switch (evcb->evcb_closure) {
1676cba59e53SNick Mathewson 		case EV_CLOSURE_EVENT_SIGNAL:
16771b065d07SNick Mathewson 			EVUTIL_ASSERT(ev != NULL);
1678b4886ec8SNick Mathewson 			event_signal_closure(base, ev);
1679b4886ec8SNick Mathewson 			break;
1680cba59e53SNick Mathewson 		case EV_CLOSURE_EVENT_PERSIST:
16811b065d07SNick Mathewson 			EVUTIL_ASSERT(ev != NULL);
1682b4886ec8SNick Mathewson 			event_persist_closure(base, ev);
1683b4886ec8SNick Mathewson 			break;
16842ea15ed0SJohn Ohl 		case EV_CLOSURE_EVENT: {
16853cc0eaceSJohn Ohl 			void (*evcb_callback)(evutil_socket_t, short, void *);
168643d92a6dSJames Synge 			short res;
16871b065d07SNick Mathewson 			EVUTIL_ASSERT(ev != NULL);
16883cc0eaceSJohn Ohl 			evcb_callback = *ev->ev_callback;
168943d92a6dSJames Synge 			res = ev->ev_res;
1690e2642f0aSNick Mathewson 			EVBASE_RELEASE_LOCK(base, th_base_lock);
169143d92a6dSJames Synge 			evcb_callback(ev->ev_fd, res, ev->ev_arg);
16922ea15ed0SJohn Ohl 		}
1693b4886ec8SNick Mathewson 		break;
16942ea15ed0SJohn Ohl 		case EV_CLOSURE_CB_SELF: {
16952ea15ed0SJohn Ohl 			void (*evcb_selfcb)(struct event_callback *, void *) = evcb->evcb_cb_union.evcb_selfcb;
1696ae2b84b2SNick Mathewson 			EVBASE_RELEASE_LOCK(base, th_base_lock);
16972ea15ed0SJohn Ohl 			evcb_selfcb(evcb, evcb->evcb_arg);
16982ea15ed0SJohn Ohl 		}
1699ae2b84b2SNick Mathewson 		break;
17008eedeabeSNick Mathewson 		case EV_CLOSURE_EVENT_FINALIZE:
17012ea15ed0SJohn Ohl 		case EV_CLOSURE_EVENT_FINALIZE_FREE: {
170298059721SNick Mathewson 			void (*evcb_evfinalize)(struct event *, void *);
1703ec99dd82SNick Mathewson 			int evcb_closure = evcb->evcb_closure;
17041c06985aSNick Mathewson 			EVUTIL_ASSERT(ev != NULL);
170598059721SNick Mathewson 			base->current_event = NULL;
170698059721SNick Mathewson 			evcb_evfinalize = ev->ev_evcallback.evcb_cb_union.evcb_evfinalize;
17078eedeabeSNick Mathewson 			EVUTIL_ASSERT((evcb->evcb_flags & EVLIST_FINALIZING));
17088eedeabeSNick Mathewson 			EVBASE_RELEASE_LOCK(base, th_base_lock);
170969b5c647SNick Mathewson 			event_debug_note_teardown_(ev);
17108ccd8f56SJan Kasiak 			evcb_evfinalize(ev, ev->ev_arg);
1711ec99dd82SNick Mathewson 			if (evcb_closure == EV_CLOSURE_EVENT_FINALIZE_FREE)
17128eedeabeSNick Mathewson 				mm_free(ev);
17132ea15ed0SJohn Ohl 		}
17148eedeabeSNick Mathewson 		break;
17152ea15ed0SJohn Ohl 		case EV_CLOSURE_CB_FINALIZE: {
17162ea15ed0SJohn Ohl 			void (*evcb_cbfinalize)(struct event_callback *, void *) = evcb->evcb_cb_union.evcb_cbfinalize;
17178eedeabeSNick Mathewson 			base->current_event = NULL;
17188eedeabeSNick Mathewson 			EVUTIL_ASSERT((evcb->evcb_flags & EVLIST_FINALIZING));
17198eedeabeSNick Mathewson 			EVBASE_RELEASE_LOCK(base, th_base_lock);
17202ea15ed0SJohn Ohl 			evcb_cbfinalize(evcb, evcb->evcb_arg);
17212ea15ed0SJohn Ohl 		}
17228eedeabeSNick Mathewson 		break;
1723cba59e53SNick Mathewson 		default:
1724cba59e53SNick Mathewson 			EVUTIL_ASSERT(0);
1725b4886ec8SNick Mathewson 		}
1726b4886ec8SNick Mathewson 
172776cd2b70SNick Mathewson 		EVBASE_ACQUIRE_LOCK(base, th_base_lock);
17286b4b77a2SNick Mathewson 		base->current_event = NULL;
172913dad99cSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
1730e0972c21SNick Mathewson 		if (base->current_event_waiters) {
1731e0972c21SNick Mathewson 			base->current_event_waiters = 0;
1732e0972c21SNick Mathewson 			EVTHREAD_COND_BROADCAST(base->current_event_cond);
1733e0972c21SNick Mathewson 		}
1734e0972c21SNick Mathewson #endif
17356b4b77a2SNick Mathewson 
17360e63e72aSNick Mathewson 		if (base->event_break)
1737e3d82497SNick Mathewson 			return -1;
1738fd4de1e7SNick Mathewson 		if (count >= max_to_process)
1739fd4de1e7SNick Mathewson 			return count;
1740fd4de1e7SNick Mathewson 		if (count && endtime) {
1741fd4de1e7SNick Mathewson 			struct timeval now;
17423c63edd1SNick Mathewson 			update_time_cache(base);
17433c63edd1SNick Mathewson 			gettime(base, &now);
1744fd4de1e7SNick Mathewson 			if (evutil_timercmp(&now, endtime, >=))
1745fd4de1e7SNick Mathewson 				return count;
1746fd4de1e7SNick Mathewson 		}
17472bfda401SNick Mathewson 		if (base->event_continue)
17482bfda401SNick Mathewson 			break;
1749aa6567feSNiels Provos 	}
1750e3d82497SNick Mathewson 	return count;
1751e3d82497SNick Mathewson }
1752e3d82497SNick Mathewson 
1753cdd4c490SNick Mathewson /*
1754e3d82497SNick Mathewson  * Active events are stored in priority queues.  Lower priorities are always
1755e3d82497SNick Mathewson  * process before higher priorities.  Low priority events can starve high
1756e3d82497SNick Mathewson  * priority ones.
1757e3d82497SNick Mathewson  */
1758e3d82497SNick Mathewson 
17590617a818SNick Mathewson static int
event_process_active(struct event_base * base)1760e3d82497SNick Mathewson event_process_active(struct event_base *base)
1761e3d82497SNick Mathewson {
17626b22e74aSNick Mathewson 	/* Caller must hold th_base_lock */
1763cba59e53SNick Mathewson 	struct evcallback_list *activeq = NULL;
17640617a818SNick Mathewson 	int i, c = 0;
1765fd4de1e7SNick Mathewson 	const struct timeval *endtime;
1766fd4de1e7SNick Mathewson 	struct timeval tv;
1767fd4de1e7SNick Mathewson 	const int maxcb = base->max_dispatch_callbacks;
1768a37a0c0eSNick Mathewson 	const int limit_after_prio = base->limit_callbacks_after_prio;
1769fd4de1e7SNick Mathewson 	if (base->max_dispatch_time.tv_sec >= 0) {
17703c63edd1SNick Mathewson 		update_time_cache(base);
17713c63edd1SNick Mathewson 		gettime(base, &tv);
1772fd4de1e7SNick Mathewson 		evutil_timeradd(&base->max_dispatch_time, &tv, &tv);
1773fd4de1e7SNick Mathewson 		endtime = &tv;
1774fd4de1e7SNick Mathewson 	} else {
1775fd4de1e7SNick Mathewson 		endtime = NULL;
1776fd4de1e7SNick Mathewson 	}
1777e3d82497SNick Mathewson 
1778e3d82497SNick Mathewson 	for (i = 0; i < base->nactivequeues; ++i) {
177974871cacSNick Mathewson 		if (TAILQ_FIRST(&base->activequeues[i]) != NULL) {
17802bfda401SNick Mathewson 			base->event_running_priority = i;
178174871cacSNick Mathewson 			activeq = &base->activequeues[i];
1782a37a0c0eSNick Mathewson 			if (i < limit_after_prio)
1783a9866aa8SAlexander Drozdov 				c = event_process_active_single_queue(base, activeq,
1784a9866aa8SAlexander Drozdov 				    INT_MAX, NULL);
1785a9866aa8SAlexander Drozdov 			else
1786fd4de1e7SNick Mathewson 				c = event_process_active_single_queue(base, activeq,
1787fd4de1e7SNick Mathewson 				    maxcb, endtime);
17882bfda401SNick Mathewson 			if (c < 0) {
1789581b5bebSNick Mathewson 				goto done;
17902bfda401SNick Mathewson 			} else if (c > 0)
1791e3d82497SNick Mathewson 				break; /* Processed a real event; do not
1792e3d82497SNick Mathewson 					* consider lower-priority events */
1793e3d82497SNick Mathewson 			/* If we get here, all of the events we processed
1794e3d82497SNick Mathewson 			 * were internal.  Continue. */
1795e3d82497SNick Mathewson 		}
1796e3d82497SNick Mathewson 	}
1797558de9b3SNiels Provos 
1798581b5bebSNick Mathewson done:
17992bfda401SNick Mathewson 	base->event_running_priority = -1;
1800581b5bebSNick Mathewson 
18010617a818SNick Mathewson 	return c;
180203589ccbSNiels Provos }
1803aa6567feSNiels Provos 
1804cd699abfSNiels Provos /*
1805e3fd294aSNick Mathewson  * Wait continuously for events.  We exit only if no events are left.
1806cd699abfSNiels Provos  */
1807cd699abfSNiels Provos 
1808aa6567feSNiels Provos int
event_dispatch(void)1809aa6567feSNiels Provos event_dispatch(void)
1810aa6567feSNiels Provos {
1811aa6567feSNiels Provos 	return (event_loop(0));
1812aa6567feSNiels Provos }
1813aa6567feSNiels Provos 
181425646045SNiels Provos int
event_base_dispatch(struct event_base * event_base)181525646045SNiels Provos event_base_dispatch(struct event_base *event_base)
181625646045SNiels Provos {
181725646045SNiels Provos 	return (event_base_loop(event_base, 0));
181825646045SNiels Provos }
181925646045SNiels Provos 
18208ab61891SNiels Provos const char *
event_base_get_method(const struct event_base * base)1821d38a7a19SNick Mathewson event_base_get_method(const struct event_base *base)
18228ab61891SNiels Provos {
18232e36dbe1SNick Mathewson 	EVUTIL_ASSERT(base);
18248ab61891SNiels Provos 	return (base->evsel->name);
18258ab61891SNiels Provos }
18268ab61891SNiels Provos 
1827cdd4c490SNick Mathewson /** Callback: used to implement event_base_loopexit by telling the event_base
1828cdd4c490SNick Mathewson  * that it's time to exit its loop. */
1829cd699abfSNiels Provos static void
event_loopexit_cb(evutil_socket_t fd,short what,void * arg)18301120f04fSNick Mathewson event_loopexit_cb(evutil_socket_t fd, short what, void *arg)
1831cd699abfSNiels Provos {
18328773c4c9SNiels Provos 	struct event_base *base = arg;
18338773c4c9SNiels Provos 	base->event_gotterm = 1;
1834cd699abfSNiels Provos }
1835cd699abfSNiels Provos 
1836cd699abfSNiels Provos int
event_loopexit(const struct timeval * tv)18378b66f1bdSNiels Provos event_loopexit(const struct timeval *tv)
1838cd699abfSNiels Provos {
18398773c4c9SNiels Provos 	return (event_once(-1, EV_TIMEOUT, event_loopexit_cb,
18408773c4c9SNiels Provos 		    current_base, tv));
1841cd699abfSNiels Provos }
1842cd699abfSNiels Provos 
1843720f7fccSNiels Provos int
event_base_loopexit(struct event_base * event_base,const struct timeval * tv)18448b66f1bdSNiels Provos event_base_loopexit(struct event_base *event_base, const struct timeval *tv)
1845720f7fccSNiels Provos {
184641b7cbc3SNiels Provos 	return (event_base_once(event_base, -1, EV_TIMEOUT, event_loopexit_cb,
1847720f7fccSNiels Provos 		    event_base, tv));
1848720f7fccSNiels Provos }
1849720f7fccSNiels Provos 
18501c23e219SNick Mathewson int
event_loopbreak(void)18511c23e219SNick Mathewson event_loopbreak(void)
18521c23e219SNick Mathewson {
18531c23e219SNick Mathewson 	return (event_base_loopbreak(current_base));
18541c23e219SNick Mathewson }
18551c23e219SNick Mathewson 
18561c23e219SNick Mathewson int
event_base_loopbreak(struct event_base * event_base)18571c23e219SNick Mathewson event_base_loopbreak(struct event_base *event_base)
18581c23e219SNick Mathewson {
1859c7a06bfaSNick Mathewson 	int r = 0;
18601c23e219SNick Mathewson 	if (event_base == NULL)
18611c23e219SNick Mathewson 		return (-1);
18621c23e219SNick Mathewson 
186376cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
18641c23e219SNick Mathewson 	event_base->event_break = 1;
1865c3e9fcf6SNick Mathewson 
1866c7a06bfaSNick Mathewson 	if (EVBASE_NEED_NOTIFY(event_base)) {
1867c7a06bfaSNick Mathewson 		r = evthread_notify_base(event_base);
1868c3e9fcf6SNick Mathewson 	} else {
1869c7a06bfaSNick Mathewson 		r = (0);
18701c23e219SNick Mathewson 	}
1871c7a06bfaSNick Mathewson 	EVBASE_RELEASE_LOCK(event_base, th_base_lock);
1872c7a06bfaSNick Mathewson 	return r;
1873ec4cfa33SNick Mathewson }
18741c23e219SNick Mathewson 
1875d5b640fcSNick Mathewson int
event_base_loopcontinue(struct event_base * event_base)18767d6aa5eeSNick Mathewson event_base_loopcontinue(struct event_base *event_base)
18777d6aa5eeSNick Mathewson {
18787d6aa5eeSNick Mathewson 	int r = 0;
18797d6aa5eeSNick Mathewson 	if (event_base == NULL)
18807d6aa5eeSNick Mathewson 		return (-1);
18817d6aa5eeSNick Mathewson 
18827d6aa5eeSNick Mathewson 	EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
18837d6aa5eeSNick Mathewson 	event_base->event_continue = 1;
18847d6aa5eeSNick Mathewson 
18857d6aa5eeSNick Mathewson 	if (EVBASE_NEED_NOTIFY(event_base)) {
18867d6aa5eeSNick Mathewson 		r = evthread_notify_base(event_base);
18877d6aa5eeSNick Mathewson 	} else {
18887d6aa5eeSNick Mathewson 		r = (0);
18897d6aa5eeSNick Mathewson 	}
18907d6aa5eeSNick Mathewson 	EVBASE_RELEASE_LOCK(event_base, th_base_lock);
18917d6aa5eeSNick Mathewson 	return r;
18927d6aa5eeSNick Mathewson }
18937d6aa5eeSNick Mathewson 
18947d6aa5eeSNick Mathewson int
event_base_got_break(struct event_base * event_base)1895d5b640fcSNick Mathewson event_base_got_break(struct event_base *event_base)
1896d5b640fcSNick Mathewson {
1897d5b640fcSNick Mathewson 	int res;
189876cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
1899d5b640fcSNick Mathewson 	res = event_base->event_break;
190076cd2b70SNick Mathewson 	EVBASE_RELEASE_LOCK(event_base, th_base_lock);
1901d5b640fcSNick Mathewson 	return res;
1902d5b640fcSNick Mathewson }
19031c23e219SNick Mathewson 
1904d5b640fcSNick Mathewson int
event_base_got_exit(struct event_base * event_base)1905d5b640fcSNick Mathewson event_base_got_exit(struct event_base *event_base)
1906d5b640fcSNick Mathewson {
1907d5b640fcSNick Mathewson 	int res;
190876cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(event_base, th_base_lock);
1909d5b640fcSNick Mathewson 	res = event_base->event_gotterm;
191076cd2b70SNick Mathewson 	EVBASE_RELEASE_LOCK(event_base, th_base_lock);
1911d5b640fcSNick Mathewson 	return res;
1912d5b640fcSNick Mathewson }
19131c23e219SNick Mathewson 
19141c23e219SNick Mathewson /* not thread safe */
19158773c4c9SNiels Provos 
1916aa6567feSNiels Provos int
event_loop(int flags)1917aa6567feSNiels Provos event_loop(int flags)
1918aa6567feSNiels Provos {
191925646045SNiels Provos 	return event_base_loop(current_base, flags);
19208773c4c9SNiels Provos }
19218773c4c9SNiels Provos 
19228773c4c9SNiels Provos int
event_base_loop(struct event_base * base,int flags)192325646045SNiels Provos event_base_loop(struct event_base *base, int flags)
19248773c4c9SNiels Provos {
19258773c4c9SNiels Provos 	const struct eventop *evsel = base->evsel;
1926aa6567feSNiels Provos 	struct timeval tv;
19273ad6b47eSNiels Provos 	struct timeval *tv_p;
1928da1718b2SNick Mathewson 	int res, done, retval = 0;
1929aa6567feSNiels Provos 
19306b22e74aSNick Mathewson 	/* Grab the lock.  We will release it inside evsel.dispatch, and again
19316b22e74aSNick Mathewson 	 * as we invoke user callbacks. */
193276cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
19336b22e74aSNick Mathewson 
1934b557b175SNick Mathewson 	if (base->running_loop) {
193519c71e74SNick Mathewson 		event_warnx("%s: reentrant invocation.  Only one event_base_loop"
1936b557b175SNick Mathewson 		    " can run on each event_base at once.", __func__);
1937b557b175SNick Mathewson 		EVBASE_RELEASE_LOCK(base, th_base_lock);
1938b557b175SNick Mathewson 		return -1;
1939b557b175SNick Mathewson 	}
1940b557b175SNick Mathewson 
1941b557b175SNick Mathewson 	base->running_loop = 1;
1942b557b175SNick Mathewson 
1943ab96b5f3SNick Mathewson 	clear_time_cache(base);
194431cfe526SNiels Provos 
1945720bd933SNick Mathewson 	if (base->sig.ev_signal_added && base->sig.ev_n_signals_added)
19468ac3c4c2SNick Mathewson 		evsig_set_base_(base);
1947720bd933SNick Mathewson 
19489c9f0651SNiels Provos 	done = 0;
1949ec35eb55SNick Mathewson 
195068120d9bSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
1951ec35eb55SNick Mathewson 	base->th_owner_id = EVTHREAD_GET_ID();
1952ec35eb55SNick Mathewson #endif
1953ec35eb55SNick Mathewson 
1954d5b640fcSNick Mathewson 	base->event_gotterm = base->event_break = 0;
1955d5b640fcSNick Mathewson 
19569c9f0651SNiels Provos 	while (!done) {
19572bfda401SNick Mathewson 		base->event_continue = 0;
1958c0e425abSNick Mathewson 		base->n_deferreds_queued = 0;
19592bfda401SNick Mathewson 
1960cd699abfSNiels Provos 		/* Terminate the loop if we have been asked to */
19618773c4c9SNiels Provos 		if (base->event_gotterm) {
19625908bd72SNiels Provos 			break;
1963cd699abfSNiels Provos 		}
1964cd699abfSNiels Provos 
19651c23e219SNick Mathewson 		if (base->event_break) {
19661c23e219SNick Mathewson 			break;
19671c23e219SNick Mathewson 		}
19681c23e219SNick Mathewson 
19693ad6b47eSNiels Provos 		tv_p = &tv;
1970b06b2649SNick Mathewson 		if (!N_ACTIVE_CALLBACKS(base) && !(flags & EVLOOP_NONBLOCK)) {
19713ad6b47eSNiels Provos 			timeout_next(base, &tv_p);
19723ad6b47eSNiels Provos 		} else {
19733ad6b47eSNiels Provos 			/*
19743ad6b47eSNiels Provos 			 * if we have active events, we just poll new events
19753ad6b47eSNiels Provos 			 * without waiting.
19763ad6b47eSNiels Provos 			 */
1977f74e7258SNick Mathewson 			evutil_timerclear(&tv);
19783ad6b47eSNiels Provos 		}
1979aa6567feSNiels Provos 
1980aa6567feSNiels Provos 		/* If we have no events, we just exit */
1981084e68f3SNick Mathewson 		if (0==(flags&EVLOOP_NO_EXIT_ON_EMPTY) &&
1982084e68f3SNick Mathewson 		    !event_haveevents(base) && !N_ACTIVE_CALLBACKS(base)) {
1983720f7fccSNiels Provos 			event_debug(("%s: no events registered.", __func__));
1984da1718b2SNick Mathewson 			retval = 1;
1985da1718b2SNick Mathewson 			goto done;
1986720f7fccSNiels Provos 		}
1987aa6567feSNiels Provos 
1988745a63dbSNick Mathewson 		event_queue_make_later_events_active(base);
1989745a63dbSNick Mathewson 
1990ab96b5f3SNick Mathewson 		clear_time_cache(base);
199145e6fb0dSNiels Provos 
199202b2b4d1SNiels Provos 		res = evsel->dispatch(base, tv_p);
1993aa6567feSNiels Provos 
1994da1718b2SNick Mathewson 		if (res == -1) {
1995da1718b2SNick Mathewson 			event_debug(("%s: dispatch returned unsuccessfully.",
1996da1718b2SNick Mathewson 				__func__));
1997da1718b2SNick Mathewson 			retval = -1;
1998da1718b2SNick Mathewson 			goto done;
1999da1718b2SNick Mathewson 		}
2000ab96b5f3SNick Mathewson 
2001ab96b5f3SNick Mathewson 		update_time_cache(base);
2002aa6567feSNiels Provos 
20038773c4c9SNiels Provos 		timeout_process(base);
2004aa6567feSNiels Provos 
2005b06b2649SNick Mathewson 		if (N_ACTIVE_CALLBACKS(base)) {
20060617a818SNick Mathewson 			int n = event_process_active(base);
20070617a818SNick Mathewson 			if ((flags & EVLOOP_ONCE)
20082d5e1bd0SNick Mathewson 			    && N_ACTIVE_CALLBACKS(base) == 0
20090617a818SNick Mathewson 			    && n != 0)
2010aa6567feSNiels Provos 				done = 1;
2011aa6567feSNiels Provos 		} else if (flags & EVLOOP_NONBLOCK)
2012aa6567feSNiels Provos 			done = 1;
2013aa6567feSNiels Provos 	}
2014da1718b2SNick Mathewson 	event_debug(("%s: asked to terminate loop.", __func__));
2015aa6567feSNiels Provos 
2016da1718b2SNick Mathewson done:
2017ab96b5f3SNick Mathewson 	clear_time_cache(base);
2018b557b175SNick Mathewson 	base->running_loop = 0;
20194fe25cefSNiels Provos 
202076cd2b70SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
20216b22e74aSNick Mathewson 
2022da1718b2SNick Mathewson 	return (retval);
2023aa6567feSNiels Provos }
2024aa6567feSNiels Provos 
2025cdd4c490SNick Mathewson /* One-time callback to implement event_base_once: invokes the user callback,
2026cdd4c490SNick Mathewson  * then deletes the allocated storage */
2027ec2c1db4SNiels Provos static void
event_once_cb(evutil_socket_t fd,short events,void * arg)20281120f04fSNick Mathewson event_once_cb(evutil_socket_t fd, short events, void *arg)
2029ec2c1db4SNiels Provos {
2030ec2c1db4SNiels Provos 	struct event_once *eonce = arg;
2031ec2c1db4SNiels Provos 
2032ec2c1db4SNiels Provos 	(*eonce->cb)(fd, events, eonce->arg);
2033f2703b2eSNick Mathewson 	EVBASE_ACQUIRE_LOCK(eonce->ev.ev_base, th_base_lock);
2034c17dd591SNick Mathewson 	LIST_REMOVE(eonce, next_once);
2035f2703b2eSNick Mathewson 	EVBASE_RELEASE_LOCK(eonce->ev.ev_base, th_base_lock);
2036a19b4a05SNick Mathewson 	event_debug_unassign(&eonce->ev);
203749868b61SNick Mathewson 	mm_free(eonce);
2038ec2c1db4SNiels Provos }
2039ec2c1db4SNiels Provos 
204041b7cbc3SNiels Provos /* not threadsafe, event scheduled once. */
2041ec2c1db4SNiels Provos int
event_once(evutil_socket_t fd,short events,void (* callback)(evutil_socket_t,short,void *),void * arg,const struct timeval * tv)20421120f04fSNick Mathewson event_once(evutil_socket_t fd, short events,
20431120f04fSNick Mathewson     void (*callback)(evutil_socket_t, short, void *),
20448b66f1bdSNiels Provos     void *arg, const struct timeval *tv)
2045ec2c1db4SNiels Provos {
204641b7cbc3SNiels Provos 	return event_base_once(current_base, fd, events, callback, arg, tv);
204741b7cbc3SNiels Provos }
204841b7cbc3SNiels Provos 
204941b7cbc3SNiels Provos /* Schedules an event once */
205041b7cbc3SNiels Provos int
event_base_once(struct event_base * base,evutil_socket_t fd,short events,void (* callback)(evutil_socket_t,short,void *),void * arg,const struct timeval * tv)20511120f04fSNick Mathewson event_base_once(struct event_base *base, evutil_socket_t fd, short events,
20521120f04fSNick Mathewson     void (*callback)(evutil_socket_t, short, void *),
20538b66f1bdSNiels Provos     void *arg, const struct timeval *tv)
205441b7cbc3SNiels Provos {
2055ec2c1db4SNiels Provos 	struct event_once *eonce;
2056181007b9SNiels Provos 	int res = 0;
2057c17dd591SNick Mathewson 	int activate = 0;
2058ec2c1db4SNiels Provos 
2059*2e9ceb16Schenguolong 	if (!base)
2060*2e9ceb16Schenguolong 		return (-1);
2061*2e9ceb16Schenguolong 
206237bc3466SNick Mathewson 	/* We cannot support signals that just fire once, or persistent
206337bc3466SNick Mathewson 	 * events. */
206437bc3466SNick Mathewson 	if (events & (EV_SIGNAL|EV_PERSIST))
2065fbf01c7fSNiels Provos 		return (-1);
2066fbf01c7fSNiels Provos 
206749868b61SNick Mathewson 	if ((eonce = mm_calloc(1, sizeof(struct event_once))) == NULL)
2068ec2c1db4SNiels Provos 		return (-1);
2069ec2c1db4SNiels Provos 
2070da971e5fSNiels Provos 	eonce->cb = callback;
2071da971e5fSNiels Provos 	eonce->arg = arg;
2072da971e5fSNiels Provos 
2073b1b69ac7SDiego Giagio 	if ((events & (EV_TIMEOUT|EV_SIGNAL|EV_READ|EV_WRITE|EV_CLOSED)) == EV_TIMEOUT) {
2074181007b9SNiels Provos 		evtimer_assign(&eonce->ev, base, event_once_cb, eonce);
207535c5c955SNick Mathewson 
207635c5c955SNick Mathewson 		if (tv == NULL || ! evutil_timerisset(tv)) {
207735c5c955SNick Mathewson 			/* If the event is going to become active immediately,
207835c5c955SNick Mathewson 			 * don't put it on the timeout queue.  This is one
207935c5c955SNick Mathewson 			 * idiom for scheduling a callback, so let's make
208035c5c955SNick Mathewson 			 * it fast (and order-preserving). */
2081c17dd591SNick Mathewson 			activate = 1;
208235c5c955SNick Mathewson 		}
2083b1b69ac7SDiego Giagio 	} else if (events & (EV_READ|EV_WRITE|EV_CLOSED)) {
2084b1b69ac7SDiego Giagio 		events &= EV_READ|EV_WRITE|EV_CLOSED;
2085ec2c1db4SNiels Provos 
2086181007b9SNiels Provos 		event_assign(&eonce->ev, base, fd, events, event_once_cb, eonce);
2087ec2c1db4SNiels Provos 	} else {
2088ec2c1db4SNiels Provos 		/* Bad event combination */
208949868b61SNick Mathewson 		mm_free(eonce);
2090ec2c1db4SNiels Provos 		return (-1);
2091ec2c1db4SNiels Provos 	}
2092ec2c1db4SNiels Provos 
2093c17dd591SNick Mathewson 	if (res == 0) {
2094c17dd591SNick Mathewson 		EVBASE_ACQUIRE_LOCK(base, th_base_lock);
2095c17dd591SNick Mathewson 		if (activate)
2096c17dd591SNick Mathewson 			event_active_nolock_(&eonce->ev, EV_TIMEOUT, 1);
2097c17dd591SNick Mathewson 		else
2098c17dd591SNick Mathewson 			res = event_add_nolock_(&eonce->ev, tv, 0);
2099c17dd591SNick Mathewson 
2100d6989659SNiels Provos 		if (res != 0) {
210149868b61SNick Mathewson 			mm_free(eonce);
2102d6989659SNiels Provos 			return (res);
2103c17dd591SNick Mathewson 		} else {
2104c17dd591SNick Mathewson 			LIST_INSERT_HEAD(&base->once_events, eonce, next_once);
2105c17dd591SNick Mathewson 		}
2106c17dd591SNick Mathewson 		EVBASE_RELEASE_LOCK(base, th_base_lock);
2107d6989659SNiels Provos 	}
2108ec2c1db4SNiels Provos 
2109ec2c1db4SNiels Provos 	return (0);
2110ec2c1db4SNiels Provos }
2111ec2c1db4SNiels Provos 
2112e9ee1057SNick Mathewson int
event_assign(struct event * ev,struct event_base * base,evutil_socket_t fd,short events,void (* callback)(evutil_socket_t,short,void *),void * arg)2113e9ee1057SNick Mathewson event_assign(struct event *ev, struct event_base *base, evutil_socket_t fd, short events, void (*callback)(evutil_socket_t, short, void *), void *arg)
2114aa6567feSNiels Provos {
2115d386dc89SNick Mathewson 	if (!base)
2116d386dc89SNick Mathewson 		base = current_base;
211709a1906aSRoss Lagerwall 	if (arg == &event_self_cbarg_ptr_)
211809a1906aSRoss Lagerwall 		arg = ev;
2119cd17c3acSNick Mathewson 
2120a39898f3SAzat Khuzhin 	if (!(events & EV_SIGNAL))
2121a39898f3SAzat Khuzhin 		event_debug_assert_socket_nonblocking_(fd);
2122cb9da0bfSNick Mathewson 	event_debug_assert_not_added_(ev);
2123cd17c3acSNick Mathewson 
2124d386dc89SNick Mathewson 	ev->ev_base = base;
21258773c4c9SNiels Provos 
2126aa6567feSNiels Provos 	ev->ev_callback = callback;
2127aa6567feSNiels Provos 	ev->ev_arg = arg;
2128aa6567feSNiels Provos 	ev->ev_fd = fd;
2129aa6567feSNiels Provos 	ev->ev_events = events;
213003589ccbSNiels Provos 	ev->ev_res = 0;
213103589ccbSNiels Provos 	ev->ev_flags = EVLIST_INIT;
21324ec4cddeSNiels Provos 	ev->ev_ncalls = 0;
21334ec4cddeSNiels Provos 	ev->ev_pncalls = NULL;
2134fa6c304dSNiels Provos 
21358c750eafSNiels Provos 	if (events & EV_SIGNAL) {
2136b1b69ac7SDiego Giagio 		if ((events & (EV_READ|EV_WRITE|EV_CLOSED)) != 0) {
2137e9ee1057SNick Mathewson 			event_warnx("%s: EV_SIGNAL is not compatible with "
2138b1b69ac7SDiego Giagio 			    "EV_READ, EV_WRITE or EV_CLOSED", __func__);
2139e9ee1057SNick Mathewson 			return -1;
2140e9ee1057SNick Mathewson 		}
2141cba59e53SNick Mathewson 		ev->ev_closure = EV_CLOSURE_EVENT_SIGNAL;
21428c750eafSNiels Provos 	} else {
214356ea4687SNiels Provos 		if (events & EV_PERSIST) {
21440fd0255fSNick Mathewson 			evutil_timerclear(&ev->ev_io_timeout);
2145cba59e53SNick Mathewson 			ev->ev_closure = EV_CLOSURE_EVENT_PERSIST;
214656ea4687SNiels Provos 		} else {
2147cba59e53SNick Mathewson 			ev->ev_closure = EV_CLOSURE_EVENT;
21488c750eafSNiels Provos 		}
214956ea4687SNiels Provos 	}
21508c750eafSNiels Provos 
21518ac3c4c2SNick Mathewson 	min_heap_elem_init_(ev);
215230ae40ccSNiels Provos 
2153e9ee1057SNick Mathewson 	if (base != NULL) {
2154fa6c304dSNiels Provos 		/* by default, we put new events into the middle priority */
2155d386dc89SNick Mathewson 		ev->ev_pri = base->nactivequeues / 2;
21568773c4c9SNiels Provos 	}
2157cd17c3acSNick Mathewson 
2158cb9da0bfSNick Mathewson 	event_debug_note_setup_(ev);
2159cd17c3acSNick Mathewson 
2160e9ee1057SNick Mathewson 	return 0;
2161e9ee1057SNick Mathewson }
21628773c4c9SNiels Provos 
21638773c4c9SNiels Provos int
event_base_set(struct event_base * base,struct event * ev)21648773c4c9SNiels Provos event_base_set(struct event_base *base, struct event *ev)
21658773c4c9SNiels Provos {
21668773c4c9SNiels Provos 	/* Only innocent events may be assigned to a different base */
216703589ccbSNiels Provos 	if (ev->ev_flags != EVLIST_INIT)
21688773c4c9SNiels Provos 		return (-1);
21698773c4c9SNiels Provos 
2170cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
2171cd17c3acSNick Mathewson 
21728773c4c9SNiels Provos 	ev->ev_base = base;
217303589ccbSNiels Provos 	ev->ev_pri = base->nactivequeues/2;
21748773c4c9SNiels Provos 
21758773c4c9SNiels Provos 	return (0);
2176fa6c304dSNiels Provos }
2177fa6c304dSNiels Provos 
2178181007b9SNiels Provos void
event_set(struct event * ev,evutil_socket_t fd,short events,void (* callback)(evutil_socket_t,short,void *),void * arg)2179e9ee1057SNick Mathewson event_set(struct event *ev, evutil_socket_t fd, short events,
2180e9ee1057SNick Mathewson 	  void (*callback)(evutil_socket_t, short, void *), void *arg)
218194fb4d0aSNick Mathewson {
2182e9ee1057SNick Mathewson 	int r;
2183d386dc89SNick Mathewson 	r = event_assign(ev, current_base, fd, events, callback, arg);
2184e9ee1057SNick Mathewson 	EVUTIL_ASSERT(r == 0);
218594fb4d0aSNick Mathewson }
218694fb4d0aSNick Mathewson 
2187ed36e6abSRoss Lagerwall void *
event_self_cbarg(void)2188ed36e6abSRoss Lagerwall event_self_cbarg(void)
2189ed36e6abSRoss Lagerwall {
2190ed36e6abSRoss Lagerwall 	return &event_self_cbarg_ptr_;
2191ed36e6abSRoss Lagerwall }
2192ed36e6abSRoss Lagerwall 
219394fb4d0aSNick Mathewson struct event *
event_base_get_running_event(struct event_base * base)2194c5732fddSNick Mathewson event_base_get_running_event(struct event_base *base)
2195c5732fddSNick Mathewson {
2196c5732fddSNick Mathewson 	struct event *ev = NULL;
2197c5732fddSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
2198cba59e53SNick Mathewson 	if (EVBASE_IN_THREAD(base)) {
2199cba59e53SNick Mathewson 		struct event_callback *evcb = base->current_event;
2200cba59e53SNick Mathewson 		if (evcb->evcb_flags & EVLIST_INIT)
2201cba59e53SNick Mathewson 			ev = event_callback_to_event(evcb);
2202cba59e53SNick Mathewson 	}
2203c5732fddSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
2204c5732fddSNick Mathewson 	return ev;
2205c5732fddSNick Mathewson }
2206c5732fddSNick Mathewson 
2207c5732fddSNick Mathewson struct event *
event_new(struct event_base * base,evutil_socket_t fd,short events,void (* cb)(evutil_socket_t,short,void *),void * arg)220894fb4d0aSNick Mathewson event_new(struct event_base *base, evutil_socket_t fd, short events, void (*cb)(evutil_socket_t, short, void *), void *arg)
220994fb4d0aSNick Mathewson {
221094fb4d0aSNick Mathewson 	struct event *ev;
221194fb4d0aSNick Mathewson 	ev = mm_malloc(sizeof(struct event));
2212181007b9SNiels Provos 	if (ev == NULL)
2213181007b9SNiels Provos 		return (NULL);
2214e9ee1057SNick Mathewson 	if (event_assign(ev, base, fd, events, cb, arg) < 0) {
2215e9ee1057SNick Mathewson 		mm_free(ev);
2216e9ee1057SNick Mathewson 		return (NULL);
2217e9ee1057SNick Mathewson 	}
2218181007b9SNiels Provos 
2219181007b9SNiels Provos 	return (ev);
222094fb4d0aSNick Mathewson }
222194fb4d0aSNick Mathewson 
222294fb4d0aSNick Mathewson void
event_free(struct event * ev)222394fb4d0aSNick Mathewson event_free(struct event *ev)
222494fb4d0aSNick Mathewson {
22258eedeabeSNick Mathewson 	/* This is disabled, so that events which have been finalized be a
22268eedeabeSNick Mathewson 	 * valid target for event_free(). That's */
22278eedeabeSNick Mathewson 	// event_debug_assert_is_setup_(ev);
2228cd17c3acSNick Mathewson 
2229fe2e7307SNick Mathewson 	/* make sure that this event won't be coming back to haunt us. */
223094fb4d0aSNick Mathewson 	event_del(ev);
2231cb9da0bfSNick Mathewson 	event_debug_note_teardown_(ev);
223294fb4d0aSNick Mathewson 	mm_free(ev);
2233cd17c3acSNick Mathewson 
2234cd17c3acSNick Mathewson }
2235cd17c3acSNick Mathewson 
2236cd17c3acSNick Mathewson void
event_debug_unassign(struct event * ev)2237cd17c3acSNick Mathewson event_debug_unassign(struct event *ev)
2238cd17c3acSNick Mathewson {
2239cb9da0bfSNick Mathewson 	event_debug_assert_not_added_(ev);
2240cb9da0bfSNick Mathewson 	event_debug_note_teardown_(ev);
2241cd17c3acSNick Mathewson 
2242cd17c3acSNick Mathewson 	ev->ev_flags &= ~EVLIST_INIT;
224394fb4d0aSNick Mathewson }
224494fb4d0aSNick Mathewson 
22458eedeabeSNick Mathewson #define EVENT_FINALIZE_FREE_ 0x10000
22465d11f4f3SNick Mathewson static int
event_finalize_nolock_(struct event_base * base,unsigned flags,struct event * ev,event_finalize_callback_fn cb)22478eedeabeSNick Mathewson event_finalize_nolock_(struct event_base *base, unsigned flags, struct event *ev, event_finalize_callback_fn cb)
22488eedeabeSNick Mathewson {
2249f2925d78SNick Mathewson 	ev_uint8_t closure = (flags & EVENT_FINALIZE_FREE_) ?
22508eedeabeSNick Mathewson 	    EV_CLOSURE_EVENT_FINALIZE_FREE : EV_CLOSURE_EVENT_FINALIZE;
22518eedeabeSNick Mathewson 
22528eedeabeSNick Mathewson 	event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
22538eedeabeSNick Mathewson 	ev->ev_closure = closure;
22548eedeabeSNick Mathewson 	ev->ev_evcallback.evcb_cb_union.evcb_evfinalize = cb;
22558eedeabeSNick Mathewson 	event_active_nolock_(ev, EV_FINALIZE, 1);
22568eedeabeSNick Mathewson 	ev->ev_flags |= EVLIST_FINALIZING;
22575d11f4f3SNick Mathewson 	return 0;
22588eedeabeSNick Mathewson }
22598eedeabeSNick Mathewson 
22605d11f4f3SNick Mathewson static int
event_finalize_impl_(unsigned flags,struct event * ev,event_finalize_callback_fn cb)22618eedeabeSNick Mathewson event_finalize_impl_(unsigned flags, struct event *ev, event_finalize_callback_fn cb)
22628eedeabeSNick Mathewson {
22635d11f4f3SNick Mathewson 	int r;
22648eedeabeSNick Mathewson 	struct event_base *base = ev->ev_base;
22658eedeabeSNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!base)) {
22668eedeabeSNick Mathewson 		event_warnx("%s: event has no event_base set.", __func__);
22675d11f4f3SNick Mathewson 		return -1;
22688eedeabeSNick Mathewson 	}
22698eedeabeSNick Mathewson 
22708eedeabeSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
22715d11f4f3SNick Mathewson 	r = event_finalize_nolock_(base, flags, ev, cb);
22728eedeabeSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
22735d11f4f3SNick Mathewson 	return r;
22748eedeabeSNick Mathewson }
22758eedeabeSNick Mathewson 
22765d11f4f3SNick Mathewson int
event_finalize(unsigned flags,struct event * ev,event_finalize_callback_fn cb)22778eedeabeSNick Mathewson event_finalize(unsigned flags, struct event *ev, event_finalize_callback_fn cb)
22788eedeabeSNick Mathewson {
22798eedeabeSNick Mathewson 	return event_finalize_impl_(flags, ev, cb);
22808eedeabeSNick Mathewson }
22818eedeabeSNick Mathewson 
22825d11f4f3SNick Mathewson int
event_free_finalize(unsigned flags,struct event * ev,event_finalize_callback_fn cb)22838eedeabeSNick Mathewson event_free_finalize(unsigned flags, struct event *ev, event_finalize_callback_fn cb)
22848eedeabeSNick Mathewson {
22858eedeabeSNick Mathewson 	return event_finalize_impl_(flags|EVENT_FINALIZE_FREE_, ev, cb);
22868eedeabeSNick Mathewson }
22878eedeabeSNick Mathewson 
22888eedeabeSNick Mathewson void
event_callback_finalize_nolock_(struct event_base * base,unsigned flags,struct event_callback * evcb,void (* cb)(struct event_callback *,void *))22898eedeabeSNick Mathewson event_callback_finalize_nolock_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *))
22908eedeabeSNick Mathewson {
22918eedeabeSNick Mathewson 	struct event *ev = NULL;
22928eedeabeSNick Mathewson 	if (evcb->evcb_flags & EVLIST_INIT) {
22938eedeabeSNick Mathewson 		ev = event_callback_to_event(evcb);
22948eedeabeSNick Mathewson 		event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
22958eedeabeSNick Mathewson 	} else {
22968eedeabeSNick Mathewson 		event_callback_cancel_nolock_(base, evcb, 0); /*XXX can this fail?*/
22978eedeabeSNick Mathewson 	}
22988eedeabeSNick Mathewson 
22998eedeabeSNick Mathewson 	evcb->evcb_closure = EV_CLOSURE_CB_FINALIZE;
23008eedeabeSNick Mathewson 	evcb->evcb_cb_union.evcb_cbfinalize = cb;
23018eedeabeSNick Mathewson 	event_callback_activate_nolock_(base, evcb); /* XXX can this really fail?*/
23028eedeabeSNick Mathewson 	evcb->evcb_flags |= EVLIST_FINALIZING;
23038eedeabeSNick Mathewson }
23048eedeabeSNick Mathewson 
23058eedeabeSNick Mathewson void
event_callback_finalize_(struct event_base * base,unsigned flags,struct event_callback * evcb,void (* cb)(struct event_callback *,void *))23068eedeabeSNick Mathewson event_callback_finalize_(struct event_base *base, unsigned flags, struct event_callback *evcb, void (*cb)(struct event_callback *, void *))
23078eedeabeSNick Mathewson {
23088eedeabeSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
23098eedeabeSNick Mathewson 	event_callback_finalize_nolock_(base, flags, evcb, cb);
23108eedeabeSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
23118eedeabeSNick Mathewson }
23128eedeabeSNick Mathewson 
23138eedeabeSNick Mathewson /** Internal: Finalize all of the n_cbs callbacks in evcbs.  The provided
23148eedeabeSNick Mathewson  * callback will be invoked on *one of them*, after they have *all* been
23158eedeabeSNick Mathewson  * finalized. */
23168eedeabeSNick Mathewson int
event_callback_finalize_many_(struct event_base * base,int n_cbs,struct event_callback ** evcbs,void (* cb)(struct event_callback *,void *))23178eedeabeSNick Mathewson event_callback_finalize_many_(struct event_base *base, int n_cbs, struct event_callback **evcbs, void (*cb)(struct event_callback *, void *))
23188eedeabeSNick Mathewson {
23198eedeabeSNick Mathewson 	int n_pending = 0, i;
23208eedeabeSNick Mathewson 
23218eedeabeSNick Mathewson 	if (base == NULL)
23228eedeabeSNick Mathewson 		base = current_base;
23238eedeabeSNick Mathewson 
23248eedeabeSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
23258eedeabeSNick Mathewson 
23268eedeabeSNick Mathewson 	event_debug(("%s: %d events finalizing", __func__, n_cbs));
23278eedeabeSNick Mathewson 
23288eedeabeSNick Mathewson 	/* At most one can be currently executing; the rest we just
23298eedeabeSNick Mathewson 	 * cancel... But we always make sure that the finalize callback
23308eedeabeSNick Mathewson 	 * runs. */
23318eedeabeSNick Mathewson 	for (i = 0; i < n_cbs; ++i) {
23328eedeabeSNick Mathewson 		struct event_callback *evcb = evcbs[i];
23338eedeabeSNick Mathewson 		if (evcb == base->current_event) {
23348eedeabeSNick Mathewson 			event_callback_finalize_nolock_(base, 0, evcb, cb);
23358eedeabeSNick Mathewson 			++n_pending;
23368eedeabeSNick Mathewson 		} else {
23378eedeabeSNick Mathewson 			event_callback_cancel_nolock_(base, evcb, 0);
23388eedeabeSNick Mathewson 		}
23398eedeabeSNick Mathewson 	}
23408eedeabeSNick Mathewson 
23418eedeabeSNick Mathewson 	if (n_pending == 0) {
23428eedeabeSNick Mathewson 		/* Just do the first one. */
23438eedeabeSNick Mathewson 		event_callback_finalize_nolock_(base, 0, evcbs[0], cb);
23448eedeabeSNick Mathewson 	}
23458eedeabeSNick Mathewson 
23468eedeabeSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
23478eedeabeSNick Mathewson 	return 0;
23488eedeabeSNick Mathewson }
23498eedeabeSNick Mathewson 
2350fa6c304dSNiels Provos /*
2351fa6c304dSNiels Provos  * Set's the priority of an event - if an event is already scheduled
2352fa6c304dSNiels Provos  * changing the priority is going to fail.
2353fa6c304dSNiels Provos  */
2354fa6c304dSNiels Provos 
2355fa6c304dSNiels Provos int
event_priority_set(struct event * ev,int pri)2356fa6c304dSNiels Provos event_priority_set(struct event *ev, int pri)
2357fa6c304dSNiels Provos {
2358cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
2359cd17c3acSNick Mathewson 
236003589ccbSNiels Provos 	if (ev->ev_flags & EVLIST_ACTIVE)
236103589ccbSNiels Provos 		return (-1);
236203589ccbSNiels Provos 	if (pri < 0 || pri >= ev->ev_base->nactivequeues)
236303589ccbSNiels Provos 		return (-1);
236403589ccbSNiels Provos 
236503589ccbSNiels Provos 	ev->ev_pri = pri;
236603589ccbSNiels Provos 
236703589ccbSNiels Provos 	return (0);
2368aa6567feSNiels Provos }
2369aa6567feSNiels Provos 
2370aa6567feSNiels Provos /*
2371aa6567feSNiels Provos  * Checks if a specific event is pending or scheduled.
2372aa6567feSNiels Provos  */
2373aa6567feSNiels Provos 
2374aa6567feSNiels Provos int
event_pending(const struct event * ev,short event,struct timeval * tv)2375d38a7a19SNick Mathewson event_pending(const struct event *ev, short event, struct timeval *tv)
2376aa6567feSNiels Provos {
2377aa6567feSNiels Provos 	int flags = 0;
2378aa6567feSNiels Provos 
2379e3cccf38SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(ev->ev_base == NULL)) {
2380e3cccf38SNick Mathewson 		event_warnx("%s: event has no event_base set.", __func__);
2381e3cccf38SNick Mathewson 		return 0;
2382e3cccf38SNick Mathewson 	}
2383e3cccf38SNick Mathewson 
2384be7a95c6SSimon Liu 	EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
2385cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
2386cd17c3acSNick Mathewson 
2387aa6567feSNiels Provos 	if (ev->ev_flags & EVLIST_INSERTED)
2388b1b69ac7SDiego Giagio 		flags |= (ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED|EV_SIGNAL));
2389745a63dbSNick Mathewson 	if (ev->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))
239003589ccbSNiels Provos 		flags |= ev->ev_res;
2391aa6567feSNiels Provos 	if (ev->ev_flags & EVLIST_TIMEOUT)
2392aa6567feSNiels Provos 		flags |= EV_TIMEOUT;
2393aa6567feSNiels Provos 
2394b1b69ac7SDiego Giagio 	event &= (EV_TIMEOUT|EV_READ|EV_WRITE|EV_CLOSED|EV_SIGNAL);
2395aa6567feSNiels Provos 
2396aa6567feSNiels Provos 	/* See if there is a timeout that we should report */
2397571ac954SNiels Provos 	if (tv != NULL && (flags & event & EV_TIMEOUT)) {
2398693c24efSNick Mathewson 		struct timeval tmp = ev->ev_timeout;
2399693c24efSNick Mathewson 		tmp.tv_usec &= MICROSECONDS_MASK;
2400a459ef70SNick Mathewson 		/* correctly remamp to real time */
2401a459ef70SNick Mathewson 		evutil_timeradd(&ev->ev_base->tv_clock_diff, &tmp, tv);
2402571ac954SNiels Provos 	}
2403aa6567feSNiels Provos 
2404be7a95c6SSimon Liu 	EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
2405be7a95c6SSimon Liu 
2406aa6567feSNiels Provos 	return (flags & event);
2407aa6567feSNiels Provos }
2408aa6567feSNiels Provos 
2409aa6567feSNiels Provos int
event_initialized(const struct event * ev)2410652024b6SNick Mathewson event_initialized(const struct event *ev)
2411d0c3644eSNick Mathewson {
2412d0c3644eSNick Mathewson 	if (!(ev->ev_flags & EVLIST_INIT))
2413d0c3644eSNick Mathewson 		return 0;
2414652024b6SNick Mathewson 
2415d0c3644eSNick Mathewson 	return 1;
2416d0c3644eSNick Mathewson }
2417d0c3644eSNick Mathewson 
241806839503SNick Mathewson void
event_get_assignment(const struct event * event,struct event_base ** base_out,evutil_socket_t * fd_out,short * events_out,event_callback_fn * callback_out,void ** arg_out)241906839503SNick Mathewson event_get_assignment(const struct event *event, struct event_base **base_out, evutil_socket_t *fd_out, short *events_out, event_callback_fn *callback_out, void **arg_out)
242006839503SNick Mathewson {
2421cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(event);
2422cd17c3acSNick Mathewson 
242306839503SNick Mathewson 	if (base_out)
242406839503SNick Mathewson 		*base_out = event->ev_base;
242506839503SNick Mathewson 	if (fd_out)
242606839503SNick Mathewson 		*fd_out = event->ev_fd;
242706839503SNick Mathewson 	if (events_out)
242806839503SNick Mathewson 		*events_out = event->ev_events;
242906839503SNick Mathewson 	if (callback_out)
243006839503SNick Mathewson 		*callback_out = event->ev_callback;
243106839503SNick Mathewson 	if (arg_out)
243206839503SNick Mathewson 		*arg_out = event->ev_arg;
243306839503SNick Mathewson }
243406839503SNick Mathewson 
243506839503SNick Mathewson size_t
event_get_struct_event_size(void)243606839503SNick Mathewson event_get_struct_event_size(void)
243706839503SNick Mathewson {
243806839503SNick Mathewson 	return sizeof(struct event);
243906839503SNick Mathewson }
244006839503SNick Mathewson 
2441d0c3644eSNick Mathewson evutil_socket_t
event_get_fd(const struct event * ev)244206839503SNick Mathewson event_get_fd(const struct event *ev)
2443d0c3644eSNick Mathewson {
2444cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
2445d0c3644eSNick Mathewson 	return ev->ev_fd;
2446d0c3644eSNick Mathewson }
2447d0c3644eSNick Mathewson 
24480fd70978SNick Mathewson struct event_base *
event_get_base(const struct event * ev)244906839503SNick Mathewson event_get_base(const struct event *ev)
24500fd70978SNick Mathewson {
2451cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
24520fd70978SNick Mathewson 	return ev->ev_base;
24530fd70978SNick Mathewson }
24540fd70978SNick Mathewson 
245506839503SNick Mathewson short
event_get_events(const struct event * ev)245606839503SNick Mathewson event_get_events(const struct event *ev)
245706839503SNick Mathewson {
2458cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
245906839503SNick Mathewson 	return ev->ev_events;
246006839503SNick Mathewson }
246106839503SNick Mathewson 
246206839503SNick Mathewson event_callback_fn
event_get_callback(const struct event * ev)246306839503SNick Mathewson event_get_callback(const struct event *ev)
246406839503SNick Mathewson {
2465cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
246606839503SNick Mathewson 	return ev->ev_callback;
246706839503SNick Mathewson }
246806839503SNick Mathewson 
246906839503SNick Mathewson void *
event_get_callback_arg(const struct event * ev)247006839503SNick Mathewson event_get_callback_arg(const struct event *ev)
247106839503SNick Mathewson {
2472cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
247306839503SNick Mathewson 	return ev->ev_arg;
247406839503SNick Mathewson }
247506839503SNick Mathewson 
2476d0c3644eSNick Mathewson int
event_get_priority(const struct event * ev)2477f90e2559SNick Mathewson event_get_priority(const struct event *ev)
2478f90e2559SNick Mathewson {
2479f90e2559SNick Mathewson 	event_debug_assert_is_setup_(ev);
2480f90e2559SNick Mathewson 	return ev->ev_pri;
2481f90e2559SNick Mathewson }
2482f90e2559SNick Mathewson 
2483f90e2559SNick Mathewson int
event_add(struct event * ev,const struct timeval * tv)24848b66f1bdSNiels Provos event_add(struct event *ev, const struct timeval *tv)
2485aa6567feSNiels Provos {
2486558de9b3SNiels Provos 	int res;
2487558de9b3SNiels Provos 
2488f1074b77SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
2489f1074b77SNick Mathewson 		event_warnx("%s: event has no event_base set.", __func__);
2490f1074b77SNick Mathewson 		return -1;
2491f1074b77SNick Mathewson 	}
2492f1074b77SNick Mathewson 
249376cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
2494558de9b3SNiels Provos 
24959cd5acb5SNick Mathewson 	res = event_add_nolock_(ev, tv, 0);
2496558de9b3SNiels Provos 
249776cd2b70SNick Mathewson 	EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
2498558de9b3SNiels Provos 
2499558de9b3SNiels Provos 	return (res);
2500558de9b3SNiels Provos }
2501558de9b3SNiels Provos 
2502cdd4c490SNick Mathewson /* Helper callback: wake an event_base from another thread.  This version
2503cdd4c490SNick Mathewson  * works by writing a byte to one end of a socketpair, so that the event_base
2504cdd4c490SNick Mathewson  * listening on the other end will wake up as the corresponding event
2505cdd4c490SNick Mathewson  * triggers */
2506ec4cfa33SNick Mathewson static int
evthread_notify_base_default(struct event_base * base)2507a5901991SNick Mathewson evthread_notify_base_default(struct event_base *base)
2508ec4cfa33SNick Mathewson {
2509ec4cfa33SNick Mathewson 	char buf[1];
2510ec4cfa33SNick Mathewson 	int r;
2511c3e9fcf6SNick Mathewson 	buf[0] = (char) 0;
25129f560bfaSNick Mathewson #ifdef _WIN32
2513ec4cfa33SNick Mathewson 	r = send(base->th_notify_fd[1], buf, 1, 0);
251434d2fd06SNick Mathewson #else
251534d2fd06SNick Mathewson 	r = write(base->th_notify_fd[1], buf, 1);
251634d2fd06SNick Mathewson #endif
2517bf7a0ff2SNick Mathewson 	return (r < 0 && ! EVUTIL_ERR_IS_EAGAIN(errno)) ? -1 : 0;
2518ec4cfa33SNick Mathewson }
2519ec4cfa33SNick Mathewson 
25202449e0c5SNick Mathewson #ifdef EVENT__HAVE_EVENTFD
2521cdd4c490SNick Mathewson /* Helper callback: wake an event_base from another thread.  This version
2522cdd4c490SNick Mathewson  * assumes that you have a working eventfd() implementation. */
2523a5901991SNick Mathewson static int
evthread_notify_base_eventfd(struct event_base * base)2524a5901991SNick Mathewson evthread_notify_base_eventfd(struct event_base *base)
2525a5901991SNick Mathewson {
2526a5901991SNick Mathewson 	ev_uint64_t msg = 1;
2527a5901991SNick Mathewson 	int r;
2528a5901991SNick Mathewson 	do {
2529a5901991SNick Mathewson 		r = write(base->th_notify_fd[0], (void*) &msg, sizeof(msg));
2530a5901991SNick Mathewson 	} while (r < 0 && errno == EAGAIN);
2531a5901991SNick Mathewson 
2532a5901991SNick Mathewson 	return (r < 0) ? -1 : 0;
2533a5901991SNick Mathewson }
25342449e0c5SNick Mathewson #endif
25352449e0c5SNick Mathewson 
2536a5901991SNick Mathewson 
2537cdd4c490SNick Mathewson /** Tell the thread currently running the event_loop for base (if any) that it
2538cdd4c490SNick Mathewson  * needs to stop waiting in its dispatch function (if it is) and process all
2539a4079aa8SNick Mathewson  * active callbacks. */
2540a5901991SNick Mathewson static int
evthread_notify_base(struct event_base * base)2541a5901991SNick Mathewson evthread_notify_base(struct event_base *base)
2542a5901991SNick Mathewson {
25434632b78eSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
2544a5901991SNick Mathewson 	if (!base->th_notify_fn)
2545a5901991SNick Mathewson 		return -1;
25464632b78eSNick Mathewson 	if (base->is_notify_pending)
25474632b78eSNick Mathewson 		return 0;
25484632b78eSNick Mathewson 	base->is_notify_pending = 1;
2549a5901991SNick Mathewson 	return base->th_notify_fn(base);
2550a5901991SNick Mathewson }
2551a5901991SNick Mathewson 
2552e3b2e086SNick Mathewson /* Implementation function to remove a timeout on a currently pending event.
2553e3b2e086SNick Mathewson  */
2554e3b2e086SNick Mathewson int
event_remove_timer_nolock_(struct event * ev)2555e3b2e086SNick Mathewson event_remove_timer_nolock_(struct event *ev)
2556e3b2e086SNick Mathewson {
2557e3b2e086SNick Mathewson 	struct event_base *base = ev->ev_base;
2558e3b2e086SNick Mathewson 
2559e3b2e086SNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
2560e3b2e086SNick Mathewson 	event_debug_assert_is_setup_(ev);
2561e3b2e086SNick Mathewson 
2562e3b2e086SNick Mathewson 	event_debug(("event_remove_timer_nolock: event: %p", ev));
2563e3b2e086SNick Mathewson 
2564e3b2e086SNick Mathewson 	/* If it's not pending on a timeout, we don't need to do anything. */
2565e3b2e086SNick Mathewson 	if (ev->ev_flags & EVLIST_TIMEOUT) {
2566e3b2e086SNick Mathewson 		event_queue_remove_timeout(base, ev);
25675623e803SNick Mathewson 		evutil_timerclear(&ev->ev_.ev_io.ev_timeout);
2568e3b2e086SNick Mathewson 	}
2569e3b2e086SNick Mathewson 
2570e3b2e086SNick Mathewson 	return (0);
2571e3b2e086SNick Mathewson }
2572e3b2e086SNick Mathewson 
2573e3b2e086SNick Mathewson int
event_remove_timer(struct event * ev)2574e3b2e086SNick Mathewson event_remove_timer(struct event *ev)
2575e3b2e086SNick Mathewson {
2576e3b2e086SNick Mathewson 	int res;
2577e3b2e086SNick Mathewson 
2578e3b2e086SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
2579e3b2e086SNick Mathewson 		event_warnx("%s: event has no event_base set.", __func__);
2580e3b2e086SNick Mathewson 		return -1;
2581e3b2e086SNick Mathewson 	}
2582e3b2e086SNick Mathewson 
2583e3b2e086SNick Mathewson 	EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
2584e3b2e086SNick Mathewson 
2585e3b2e086SNick Mathewson 	res = event_remove_timer_nolock_(ev);
2586e3b2e086SNick Mathewson 
2587e3b2e086SNick Mathewson 	EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
2588e3b2e086SNick Mathewson 
2589e3b2e086SNick Mathewson 	return (res);
2590e3b2e086SNick Mathewson }
2591e3b2e086SNick Mathewson 
2592cdd4c490SNick Mathewson /* Implementation function to add an event.  Works just like event_add,
2593cdd4c490SNick Mathewson  * except: 1) it requires that we have the lock.  2) if tv_is_absolute is set,
2594cdd4c490SNick Mathewson  * we treat tv as an absolute time, not as an interval to add to the current
2595cdd4c490SNick Mathewson  * time */
25969cd5acb5SNick Mathewson int
event_add_nolock_(struct event * ev,const struct timeval * tv,int tv_is_absolute)25979cd5acb5SNick Mathewson event_add_nolock_(struct event *ev, const struct timeval *tv,
2598e88079a8SNick Mathewson     int tv_is_absolute)
2599558de9b3SNiels Provos {
26008773c4c9SNiels Provos 	struct event_base *base = ev->ev_base;
2601558de9b3SNiels Provos 	int res = 0;
2602ba8a1771SNick Mathewson 	int notify = 0;
26038773c4c9SNiels Provos 
2604e2642f0aSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
2605cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
2606cd17c3acSNick Mathewson 
2607fbdaf3abSNiels Provos 	event_debug((
2608b1b69ac7SDiego Giagio 		 "event_add: event: %p (fd "EV_SOCK_FMT"), %s%s%s%scall %p",
2609aa6567feSNiels Provos 		 ev,
261094866c27SNick Mathewson 		 EV_SOCK_ARG(ev->ev_fd),
2611aa6567feSNiels Provos 		 ev->ev_events & EV_READ ? "EV_READ " : " ",
2612aa6567feSNiels Provos 		 ev->ev_events & EV_WRITE ? "EV_WRITE " : " ",
2613b1b69ac7SDiego Giagio 		 ev->ev_events & EV_CLOSED ? "EV_CLOSED " : " ",
2614aa6567feSNiels Provos 		 tv ? "EV_TIMEOUT " : " ",
2615aa6567feSNiels Provos 		 ev->ev_callback));
2616aa6567feSNiels Provos 
26172e36dbe1SNick Mathewson 	EVUTIL_ASSERT(!(ev->ev_flags & ~EVLIST_ALL));
2618aa6567feSNiels Provos 
26198eedeabeSNick Mathewson 	if (ev->ev_flags & EVLIST_FINALIZING) {
26208eedeabeSNick Mathewson 		/* XXXX debug */
26218eedeabeSNick Mathewson 		return (-1);
26228eedeabeSNick Mathewson 	}
26238eedeabeSNick Mathewson 
2624cca2f8faSNiels Provos 	/*
2625cca2f8faSNiels Provos 	 * prepare for timeout insertion further below, if we get a
2626cca2f8faSNiels Provos 	 * failure on any step, we should not change any state.
2627cca2f8faSNiels Provos 	 */
2628cca2f8faSNiels Provos 	if (tv != NULL && !(ev->ev_flags & EVLIST_TIMEOUT)) {
26298ac3c4c2SNick Mathewson 		if (min_heap_reserve_(&base->timeheap,
26308ac3c4c2SNick Mathewson 			1 + min_heap_size_(&base->timeheap)) == -1)
263130ae40ccSNiels Provos 			return (-1);  /* ENOMEM == errno */
2632cca2f8faSNiels Provos 	}
2633cca2f8faSNiels Provos 
2634fc5e0a23SNick Mathewson 	/* If the main thread is currently executing a signal event's
2635fc5e0a23SNick Mathewson 	 * callback, and we are not the main thread, then we want to wait
2636fc5e0a23SNick Mathewson 	 * until the callback is done before we mess with the event, or else
2637fc5e0a23SNick Mathewson 	 * we can race on ev_ncalls and ev_pncalls below. */
263868120d9bSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
2639cba59e53SNick Mathewson 	if (base->current_event == event_to_event_callback(ev) &&
2640cba59e53SNick Mathewson 	    (ev->ev_events & EV_SIGNAL)
2641e0972c21SNick Mathewson 	    && !EVBASE_IN_THREAD(base)) {
2642e0972c21SNick Mathewson 		++base->current_event_waiters;
2643e0972c21SNick Mathewson 		EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
2644e0972c21SNick Mathewson 	}
2645e0972c21SNick Mathewson #endif
2646fc5e0a23SNick Mathewson 
2647b1b69ac7SDiego Giagio 	if ((ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED|EV_SIGNAL)) &&
2648745a63dbSNick Mathewson 	    !(ev->ev_flags & (EVLIST_INSERTED|EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))) {
2649b1b69ac7SDiego Giagio 		if (ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED))
26508ac3c4c2SNick Mathewson 			res = evmap_io_add_(base, ev->ev_fd, ev);
265102b2b4d1SNiels Provos 		else if (ev->ev_events & EV_SIGNAL)
26528ac3c4c2SNick Mathewson 			res = evmap_signal_add_(base, (int)ev->ev_fd, ev);
2653cca2f8faSNiels Provos 		if (res != -1)
2654efc4dc50SNick Mathewson 			event_queue_insert_inserted(base, ev);
2655ba8a1771SNick Mathewson 		if (res == 1) {
2656ba8a1771SNick Mathewson 			/* evmap says we need to notify the main thread. */
2657ba8a1771SNick Mathewson 			notify = 1;
2658ba8a1771SNick Mathewson 			res = 0;
2659ba8a1771SNick Mathewson 		}
2660cca2f8faSNiels Provos 	}
2661cca2f8faSNiels Provos 
2662cca2f8faSNiels Provos 	/*
2663e3fd294aSNick Mathewson 	 * we should change the timeout state only if the previous event
2664cca2f8faSNiels Provos 	 * addition succeeded.
2665cca2f8faSNiels Provos 	 */
2666cca2f8faSNiels Provos 	if (res != -1 && tv != NULL) {
2667cca2f8faSNiels Provos 		struct timeval now;
2668693c24efSNick Mathewson 		int common_timeout;
266909cbc3dcSNick Mathewson #ifdef USE_REINSERT_TIMEOUT
26708c36acd0SNick Mathewson 		int was_common;
26718c36acd0SNick Mathewson 		int old_timeout_idx;
267209cbc3dcSNick Mathewson #endif
2673cca2f8faSNiels Provos 
2674cca2f8faSNiels Provos 		/*
267556ea4687SNiels Provos 		 * for persistent timeout events, we remember the
267656ea4687SNiels Provos 		 * timeout value and re-add the event.
2677e88079a8SNick Mathewson 		 *
2678e88079a8SNick Mathewson 		 * If tv_is_absolute, this was already set.
267956ea4687SNiels Provos 		 */
2680cba59e53SNick Mathewson 		if (ev->ev_closure == EV_CLOSURE_EVENT_PERSIST && !tv_is_absolute)
268156ea4687SNiels Provos 			ev->ev_io_timeout = *tv;
268256ea4687SNiels Provos 
268309cbc3dcSNick Mathewson #ifndef USE_REINSERT_TIMEOUT
268409cbc3dcSNick Mathewson 		if (ev->ev_flags & EVLIST_TIMEOUT) {
268509cbc3dcSNick Mathewson 			event_queue_remove_timeout(base, ev);
268609cbc3dcSNick Mathewson 		}
268709cbc3dcSNick Mathewson #endif
268809cbc3dcSNick Mathewson 
2689f9e0c449SNiels Provos 		/* Check if it is active due to a timeout.  Rescheduling
2690f9e0c449SNiels Provos 		 * this timeout before the callback can be executed
2691f9e0c449SNiels Provos 		 * removes it from the active list. */
269203589ccbSNiels Provos 		if ((ev->ev_flags & EVLIST_ACTIVE) &&
269303589ccbSNiels Provos 		    (ev->ev_res & EV_TIMEOUT)) {
2694f7e61870SNiels Provos 			if (ev->ev_events & EV_SIGNAL) {
26958c750eafSNiels Provos 				/* See if we are just active executing
26968c750eafSNiels Provos 				 * this event in a loop
2697f9e0c449SNiels Provos 				 */
2698f9e0c449SNiels Provos 				if (ev->ev_ncalls && ev->ev_pncalls) {
2699f9e0c449SNiels Provos 					/* Abort loop */
2700f9e0c449SNiels Provos 					*ev->ev_pncalls = 0;
2701f9e0c449SNiels Provos 				}
27028c750eafSNiels Provos 			}
2703f9e0c449SNiels Provos 
2704cba59e53SNick Mathewson 			event_queue_remove_active(base, event_to_event_callback(ev));
2705f9e0c449SNiels Provos 		}
2706f9e0c449SNiels Provos 
270745e6fb0dSNiels Provos 		gettime(base, &now);
2708e88079a8SNick Mathewson 
2709693c24efSNick Mathewson 		common_timeout = is_common_timeout(tv, base);
271009cbc3dcSNick Mathewson #ifdef USE_REINSERT_TIMEOUT
27118c36acd0SNick Mathewson 		was_common = is_common_timeout(&ev->ev_timeout, base);
27128c36acd0SNick Mathewson 		old_timeout_idx = COMMON_TIMEOUT_IDX(&ev->ev_timeout);
271309cbc3dcSNick Mathewson #endif
27148c36acd0SNick Mathewson 
2715e88079a8SNick Mathewson 		if (tv_is_absolute) {
2716e88079a8SNick Mathewson 			ev->ev_timeout = *tv;
2717e88079a8SNick Mathewson 		} else if (common_timeout) {
2718693c24efSNick Mathewson 			struct timeval tmp = *tv;
2719693c24efSNick Mathewson 			tmp.tv_usec &= MICROSECONDS_MASK;
2720693c24efSNick Mathewson 			evutil_timeradd(&now, &tmp, &ev->ev_timeout);
2721693c24efSNick Mathewson 			ev->ev_timeout.tv_usec |=
2722693c24efSNick Mathewson 			    (tv->tv_usec & ~MICROSECONDS_MASK);
2723693c24efSNick Mathewson 		} else {
2724f74e7258SNick Mathewson 			evutil_timeradd(&now, tv, &ev->ev_timeout);
2725693c24efSNick Mathewson 		}
2726aa6567feSNiels Provos 
2727fbdaf3abSNiels Provos 		event_debug((
27284b7d2984SMark Ellzey 			 "event_add: event %p, timeout in %d seconds %d useconds, call %p",
27294b7d2984SMark Ellzey 			 ev, (int)tv->tv_sec, (int)tv->tv_usec, ev->ev_callback));
2730aa6567feSNiels Provos 
273109cbc3dcSNick Mathewson #ifdef USE_REINSERT_TIMEOUT
27328c36acd0SNick Mathewson 		event_queue_reinsert_timeout(base, ev, was_common, common_timeout, old_timeout_idx);
273309cbc3dcSNick Mathewson #else
273409cbc3dcSNick Mathewson 		event_queue_insert_timeout(base, ev);
273509cbc3dcSNick Mathewson #endif
2736e47042feSNick Mathewson 
2737693c24efSNick Mathewson 		if (common_timeout) {
2738693c24efSNick Mathewson 			struct common_timeout_list *ctl =
2739693c24efSNick Mathewson 			    get_common_timeout_list(base, &ev->ev_timeout);
2740693c24efSNick Mathewson 			if (ev == TAILQ_FIRST(&ctl->events)) {
2741693c24efSNick Mathewson 				common_timeout_schedule(ctl, &now, ev);
2742693c24efSNick Mathewson 			}
2743693c24efSNick Mathewson 		} else {
27449443868dSNate Rosenblum 			struct event* top = NULL;
2745693c24efSNick Mathewson 			/* See if the earliest timeout is now earlier than it
2746693c24efSNick Mathewson 			 * was before: if so, we will need to tell the main
27479443868dSNate Rosenblum 			 * thread to wake up earlier than it would otherwise.
27489443868dSNate Rosenblum 			 * We double check the timeout of the top element to
27499443868dSNate Rosenblum 			 * handle time distortions due to system suspension.
27509443868dSNate Rosenblum 			 */
27518ac3c4c2SNick Mathewson 			if (min_heap_elt_is_top_(ev))
2752ba8a1771SNick Mathewson 				notify = 1;
27539443868dSNate Rosenblum 			else if ((top = min_heap_top_(&base->timeheap)) != NULL &&
27549443868dSNate Rosenblum 					 evutil_timercmp(&top->ev_timeout, &now, <))
27559443868dSNate Rosenblum 				notify = 1;
2756ba8a1771SNick Mathewson 		}
2757aa6567feSNiels Provos 	}
2758aa6567feSNiels Provos 
2759558de9b3SNiels Provos 	/* if we are not in the right thread, we need to wake up the loop */
2760c7a06bfaSNick Mathewson 	if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
2761c3e9fcf6SNick Mathewson 		evthread_notify_base(base);
2762558de9b3SNiels Provos 
2763cb9da0bfSNick Mathewson 	event_debug_note_add_(ev);
2764cd17c3acSNick Mathewson 
2765558de9b3SNiels Provos 	return (res);
2766aa6567feSNiels Provos }
2767aa6567feSNiels Provos 
27688eedeabeSNick Mathewson static int
event_del_(struct event * ev,int blocking)27698eedeabeSNick Mathewson event_del_(struct event *ev, int blocking)
2770aa6567feSNiels Provos {
2771558de9b3SNiels Provos 	int res;
27724f0f40e3SAzat Khuzhin 	struct event_base *base = ev->ev_base;
2773558de9b3SNiels Provos 
27744f0f40e3SAzat Khuzhin 	if (EVUTIL_FAILURE_CHECK(!base)) {
2775f1074b77SNick Mathewson 		event_warnx("%s: event has no event_base set.", __func__);
2776f1074b77SNick Mathewson 		return -1;
2777f1074b77SNick Mathewson 	}
2778f1074b77SNick Mathewson 
27794f0f40e3SAzat Khuzhin 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
27808eedeabeSNick Mathewson 	res = event_del_nolock_(ev, blocking);
27814f0f40e3SAzat Khuzhin 	EVBASE_RELEASE_LOCK(base, th_base_lock);
2782558de9b3SNiels Provos 
2783558de9b3SNiels Provos 	return (res);
2784558de9b3SNiels Provos }
2785558de9b3SNiels Provos 
27869cd5acb5SNick Mathewson int
event_del(struct event * ev)27878eedeabeSNick Mathewson event_del(struct event *ev)
27888eedeabeSNick Mathewson {
27898eedeabeSNick Mathewson 	return event_del_(ev, EVENT_DEL_AUTOBLOCK);
27908eedeabeSNick Mathewson }
27918eedeabeSNick Mathewson 
27928eedeabeSNick Mathewson int
event_del_block(struct event * ev)27938eedeabeSNick Mathewson event_del_block(struct event *ev)
27948eedeabeSNick Mathewson {
27958eedeabeSNick Mathewson 	return event_del_(ev, EVENT_DEL_BLOCK);
27968eedeabeSNick Mathewson }
27978eedeabeSNick Mathewson 
27988eedeabeSNick Mathewson int
event_del_noblock(struct event * ev)27998eedeabeSNick Mathewson event_del_noblock(struct event *ev)
28008eedeabeSNick Mathewson {
28018eedeabeSNick Mathewson 	return event_del_(ev, EVENT_DEL_NOBLOCK);
28028eedeabeSNick Mathewson }
28038eedeabeSNick Mathewson 
2804a800b913SNick Mathewson /** Helper for event_del: always called with th_base_lock held.
2805a800b913SNick Mathewson  *
2806a800b913SNick Mathewson  * "blocking" must be one of the EVENT_DEL_{BLOCK, NOBLOCK, AUTOBLOCK,
2807a800b913SNick Mathewson  * EVEN_IF_FINALIZING} values. See those for more information.
2808a800b913SNick Mathewson  */
28098eedeabeSNick Mathewson int
event_del_nolock_(struct event * ev,int blocking)28108eedeabeSNick Mathewson event_del_nolock_(struct event *ev, int blocking)
2811558de9b3SNiels Provos {
2812bd6999b4SNiels Provos 	struct event_base *base;
2813ba8a1771SNick Mathewson 	int res = 0, notify = 0;
28148773c4c9SNiels Provos 
281594866c27SNick Mathewson 	event_debug(("event_del: %p (fd "EV_SOCK_FMT"), callback %p",
281694866c27SNick Mathewson 		ev, EV_SOCK_ARG(ev->ev_fd), ev->ev_callback));
2817aa6567feSNiels Provos 
2818bd6999b4SNiels Provos 	/* An event without a base has not been added */
2819bd6999b4SNiels Provos 	if (ev->ev_base == NULL)
2820905ee67dSNiels Provos 		return (-1);
2821bd6999b4SNiels Provos 
2822e2642f0aSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(ev->ev_base);
2823e2642f0aSNick Mathewson 
28248eedeabeSNick Mathewson 	if (blocking != EVENT_DEL_EVEN_IF_FINALIZING) {
28258eedeabeSNick Mathewson 		if (ev->ev_flags & EVLIST_FINALIZING) {
28268eedeabeSNick Mathewson 			/* XXXX Debug */
28278eedeabeSNick Mathewson 			return 0;
28288eedeabeSNick Mathewson 		}
28298eedeabeSNick Mathewson 	}
28308eedeabeSNick Mathewson 
2831bd6999b4SNiels Provos 	base = ev->ev_base;
2832bd6999b4SNiels Provos 
28332e36dbe1SNick Mathewson 	EVUTIL_ASSERT(!(ev->ev_flags & ~EVLIST_ALL));
2834aa6567feSNiels Provos 
283559137c11SNiels Provos 	/* See if we are just active executing this event in a loop */
2836f7e61870SNiels Provos 	if (ev->ev_events & EV_SIGNAL) {
283759137c11SNiels Provos 		if (ev->ev_ncalls && ev->ev_pncalls) {
283859137c11SNiels Provos 			/* Abort loop */
283959137c11SNiels Provos 			*ev->ev_pncalls = 0;
284059137c11SNiels Provos 		}
28418c750eafSNiels Provos 	}
284259137c11SNiels Provos 
2843ba8a1771SNick Mathewson 	if (ev->ev_flags & EVLIST_TIMEOUT) {
2844ba8a1771SNick Mathewson 		/* NOTE: We never need to notify the main thread because of a
2845ba8a1771SNick Mathewson 		 * deleted timeout event: all that could happen if we don't is
2846ba8a1771SNick Mathewson 		 * that the dispatch loop might wake up too early.  But the
2847ba8a1771SNick Mathewson 		 * point of notifying the main thread _is_ to wake up the
2848ba8a1771SNick Mathewson 		 * dispatch loop early anyway, so we wouldn't gain anything by
2849ba8a1771SNick Mathewson 		 * doing it.
2850ba8a1771SNick Mathewson 		 */
2851efc4dc50SNick Mathewson 		event_queue_remove_timeout(base, ev);
2852ba8a1771SNick Mathewson 	}
2853aa6567feSNiels Provos 
285403589ccbSNiels Provos 	if (ev->ev_flags & EVLIST_ACTIVE)
2855cba59e53SNick Mathewson 		event_queue_remove_active(base, event_to_event_callback(ev));
2856745a63dbSNick Mathewson 	else if (ev->ev_flags & EVLIST_ACTIVE_LATER)
2857745a63dbSNick Mathewson 		event_queue_remove_active_later(base, event_to_event_callback(ev));
2858aa6567feSNiels Provos 
2859aa6567feSNiels Provos 	if (ev->ev_flags & EVLIST_INSERTED) {
2860efc4dc50SNick Mathewson 		event_queue_remove_inserted(base, ev);
2861b1b69ac7SDiego Giagio 		if (ev->ev_events & (EV_READ|EV_WRITE|EV_CLOSED))
28628ac3c4c2SNick Mathewson 			res = evmap_io_del_(base, ev->ev_fd, ev);
286302b2b4d1SNiels Provos 		else
28648ac3c4c2SNick Mathewson 			res = evmap_signal_del_(base, (int)ev->ev_fd, ev);
2865ba8a1771SNick Mathewson 		if (res == 1) {
2866ba8a1771SNick Mathewson 			/* evmap says we need to notify the main thread. */
2867ba8a1771SNick Mathewson 			notify = 1;
2868ba8a1771SNick Mathewson 			res = 0;
2869ba8a1771SNick Mathewson 		}
2870d9d1c09eSAzat Khuzhin 		/* If we do not have events, let's notify event base so it can
2871d9d1c09eSAzat Khuzhin 		 * exit without waiting */
2872d9d1c09eSAzat Khuzhin 		if (!event_haveevents(base) && !N_ACTIVE_CALLBACKS(base))
2873d9d1c09eSAzat Khuzhin 			notify = 1;
2874aa6567feSNiels Provos 	}
2875aa6567feSNiels Provos 
2876558de9b3SNiels Provos 	/* if we are not in the right thread, we need to wake up the loop */
2877c7a06bfaSNick Mathewson 	if (res != -1 && notify && EVBASE_NEED_NOTIFY(base))
2878c3e9fcf6SNick Mathewson 		evthread_notify_base(base);
2879558de9b3SNiels Provos 
2880cb9da0bfSNick Mathewson 	event_debug_note_del_(ev);
2881cd17c3acSNick Mathewson 
2882876c7ac7SJosé Luis Millán 	/* If the main thread is currently executing this event's callback,
2883876c7ac7SJosé Luis Millán 	 * and we are not the main thread, then we want to wait until the
2884876c7ac7SJosé Luis Millán 	 * callback is done before returning. That way, when this function
2885876c7ac7SJosé Luis Millán 	 * returns, it will be safe to free the user-supplied argument.
2886876c7ac7SJosé Luis Millán 	 */
2887876c7ac7SJosé Luis Millán #ifndef EVENT__DISABLE_THREAD_SUPPORT
2888876c7ac7SJosé Luis Millán 	if (blocking != EVENT_DEL_NOBLOCK &&
2889876c7ac7SJosé Luis Millán 	    base->current_event == event_to_event_callback(ev) &&
2890876c7ac7SJosé Luis Millán 	    !EVBASE_IN_THREAD(base) &&
2891876c7ac7SJosé Luis Millán 	    (blocking == EVENT_DEL_BLOCK || !(ev->ev_events & EV_FINALIZE))) {
2892876c7ac7SJosé Luis Millán 		++base->current_event_waiters;
2893876c7ac7SJosé Luis Millán 		EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
2894876c7ac7SJosé Luis Millán 	}
2895876c7ac7SJosé Luis Millán #endif
2896876c7ac7SJosé Luis Millán 
2897558de9b3SNiels Provos 	return (res);
2898aa6567feSNiels Provos }
2899aa6567feSNiels Provos 
2900aa6567feSNiels Provos void
event_active(struct event * ev,int res,short ncalls)2901d10f85dbSNiels Provos event_active(struct event *ev, int res, short ncalls)
2902aa6567feSNiels Provos {
2903f1074b77SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!ev->ev_base)) {
2904f1074b77SNick Mathewson 		event_warnx("%s: event has no event_base set.", __func__);
2905f1074b77SNick Mathewson 		return;
2906f1074b77SNick Mathewson 	}
2907f1074b77SNick Mathewson 
290876cd2b70SNick Mathewson 	EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
2909558de9b3SNiels Provos 
2910cb9da0bfSNick Mathewson 	event_debug_assert_is_setup_(ev);
2911cd17c3acSNick Mathewson 
29128ac3c4c2SNick Mathewson 	event_active_nolock_(ev, res, ncalls);
2913558de9b3SNiels Provos 
291476cd2b70SNick Mathewson 	EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
2915558de9b3SNiels Provos }
2916558de9b3SNiels Provos 
2917558de9b3SNiels Provos 
2918a2a7d1d1SNick Mathewson void
event_active_nolock_(struct event * ev,int res,short ncalls)29198ac3c4c2SNick Mathewson event_active_nolock_(struct event *ev, int res, short ncalls)
2920558de9b3SNiels Provos {
2921558de9b3SNiels Provos 	struct event_base *base;
2922558de9b3SNiels Provos 
292394866c27SNick Mathewson 	event_debug(("event_active: %p (fd "EV_SOCK_FMT"), res %d, callback %p",
292494866c27SNick Mathewson 		ev, EV_SOCK_ARG(ev->ev_fd), (int)res, ev->ev_callback));
2925e1198997SNick Mathewson 
2926558de9b3SNiels Provos 	base = ev->ev_base;
2927e2642f0aSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
2928e2642f0aSNick Mathewson 
29298eedeabeSNick Mathewson 	if (ev->ev_flags & EVLIST_FINALIZING) {
29308eedeabeSNick Mathewson 		/* XXXX debug */
29318eedeabeSNick Mathewson 		return;
29328eedeabeSNick Mathewson 	}
29338eedeabeSNick Mathewson 
2934745a63dbSNick Mathewson 	switch ((ev->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))) {
2935745a63dbSNick Mathewson 	default:
2936745a63dbSNick Mathewson 	case EVLIST_ACTIVE|EVLIST_ACTIVE_LATER:
2937745a63dbSNick Mathewson 		EVUTIL_ASSERT(0);
2938745a63dbSNick Mathewson 		break;
2939745a63dbSNick Mathewson 	case EVLIST_ACTIVE:
2940745a63dbSNick Mathewson 		/* We get different kinds of events, add them together */
2941745a63dbSNick Mathewson 		ev->ev_res |= res;
2942745a63dbSNick Mathewson 		return;
2943745a63dbSNick Mathewson 	case EVLIST_ACTIVE_LATER:
2944745a63dbSNick Mathewson 		ev->ev_res |= res;
2945745a63dbSNick Mathewson 		break;
2946745a63dbSNick Mathewson 	case 0:
294703589ccbSNiels Provos 		ev->ev_res = res;
2948745a63dbSNick Mathewson 		break;
2949745a63dbSNick Mathewson 	}
29508c750eafSNiels Provos 
29512bfda401SNick Mathewson 	if (ev->ev_pri < base->event_running_priority)
29522bfda401SNick Mathewson 		base->event_continue = 1;
29532bfda401SNick Mathewson 
2954f7e61870SNiels Provos 	if (ev->ev_events & EV_SIGNAL) {
295568120d9bSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
2956cba59e53SNick Mathewson 		if (base->current_event == event_to_event_callback(ev) &&
2957cba59e53SNick Mathewson 		    !EVBASE_IN_THREAD(base)) {
2958e0972c21SNick Mathewson 			++base->current_event_waiters;
2959e0972c21SNick Mathewson 			EVTHREAD_COND_WAIT(base->current_event_cond, base->th_base_lock);
2960e0972c21SNick Mathewson 		}
2961e0972c21SNick Mathewson #endif
2962d10f85dbSNiels Provos 		ev->ev_ncalls = ncalls;
296359137c11SNiels Provos 		ev->ev_pncalls = NULL;
29648c750eafSNiels Provos 	}
29658c750eafSNiels Provos 
2966cba59e53SNick Mathewson 	event_callback_activate_nolock_(base, event_to_event_callback(ev));
2967cba59e53SNick Mathewson }
2968cba59e53SNick Mathewson 
2969cba59e53SNick Mathewson void
event_active_later_(struct event * ev,int res)2970745a63dbSNick Mathewson event_active_later_(struct event *ev, int res)
2971745a63dbSNick Mathewson {
2972745a63dbSNick Mathewson 	EVBASE_ACQUIRE_LOCK(ev->ev_base, th_base_lock);
2973745a63dbSNick Mathewson 	event_active_later_nolock_(ev, res);
2974745a63dbSNick Mathewson 	EVBASE_RELEASE_LOCK(ev->ev_base, th_base_lock);
2975745a63dbSNick Mathewson }
2976745a63dbSNick Mathewson 
2977745a63dbSNick Mathewson void
event_active_later_nolock_(struct event * ev,int res)2978745a63dbSNick Mathewson event_active_later_nolock_(struct event *ev, int res)
2979745a63dbSNick Mathewson {
2980745a63dbSNick Mathewson 	struct event_base *base = ev->ev_base;
2981745a63dbSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
2982745a63dbSNick Mathewson 
2983745a63dbSNick Mathewson 	if (ev->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) {
2984745a63dbSNick Mathewson 		/* We get different kinds of events, add them together */
2985745a63dbSNick Mathewson 		ev->ev_res |= res;
2986745a63dbSNick Mathewson 		return;
2987745a63dbSNick Mathewson 	}
2988745a63dbSNick Mathewson 
2989745a63dbSNick Mathewson 	ev->ev_res = res;
2990745a63dbSNick Mathewson 
2991745a63dbSNick Mathewson 	event_callback_activate_later_nolock_(base, event_to_event_callback(ev));
2992745a63dbSNick Mathewson }
2993745a63dbSNick Mathewson 
2994ae2b84b2SNick Mathewson int
event_callback_activate_(struct event_base * base,struct event_callback * evcb)2995ae2b84b2SNick Mathewson event_callback_activate_(struct event_base *base,
2996ae2b84b2SNick Mathewson     struct event_callback *evcb)
2997ae2b84b2SNick Mathewson {
2998ae2b84b2SNick Mathewson 	int r;
2999ae2b84b2SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
3000ae2b84b2SNick Mathewson 	r = event_callback_activate_nolock_(base, evcb);
3001ae2b84b2SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3002ae2b84b2SNick Mathewson 	return r;
3003ae2b84b2SNick Mathewson }
3004ae2b84b2SNick Mathewson 
3005ae2b84b2SNick Mathewson int
event_callback_activate_nolock_(struct event_base * base,struct event_callback * evcb)3006cba59e53SNick Mathewson event_callback_activate_nolock_(struct event_base *base,
3007cba59e53SNick Mathewson     struct event_callback *evcb)
3008cba59e53SNick Mathewson {
3009ae2b84b2SNick Mathewson 	int r = 1;
3010ae2b84b2SNick Mathewson 
30118eedeabeSNick Mathewson 	if (evcb->evcb_flags & EVLIST_FINALIZING)
30128eedeabeSNick Mathewson 		return 0;
30138eedeabeSNick Mathewson 
3014ae2b84b2SNick Mathewson 	switch (evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) {
3015ae2b84b2SNick Mathewson 	default:
3016ae2b84b2SNick Mathewson 		EVUTIL_ASSERT(0);
301740da44bdSAzat Khuzhin 		EVUTIL_FALLTHROUGH;
3018ae2b84b2SNick Mathewson 	case EVLIST_ACTIVE_LATER:
3019745a63dbSNick Mathewson 		event_queue_remove_active_later(base, evcb);
3020ae2b84b2SNick Mathewson 		r = 0;
3021ae2b84b2SNick Mathewson 		break;
3022ae2b84b2SNick Mathewson 	case EVLIST_ACTIVE:
3023ae2b84b2SNick Mathewson 		return 0;
3024ae2b84b2SNick Mathewson 	case 0:
3025ae2b84b2SNick Mathewson 		break;
3026ae2b84b2SNick Mathewson 	}
3027745a63dbSNick Mathewson 
3028cba59e53SNick Mathewson 	event_queue_insert_active(base, evcb);
30295beeec9dSNick Mathewson 
30305beeec9dSNick Mathewson 	if (EVBASE_NEED_NOTIFY(base))
30315beeec9dSNick Mathewson 		evthread_notify_base(base);
3032ae2b84b2SNick Mathewson 
3033ae2b84b2SNick Mathewson 	return r;
3034aa6567feSNiels Provos }
3035aa6567feSNiels Provos 
303638cef641SGreg Hazel int
event_callback_activate_later_nolock_(struct event_base * base,struct event_callback * evcb)3037745a63dbSNick Mathewson event_callback_activate_later_nolock_(struct event_base *base,
3038745a63dbSNick Mathewson     struct event_callback *evcb)
3039745a63dbSNick Mathewson {
3040745a63dbSNick Mathewson 	if (evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))
304138cef641SGreg Hazel 		return 0;
3042745a63dbSNick Mathewson 
3043745a63dbSNick Mathewson 	event_queue_insert_active_later(base, evcb);
3044745a63dbSNick Mathewson 	if (EVBASE_NEED_NOTIFY(base))
3045745a63dbSNick Mathewson 		evthread_notify_base(base);
304638cef641SGreg Hazel 	return 1;
3047745a63dbSNick Mathewson }
3048745a63dbSNick Mathewson 
3049745a63dbSNick Mathewson void
event_callback_init_(struct event_base * base,struct event_callback * cb)3050745a63dbSNick Mathewson event_callback_init_(struct event_base *base,
3051745a63dbSNick Mathewson     struct event_callback *cb)
3052745a63dbSNick Mathewson {
3053745a63dbSNick Mathewson 	memset(cb, 0, sizeof(*cb));
3054745a63dbSNick Mathewson 	cb->evcb_pri = base->nactivequeues - 1;
3055745a63dbSNick Mathewson }
3056745a63dbSNick Mathewson 
3057745a63dbSNick Mathewson int
event_callback_cancel_(struct event_base * base,struct event_callback * evcb)3058745a63dbSNick Mathewson event_callback_cancel_(struct event_base *base,
3059745a63dbSNick Mathewson     struct event_callback *evcb)
3060745a63dbSNick Mathewson {
3061745a63dbSNick Mathewson 	int r;
3062745a63dbSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
30638eedeabeSNick Mathewson 	r = event_callback_cancel_nolock_(base, evcb, 0);
3064745a63dbSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3065745a63dbSNick Mathewson 	return r;
3066745a63dbSNick Mathewson }
3067745a63dbSNick Mathewson 
3068745a63dbSNick Mathewson int
event_callback_cancel_nolock_(struct event_base * base,struct event_callback * evcb,int even_if_finalizing)3069745a63dbSNick Mathewson event_callback_cancel_nolock_(struct event_base *base,
30708eedeabeSNick Mathewson     struct event_callback *evcb, int even_if_finalizing)
3071745a63dbSNick Mathewson {
30728eedeabeSNick Mathewson 	if ((evcb->evcb_flags & EVLIST_FINALIZING) && !even_if_finalizing)
30738eedeabeSNick Mathewson 		return 0;
30748eedeabeSNick Mathewson 
3075745a63dbSNick Mathewson 	if (evcb->evcb_flags & EVLIST_INIT)
30768eedeabeSNick Mathewson 		return event_del_nolock_(event_callback_to_event(evcb),
30778eedeabeSNick Mathewson 		    even_if_finalizing ? EVENT_DEL_EVEN_IF_FINALIZING : EVENT_DEL_AUTOBLOCK);
3078745a63dbSNick Mathewson 
3079745a63dbSNick Mathewson 	switch ((evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER))) {
3080745a63dbSNick Mathewson 	default:
3081745a63dbSNick Mathewson 	case EVLIST_ACTIVE|EVLIST_ACTIVE_LATER:
3082745a63dbSNick Mathewson 		EVUTIL_ASSERT(0);
3083745a63dbSNick Mathewson 		break;
3084745a63dbSNick Mathewson 	case EVLIST_ACTIVE:
3085745a63dbSNick Mathewson 		/* We get different kinds of events, add them together */
3086745a63dbSNick Mathewson 		event_queue_remove_active(base, evcb);
3087745a63dbSNick Mathewson 		return 0;
3088745a63dbSNick Mathewson 	case EVLIST_ACTIVE_LATER:
3089745a63dbSNick Mathewson 		event_queue_remove_active_later(base, evcb);
3090745a63dbSNick Mathewson 		break;
3091745a63dbSNick Mathewson 	case 0:
3092745a63dbSNick Mathewson 		break;
3093745a63dbSNick Mathewson 	}
3094c0e425abSNick Mathewson 
3095745a63dbSNick Mathewson 	return 0;
3096745a63dbSNick Mathewson }
3097745a63dbSNick Mathewson 
3098745a63dbSNick Mathewson void
event_deferred_cb_init_(struct event_callback * cb,ev_uint8_t priority,deferred_cb_fn fn,void * arg)3099c0e425abSNick Mathewson event_deferred_cb_init_(struct event_callback *cb, ev_uint8_t priority, deferred_cb_fn fn, void *arg)
31004868f4d2SNick Mathewson {
3101ae2b84b2SNick Mathewson 	memset(cb, 0, sizeof(*cb));
3102ae2b84b2SNick Mathewson 	cb->evcb_cb_union.evcb_selfcb = fn;
3103ae2b84b2SNick Mathewson 	cb->evcb_arg = arg;
3104c0e425abSNick Mathewson 	cb->evcb_pri = priority;
3105ae2b84b2SNick Mathewson 	cb->evcb_closure = EV_CLOSURE_CB_SELF;
31064868f4d2SNick Mathewson }
31074868f4d2SNick Mathewson 
31084868f4d2SNick Mathewson void
event_deferred_cb_set_priority_(struct event_callback * cb,ev_uint8_t priority)3109c0e425abSNick Mathewson event_deferred_cb_set_priority_(struct event_callback *cb, ev_uint8_t priority)
3110c0e425abSNick Mathewson {
3111c0e425abSNick Mathewson 	cb->evcb_pri = priority;
3112c0e425abSNick Mathewson }
3113c0e425abSNick Mathewson 
3114c0e425abSNick Mathewson void
event_deferred_cb_cancel_(struct event_base * base,struct event_callback * cb)3115ae2b84b2SNick Mathewson event_deferred_cb_cancel_(struct event_base *base, struct event_callback *cb)
31164868f4d2SNick Mathewson {
3117ae2b84b2SNick Mathewson 	if (!base)
3118ae2b84b2SNick Mathewson 		base = current_base;
3119ae2b84b2SNick Mathewson 	event_callback_cancel_(base, cb);
3120b06b2649SNick Mathewson }
31214868f4d2SNick Mathewson 
3122c0e425abSNick Mathewson #define MAX_DEFERREDS_QUEUED 32
3123ae2b84b2SNick Mathewson int
event_deferred_cb_schedule_(struct event_base * base,struct event_callback * cb)3124ae2b84b2SNick Mathewson event_deferred_cb_schedule_(struct event_base *base, struct event_callback *cb)
31254868f4d2SNick Mathewson {
3126c0e425abSNick Mathewson 	int r = 1;
3127ae2b84b2SNick Mathewson 	if (!base)
3128ae2b84b2SNick Mathewson 		base = current_base;
3129c0e425abSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
3130c0e425abSNick Mathewson 	if (base->n_deferreds_queued > MAX_DEFERREDS_QUEUED) {
313138cef641SGreg Hazel 		r = event_callback_activate_later_nolock_(base, cb);
3132c0e425abSNick Mathewson 	} else {
3133c0e425abSNick Mathewson 		r = event_callback_activate_nolock_(base, cb);
313438cef641SGreg Hazel 		if (r) {
313538cef641SGreg Hazel 			++base->n_deferreds_queued;
313638cef641SGreg Hazel 		}
3137c0e425abSNick Mathewson 	}
3138c0e425abSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3139c0e425abSNick Mathewson 	return r;
31404868f4d2SNick Mathewson }
31414868f4d2SNick Mathewson 
31423ad6b47eSNiels Provos static int
timeout_next(struct event_base * base,struct timeval ** tv_p)31433ad6b47eSNiels Provos timeout_next(struct event_base *base, struct timeval **tv_p)
3144aa6567feSNiels Provos {
31456b22e74aSNick Mathewson 	/* Caller must hold th_base_lock */
3146aa6567feSNiels Provos 	struct timeval now;
3147aa6567feSNiels Provos 	struct event *ev;
31483ad6b47eSNiels Provos 	struct timeval *tv = *tv_p;
3149558de9b3SNiels Provos 	int res = 0;
3150aa6567feSNiels Provos 
31518ac3c4c2SNick Mathewson 	ev = min_heap_top_(&base->timeheap);
3152558de9b3SNiels Provos 
3153558de9b3SNiels Provos 	if (ev == NULL) {
31543ad6b47eSNiels Provos 		/* if no time-based events are active wait for I/O */
31553ad6b47eSNiels Provos 		*tv_p = NULL;
3156558de9b3SNiels Provos 		goto out;
3157aa6567feSNiels Provos 	}
3158aa6567feSNiels Provos 
315945e6fb0dSNiels Provos 	if (gettime(base, &now) == -1) {
3160558de9b3SNiels Provos 		res = -1;
3161558de9b3SNiels Provos 		goto out;
3162558de9b3SNiels Provos 	}
3163aa6567feSNiels Provos 
3164f74e7258SNick Mathewson 	if (evutil_timercmp(&ev->ev_timeout, &now, <=)) {
3165f74e7258SNick Mathewson 		evutil_timerclear(tv);
3166558de9b3SNiels Provos 		goto out;
3167aa6567feSNiels Provos 	}
3168aa6567feSNiels Provos 
3169f74e7258SNick Mathewson 	evutil_timersub(&ev->ev_timeout, &now, tv);
3170aa6567feSNiels Provos 
31712e36dbe1SNick Mathewson 	EVUTIL_ASSERT(tv->tv_sec >= 0);
31722e36dbe1SNick Mathewson 	EVUTIL_ASSERT(tv->tv_usec >= 0);
31734b7d2984SMark Ellzey 	event_debug(("timeout_next: event: %p, in %d seconds, %d useconds", ev, (int)tv->tv_sec, (int)tv->tv_usec));
3174558de9b3SNiels Provos 
3175558de9b3SNiels Provos out:
3176558de9b3SNiels Provos 	return (res);
3177aa6567feSNiels Provos }
3178aa6567feSNiels Provos 
3179cdd4c490SNick Mathewson /* Activate every event whose timeout has elapsed. */
3180f98385a4SNick Mathewson static void
timeout_process(struct event_base * base)31818773c4c9SNiels Provos timeout_process(struct event_base *base)
3182aa6567feSNiels Provos {
31836b22e74aSNick Mathewson 	/* Caller must hold lock. */
3184aa6567feSNiels Provos 	struct timeval now;
318530ae40ccSNiels Provos 	struct event *ev;
3186aa6567feSNiels Provos 
31878ac3c4c2SNick Mathewson 	if (min_heap_empty_(&base->timeheap)) {
3188f4c84e86SNick Mathewson 		return;
3189558de9b3SNiels Provos 	}
3190f4c84e86SNick Mathewson 
319145e6fb0dSNiels Provos 	gettime(base, &now);
3192aa6567feSNiels Provos 
31938ac3c4c2SNick Mathewson 	while ((ev = min_heap_top_(&base->timeheap))) {
3194f74e7258SNick Mathewson 		if (evutil_timercmp(&ev->ev_timeout, &now, >))
3195aa6567feSNiels Provos 			break;
3196aa6567feSNiels Provos 
3197aa6567feSNiels Provos 		/* delete this event from the I/O queues */
31988eedeabeSNick Mathewson 		event_del_nolock_(ev, EVENT_DEL_NOBLOCK);
3199aa6567feSNiels Provos 
320067275433SMark Ellzey 		event_debug(("timeout_process: event: %p, call %p",
320167275433SMark Ellzey 			 ev, ev->ev_callback));
32028ac3c4c2SNick Mathewson 		event_active_nolock_(ev, EV_TIMEOUT, 1);
3203aa6567feSNiels Provos 	}
3204aa6567feSNiels Provos }
3205aa6567feSNiels Provos 
32065173bef5SAndrew Sweeney #ifndef MAX
32075173bef5SAndrew Sweeney #define MAX(a,b) (((a)>(b))?(a):(b))
32085173bef5SAndrew Sweeney #endif
32095173bef5SAndrew Sweeney 
32105173bef5SAndrew Sweeney #define MAX_EVENT_COUNT(var, v) var = MAX(var, v)
32115173bef5SAndrew Sweeney 
3212d1cee3b1SNick Mathewson /* These are a fancy way to spell
321327a2ef5cSAzat Khuzhin      if (~flags & EVLIST_INTERNAL)
3214d1cee3b1SNick Mathewson          base->event_count--/++;
3215d1cee3b1SNick Mathewson */
3216cba59e53SNick Mathewson #define DECR_EVENT_COUNT(base,flags) \
321727a2ef5cSAzat Khuzhin 	((base)->event_count -= !((flags) & EVLIST_INTERNAL))
32185173bef5SAndrew Sweeney #define INCR_EVENT_COUNT(base,flags) do {					\
321927a2ef5cSAzat Khuzhin 	((base)->event_count += !((flags) & EVLIST_INTERNAL));			\
3220efbd3dcfSAndrew Sweeney 	MAX_EVENT_COUNT((base)->event_count_max, (base)->event_count);		\
32215173bef5SAndrew Sweeney } while (0)
3222d1cee3b1SNick Mathewson 
322359e8e959SNick Mathewson static void
event_queue_remove_inserted(struct event_base * base,struct event * ev)3224efc4dc50SNick Mathewson event_queue_remove_inserted(struct event_base *base, struct event *ev)
3225aa6567feSNiels Provos {
3226e2642f0aSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3227efc4dc50SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!(ev->ev_flags & EVLIST_INSERTED))) {
322856e48c10SNick Mathewson 		event_errx(1, "%s: %p(fd "EV_SOCK_FMT") not on queue %x", __func__,
322956e48c10SNick Mathewson 		    ev, EV_SOCK_ARG(ev->ev_fd), EVLIST_INSERTED);
323091fe23fcSNick Mathewson 		return;
323191fe23fcSNick Mathewson 	}
3232cba59e53SNick Mathewson 	DECR_EVENT_COUNT(base, ev->ev_flags);
3233efc4dc50SNick Mathewson 	ev->ev_flags &= ~EVLIST_INSERTED;
3234efc4dc50SNick Mathewson }
3235efc4dc50SNick Mathewson static void
event_queue_remove_active(struct event_base * base,struct event_callback * evcb)3236cba59e53SNick Mathewson event_queue_remove_active(struct event_base *base, struct event_callback *evcb)
3237efc4dc50SNick Mathewson {
3238efc4dc50SNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3239cba59e53SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!(evcb->evcb_flags & EVLIST_ACTIVE))) {
3240cba59e53SNick Mathewson 		event_errx(1, "%s: %p not on queue %x", __func__,
3241cba59e53SNick Mathewson 			   evcb, EVLIST_ACTIVE);
3242efc4dc50SNick Mathewson 		return;
3243efc4dc50SNick Mathewson 	}
3244cba59e53SNick Mathewson 	DECR_EVENT_COUNT(base, evcb->evcb_flags);
3245cba59e53SNick Mathewson 	evcb->evcb_flags &= ~EVLIST_ACTIVE;
324603589ccbSNiels Provos 	base->event_count_active--;
3247cba59e53SNick Mathewson 
3248cba59e53SNick Mathewson 	TAILQ_REMOVE(&base->activequeues[evcb->evcb_pri],
3249cba59e53SNick Mathewson 	    evcb, evcb_active_next);
3250efc4dc50SNick Mathewson }
3251efc4dc50SNick Mathewson static void
event_queue_remove_active_later(struct event_base * base,struct event_callback * evcb)3252745a63dbSNick Mathewson event_queue_remove_active_later(struct event_base *base, struct event_callback *evcb)
3253745a63dbSNick Mathewson {
3254745a63dbSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3255745a63dbSNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!(evcb->evcb_flags & EVLIST_ACTIVE_LATER))) {
3256745a63dbSNick Mathewson 		event_errx(1, "%s: %p not on queue %x", __func__,
3257745a63dbSNick Mathewson 			   evcb, EVLIST_ACTIVE_LATER);
3258745a63dbSNick Mathewson 		return;
3259745a63dbSNick Mathewson 	}
3260745a63dbSNick Mathewson 	DECR_EVENT_COUNT(base, evcb->evcb_flags);
3261745a63dbSNick Mathewson 	evcb->evcb_flags &= ~EVLIST_ACTIVE_LATER;
3262745a63dbSNick Mathewson 	base->event_count_active--;
3263745a63dbSNick Mathewson 
3264745a63dbSNick Mathewson 	TAILQ_REMOVE(&base->active_later_queue, evcb, evcb_active_next);
3265745a63dbSNick Mathewson }
3266745a63dbSNick Mathewson static void
event_queue_remove_timeout(struct event_base * base,struct event * ev)3267efc4dc50SNick Mathewson event_queue_remove_timeout(struct event_base *base, struct event *ev)
3268efc4dc50SNick Mathewson {
3269efc4dc50SNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3270efc4dc50SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(!(ev->ev_flags & EVLIST_TIMEOUT))) {
32712e6a9850SNick Mathewson 		event_errx(1, "%s: %p(fd "EV_SOCK_FMT") not on queue %x", __func__,
32722e6a9850SNick Mathewson 		    ev, EV_SOCK_ARG(ev->ev_fd), EVLIST_TIMEOUT);
3273efc4dc50SNick Mathewson 		return;
3274efc4dc50SNick Mathewson 	}
3275cba59e53SNick Mathewson 	DECR_EVENT_COUNT(base, ev->ev_flags);
3276efc4dc50SNick Mathewson 	ev->ev_flags &= ~EVLIST_TIMEOUT;
3277efc4dc50SNick Mathewson 
3278693c24efSNick Mathewson 	if (is_common_timeout(&ev->ev_timeout, base)) {
3279693c24efSNick Mathewson 		struct common_timeout_list *ctl =
3280693c24efSNick Mathewson 		    get_common_timeout_list(base, &ev->ev_timeout);
3281693c24efSNick Mathewson 		TAILQ_REMOVE(&ctl->events, ev,
3282693c24efSNick Mathewson 		    ev_timeout_pos.ev_next_with_common_timeout);
3283693c24efSNick Mathewson 	} else {
32848ac3c4c2SNick Mathewson 		min_heap_erase_(&base->timeheap, ev);
3285693c24efSNick Mathewson 	}
3286aa6567feSNiels Provos }
3287aa6567feSNiels Provos 
328809cbc3dcSNick Mathewson #ifdef USE_REINSERT_TIMEOUT
3289e91d57f1SNick Mathewson /* Remove and reinsert 'ev' into the timeout queue. */
3290e47042feSNick Mathewson static void
event_queue_reinsert_timeout(struct event_base * base,struct event * ev,int was_common,int is_common,int old_timeout_idx)32918c36acd0SNick Mathewson event_queue_reinsert_timeout(struct event_base *base, struct event *ev,
32928c36acd0SNick Mathewson     int was_common, int is_common, int old_timeout_idx)
3293e47042feSNick Mathewson {
32948c36acd0SNick Mathewson 	struct common_timeout_list *ctl;
3295e91d57f1SNick Mathewson 	if (!(ev->ev_flags & EVLIST_TIMEOUT)) {
3296e91d57f1SNick Mathewson 		event_queue_insert_timeout(base, ev);
3297e47042feSNick Mathewson 		return;
3298e47042feSNick Mathewson 	}
3299e47042feSNick Mathewson 
33008c36acd0SNick Mathewson 	switch ((was_common<<1) | is_common) {
33018c36acd0SNick Mathewson 	case 3: /* Changing from one common timeout to another */
33028c36acd0SNick Mathewson 		ctl = base->common_timeout_queues[old_timeout_idx];
3303e47042feSNick Mathewson 		TAILQ_REMOVE(&ctl->events, ev,
3304e47042feSNick Mathewson 		    ev_timeout_pos.ev_next_with_common_timeout);
33058c36acd0SNick Mathewson 		ctl = get_common_timeout_list(base, &ev->ev_timeout);
3306e47042feSNick Mathewson 		insert_common_timeout_inorder(ctl, ev);
33078c36acd0SNick Mathewson 		break;
33088c36acd0SNick Mathewson 	case 2: /* Was common; is no longer common */
33098c36acd0SNick Mathewson 		ctl = base->common_timeout_queues[old_timeout_idx];
33108c36acd0SNick Mathewson 		TAILQ_REMOVE(&ctl->events, ev,
33118c36acd0SNick Mathewson 		    ev_timeout_pos.ev_next_with_common_timeout);
33128c36acd0SNick Mathewson 		min_heap_push_(&base->timeheap, ev);
33138c36acd0SNick Mathewson 		break;
33148c36acd0SNick Mathewson 	case 1: /* Wasn't common; has become common. */
33158c36acd0SNick Mathewson 		min_heap_erase_(&base->timeheap, ev);
33168c36acd0SNick Mathewson 		ctl = get_common_timeout_list(base, &ev->ev_timeout);
33178c36acd0SNick Mathewson 		insert_common_timeout_inorder(ctl, ev);
33188c36acd0SNick Mathewson 		break;
33198c36acd0SNick Mathewson 	case 0: /* was in heap; is still on heap. */
33208ac3c4c2SNick Mathewson 		min_heap_adjust_(&base->timeheap, ev);
33218c36acd0SNick Mathewson 		break;
33228c36acd0SNick Mathewson 	default:
33238c36acd0SNick Mathewson 		EVUTIL_ASSERT(0); /* unreachable */
33248c36acd0SNick Mathewson 		break;
3325e47042feSNick Mathewson 	}
3326e47042feSNick Mathewson }
332709cbc3dcSNick Mathewson #endif
3328e47042feSNick Mathewson 
3329cdd4c490SNick Mathewson /* Add 'ev' to the common timeout list in 'ev'. */
333059e8e959SNick Mathewson static void
insert_common_timeout_inorder(struct common_timeout_list * ctl,struct event * ev)333159be8942SNick Mathewson insert_common_timeout_inorder(struct common_timeout_list *ctl,
333259be8942SNick Mathewson     struct event *ev)
333359be8942SNick Mathewson {
333459be8942SNick Mathewson 	struct event *e;
3335cdd4c490SNick Mathewson 	/* By all logic, we should just be able to append 'ev' to the end of
3336cdd4c490SNick Mathewson 	 * ctl->events, since the timeout on each 'ev' is set to {the common
3337cdd4c490SNick Mathewson 	 * timeout} + {the time when we add the event}, and so the events
3338cdd4c490SNick Mathewson 	 * should arrive in order of their timeeouts.  But just in case
3339cdd4c490SNick Mathewson 	 * there's some wacky threading issue going on, we do a search from
3340cdd4c490SNick Mathewson 	 * the end of 'ev' to find the right insertion point.
3341cdd4c490SNick Mathewson 	 */
334259be8942SNick Mathewson 	TAILQ_FOREACH_REVERSE(e, &ctl->events,
334371afc525SFrank Denis 	    event_list, ev_timeout_pos.ev_next_with_common_timeout) {
334459be8942SNick Mathewson 		/* This timercmp is a little sneaky, since both ev and e have
334559be8942SNick Mathewson 		 * magic values in tv_usec.  Fortunately, they ought to have
334659be8942SNick Mathewson 		 * the _same_ magic values in tv_usec.  Let's assert for that.
334759be8942SNick Mathewson 		 */
3348e88079a8SNick Mathewson 		EVUTIL_ASSERT(
3349e88079a8SNick Mathewson 			is_same_common_timeout(&e->ev_timeout, &ev->ev_timeout));
335059be8942SNick Mathewson 		if (evutil_timercmp(&ev->ev_timeout, &e->ev_timeout, >=)) {
335159be8942SNick Mathewson 			TAILQ_INSERT_AFTER(&ctl->events, e, ev,
335259be8942SNick Mathewson 			    ev_timeout_pos.ev_next_with_common_timeout);
335359be8942SNick Mathewson 			return;
335459be8942SNick Mathewson 		}
335559be8942SNick Mathewson 	}
335659be8942SNick Mathewson 	TAILQ_INSERT_HEAD(&ctl->events, ev,
335759be8942SNick Mathewson 	    ev_timeout_pos.ev_next_with_common_timeout);
335859be8942SNick Mathewson }
335959be8942SNick Mathewson 
336059be8942SNick Mathewson static void
event_queue_insert_inserted(struct event_base * base,struct event * ev)3361efc4dc50SNick Mathewson event_queue_insert_inserted(struct event_base *base, struct event *ev)
3362aa6567feSNiels Provos {
3363e2642f0aSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3364e2642f0aSNick Mathewson 
3365efc4dc50SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(ev->ev_flags & EVLIST_INSERTED)) {
33662e6a9850SNick Mathewson 		event_errx(1, "%s: %p(fd "EV_SOCK_FMT") already inserted", __func__,
33672e6a9850SNick Mathewson 		    ev, EV_SOCK_ARG(ev->ev_fd));
336891fe23fcSNick Mathewson 		return;
336903589ccbSNiels Provos 	}
3370aa6567feSNiels Provos 
3371cba59e53SNick Mathewson 	INCR_EVENT_COUNT(base, ev->ev_flags);
3372025d1bc2SNiels Provos 
3373efc4dc50SNick Mathewson 	ev->ev_flags |= EVLIST_INSERTED;
3374efc4dc50SNick Mathewson }
3375efc4dc50SNick Mathewson 
3376efc4dc50SNick Mathewson static void
event_queue_insert_active(struct event_base * base,struct event_callback * evcb)3377cba59e53SNick Mathewson event_queue_insert_active(struct event_base *base, struct event_callback *evcb)
3378efc4dc50SNick Mathewson {
3379efc4dc50SNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3380efc4dc50SNick Mathewson 
3381cba59e53SNick Mathewson 	if (evcb->evcb_flags & EVLIST_ACTIVE) {
3382efc4dc50SNick Mathewson 		/* Double insertion is possible for active events */
3383efc4dc50SNick Mathewson 		return;
3384efc4dc50SNick Mathewson 	}
3385efc4dc50SNick Mathewson 
3386cba59e53SNick Mathewson 	INCR_EVENT_COUNT(base, evcb->evcb_flags);
3387efc4dc50SNick Mathewson 
3388cba59e53SNick Mathewson 	evcb->evcb_flags |= EVLIST_ACTIVE;
3389efc4dc50SNick Mathewson 
339003589ccbSNiels Provos 	base->event_count_active++;
33915173bef5SAndrew Sweeney 	MAX_EVENT_COUNT(base->event_count_active_max, base->event_count_active);
3392c0e425abSNick Mathewson 	EVUTIL_ASSERT(evcb->evcb_pri < base->nactivequeues);
3393cba59e53SNick Mathewson 	TAILQ_INSERT_TAIL(&base->activequeues[evcb->evcb_pri],
3394cba59e53SNick Mathewson 	    evcb, evcb_active_next);
3395efc4dc50SNick Mathewson }
3396efc4dc50SNick Mathewson 
3397efc4dc50SNick Mathewson static void
event_queue_insert_active_later(struct event_base * base,struct event_callback * evcb)3398745a63dbSNick Mathewson event_queue_insert_active_later(struct event_base *base, struct event_callback *evcb)
3399745a63dbSNick Mathewson {
3400745a63dbSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3401745a63dbSNick Mathewson 	if (evcb->evcb_flags & (EVLIST_ACTIVE_LATER|EVLIST_ACTIVE)) {
3402745a63dbSNick Mathewson 		/* Double insertion is possible */
3403745a63dbSNick Mathewson 		return;
3404745a63dbSNick Mathewson 	}
3405745a63dbSNick Mathewson 
3406745a63dbSNick Mathewson 	INCR_EVENT_COUNT(base, evcb->evcb_flags);
3407745a63dbSNick Mathewson 	evcb->evcb_flags |= EVLIST_ACTIVE_LATER;
3408745a63dbSNick Mathewson 	base->event_count_active++;
34095173bef5SAndrew Sweeney 	MAX_EVENT_COUNT(base->event_count_active_max, base->event_count_active);
3410c0e425abSNick Mathewson 	EVUTIL_ASSERT(evcb->evcb_pri < base->nactivequeues);
3411745a63dbSNick Mathewson 	TAILQ_INSERT_TAIL(&base->active_later_queue, evcb, evcb_active_next);
3412745a63dbSNick Mathewson }
3413745a63dbSNick Mathewson 
3414745a63dbSNick Mathewson static void
event_queue_insert_timeout(struct event_base * base,struct event * ev)3415efc4dc50SNick Mathewson event_queue_insert_timeout(struct event_base *base, struct event *ev)
3416efc4dc50SNick Mathewson {
3417efc4dc50SNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3418efc4dc50SNick Mathewson 
3419efc4dc50SNick Mathewson 	if (EVUTIL_FAILURE_CHECK(ev->ev_flags & EVLIST_TIMEOUT)) {
34202e6a9850SNick Mathewson 		event_errx(1, "%s: %p(fd "EV_SOCK_FMT") already on timeout", __func__,
34212e6a9850SNick Mathewson 		    ev, EV_SOCK_ARG(ev->ev_fd));
3422efc4dc50SNick Mathewson 		return;
3423efc4dc50SNick Mathewson 	}
3424efc4dc50SNick Mathewson 
3425cba59e53SNick Mathewson 	INCR_EVENT_COUNT(base, ev->ev_flags);
3426efc4dc50SNick Mathewson 
3427efc4dc50SNick Mathewson 	ev->ev_flags |= EVLIST_TIMEOUT;
3428efc4dc50SNick Mathewson 
3429693c24efSNick Mathewson 	if (is_common_timeout(&ev->ev_timeout, base)) {
3430693c24efSNick Mathewson 		struct common_timeout_list *ctl =
3431693c24efSNick Mathewson 		    get_common_timeout_list(base, &ev->ev_timeout);
343259be8942SNick Mathewson 		insert_common_timeout_inorder(ctl, ev);
3433efc4dc50SNick Mathewson 	} else {
34348ac3c4c2SNick Mathewson 		min_heap_push_(&base->timeheap, ev);
3435aa6567feSNiels Provos 	}
3436aa6567feSNiels Provos }
3437c5e4eee0SNiels Provos 
3438745a63dbSNick Mathewson static void
event_queue_make_later_events_active(struct event_base * base)3439745a63dbSNick Mathewson event_queue_make_later_events_active(struct event_base *base)
3440745a63dbSNick Mathewson {
3441745a63dbSNick Mathewson 	struct event_callback *evcb;
3442745a63dbSNick Mathewson 	EVENT_BASE_ASSERT_LOCKED(base);
3443745a63dbSNick Mathewson 
3444745a63dbSNick Mathewson 	while ((evcb = TAILQ_FIRST(&base->active_later_queue))) {
3445745a63dbSNick Mathewson 		TAILQ_REMOVE(&base->active_later_queue, evcb, evcb_active_next);
3446745a63dbSNick Mathewson 		evcb->evcb_flags = (evcb->evcb_flags & ~EVLIST_ACTIVE_LATER) | EVLIST_ACTIVE;
3447c0e425abSNick Mathewson 		EVUTIL_ASSERT(evcb->evcb_pri < base->nactivequeues);
3448745a63dbSNick Mathewson 		TAILQ_INSERT_TAIL(&base->activequeues[evcb->evcb_pri], evcb, evcb_active_next);
3449c0e425abSNick Mathewson 		base->n_deferreds_queued += (evcb->evcb_closure == EV_CLOSURE_CB_SELF);
3450745a63dbSNick Mathewson 	}
3451745a63dbSNick Mathewson }
3452745a63dbSNick Mathewson 
3453c5e4eee0SNiels Provos /* Functions for debugging */
3454c5e4eee0SNiels Provos 
3455c5e4eee0SNiels Provos const char *
event_get_version(void)3456c5e4eee0SNiels Provos event_get_version(void)
3457c5e4eee0SNiels Provos {
345868120d9bSNick Mathewson 	return (EVENT__VERSION);
3459c5e4eee0SNiels Provos }
3460c5e4eee0SNiels Provos 
3461d047b323SNick Mathewson ev_uint32_t
event_get_version_number(void)3462d047b323SNick Mathewson event_get_version_number(void)
3463d047b323SNick Mathewson {
346468120d9bSNick Mathewson 	return (EVENT__NUMERIC_VERSION);
3465d047b323SNick Mathewson }
3466d047b323SNick Mathewson 
3467c5e4eee0SNiels Provos /*
3468c5e4eee0SNiels Provos  * No thread-safe interface needed - the information should be the same
3469c5e4eee0SNiels Provos  * for all threads.
3470c5e4eee0SNiels Provos  */
3471c5e4eee0SNiels Provos 
3472c5e4eee0SNiels Provos const char *
event_get_method(void)3473c5e4eee0SNiels Provos event_get_method(void)
3474c5e4eee0SNiels Provos {
3475c5e4eee0SNiels Provos 	return (current_base->evsel->name);
3476c5e4eee0SNiels Provos }
34777eb250e9SNick Mathewson 
347868120d9bSNick Mathewson #ifndef EVENT__DISABLE_MM_REPLACEMENT
3479cb9da0bfSNick Mathewson static void *(*mm_malloc_fn_)(size_t sz) = NULL;
3480cb9da0bfSNick Mathewson static void *(*mm_realloc_fn_)(void *p, size_t sz) = NULL;
3481cb9da0bfSNick Mathewson static void (*mm_free_fn_)(void *p) = NULL;
34827eb250e9SNick Mathewson 
34837eb250e9SNick Mathewson void *
event_mm_malloc_(size_t sz)348499e50e90SNick Mathewson event_mm_malloc_(size_t sz)
34857eb250e9SNick Mathewson {
3486c8953d1bSMansour Moufid 	if (sz == 0)
3487c8953d1bSMansour Moufid 		return NULL;
3488c8953d1bSMansour Moufid 
3489cb9da0bfSNick Mathewson 	if (mm_malloc_fn_)
3490cb9da0bfSNick Mathewson 		return mm_malloc_fn_(sz);
34917eb250e9SNick Mathewson 	else
34927eb250e9SNick Mathewson 		return malloc(sz);
34937eb250e9SNick Mathewson }
34947eb250e9SNick Mathewson 
34957eb250e9SNick Mathewson void *
event_mm_calloc_(size_t count,size_t size)349699e50e90SNick Mathewson event_mm_calloc_(size_t count, size_t size)
34977eb250e9SNick Mathewson {
3498c8953d1bSMansour Moufid 	if (count == 0 || size == 0)
3499c8953d1bSMansour Moufid 		return NULL;
3500c8953d1bSMansour Moufid 
3501cb9da0bfSNick Mathewson 	if (mm_malloc_fn_) {
35027eb250e9SNick Mathewson 		size_t sz = count * size;
3503c8953d1bSMansour Moufid 		void *p = NULL;
3504c8953d1bSMansour Moufid 		if (count > EV_SIZE_MAX / size)
3505c8953d1bSMansour Moufid 			goto error;
3506cb9da0bfSNick Mathewson 		p = mm_malloc_fn_(sz);
35077eb250e9SNick Mathewson 		if (p)
3508c8953d1bSMansour Moufid 			return memset(p, 0, sz);
3509af7ba695SNick Mathewson 	} else {
3510af7ba695SNick Mathewson 		void *p = calloc(count, size);
3511af7ba695SNick Mathewson #ifdef _WIN32
3512af7ba695SNick Mathewson 		/* Windows calloc doesn't reliably set ENOMEM */
3513af7ba695SNick Mathewson 		if (p == NULL)
3514af7ba695SNick Mathewson 			goto error;
3515af7ba695SNick Mathewson #endif
3516af7ba695SNick Mathewson 		return p;
3517af7ba695SNick Mathewson 	}
3518c8953d1bSMansour Moufid 
3519c8953d1bSMansour Moufid error:
3520c8953d1bSMansour Moufid 	errno = ENOMEM;
3521c8953d1bSMansour Moufid 	return NULL;
35227eb250e9SNick Mathewson }
35237eb250e9SNick Mathewson 
35247eb250e9SNick Mathewson char *
event_mm_strdup_(const char * str)352599e50e90SNick Mathewson event_mm_strdup_(const char *str)
35267eb250e9SNick Mathewson {
3527c8953d1bSMansour Moufid 	if (!str) {
3528c8953d1bSMansour Moufid 		errno = EINVAL;
3529c8953d1bSMansour Moufid 		return NULL;
3530c8953d1bSMansour Moufid 	}
3531c8953d1bSMansour Moufid 
3532cb9da0bfSNick Mathewson 	if (mm_malloc_fn_) {
35337eb250e9SNick Mathewson 		size_t ln = strlen(str);
3534c8953d1bSMansour Moufid 		void *p = NULL;
3535c8953d1bSMansour Moufid 		if (ln == EV_SIZE_MAX)
3536c8953d1bSMansour Moufid 			goto error;
3537cb9da0bfSNick Mathewson 		p = mm_malloc_fn_(ln+1);
35387eb250e9SNick Mathewson 		if (p)
3539c8953d1bSMansour Moufid 			return memcpy(p, str, ln+1);
35407eb250e9SNick Mathewson 	} else
35419f560bfaSNick Mathewson #ifdef _WIN32
35427eb250e9SNick Mathewson 		return _strdup(str);
35437eb250e9SNick Mathewson #else
35447eb250e9SNick Mathewson 		return strdup(str);
35457eb250e9SNick Mathewson #endif
3546c8953d1bSMansour Moufid 
3547c8953d1bSMansour Moufid error:
3548c8953d1bSMansour Moufid 	errno = ENOMEM;
3549c8953d1bSMansour Moufid 	return NULL;
35507eb250e9SNick Mathewson }
35517eb250e9SNick Mathewson 
35527eb250e9SNick Mathewson void *
event_mm_realloc_(void * ptr,size_t sz)355399e50e90SNick Mathewson event_mm_realloc_(void *ptr, size_t sz)
35547eb250e9SNick Mathewson {
3555cb9da0bfSNick Mathewson 	if (mm_realloc_fn_)
3556cb9da0bfSNick Mathewson 		return mm_realloc_fn_(ptr, sz);
35577eb250e9SNick Mathewson 	else
35587eb250e9SNick Mathewson 		return realloc(ptr, sz);
35597eb250e9SNick Mathewson }
35607eb250e9SNick Mathewson 
35617eb250e9SNick Mathewson void
event_mm_free_(void * ptr)356299e50e90SNick Mathewson event_mm_free_(void *ptr)
35637eb250e9SNick Mathewson {
3564cb9da0bfSNick Mathewson 	if (mm_free_fn_)
3565cb9da0bfSNick Mathewson 		mm_free_fn_(ptr);
35667eb250e9SNick Mathewson 	else
35677eb250e9SNick Mathewson 		free(ptr);
35687eb250e9SNick Mathewson }
35697eb250e9SNick Mathewson 
35707eb250e9SNick Mathewson void
event_set_mem_functions(void * (* malloc_fn)(size_t sz),void * (* realloc_fn)(void * ptr,size_t sz),void (* free_fn)(void * ptr))35717eb250e9SNick Mathewson event_set_mem_functions(void *(*malloc_fn)(size_t sz),
35727eb250e9SNick Mathewson 			void *(*realloc_fn)(void *ptr, size_t sz),
35737eb250e9SNick Mathewson 			void (*free_fn)(void *ptr))
35747eb250e9SNick Mathewson {
3575cb9da0bfSNick Mathewson 	mm_malloc_fn_ = malloc_fn;
3576cb9da0bfSNick Mathewson 	mm_realloc_fn_ = realloc_fn;
3577cb9da0bfSNick Mathewson 	mm_free_fn_ = free_fn;
35787eb250e9SNick Mathewson }
35797fa8451dSNick Mathewson #endif
3580ec35eb55SNick Mathewson 
35812449e0c5SNick Mathewson #ifdef EVENT__HAVE_EVENTFD
3582558de9b3SNiels Provos static void
evthread_notify_drain_eventfd(evutil_socket_t fd,short what,void * arg)3583c7cf6f00SNick Mathewson evthread_notify_drain_eventfd(evutil_socket_t fd, short what, void *arg)
3584a5901991SNick Mathewson {
3585a5901991SNick Mathewson 	ev_uint64_t msg;
358606a4443aSNick Mathewson 	ev_ssize_t r;
35874632b78eSNick Mathewson 	struct event_base *base = arg;
3588a5901991SNick Mathewson 
358906a4443aSNick Mathewson 	r = read(fd, (void*) &msg, sizeof(msg));
359006a4443aSNick Mathewson 	if (r<0 && errno != EAGAIN) {
359106a4443aSNick Mathewson 		event_sock_warn(fd, "Error reading from eventfd");
359206a4443aSNick Mathewson 	}
35934632b78eSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
35944632b78eSNick Mathewson 	base->is_notify_pending = 0;
35954632b78eSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3596a5901991SNick Mathewson }
35972449e0c5SNick Mathewson #endif
3598a5901991SNick Mathewson 
3599a5901991SNick Mathewson static void
evthread_notify_drain_default(evutil_socket_t fd,short what,void * arg)3600a5901991SNick Mathewson evthread_notify_drain_default(evutil_socket_t fd, short what, void *arg)
3601558de9b3SNiels Provos {
3602a5bc15b2SNick Mathewson 	unsigned char buf[1024];
36034632b78eSNick Mathewson 	struct event_base *base = arg;
36049f560bfaSNick Mathewson #ifdef _WIN32
3605c3e9fcf6SNick Mathewson 	while (recv(fd, (char*)buf, sizeof(buf), 0) > 0)
3606c3e9fcf6SNick Mathewson 		;
360734d2fd06SNick Mathewson #else
3608c3e9fcf6SNick Mathewson 	while (read(fd, (char*)buf, sizeof(buf)) > 0)
3609c3e9fcf6SNick Mathewson 		;
361034d2fd06SNick Mathewson #endif
36114632b78eSNick Mathewson 
36124632b78eSNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
36134632b78eSNick Mathewson 	base->is_notify_pending = 0;
36144632b78eSNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3615558de9b3SNiels Provos }
3616558de9b3SNiels Provos 
3617ec4cfa33SNick Mathewson int
evthread_make_base_notifiable(struct event_base * base)3618ec4cfa33SNick Mathewson evthread_make_base_notifiable(struct event_base *base)
3619ec4cfa33SNick Mathewson {
36209cd5acb5SNick Mathewson 	int r;
3621ec4cfa33SNick Mathewson 	if (!base)
3622ec4cfa33SNick Mathewson 		return -1;
3623ec4cfa33SNick Mathewson 
36249cd5acb5SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
36259cd5acb5SNick Mathewson 	r = evthread_make_base_notifiable_nolock_(base);
36269cd5acb5SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
36279cd5acb5SNick Mathewson 	return r;
36289cd5acb5SNick Mathewson }
36299cd5acb5SNick Mathewson 
36309cd5acb5SNick Mathewson static int
evthread_make_base_notifiable_nolock_(struct event_base * base)36319cd5acb5SNick Mathewson evthread_make_base_notifiable_nolock_(struct event_base *base)
36329cd5acb5SNick Mathewson {
36339cd5acb5SNick Mathewson 	void (*cb)(evutil_socket_t, short, void *);
36349cd5acb5SNick Mathewson 	int (*notify)(struct event_base *);
36359cd5acb5SNick Mathewson 
363694b8e676SNick Mathewson 	if (base->th_notify_fn != NULL) {
363794b8e676SNick Mathewson 		/* The base is already notifiable: we're doing fine. */
3638ec4cfa33SNick Mathewson 		return 0;
363994b8e676SNick Mathewson 	}
3640ec4cfa33SNick Mathewson 
364153a07fe2SNick Mathewson #if defined(EVENT__HAVE_WORKING_KQUEUE)
364253a07fe2SNick Mathewson 	if (base->evsel == &kqops && event_kq_add_notify_event_(base) == 0) {
364353a07fe2SNick Mathewson 		base->th_notify_fn = event_kq_notify_base_;
364453a07fe2SNick Mathewson 		/* No need to add an event here; the backend can wake
364553a07fe2SNick Mathewson 		 * itself up just fine. */
364653a07fe2SNick Mathewson 		return 0;
364753a07fe2SNick Mathewson 	}
364853a07fe2SNick Mathewson #endif
364953a07fe2SNick Mathewson 
36502449e0c5SNick Mathewson #ifdef EVENT__HAVE_EVENTFD
36518ac3c4c2SNick Mathewson 	base->th_notify_fd[0] = evutil_eventfd_(0,
3652ca76cd93SNick Mathewson 	    EVUTIL_EFD_CLOEXEC|EVUTIL_EFD_NONBLOCK);
3653a5901991SNick Mathewson 	if (base->th_notify_fd[0] >= 0) {
3654ca76cd93SNick Mathewson 		base->th_notify_fd[1] = -1;
3655a5901991SNick Mathewson 		notify = evthread_notify_base_eventfd;
3656a5901991SNick Mathewson 		cb = evthread_notify_drain_eventfd;
36572449e0c5SNick Mathewson 	} else
36582449e0c5SNick Mathewson #endif
36592449e0c5SNick Mathewson 	if (evutil_make_internal_pipe_(base->th_notify_fd) == 0) {
3660ca76cd93SNick Mathewson 		notify = evthread_notify_base_default;
3661ca76cd93SNick Mathewson 		cb = evthread_notify_drain_default;
36623ab578f8SNick Mathewson 	} else {
3663ca76cd93SNick Mathewson 		return -1;
36643ab578f8SNick Mathewson 	}
3665ec4cfa33SNick Mathewson 
3666a5901991SNick Mathewson 	base->th_notify_fn = notify;
3667a5901991SNick Mathewson 
3668558de9b3SNiels Provos 	/* prepare an event that we can use for wakeup */
36695e6f6dcdSNick Mathewson 	event_assign(&base->th_notify, base, base->th_notify_fd[0],
36705e6f6dcdSNick Mathewson 				 EV_READ|EV_PERSIST, cb, base);
36715fbc7f0aSNick Mathewson 
3672558de9b3SNiels Provos 	/* we need to mark this as internal event */
3673558de9b3SNiels Provos 	base->th_notify.ev_flags |= EVLIST_INTERNAL;
367490651b32SNick Mathewson 	event_priority_set(&base->th_notify, 0);
3675558de9b3SNiels Provos 
36769cd5acb5SNick Mathewson 	return event_add_nolock_(&base->th_notify, NULL, 0);
3677558de9b3SNiels Provos }
3678558de9b3SNiels Provos 
3679c89b4e63SNick Mathewson int
event_base_foreach_event_nolock_(struct event_base * base,event_base_foreach_event_cb fn,void * arg)3680232055efSNick Mathewson event_base_foreach_event_nolock_(struct event_base *base,
368184fd6d75SRoman Puls     event_base_foreach_event_cb fn, void *arg)
3682a68de252SNick Mathewson {
3683c89b4e63SNick Mathewson 	int r, i;
368418104973SAzat Khuzhin 	unsigned u;
3685c89b4e63SNick Mathewson 	struct event *ev;
3686c89b4e63SNick Mathewson 
3687c89b4e63SNick Mathewson 	/* Start out with all the EVLIST_INSERTED events. */
36888ac3c4c2SNick Mathewson 	if ((r = evmap_foreach_event_(base, fn, arg)))
3689c89b4e63SNick Mathewson 		return r;
3690c89b4e63SNick Mathewson 
3691c89b4e63SNick Mathewson 	/* Okay, now we deal with those events that have timeouts and are in
3692c89b4e63SNick Mathewson 	 * the min-heap. */
3693c89b4e63SNick Mathewson 	for (u = 0; u < base->timeheap.n; ++u) {
3694c89b4e63SNick Mathewson 		ev = base->timeheap.p[u];
3695c89b4e63SNick Mathewson 		if (ev->ev_flags & EVLIST_INSERTED) {
3696c89b4e63SNick Mathewson 			/* we already processed this one */
3697c89b4e63SNick Mathewson 			continue;
3698c89b4e63SNick Mathewson 		}
3699c89b4e63SNick Mathewson 		if ((r = fn(base, ev, arg)))
3700c89b4e63SNick Mathewson 			return r;
3701c89b4e63SNick Mathewson 	}
3702c89b4e63SNick Mathewson 
3703c89b4e63SNick Mathewson 	/* Now for the events in one of the timeout queues.
3704c89b4e63SNick Mathewson 	 * the min-heap. */
3705c89b4e63SNick Mathewson 	for (i = 0; i < base->n_common_timeouts; ++i) {
3706c89b4e63SNick Mathewson 		struct common_timeout_list *ctl =
3707c89b4e63SNick Mathewson 		    base->common_timeout_queues[i];
3708c89b4e63SNick Mathewson 		TAILQ_FOREACH(ev, &ctl->events,
3709c89b4e63SNick Mathewson 		    ev_timeout_pos.ev_next_with_common_timeout) {
3710c89b4e63SNick Mathewson 			if (ev->ev_flags & EVLIST_INSERTED) {
3711c89b4e63SNick Mathewson 				/* we already processed this one */
3712c89b4e63SNick Mathewson 				continue;
3713c89b4e63SNick Mathewson 			}
3714c89b4e63SNick Mathewson 			if ((r = fn(base, ev, arg)))
3715c89b4e63SNick Mathewson 				return r;
3716c89b4e63SNick Mathewson 		}
3717c89b4e63SNick Mathewson 	}
3718c89b4e63SNick Mathewson 
3719c89b4e63SNick Mathewson 	/* Finally, we deal wit all the active events that we haven't touched
3720c89b4e63SNick Mathewson 	 * yet. */
3721c89b4e63SNick Mathewson 	for (i = 0; i < base->nactivequeues; ++i) {
3722cba59e53SNick Mathewson 		struct event_callback *evcb;
3723cba59e53SNick Mathewson 		TAILQ_FOREACH(evcb, &base->activequeues[i], evcb_active_next) {
3724cba59e53SNick Mathewson 			if ((evcb->evcb_flags & (EVLIST_INIT|EVLIST_INSERTED|EVLIST_TIMEOUT)) != EVLIST_INIT) {
3725cba59e53SNick Mathewson 				/* This isn't an event (evlist_init clear), or
3726cba59e53SNick Mathewson 				 * we already processed it. (inserted or
3727cba59e53SNick Mathewson 				 * timeout set */
3728c89b4e63SNick Mathewson 				continue;
3729c89b4e63SNick Mathewson 			}
3730cba59e53SNick Mathewson 			ev = event_callback_to_event(evcb);
3731c89b4e63SNick Mathewson 			if ((r = fn(base, ev, arg)))
3732c89b4e63SNick Mathewson 				return r;
3733c89b4e63SNick Mathewson 		}
3734c89b4e63SNick Mathewson 	}
3735c89b4e63SNick Mathewson 
3736c89b4e63SNick Mathewson 	return 0;
3737c89b4e63SNick Mathewson }
3738c89b4e63SNick Mathewson 
3739c89b4e63SNick Mathewson /* Helper for event_base_dump_events: called on each event in the event base;
3740c89b4e63SNick Mathewson  * dumps only the inserted events. */
3741c89b4e63SNick Mathewson static int
dump_inserted_event_fn(const struct event_base * base,const struct event * e,void * arg)374284fd6d75SRoman Puls dump_inserted_event_fn(const struct event_base *base, const struct event *e, void *arg)
3743c89b4e63SNick Mathewson {
3744c89b4e63SNick Mathewson 	FILE *output = arg;
3745c89b4e63SNick Mathewson 	const char *gloss = (e->ev_events & EV_SIGNAL) ?
3746c89b4e63SNick Mathewson 	    "sig" : "fd ";
3747c89b4e63SNick Mathewson 
3748c89b4e63SNick Mathewson 	if (! (e->ev_flags & (EVLIST_INSERTED|EVLIST_TIMEOUT)))
3749c89b4e63SNick Mathewson 		return 0;
3750c89b4e63SNick Mathewson 
3751ca4b6404SAzat Khuzhin 	fprintf(output, "  %p [%s "EV_SOCK_FMT"]%s%s%s%s%s%s%s",
37522e6a9850SNick Mathewson 	    (void*)e, gloss, EV_SOCK_ARG(e->ev_fd),
3753a68de252SNick Mathewson 	    (e->ev_events&EV_READ)?" Read":"",
3754a68de252SNick Mathewson 	    (e->ev_events&EV_WRITE)?" Write":"",
3755b1b69ac7SDiego Giagio 	    (e->ev_events&EV_CLOSED)?" EOF":"",
3756a68de252SNick Mathewson 	    (e->ev_events&EV_SIGNAL)?" Signal":"",
37570343d8feSNick Mathewson 	    (e->ev_events&EV_PERSIST)?" Persist":"",
3758ca4b6404SAzat Khuzhin 	    (e->ev_events&EV_ET)?" ET":"",
37590343d8feSNick Mathewson 	    (e->ev_flags&EVLIST_INTERNAL)?" Internal":"");
3760c89b4e63SNick Mathewson 	if (e->ev_flags & EVLIST_TIMEOUT) {
3761c89b4e63SNick Mathewson 		struct timeval tv;
3762c89b4e63SNick Mathewson 		tv.tv_sec = e->ev_timeout.tv_sec;
3763c89b4e63SNick Mathewson 		tv.tv_usec = e->ev_timeout.tv_usec & MICROSECONDS_MASK;
3764c89b4e63SNick Mathewson 		evutil_timeradd(&tv, &base->tv_clock_diff, &tv);
3765c89b4e63SNick Mathewson 		fprintf(output, " Timeout=%ld.%06d",
3766c89b4e63SNick Mathewson 		    (long)tv.tv_sec, (int)(tv.tv_usec & MICROSECONDS_MASK));
3767a68de252SNick Mathewson 	}
3768c89b4e63SNick Mathewson 	fputc('\n', output);
3769c89b4e63SNick Mathewson 
3770c89b4e63SNick Mathewson 	return 0;
3771c89b4e63SNick Mathewson }
3772c89b4e63SNick Mathewson 
3773c89b4e63SNick Mathewson /* Helper for event_base_dump_events: called on each event in the event base;
3774c89b4e63SNick Mathewson  * dumps only the active events. */
3775c89b4e63SNick Mathewson static int
dump_active_event_fn(const struct event_base * base,const struct event * e,void * arg)377684fd6d75SRoman Puls dump_active_event_fn(const struct event_base *base, const struct event *e, void *arg)
3777c89b4e63SNick Mathewson {
3778c89b4e63SNick Mathewson 	FILE *output = arg;
3779c89b4e63SNick Mathewson 	const char *gloss = (e->ev_events & EV_SIGNAL) ?
3780c89b4e63SNick Mathewson 	    "sig" : "fd ";
3781c89b4e63SNick Mathewson 
3782745a63dbSNick Mathewson 	if (! (e->ev_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)))
3783c89b4e63SNick Mathewson 		return 0;
3784c89b4e63SNick Mathewson 
3785b1b69ac7SDiego Giagio 	fprintf(output, "  %p [%s "EV_SOCK_FMT", priority=%d]%s%s%s%s%s active%s%s\n",
37862e6a9850SNick Mathewson 	    (void*)e, gloss, EV_SOCK_ARG(e->ev_fd), e->ev_pri,
37870343d8feSNick Mathewson 	    (e->ev_res&EV_READ)?" Read":"",
37880343d8feSNick Mathewson 	    (e->ev_res&EV_WRITE)?" Write":"",
3789b1b69ac7SDiego Giagio 	    (e->ev_res&EV_CLOSED)?" EOF":"",
37900343d8feSNick Mathewson 	    (e->ev_res&EV_SIGNAL)?" Signal":"",
37910343d8feSNick Mathewson 	    (e->ev_res&EV_TIMEOUT)?" Timeout":"",
3792745a63dbSNick Mathewson 	    (e->ev_flags&EVLIST_INTERNAL)?" [Internal]":"",
3793745a63dbSNick Mathewson 	    (e->ev_flags&EVLIST_ACTIVE_LATER)?" [NextTime]":"");
3794c89b4e63SNick Mathewson 
3795c89b4e63SNick Mathewson 	return 0;
3796a68de252SNick Mathewson }
3797c89b4e63SNick Mathewson 
3798232055efSNick Mathewson int
event_base_foreach_event(struct event_base * base,event_base_foreach_event_cb fn,void * arg)379984fd6d75SRoman Puls event_base_foreach_event(struct event_base *base,
380084fd6d75SRoman Puls     event_base_foreach_event_cb fn, void *arg)
380184fd6d75SRoman Puls {
3802232055efSNick Mathewson 	int r;
380384fd6d75SRoman Puls 	if ((!fn) || (!base)) {
3804ffe1643bSNick Mathewson 		return -1;
380584fd6d75SRoman Puls 	}
380684fd6d75SRoman Puls 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
3807232055efSNick Mathewson 	r = event_base_foreach_event_nolock_(base, fn, arg);
380884fd6d75SRoman Puls 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3809232055efSNick Mathewson 	return r;
381084fd6d75SRoman Puls }
381184fd6d75SRoman Puls 
381284fd6d75SRoman Puls 
381384fd6d75SRoman Puls void
event_base_dump_events(struct event_base * base,FILE * output)3814c89b4e63SNick Mathewson event_base_dump_events(struct event_base *base, FILE *output)
3815c89b4e63SNick Mathewson {
381684fd6d75SRoman Puls 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
3817c89b4e63SNick Mathewson 	fprintf(output, "Inserted events:\n");
3818232055efSNick Mathewson 	event_base_foreach_event_nolock_(base, dump_inserted_event_fn, output);
3819c89b4e63SNick Mathewson 
3820c89b4e63SNick Mathewson 	fprintf(output, "Active events:\n");
3821232055efSNick Mathewson 	event_base_foreach_event_nolock_(base, dump_active_event_fn, output);
382284fd6d75SRoman Puls 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3823a68de252SNick Mathewson }
382476f7e7aeSChristopher Davis 
382576f7e7aeSChristopher Davis void
event_base_active_by_fd(struct event_base * base,evutil_socket_t fd,short events)3826865a1426SGreg Hazel event_base_active_by_fd(struct event_base *base, evutil_socket_t fd, short events)
3827865a1426SGreg Hazel {
3828865a1426SGreg Hazel 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
38293f893f0aSJohn Ohl 
38303f893f0aSJohn Ohl 	/* Activate any non timer events */
38313f893f0aSJohn Ohl 	if (!(events & EV_TIMEOUT)) {
3832b1b69ac7SDiego Giagio 		evmap_io_active_(base, fd, events & (EV_READ|EV_WRITE|EV_CLOSED));
38333f893f0aSJohn Ohl 	} else {
38343f893f0aSJohn Ohl 		/* If we want to activate timer events, loop and activate each event with
38353f893f0aSJohn Ohl 		 * the same fd in both the timeheap and common timeouts list */
38363f893f0aSJohn Ohl 		int i;
383718104973SAzat Khuzhin 		unsigned u;
38383f893f0aSJohn Ohl 		struct event *ev;
38393f893f0aSJohn Ohl 
38403f893f0aSJohn Ohl 		for (u = 0; u < base->timeheap.n; ++u) {
38413f893f0aSJohn Ohl 			ev = base->timeheap.p[u];
38423f893f0aSJohn Ohl 			if (ev->ev_fd == fd) {
38433f893f0aSJohn Ohl 				event_active_nolock_(ev, EV_TIMEOUT, 1);
38443f893f0aSJohn Ohl 			}
38453f893f0aSJohn Ohl 		}
38463f893f0aSJohn Ohl 
38473f893f0aSJohn Ohl 		for (i = 0; i < base->n_common_timeouts; ++i) {
38483f893f0aSJohn Ohl 			struct common_timeout_list *ctl = base->common_timeout_queues[i];
38493f893f0aSJohn Ohl 			TAILQ_FOREACH(ev, &ctl->events,
38503f893f0aSJohn Ohl 				ev_timeout_pos.ev_next_with_common_timeout) {
38513f893f0aSJohn Ohl 				if (ev->ev_fd == fd) {
38523f893f0aSJohn Ohl 					event_active_nolock_(ev, EV_TIMEOUT, 1);
38533f893f0aSJohn Ohl 				}
38543f893f0aSJohn Ohl 			}
38553f893f0aSJohn Ohl 		}
38563f893f0aSJohn Ohl 	}
38573f893f0aSJohn Ohl 
3858865a1426SGreg Hazel 	EVBASE_RELEASE_LOCK(base, th_base_lock);
3859865a1426SGreg Hazel }
3860865a1426SGreg Hazel 
3861865a1426SGreg Hazel void
event_base_active_by_signal(struct event_base * base,int sig)386248659433SNick Mathewson event_base_active_by_signal(struct event_base *base, int sig)
386348659433SNick Mathewson {
386448659433SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
386548659433SNick Mathewson 	evmap_signal_active_(base, sig, 1);
386648659433SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
386748659433SNick Mathewson }
386848659433SNick Mathewson 
386948659433SNick Mathewson 
387048659433SNick Mathewson void
event_base_add_virtual_(struct event_base * base)38718ac3c4c2SNick Mathewson event_base_add_virtual_(struct event_base *base)
387276f7e7aeSChristopher Davis {
387376f7e7aeSChristopher Davis 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
387476f7e7aeSChristopher Davis 	base->virtual_event_count++;
38755173bef5SAndrew Sweeney 	MAX_EVENT_COUNT(base->virtual_event_count_max, base->virtual_event_count);
387676f7e7aeSChristopher Davis 	EVBASE_RELEASE_LOCK(base, th_base_lock);
387776f7e7aeSChristopher Davis }
387876f7e7aeSChristopher Davis 
387976f7e7aeSChristopher Davis void
event_base_del_virtual_(struct event_base * base)38808ac3c4c2SNick Mathewson event_base_del_virtual_(struct event_base *base)
388176f7e7aeSChristopher Davis {
388276f7e7aeSChristopher Davis 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
388371b68014SChristopher Davis 	EVUTIL_ASSERT(base->virtual_event_count > 0);
388476f7e7aeSChristopher Davis 	base->virtual_event_count--;
3885d98511c0SChristopher Davis 	if (base->virtual_event_count == 0 && EVBASE_NEED_NOTIFY(base))
3886d98511c0SChristopher Davis 		evthread_notify_base(base);
388776f7e7aeSChristopher Davis 	EVBASE_RELEASE_LOCK(base, th_base_lock);
388876f7e7aeSChristopher Davis }
3889b683cae3SNick Mathewson 
3890041ca00cSMark Ellzey static void
event_free_debug_globals_locks(void)3891041ca00cSMark Ellzey event_free_debug_globals_locks(void)
3892041ca00cSMark Ellzey {
3893041ca00cSMark Ellzey #ifndef EVENT__DISABLE_THREAD_SUPPORT
3894041ca00cSMark Ellzey #ifndef EVENT__DISABLE_DEBUG_MODE
3895041ca00cSMark Ellzey 	if (event_debug_map_lock_ != NULL) {
3896041ca00cSMark Ellzey 		EVTHREAD_FREE_LOCK(event_debug_map_lock_, 0);
389755e991b2SNick Mathewson 		event_debug_map_lock_ = NULL;
3898e5c87d18SAzat Khuzhin 		evthreadimpl_disable_lock_debugging_();
3899041ca00cSMark Ellzey 	}
3900041ca00cSMark Ellzey #endif /* EVENT__DISABLE_DEBUG_MODE */
3901041ca00cSMark Ellzey #endif /* EVENT__DISABLE_THREAD_SUPPORT */
3902041ca00cSMark Ellzey 	return;
3903041ca00cSMark Ellzey }
3904041ca00cSMark Ellzey 
3905041ca00cSMark Ellzey static void
event_free_debug_globals(void)3906041ca00cSMark Ellzey event_free_debug_globals(void)
3907041ca00cSMark Ellzey {
3908041ca00cSMark Ellzey 	event_free_debug_globals_locks();
3909041ca00cSMark Ellzey }
3910041ca00cSMark Ellzey 
3911041ca00cSMark Ellzey static void
event_free_evsig_globals(void)3912041ca00cSMark Ellzey event_free_evsig_globals(void)
3913041ca00cSMark Ellzey {
3914041ca00cSMark Ellzey 	evsig_free_globals_();
3915041ca00cSMark Ellzey }
3916041ca00cSMark Ellzey 
3917041ca00cSMark Ellzey static void
event_free_evutil_globals(void)3918041ca00cSMark Ellzey event_free_evutil_globals(void)
3919041ca00cSMark Ellzey {
3920041ca00cSMark Ellzey 	evutil_free_globals_();
3921041ca00cSMark Ellzey }
3922041ca00cSMark Ellzey 
3923041ca00cSMark Ellzey static void
event_free_globals(void)3924041ca00cSMark Ellzey event_free_globals(void)
3925041ca00cSMark Ellzey {
3926041ca00cSMark Ellzey 	event_free_debug_globals();
3927041ca00cSMark Ellzey 	event_free_evsig_globals();
3928041ca00cSMark Ellzey 	event_free_evutil_globals();
3929041ca00cSMark Ellzey }
3930041ca00cSMark Ellzey 
3931041ca00cSMark Ellzey void
libevent_global_shutdown(void)3932041ca00cSMark Ellzey libevent_global_shutdown(void)
3933041ca00cSMark Ellzey {
3934941faaedSAzat Khuzhin 	event_disable_debug_mode();
3935041ca00cSMark Ellzey 	event_free_globals();
3936041ca00cSMark Ellzey }
3937041ca00cSMark Ellzey 
393868120d9bSNick Mathewson #ifndef EVENT__DISABLE_THREAD_SUPPORT
3939b683cae3SNick Mathewson int
event_global_setup_locks_(const int enable_locks)3940b683cae3SNick Mathewson event_global_setup_locks_(const int enable_locks)
3941b683cae3SNick Mathewson {
394268120d9bSNick Mathewson #ifndef EVENT__DISABLE_DEBUG_MODE
3943cb9da0bfSNick Mathewson 	EVTHREAD_SETUP_GLOBAL_LOCK(event_debug_map_lock_, 0);
3944b683cae3SNick Mathewson #endif
3945b683cae3SNick Mathewson 	if (evsig_global_setup_locks_(enable_locks) < 0)
3946b683cae3SNick Mathewson 		return -1;
39470c6ec5d8SPatrick Pelletier 	if (evutil_global_setup_locks_(enable_locks) < 0)
39480c6ec5d8SPatrick Pelletier 		return -1;
3949b683cae3SNick Mathewson 	if (evutil_secure_rng_global_setup_locks_(enable_locks) < 0)
3950b683cae3SNick Mathewson 		return -1;
3951b683cae3SNick Mathewson 	return 0;
3952b683cae3SNick Mathewson }
3953b683cae3SNick Mathewson #endif
395427737d55SNick Mathewson 
395527737d55SNick Mathewson void
event_base_assert_ok_(struct event_base * base)39568ac3c4c2SNick Mathewson event_base_assert_ok_(struct event_base *base)
395727737d55SNick Mathewson {
39589cd5acb5SNick Mathewson 	EVBASE_ACQUIRE_LOCK(base, th_base_lock);
39599cd5acb5SNick Mathewson 	event_base_assert_ok_nolock_(base);
39609cd5acb5SNick Mathewson 	EVBASE_RELEASE_LOCK(base, th_base_lock);
39619cd5acb5SNick Mathewson }
39629cd5acb5SNick Mathewson 
39639cd5acb5SNick Mathewson void
event_base_assert_ok_nolock_(struct event_base * base)39649cd5acb5SNick Mathewson event_base_assert_ok_nolock_(struct event_base *base)
39659cd5acb5SNick Mathewson {
396627737d55SNick Mathewson 	int i;
3967fec8bae2SNick Mathewson 	int count;
3968c89b4e63SNick Mathewson 
3969c89b4e63SNick Mathewson 	/* First do checks on the per-fd and per-signal lists */
39708ac3c4c2SNick Mathewson 	evmap_check_integrity_(base);
397127737d55SNick Mathewson 
397227737d55SNick Mathewson 	/* Check the heap property */
397318104973SAzat Khuzhin 	for (i = 1; i < (int)base->timeheap.n; ++i) {
397418104973SAzat Khuzhin 		int parent = (i - 1) / 2;
397527737d55SNick Mathewson 		struct event *ev, *p_ev;
397618104973SAzat Khuzhin 		ev = base->timeheap.p[i];
397727737d55SNick Mathewson 		p_ev = base->timeheap.p[parent];
3978c89b4e63SNick Mathewson 		EVUTIL_ASSERT(ev->ev_flags & EVLIST_TIMEOUT);
397927737d55SNick Mathewson 		EVUTIL_ASSERT(evutil_timercmp(&p_ev->ev_timeout, &ev->ev_timeout, <=));
398018104973SAzat Khuzhin 		EVUTIL_ASSERT(ev->ev_timeout_pos.min_heap_idx == i);
398127737d55SNick Mathewson 	}
398227737d55SNick Mathewson 
398327737d55SNick Mathewson 	/* Check that the common timeouts are fine */
398427737d55SNick Mathewson 	for (i = 0; i < base->n_common_timeouts; ++i) {
398527737d55SNick Mathewson 		struct common_timeout_list *ctl = base->common_timeout_queues[i];
398627737d55SNick Mathewson 		struct event *last=NULL, *ev;
3987c89b4e63SNick Mathewson 
3988c89b4e63SNick Mathewson 		EVUTIL_ASSERT_TAILQ_OK(&ctl->events, event, ev_timeout_pos.ev_next_with_common_timeout);
3989c89b4e63SNick Mathewson 
399027737d55SNick Mathewson 		TAILQ_FOREACH(ev, &ctl->events, ev_timeout_pos.ev_next_with_common_timeout) {
399127737d55SNick Mathewson 			if (last)
399227737d55SNick Mathewson 				EVUTIL_ASSERT(evutil_timercmp(&last->ev_timeout, &ev->ev_timeout, <=));
3993c89b4e63SNick Mathewson 			EVUTIL_ASSERT(ev->ev_flags & EVLIST_TIMEOUT);
399427737d55SNick Mathewson 			EVUTIL_ASSERT(is_common_timeout(&ev->ev_timeout,base));
399527737d55SNick Mathewson 			EVUTIL_ASSERT(COMMON_TIMEOUT_IDX(&ev->ev_timeout) == i);
399627737d55SNick Mathewson 			last = ev;
399727737d55SNick Mathewson 		}
399827737d55SNick Mathewson 	}
399927737d55SNick Mathewson 
4000c89b4e63SNick Mathewson 	/* Check the active queues. */
4001fec8bae2SNick Mathewson 	count = 0;
4002c89b4e63SNick Mathewson 	for (i = 0; i < base->nactivequeues; ++i) {
4003cba59e53SNick Mathewson 		struct event_callback *evcb;
4004cba59e53SNick Mathewson 		EVUTIL_ASSERT_TAILQ_OK(&base->activequeues[i], event_callback, evcb_active_next);
4005cba59e53SNick Mathewson 		TAILQ_FOREACH(evcb, &base->activequeues[i], evcb_active_next) {
4006745a63dbSNick Mathewson 			EVUTIL_ASSERT((evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) == EVLIST_ACTIVE);
4007cba59e53SNick Mathewson 			EVUTIL_ASSERT(evcb->evcb_pri == i);
4008fec8bae2SNick Mathewson 			++count;
4009c89b4e63SNick Mathewson 		}
4010c89b4e63SNick Mathewson 	}
4011c89b4e63SNick Mathewson 
4012745a63dbSNick Mathewson 	{
4013745a63dbSNick Mathewson 		struct event_callback *evcb;
4014745a63dbSNick Mathewson 		TAILQ_FOREACH(evcb, &base->active_later_queue, evcb_active_next) {
4015745a63dbSNick Mathewson 			EVUTIL_ASSERT((evcb->evcb_flags & (EVLIST_ACTIVE|EVLIST_ACTIVE_LATER)) == EVLIST_ACTIVE_LATER);
4016fec8bae2SNick Mathewson 			++count;
4017745a63dbSNick Mathewson 		}
4018745a63dbSNick Mathewson 	}
4019fec8bae2SNick Mathewson 	EVUTIL_ASSERT(count == base->event_count_active);
402027737d55SNick Mathewson }
4021