]> arthur.barton.de Git - netatalk.git/blob - libevent/bufferevent-internal.h
Add libevent
[netatalk.git] / libevent / bufferevent-internal.h
1 /*
2  * Copyright (c) 2008-2010 Niels Provos and Nick Mathewson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  * 3. The name of the author may not be used to endorse or promote products
13  *    derived from this software without specific prior written permission.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 #ifndef _BUFFEREVENT_INTERNAL_H_
27 #define _BUFFEREVENT_INTERNAL_H_
28
29 #ifdef __cplusplus
30 extern "C" {
31 #endif
32
33 #include "event2/event-config.h"
34 #include "event2/util.h"
35 #include "defer-internal.h"
36 #include "evthread-internal.h"
37 #include "event2/thread.h"
38 #include "ratelim-internal.h"
39
40 /* These flags are reasons that we might be declining to actually enable
41    reading or writing on a bufferevent.
42  */
43
44 /* On a all bufferevents, for reading: used when we have read up to the
45    watermark value.
46
47    On a filtering bufferevent, for writing: used when the underlying
48    bufferevent's write buffer has been filled up to its watermark
49    value.
50 */
51 #define BEV_SUSPEND_WM 0x01
52 /* On a base bufferevent: when we have emptied a bandwidth buckets */
53 #define BEV_SUSPEND_BW 0x02
54 /* On a base bufferevent: when we have emptied the group's bandwidth bucket. */
55 #define BEV_SUSPEND_BW_GROUP 0x04
56 /* On a socket bufferevent: can't do any operations while we're waiting for
57  * name lookup to finish. */
58 #define BEV_SUSPEND_LOOKUP 0x08
59 /* On a base bufferevent, for reading: used when a filter has choked this
60  * (underlying) bufferevent because it has stopped reading from it. */
61 #define BEV_SUSPEND_FILT_READ 0x10
62
63 typedef ev_uint16_t bufferevent_suspend_flags;
64
65 struct bufferevent_rate_limit_group {
66         /** List of all members in the group */
67         TAILQ_HEAD(rlim_group_member_list, bufferevent_private) members;
68         /** Current limits for the group. */
69         struct ev_token_bucket rate_limit;
70         struct ev_token_bucket_cfg rate_limit_cfg;
71
72         /** True iff we don't want to read from any member of the group.until
73          * the token bucket refills.  */
74         unsigned read_suspended : 1;
75         /** True iff we don't want to write from any member of the group.until
76          * the token bucket refills.  */
77         unsigned write_suspended : 1;
78         /** True iff we were unable to suspend one of the bufferevents in the
79          * group for reading the last time we tried, and we should try
80          * again. */
81         unsigned pending_unsuspend_read : 1;
82         /** True iff we were unable to suspend one of the bufferevents in the
83          * group for writing the last time we tried, and we should try
84          * again. */
85         unsigned pending_unsuspend_write : 1;
86
87         /*@{*/
88         /** Total number of bytes read or written in this group since last
89          * reset. */
90         ev_uint64_t total_read;
91         ev_uint64_t total_written;
92         /*@}*/
93
94         /** The number of bufferevents in the group. */
95         int n_members;
96
97         /** The smallest number of bytes that any member of the group should
98          * be limited to read or write at a time. */
99         ev_ssize_t min_share;
100         /** Timeout event that goes off once a tick, when the bucket is ready
101          * to refill. */
102         struct event master_refill_event;
103         /** Lock to protect the members of this group.  This lock should nest
104          * within every bufferevent lock: if you are holding this lock, do
105          * not assume you can lock another bufferevent. */
106         void *lock;
107 };
108
109 /** Fields for rate-limiting a single bufferevent. */
110 struct bufferevent_rate_limit {
111         /* Linked-list elements for storing this bufferevent_private in a
112          * group.
113          *
114          * Note that this field is supposed to be protected by the group
115          * lock */
116         TAILQ_ENTRY(bufferevent_private) next_in_group;
117         /** The rate-limiting group for this bufferevent, or NULL if it is
118          * only rate-limited on its own. */
119         struct bufferevent_rate_limit_group *group;
120
121         /* This bufferevent's current limits. */
122         struct ev_token_bucket limit;
123         /* Pointer to the rate-limit configuration for this bufferevent.
124          * Can be shared.  XXX reference-count this? */
125         struct ev_token_bucket_cfg *cfg;
126
127         /* Timeout event used when one this bufferevent's buckets are
128          * empty. */
129         struct event refill_bucket_event;
130 };
131
132 /** Parts of the bufferevent structure that are shared among all bufferevent
133  * types, but not exposed in bufferevent_struct.h. */
134 struct bufferevent_private {
135         /** The underlying bufferevent structure. */
136         struct bufferevent bev;
137
138         /** Evbuffer callback to enforce watermarks on input. */
139         struct evbuffer_cb_entry *read_watermarks_cb;
140
141         /** If set, we should free the lock when we free the bufferevent. */
142         unsigned own_lock : 1;
143
144         /** Flag: set if we have deferred callbacks and a read callback is
145          * pending. */
146         unsigned readcb_pending : 1;
147         /** Flag: set if we have deferred callbacks and a write callback is
148          * pending. */
149         unsigned writecb_pending : 1;
150         /** Flag: set if we are currently busy connecting. */
151         unsigned connecting : 1;
152         /** Flag: set if a connect failed prematurely; this is a hack for
153          * getting around the bufferevent abstraction. */
154         unsigned connection_refused : 1;
155         /** Set to the events pending if we have deferred callbacks and
156          * an events callback is pending. */
157         short eventcb_pending;
158
159         /** If set, read is suspended until one or more conditions are over.
160          * The actual value here is a bitfield of those conditions; see the
161          * BEV_SUSPEND_* flags above. */
162         bufferevent_suspend_flags read_suspended;
163
164         /** If set, writing is suspended until one or more conditions are over.
165          * The actual value here is a bitfield of those conditions; see the
166          * BEV_SUSPEND_* flags above. */
167         bufferevent_suspend_flags write_suspended;
168
169         /** Set to the current socket errno if we have deferred callbacks and
170          * an events callback is pending. */
171         int errno_pending;
172
173         /** The DNS error code for bufferevent_socket_connect_hostname */
174         int dns_error;
175
176         /** Used to implement deferred callbacks */
177         struct deferred_cb deferred;
178
179         /** The options this bufferevent was constructed with */
180         enum bufferevent_options options;
181
182         /** Current reference count for this bufferevent. */
183         int refcnt;
184
185         /** Lock for this bufferevent.  Shared by the inbuf and the outbuf.
186          * If NULL, locking is disabled. */
187         void *lock;
188
189         /** Rate-limiting information for this bufferevent */
190         struct bufferevent_rate_limit *rate_limiting;
191 };
192
193 /** Possible operations for a control callback. */
194 enum bufferevent_ctrl_op {
195         BEV_CTRL_SET_FD,
196         BEV_CTRL_GET_FD,
197         BEV_CTRL_GET_UNDERLYING
198 };
199
200 /** Possible data types for a control callback */
201 union bufferevent_ctrl_data {
202         void *ptr;
203         evutil_socket_t fd;
204 };
205
206 /**
207    Implementation table for a bufferevent: holds function pointers and other
208    information to make the various bufferevent types work.
209 */
210 struct bufferevent_ops {
211         /** The name of the bufferevent's type. */
212         const char *type;
213         /** At what offset into the implementation type will we find a
214             bufferevent structure?
215
216             Example: if the type is implemented as
217             struct bufferevent_x {
218                int extra_data;
219                struct bufferevent bev;
220             }
221             then mem_offset should be offsetof(struct bufferevent_x, bev)
222         */
223         off_t mem_offset;
224
225         /** Enables one or more of EV_READ|EV_WRITE on a bufferevent.  Does
226             not need to adjust the 'enabled' field.  Returns 0 on success, -1
227             on failure.
228          */
229         int (*enable)(struct bufferevent *, short);
230
231         /** Disables one or more of EV_READ|EV_WRITE on a bufferevent.  Does
232             not need to adjust the 'enabled' field.  Returns 0 on success, -1
233             on failure.
234          */
235         int (*disable)(struct bufferevent *, short);
236
237         /** Free any storage and deallocate any extra data or structures used
238             in this implementation.
239          */
240         void (*destruct)(struct bufferevent *);
241
242         /** Called when the timeouts on the bufferevent have changed.*/
243         int (*adj_timeouts)(struct bufferevent *);
244
245         /** Called to flush data. */
246         int (*flush)(struct bufferevent *, short, enum bufferevent_flush_mode);
247
248         /** Called to access miscellaneous fields. */
249         int (*ctrl)(struct bufferevent *, enum bufferevent_ctrl_op, union bufferevent_ctrl_data *);
250
251 };
252
253 extern const struct bufferevent_ops bufferevent_ops_socket;
254 extern const struct bufferevent_ops bufferevent_ops_filter;
255 extern const struct bufferevent_ops bufferevent_ops_pair;
256
257 #define BEV_IS_SOCKET(bevp) ((bevp)->be_ops == &bufferevent_ops_socket)
258 #define BEV_IS_FILTER(bevp) ((bevp)->be_ops == &bufferevent_ops_filter)
259 #define BEV_IS_PAIR(bevp) ((bevp)->be_ops == &bufferevent_ops_pair)
260
261 #ifdef WIN32
262 extern const struct bufferevent_ops bufferevent_ops_async;
263 #define BEV_IS_ASYNC(bevp) ((bevp)->be_ops == &bufferevent_ops_async)
264 #else
265 #define BEV_IS_ASYNC(bevp) 0
266 #endif
267
268 /** Initialize the shared parts of a bufferevent. */
269 int bufferevent_init_common(struct bufferevent_private *, struct event_base *, const struct bufferevent_ops *, enum bufferevent_options options);
270
271 /** For internal use: temporarily stop all reads on bufev, until the conditions
272  * in 'what' are over. */
273 void bufferevent_suspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what);
274 /** For internal use: clear the conditions 'what' on bufev, and re-enable
275  * reading if there are no conditions left. */
276 void bufferevent_unsuspend_read(struct bufferevent *bufev, bufferevent_suspend_flags what);
277
278 /** For internal use: temporarily stop all writes on bufev, until the conditions
279  * in 'what' are over. */
280 void bufferevent_suspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what);
281 /** For internal use: clear the conditions 'what' on bufev, and re-enable
282  * writing if there are no conditions left. */
283 void bufferevent_unsuspend_write(struct bufferevent *bufev, bufferevent_suspend_flags what);
284
285 #define bufferevent_wm_suspend_read(b) \
286         bufferevent_suspend_read((b), BEV_SUSPEND_WM)
287 #define bufferevent_wm_unsuspend_read(b) \
288         bufferevent_unsuspend_read((b), BEV_SUSPEND_WM)
289
290 /** Internal: Set up locking on a bufferevent.  If lock is set, use it.
291  * Otherwise, use a new lock. */
292 int bufferevent_enable_locking(struct bufferevent *bufev, void *lock);
293 /** Internal: Increment the reference count on bufev. */
294 void bufferevent_incref(struct bufferevent *bufev);
295 /** Internal: Lock bufev and increase its reference count.
296  * unlocking it otherwise. */
297 void _bufferevent_incref_and_lock(struct bufferevent *bufev);
298 /** Internal: Decrement the reference count on bufev.  Returns 1 if it freed
299  * the bufferevent.*/
300 int bufferevent_decref(struct bufferevent *bufev);
301 /** Internal: Drop the reference count on bufev, freeing as necessary, and
302  * unlocking it otherwise.  Returns 1 if it freed the bufferevent. */
303 int _bufferevent_decref_and_unlock(struct bufferevent *bufev);
304
305 /** Internal: If callbacks are deferred and we have a read callback, schedule
306  * a readcb.  Otherwise just run the readcb. */
307 void _bufferevent_run_readcb(struct bufferevent *bufev);
308 /** Internal: If callbacks are deferred and we have a write callback, schedule
309  * a writecb.  Otherwise just run the writecb. */
310 void _bufferevent_run_writecb(struct bufferevent *bufev);
311 /** Internal: If callbacks are deferred and we have an eventcb, schedule
312  * it to run with events "what".  Otherwise just run the eventcb. */
313 void _bufferevent_run_eventcb(struct bufferevent *bufev, short what);
314
315 /** Internal: Add the event 'ev' with timeout tv, unless tv is set to 0, in
316  * which case add ev with no timeout. */
317 int _bufferevent_add_event(struct event *ev, const struct timeval *tv);
318
319 /* =========
320  * These next functions implement timeouts for bufferevents that aren't doing
321  * anything else with ev_read and ev_write, to handle timeouts.
322  * ========= */
323 /** Internal use: Set up the ev_read and ev_write callbacks so that
324  * the other "generic_timeout" functions will work on it.  Call this from
325  * the constructor function. */
326 void _bufferevent_init_generic_timeout_cbs(struct bufferevent *bev);
327 /** Internal use: Delete the ev_read and ev_write callbacks if they're pending.
328  * Call this from the destructor function. */
329 int _bufferevent_del_generic_timeout_cbs(struct bufferevent *bev);
330 /** Internal use: Add or delete the generic timeout events as appropriate.
331  * (If an event is enabled and a timeout is set, we add the event.  Otherwise
332  * we delete it.)  Call this from anything that changes the timeout values,
333  * that enabled EV_READ or EV_WRITE, or that disables EV_READ or EV_WRITE. */
334 int _bufferevent_generic_adj_timeouts(struct bufferevent *bev);
335
336 /** Internal use: We have just successfully read data into an inbuf, so
337  * reset the read timeout (if any). */
338 #define BEV_RESET_GENERIC_READ_TIMEOUT(bev)                             \
339         do {                                                            \
340                 if (evutil_timerisset(&(bev)->timeout_read))            \
341                         event_add(&(bev)->ev_read, &(bev)->timeout_read); \
342         } while (0)
343 /** Internal use: We have just successfully written data from an inbuf, so
344  * reset the read timeout (if any). */
345 #define BEV_RESET_GENERIC_WRITE_TIMEOUT(bev)                            \
346         do {                                                            \
347                 if (evutil_timerisset(&(bev)->timeout_write))           \
348                         event_add(&(bev)->ev_write, &(bev)->timeout_write); \
349         } while (0)
350 #define BEV_DEL_GENERIC_READ_TIMEOUT(bev)       \
351                 event_del(&(bev)->ev_read)
352 #define BEV_DEL_GENERIC_WRITE_TIMEOUT(bev)      \
353                 event_del(&(bev)->ev_write)
354
355
356 /** Internal: Given a bufferevent, return its corresponding
357  * bufferevent_private. */
358 #define BEV_UPCAST(b) EVUTIL_UPCAST((b), struct bufferevent_private, bev)
359
360 #ifdef _EVENT_DISABLE_THREAD_SUPPORT
361 #define BEV_LOCK(b) _EVUTIL_NIL_STMT
362 #define BEV_UNLOCK(b) _EVUTIL_NIL_STMT
363 #else
364 /** Internal: Grab the lock (if any) on a bufferevent */
365 #define BEV_LOCK(b) do {                                                \
366                 struct bufferevent_private *locking =  BEV_UPCAST(b);   \
367                 EVLOCK_LOCK(locking->lock, 0);                          \
368         } while (0)
369
370 /** Internal: Release the lock (if any) on a bufferevent */
371 #define BEV_UNLOCK(b) do {                                              \
372                 struct bufferevent_private *locking =  BEV_UPCAST(b);   \
373                 EVLOCK_UNLOCK(locking->lock, 0);                        \
374         } while (0)
375 #endif
376
377
378 /* ==== For rate-limiting. */
379
380 int _bufferevent_decrement_write_buckets(struct bufferevent_private *bev,
381     ev_ssize_t bytes);
382 int _bufferevent_decrement_read_buckets(struct bufferevent_private *bev,
383     ev_ssize_t bytes);
384 ev_ssize_t _bufferevent_get_read_max(struct bufferevent_private *bev);
385 ev_ssize_t _bufferevent_get_write_max(struct bufferevent_private *bev);
386
387 #ifdef __cplusplus
388 }
389 #endif
390
391
392 #endif /* _BUFFEREVENT_INTERNAL_H_ */