Debian Codegraph @

src/util/dispatch.c

raw
1 /*
2 * Event Dispatcher
3 *
4 * This event dispatcher provides a simple wrapper around edge-triggered epoll.
5 * It consists of a DispatchContext to represent the epoll-set, and a
6 * DispatchFile for each file-descriptor added to that epoll-set. All events
7 * are delivered in edge-triggered mode and cached in the DispatchFile. By
8 * default, this means that we will get woken up for each event once, and cache
9 * it. Since we don't use level-triggered mode, a continuous unhandled event
10 * will not cause any further wakeups, unless the event is triggered by the
11 * kernel again.
12 *
13 * On top of this edge-triggered mirror of the kernel space, we provide a
14 * level-triggered callback mechanism. That is, on each dispatch-file you can
15 * `select` and `deselect` events you're interested in. As long as an event is
16 * selected, you will get notified of it in level-triggered mode (that is,
17 * until you handled it). Since our cache is distinct from the kernel data, we
18 * need explicit notification of when an event is handled. Therefore, you must
19 * clear any event when you handled it. This usually means catching EAGAIN
20 * and then clearing the event.
21 *
22 * Every DispatchFile has 3 event masks:
23 *
24 * * kernel_mask: This mask is constant and must be provided at
25 * initialization time. It describes the events that we
26 * asked the kernel to report via epoll_ctl(2). For
27 * performance reasons we never modify this mask. If there
28 * ever arises a need to update this mask according to our
29 * user-mask, this can be added later on.
30 *
31 * * user_mask: This mask reflects the events that the user selected and
32 * thus is interested in. It must always be a subset of
33 * @kernel_mask. As long as an event is set in the event-mask
34 * and in @user_mask, its callback will be invoked in a
35 * level-triggered manner.
36 *
37 * * events: This mask reflects the events the kernel signalled. That is,
38 * those events are always a subset of @kernel_mask and cached as
39 * soon as the kernel signalled them.
40 * You must explicitly clear events once you handled them. The
41 * kernel never tells us about falling edges, so we must detect
42 * them manually (usually via EAGAIN).
43 */
44
45 #include <c-list.h>
46 #include <c-stdaux.h>
47 #include <stdlib.h>
48 #include <sys/epoll.h>
49 #include "util/dispatch.h"
50 #include "util/error.h"
51
52 /**
53 * dispatch_file_init() - initialize dispatch file
54 * @file: dispatch file
55 * @ctx: dispatch context
56 * @fn: callback function
57 * @fd: file descriptor
58 * @mask: EPOLL* event mask
59 * @events: initial EPOLL* event mask before calling into the kernel
60 *
61 * This initializes a new dispatch-file and registers it with the given
62 * dispatch-context. The file-descriptor @fd is added to the epoll-set of @ctx
63 * with the event mask @mask.
64 *
65 * Note that all event handling is always edge-triggered. Hence, EPOLLET must
66 * not be passed in @mask, but is added automatically. Furthermore, the event
67 * mask in @mask is used to select kernel events for edge-triggered mode. To
68 * actually get notified via your callback, you must select the user-mask via
69 * dispatch_file_select().
70 *
71 * The file-descriptor @fd is *NOT* consumed by this function. That is, the
72 * caller still owns it, and is responsible to close it when done. However, the
73 * caller must make sure to call dispatch_file_deinit() *BEFORE* closing the
74 * FD.
75 *
76 * Return: 0 on success, negative error code on failure.
77 */
78 int dispatch_file_init(DispatchFile *file,
79 DispatchContext *ctx,
80 DispatchFn fn,
81 int fd,
82 uint32_t mask,
83 uint32_t events) {
84 int r;
85
86 c_assert(!(mask & EPOLLET));
87 c_assert(!(events & ~mask));
88
89 r = epoll_ctl(ctx->epoll_fd,
90 EPOLL_CTL_ADD,
91 fd,
92 &(struct epoll_event) {
93 .events = mask | EPOLLET,
94 .data.ptr = file,
95 });
96 if (r < 0)
97 return error_origin(-errno);
98
99 file->context = ctx;
100 file->ready_link = (CList)C_LIST_INIT(file->ready_link);
101 file->fn = fn;
102 file->fd = fd;
103 file->user_mask = 0;
104 file->kernel_mask = mask;
105 file->events = events;
106
107 ++file->context->n_files;
108
109 return 0;
110 }
111
112 /**
113 * dispatch_file_deinit() - deinitialize dispatch file
114 * @file: dispatch file
115 *
116 * This deinitialized the dispatch-file @file and unregisters it from its
117 * context. The file is put into a deinitialized state, hence, it is safe to
118 * call this function multiple times.
119 *
120 * The file-descriptor provided via dispatch_file_init() is *NOT* closed, but
121 * left unchanged. However, the caller must make sure to call
122 * dispatch_file_deinit() *BEFORE* closing the FD.
123 */
124 void dispatch_file_deinit(DispatchFile *file) {
125 int r;
126
127 if (file->context) {
128 /*
129 * There is no excuse to ever skip EPOLL_CTL_DEL. Epoll
130 * descriptors are not tied to FDs, but rather combinations of
131 * file+fd. Only if the file-description (sic) is destroyed, an
132 * epoll description is removed from the epoll set. Hence, we
133 * have no way to know whether this FD is the only FD for the
134 * given file-description. Nor do we know whether the caller
135 * intends to continue using the FD.
136 *
137 * Therefore, we always unconditionally remove FDs from the
138 * epoll-set, and require it to succeed. If the removal fails,
139 * you did something wrong and better fix it.
140 */
141 r = epoll_ctl(file->context->epoll_fd, EPOLL_CTL_DEL, file->fd, NULL);
142 c_assert(r >= 0);
143
144 --file->context->n_files;
145 c_list_unlink(&file->ready_link);
146 }
147
148 file->fd = -1;
149 file->fn = NULL;
150 file->context = NULL;
151 }
152
153 /**
154 * dispatch_file_select() - select notification mask
155 * @file: dispatch file
156 * @mask: event mask
157 *
158 * This selects the events specified in @mask for notification. That is, if
159 * those events are signalled by the kernel, the callback of @file will be
160 * invoked for those events.
161 *
162 * Once you lost interest in a given event, you must deselect it via
163 * dispatch_file_deselect(). Otherwise, you will keep being notified of the
164 * event.
165 *
166 * Once you handled an event fully, you must clear it via dispatch_file_clear()
167 * to tell the dispatcher that you should only be invoked for the event
168 * when the kernel signals it again.
169 */
170 void dispatch_file_select(DispatchFile *file, uint32_t mask) {
171 c_assert(!(mask & ~file->kernel_mask));
172
173 file->user_mask |= mask;
174 if ((file->user_mask & file->events) && !c_list_is_linked(&file->ready_link))
175 c_list_link_tail(&file->context->ready_list, &file->ready_link);
176 }
177
178 /**
179 * dispatch_file_deselect() - deselect notification mask
180 * @file: dispatch file
181 * @mask: event mask
182 *
183 * This is the inverse of dispatch_file_select() and removes a given event mask
184 * from the user-mask. The callback will no longer be invoked for those events.
185 */
186 void dispatch_file_deselect(DispatchFile *file, uint32_t mask) {
187 c_assert(!(mask & ~file->kernel_mask));
188
189 file->user_mask &= ~mask;
190 if (!(file->events & file->user_mask))
191 c_list_unlink(&file->ready_link);
192 }
193
194 /**
195 * dispatch_file_clear() - clear kernel event mask
196 * @file: dispatch file
197 * @mask: event mask
198 *
199 * This clears the events in @mask from the pending kernel event mask. That is,
200 * those events are now considered as 'handled'. The kernel must notify us of
201 * them again to reconsider them.
202 */
203 void dispatch_file_clear(DispatchFile *file, uint32_t mask) {
204 c_assert(!(mask & ~file->kernel_mask));
205
206 file->events &= ~mask;
207 if (!(file->events & file->user_mask))
208 c_list_unlink(&file->ready_link);
209 }
210
211 /**
212 * dispatch_context_init() - initialize dispatch context
213 * @ctx: dispatch context
214 *
215 * This initializes a new dispatch context.
216 *
217 * Return: 0 on success, negative error code on failure.
218 */
219 int dispatch_context_init(DispatchContext *ctx) {
220 *ctx = (DispatchContext)DISPATCH_CONTEXT_NULL(*ctx);
221
222 ctx->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
223 if (ctx->epoll_fd < 0)
224 return error_origin(-errno);
225
226 return 0;
227 }
228
229 /**
230 * dispatch_context_deinit() - deinitialize dispatch context
231 * @ctx: dispatch context
232 *
233 * This deinitializes a dispatch context. The caller must make sure no
234 * dispatch-file is registered on it.
235 *
236 * The context will be set into an deinitialized state afterwards. Hence, it is
237 * safe to call this function multiple times.
238 */
239 void dispatch_context_deinit(DispatchContext *ctx) {
240 c_assert(!ctx->n_files);
241 c_assert(c_list_is_empty(&ctx->ready_list));
242
243 ctx->epoll_fd = c_close(ctx->epoll_fd);
244 }
245
246 /**
247 * dispatch_context_poll() - fetch events from kernel
248 * @ctx: dispatch context
249 * @timeout: poll timeout
250 *
251 * This calls into epoll_wait(2) to fetch events on all registered
252 * dispatch-files from the kernel. @timeout is passed unmodified to
253 * epoll_wait().
254 *
255 * The events fetched from the kernel are merged into our list of
256 * dispatch-files. Nothing is dispatched! The data is merely fetched from the
257 * kernel.
258 *
259 * Return: 0 on success, negative error code on failure.
260 */
261 int dispatch_context_poll(DispatchContext *ctx, int timeout) {
262 _c_cleanup_(c_freep) void *buffer = NULL;
263 struct epoll_event *events, *e;
264 DispatchFile *f;
265 size_t n;
266 int r;
267
268 n = ctx->n_files * sizeof(*events);
269 if (n > 128UL * 1024UL) {
270 buffer = malloc(n);
271 if (!buffer)
272 return error_origin(-ENOMEM);
273
274 events = buffer;
275 } else {
276 events = alloca(n);
277 }
278
279 r = epoll_wait(ctx->epoll_fd, events, ctx->n_files, timeout);
280 if (r < 0) {
281 if (errno == EINTR)
282 return 0;
283
284 return error_origin(-errno);
285 }
286
287 while (r > 0) {
288 e = &events[--r];
289 f = e->data.ptr;
290
291 c_assert(f->context == ctx);
292
293 f->events |= e->events & f->kernel_mask;
294 if ((f->events & f->user_mask) && !c_list_is_linked(&f->ready_link))
295 c_list_link_tail(&f->context->ready_list, &f->ready_link);
296 }
297
298 return 0;
299 }
300
301 /**
302 * dispatch_context_dispatch() - dispatch pending events
303 * @ctx: dispatch context
304 *
305 * This runs one dispatch round on the given dispatch context. That is, it
306 * dispatches all pending events and calls into the callbacks of the respective
307 * dispatch-file.
308 *
309 * The first non-zero return code of any dispatch-file callback will break the
310 * loop and cause a propagation of that error code to the caller.
311 *
312 * Return: 0 on success, otherwise the first non-zero return code of any
313 * dispatched file stops dispatching and is returned unmodified.
314 */
315 int dispatch_context_dispatch(DispatchContext *ctx) {
316 CList todo = (CList)C_LIST_INIT(todo);
317 DispatchFile *file;
318 int r;
319
320 r = dispatch_context_poll(ctx, c_list_is_empty(&ctx->ready_list) ? -1 : 0);
321 if (r)
322 return error_fold(r);
323
324 /*
325 * We want to dispatch @ctx->ready_list exactly once here. The trivial
326 * approach would be to iterate it via c_list_for_each(). However, we
327 * want to allow callbacks to modify their event masks, so we must
328 * allow them to add and remove files arbitrarily. At the same time, we
329 * want to prevent dispatching a single file twice, so we must make
330 * sure to detect detach+reattach cycles to avoid starvation.
331 *
332 * Therefore, we simply fetch the entire ready-list into @todo and
333 * handle it one-by-one, moving them back onto the ready-list. This is
334 * safe against entry-removal in the callbacks, and it has a clearly
335 * determined runtime.
336 */
337 c_list_swap(&todo, &ctx->ready_list);
338
339 while ((file = c_list_first_entry(&todo, DispatchFile, ready_link))) {
340 c_list_unlink(&file->ready_link);
341 c_list_link_tail(&ctx->ready_list, &file->ready_link);
342
343 r = file->fn(file);
344 if (error_trace(r)) {
345 c_list_splice(&ctx->ready_list, &todo);
346 break;
347 }
348 }
349
350 c_assert(c_list_is_empty(&todo));
351 return r;
352 }