Modify it to adjust Tizen IVI enviroment
[platform/upstream/kmscon.git] / src / eloop.c
1 /*
2  * Event Loop
3  *
4  * Copyright (c) 2011-2013 David Herrmann <dh.herrmann@googlemail.com>
5  * Copyright (c) 2011 University of Tuebingen
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining
8  * a copy of this software and associated documentation files
9  * (the "Software"), to deal in the Software without restriction, including
10  * without limitation the rights to use, copy, modify, merge, publish,
11  * distribute, sublicense, and/or sell copies of the Software, and to
12  * permit persons to whom the Software is furnished to do so, subject to
13  * the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included
16  * in all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25  */
26
27 /**
28  * SECTION:eloop
29  * @short_description: Event loop
30  * @include: eloop.h
31  *
32  * The event loop allows to register event sources and poll them for events.
33  * When an event occurs, the user-supplied callback is called.
34  *
35  * The event-loop allows the callbacks to modify _any_ data they want. They can
36  * remove themselves or other sources from the event loop even in a callback.
37  * This, however, means that recursive dispatch calls are not supported to
38  * increase performance and avoid internal dispatch-stacks.
39  *
40  * Sources can be one of:
41  *  - File descriptors: An fd that is watched for readable/writeable events
42  *  - Timers: An event that occurs after a relative timeout
43  *  - Counters: An event that occurs when the counter is non-zero
44  *  - Signals: An event that occurs when a signal is caught
45  *  - Idle: An event that occurs when nothing else is done
46  *  - Eloop: An event loop itself can be a source of another event loop
47  *
48  * A source can be registered for a single event-loop only! You cannot add it
49  * to multiple event loops simultaneously. Also all provided sources are based
50  * on the file-descriptor source so it is guaranteed that you can get a
51  * file-descriptor for every source-type. This is not exported via the public
52  * API, but you can get the epoll-fd which is basically a selectable FD summary
53  * of all event sources.
54  *
55  * For instance, if you're developing a library, you can use the eloop library
56  * internally and you will have a full event-loop implementation inside of a
57  * library without any side-effects. You simply export the epoll-fd of the
58  * eloop-object via your public API and the outside users think you only use a
59  * single file-descriptor. They include this FD in their own application event
60  * loop which will then dispatch the messages to your library. Internally, you
61  * simply forward this dispatching to ev_eloop_dispatch() which then calls all
62  * your internal callbacks.
63  * That is, you have an event loop inside your library without requiring the
64  * outside-user to use the same event loop. You also have no global state or
65  * thread-bound event-loops like the Qt/Gtk event loops. So you have full
66  * access to the whole event loop without any side-effects.
67  *
68  *
69  * The whole eloop library does not use any global data. Therefore, it is fully
70  * re-entrant and no synchronization needed. However, a single object is not
71  * thread-safe. This means, if you access a single eloop object or registered
72  * sources on this eloop object in two different threads, you need to
73  * synchronize them. Furthermore, all callbacks are called from the thread that
74  * calls ev_eloop_dispatch() or ev_eloop_run().
75  * This guarantees that you have full control over the eloop but that you also
76  * have to implement additional functionality like thread-affinity yourself
77  * (obviously, only if you need it).
78  *
79  * The philosophy behind this library is that a proper application needs only a
80  * single thread that uses an event loop. Multiple threads should be used to do
81  * calculations, but not to avoid learning how to do non-blocking I/O!
82  * Therefore, only the application threads needs an event-loop, all other
83  * threads only perform calculation and return the data to the main thread.
84  * However, the library does not enforce this design-choice. On the contrary,
85  * it supports all other types of application-designs, too. But as it is
86  * optimized for performance, other application-designs may need to add further
87  * functionality (like thread-affinity) by themselves as it would slow down the
88  * event loop if it was natively implemented.
89  *
90  *
91  * To get started simply create an eloop object with ev_eloop_new(). All
92  * functions return 0 on success and a negative error code like -EFAULT on
93  * failure. -EINVAL is returned if invalid parameters were passed.
94  * Every object can be ref-counted. *_ref() increases the reference-count and
95  * *_unref() decreases it. *_unref() also destroys the object if the ref-count
96  * drops to 0.
97  * To create new objects you call *_new(). It stores a pointer to the new
98  * object in the location you passed as parameter. Nearly all structues are
99  * opaque, that is, you cannot access member fields directly. This guarantees
100  * ABI stability.
101  *
102  * You can create sources with ev_fd_new(), ev_timer_new(), ... and you can add
103  * them to you eloop with ev_eloop_add_fd() or ev_eloop_add_timer(), ...
104  * After they are added you can call ev_eloop_run() to run this eloop for the
105  * given time. If you pass -1 as timeout, it runs until some callback calls
106  * ev_eloop_exit() on this eloop.
107  * You can perform _any_ operations on an eloop object inside of callbacks. You
108  * can add new sources, remove sources, destroy sources, modify sources. You
109  * also do all this on the currently active source.
110  *
111  * All objects are enabled by default. You can disable them with *_disable()
112  * and re-enable them with *_enable(). Only when enabled, they are added to the
113  * dispatcher and callbacks are called.
114  *
115  * Two sources are different for performance reasons:
116  *   Idle sources: Idle sources can be registered with
117  *   ev_eloop_register_idle_cb() and unregistered with
118  *   ev_eloop_unregister_idle_cb(). They internally share a single
119  *   file-descriptor to make them faster so you cannot get the same access as
120  *   to other event sources (you cannot enable/disable them or similar).
121  *   Idle sources are called every-time ev_eloop_dispatch() is called. That is,
122  *   as long as an idle-source is registered, the event-loop will not go to
123  *   sleep!
124  *
125  *   Signal sources: Talking about the API they are very similar to
126  *   idle-sources. They same restrictions apply, however, their type is very
127  *   different. A signal-callback is called when the specified signal is
128  *   received. They are not called in signal-context! But rather called in the
129  *   same context as every other source. They are implemented with
130  *   linux-signalfd.
131  *   You can register multiple callbacks for the same signal and all callbacks
132  *   will be called (compared to plain signalfd where only one fd gets the
133  *   signal). This is done internally by sharing the signalfd.
134  *   However, there is one restriction: You cannot share a signalfd between
135  *   multiple eloop-instances. That is, if you register a callback for the same
136  *   signal on two different eloop-instances (which are connected themselves),
137  *   then only one eloop-instance will fire the signal source. This is a
138  *   restriction of signalfd that cannot be overcome. However, it is very
139  *   uncommon to register multiple callbacks for a signal so this shouldn't
140  *   affect common application use-cases.
141  *   Also note that if you register a callback for SIGCHLD then the eloop-
142  *   object will automatically reap all pending zombies _after_ your callback
143  *   has been called. So if you need to check for them, then check for all of
144  *   them in the callback. After you return, they will be gone.
145  *   When adding a signal handler the signal is automatically added to the
146  *   currently blocked signals. It is not removed when dropping the
147  *   signal-source, though.
148  *
149  * Eloop uses several system calls which may fail. All errors (including memory
150  * allocation errors via -ENOMEM) are forwarded to the caller, however, it is
151  * often preferable to have a more detailed logging message. Therefore, eloop
152  * takes a loggin-function as argument for each object. Pass NULL if you are
153  * not interested in logging. This will disable logging entirely.
154  * Otherwise, pass in a callback from your application. This callback will be
155  * called when a message is to be logged. The function may be called under any
156  * circumstances (out-of-memory, etc...) and should always behave well.
157  * Nothing is ever logged except through this callback.
158  */
159
160 #include <errno.h>
161 #include <inttypes.h>
162 #include <pthread.h>
163 #include <signal.h>
164 #include <stdbool.h>
165 #include <stdlib.h>
166 #include <string.h>
167 #include <sys/epoll.h>
168 #include <sys/eventfd.h>
169 #include <sys/signalfd.h>
170 #include <sys/time.h>
171 #include <sys/timerfd.h>
172 #include <sys/wait.h>
173 #include <time.h>
174 #include <unistd.h>
175 #include "eloop.h"
176 #include "shl_dlist.h"
177 #include "shl_hook.h"
178 #include "shl_llog.h"
179 #include "shl_misc.h"
180
181 #define LLOG_SUBSYSTEM "eloop"
182
183 /**
184  * ev_eloop:
185  * @ref: refcnt of this object
186  * @llog: llog log function
187  * @llog_data: llog log function user-data
188  * @efd: The epoll file descriptor.
189  * @fd: Event source around \efd so you can nest event loops
190  * @cnt: Counter source used for idle events
191  * @sig_list: Shared signal sources
192  * @idlers: List of idle sources
193  * @cur_fds: Current dispatch array of fds
194  * @cur_fds_cnt: current length of \cur_fds
195  * @cur_fds_size: absolute size of \cur_fds
196  * @exit: true if we should exit the main loop
197  *
198  * An event loop is an object where you can register event sources. If you then
199  * sleep on the event loop, you will be woken up if a single event source is
200  * firing up. An event loop itself is an event source so you can nest them.
201  */
202 struct ev_eloop {
203         unsigned long ref;
204         llog_submit_t llog;
205         void *llog_data;
206         int efd;
207         struct ev_fd *fd;
208         int idle_fd;
209
210         struct shl_dlist sig_list;
211         struct shl_hook *chlds;
212         struct shl_hook *idlers;
213         struct shl_hook *pres;
214         struct shl_hook *posts;
215
216         bool dispatching;
217         struct epoll_event *cur_fds;
218         size_t cur_fds_cnt;
219         size_t cur_fds_size;
220         bool exit;
221 };
222
223 /**
224  * ev_fd:
225  * @ref: refcnt for object
226  * @llog: llog log function
227  * @llog_data: llog log function user-data
228  * @fd: the actual file descriptor
229  * @mask: the event mask for this fd (EV_READABLE, EV_WRITEABLE, ...)
230  * @cb: the user callback
231  * @data: the user data
232  * @enabled: true if the object is currently enabled
233  * @loop: NULL or pointer to eloop if bound
234  *
235  * File descriptors are the most basic event source. Internally, they are used
236  * to implement all other kinds of event sources.
237  */
238 struct ev_fd {
239         unsigned long ref;
240         llog_submit_t llog;
241         void *llog_data;
242         int fd;
243         int mask;
244         ev_fd_cb cb;
245         void *data;
246
247         bool enabled;
248         struct ev_eloop *loop;
249 };
250
251 /**
252  * ev_timer:
253  * @ref: refcnt of this object
254  * @llog: llog log function
255  * @llog_data: llog log function user-data
256  * @cb: user callback
257  * @data: user data
258  * @fd: the timerfd file descriptor
259  * @efd: fd-source for @fd
260  *
261  * Based on timerfd this allows firing events based on relative timeouts.
262  */
263 struct ev_timer {
264         unsigned long ref;
265         llog_submit_t llog;
266         void *llog_data;
267         ev_timer_cb cb;
268         void *data;
269
270         int fd;
271         struct ev_fd *efd;
272 };
273
274 /**
275  * ev_counter:
276  * @ref: refcnt of counter object
277  * @llog: llog log function
278  * @llog_data: llog log function user-data
279  * @cb: user callback
280  * @data: user data
281  * @fd: eventfd file descriptor
282  * @efd: fd-source for @fd
283  *
284  * Counter sources fire if they are non-zero. They are based on the eventfd
285  * syscall in linux.
286  */
287 struct ev_counter {
288         unsigned long ref;
289         llog_submit_t llog;
290         void *llog_data;
291         ev_counter_cb cb;
292         void *data;
293
294         int fd;
295         struct ev_fd *efd;
296 };
297
298 /**
299  * ev_signal_shared:
300  * @list: list integration into ev_eloop object
301  * @fd: the signalfd file descriptor for this signal
302  * @signum: the actual signal number
303  * @hook: list of registered user callbacks for this signal
304  *
305  * A shared signal allows multiple listeners for the same signal. All listeners
306  * are called if the signal is caught.
307  */
308 struct ev_signal_shared {
309         struct shl_dlist list;
310
311         struct ev_fd *fd;
312         int signum;
313         struct shl_hook *hook;
314 };
315
316 /*
317  * Shared signals
318  * signalfd allows us to conveniently listen for incoming signals. However, if
319  * multiple signalfds are registered for the same signal, then only one of them
320  * will get signaled. To avoid this restriction, we provide shared signals.
321  * That means, the user can register for a signal and if no other user is
322  * registered for this signal, yet, we create a new shared signal. Otherwise,
323  * we add the user to the existing shared signals.
324  * If the signal is caught, we simply call all users that are registered for
325  * this signal.
326  * To avoid side-effects, we automatically block all signals for the current
327  * thread when a signalfd is created. We never unblock the signal. However,
328  * most modern linux user-space programs avoid signal handlers, anyway, so you
329  * can use signalfd only.
330  */
331
332 static void sig_child(struct ev_eloop *loop, struct signalfd_siginfo *info,
333                       void *data)
334 {
335         pid_t pid;
336         int status;
337         struct ev_child_data d;
338
339         while (1) {
340                 pid = waitpid(-1, &status, WNOHANG);
341                 if (pid == -1) {
342                         if (errno != ECHILD)
343                                 llog_warn(loop, "cannot wait on child: %m");
344                         break;
345                 } else if (pid == 0) {
346                         break;
347                 } else if (WIFEXITED(status)) {
348                         if (WEXITSTATUS(status) != 0)
349                                 llog_debug(loop, "child %d exited with status %d",
350                                            pid, WEXITSTATUS(status));
351                         else
352                                 llog_debug(loop, "child %d exited successfully",
353                                            pid);
354                 } else if (WIFSIGNALED(status)) {
355                         llog_debug(loop, "child %d exited by signal %d", pid,
356                                    WTERMSIG(status));
357                 }
358
359                 d.pid = pid;
360                 d.status = status;
361                 shl_hook_call(loop->chlds, loop, &d);
362         }
363 }
364
365 static void shared_signal_cb(struct ev_fd *fd, int mask, void *data)
366 {
367         struct ev_signal_shared *sig = data;
368         struct signalfd_siginfo info;
369         int len;
370
371         if (mask & EV_READABLE) {
372                 len = read(fd->fd, &info, sizeof(info));
373                 if (len != sizeof(info))
374                         llog_warn(fd, "cannot read signalfd (%d): %m", errno);
375                 else
376                         shl_hook_call(sig->hook, sig->fd->loop, &info);
377         } else if (mask & (EV_HUP | EV_ERR)) {
378                 llog_warn(fd, "HUP/ERR on signal source");
379         }
380 }
381
382 /**
383  * signal_new:
384  * @out: Shared signal storage where the new object is stored
385  * @loop: The event loop where this shared signal is registered
386  * @signum: Signal number that this shared signal is for
387  *
388  * This creates a new shared signal and links it into the list of shared
389  * signals in @loop. It automatically adds @signum to the signal mask of the
390  * current thread so the signal is blocked.
391  *
392  * Returns: 0 on success, otherwise negative error code
393  */
394 static int signal_new(struct ev_signal_shared **out, struct ev_eloop *loop,
395                         int signum)
396 {
397         sigset_t mask;
398         int ret, fd;
399         struct ev_signal_shared *sig;
400
401         if (signum < 0)
402                 return llog_EINVAL(loop);
403
404         sig = malloc(sizeof(*sig));
405         if (!sig)
406                 return llog_ENOMEM(loop);
407         memset(sig, 0, sizeof(*sig));
408         sig->signum = signum;
409
410         ret = shl_hook_new(&sig->hook);
411         if (ret)
412                 goto err_free;
413
414         sigemptyset(&mask);
415         sigaddset(&mask, signum);
416
417         fd = signalfd(-1, &mask, SFD_CLOEXEC | SFD_NONBLOCK);
418         if (fd < 0) {
419                 ret = -errno;
420                 llog_error(loop, "cannot created signalfd");
421                 goto err_hook;
422         }
423
424         ret = ev_eloop_new_fd(loop, &sig->fd, fd, EV_READABLE,
425                                 shared_signal_cb, sig);
426         if (ret)
427                 goto err_sig;
428
429         pthread_sigmask(SIG_BLOCK, &mask, NULL);
430         shl_dlist_link(&loop->sig_list, &sig->list);
431
432         *out = sig;
433         return 0;
434
435 err_sig:
436         close(fd);
437 err_hook:
438         shl_hook_free(sig->hook);
439 err_free:
440         free(sig);
441         return ret;
442 }
443
444 /**
445  * signal_free:
446  * @sig: The shared signal to be freed
447  *
448  * This unlinks the given shared signal from the event-loop where it was
449  * registered and destroys it. This does _not_ unblock the signal number that it
450  * was associated to. If you want this, you need to do this manually with
451  * pthread_sigmask().
452  */
453 static void signal_free(struct ev_signal_shared *sig)
454 {
455         int fd;
456
457         if (!sig)
458                 return;
459
460         shl_dlist_unlink(&sig->list);
461         fd = sig->fd->fd;
462         ev_eloop_rm_fd(sig->fd);
463         close(fd);
464         shl_hook_free(sig->hook);
465         free(sig);
466         /*
467          * We do not unblock the signal here as there may be other subsystems
468          * which blocked this signal so we do not want to interfere. If you
469          * need a clean sigmask then do it yourself.
470          */
471 }
472
473 /*
474  * Eloop mainloop
475  * The main eloop object is responsible for correctly dispatching all events.
476  * You can register fd, idle or signal sources with it. All other kinds of
477  * sources are based on these. In fact, event idle and signal sources are based
478  * on fd sources.
479  * As special feature, you can retrieve an fd of an eloop object, too, and pass
480  * it to your own event loop. If this fd is readable, then call
481  * ev_eloop_dispatch() to make this loop dispatch all pending events.
482  *
483  * There is one restriction when nesting eloops, though. You cannot share
484  * signals across eloop boundaries. That is, if you have registered for shared
485  * signals in two eloops for the _same_ signal, then only one eloop will
486  * receive the signal (and this is pretty random).
487  * However, such a setup is most often broken in design and hence should never
488  * occur. Even shared signals are quite rare.
489  * Anyway, you must take this into account when nesting eloops.
490  *
491  * For the curious reader: We implement idle sources with counter sources. That
492  * is, whenever there is an idle source we increase the counter source. Hence,
493  * the next dispatch call will call the counter source and this will call all
494  * registered idle source. If the idle sources do not unregister them, then we
495  * directly increase the counter again and the next dispatch round will call
496  * all idle sources again. This, however, has the side-effect that idle sources
497  * are _not_ called before other fd events but are rather mixed in between.
498  */
499
500 static void eloop_event(struct ev_fd *fd, int mask, void *data)
501 {
502         struct ev_eloop *eloop = data;
503
504         if (mask & EV_READABLE)
505                 ev_eloop_dispatch(eloop, 0);
506         if (mask & (EV_HUP | EV_ERR))
507                 llog_warn(eloop, "HUP/ERR on eloop source");
508 }
509
510 static int write_eventfd(llog_submit_t llog, void *llog_data, int fd,
511                          uint64_t val)
512 {
513         int ret;
514
515         if (!val)
516                 return llog_dEINVAL(llog, llog_data);
517
518         if (val == 0xffffffffffffffffULL) {
519                 llog_dwarning(llog, llog_data,
520                               "increasing counter with invalid value %" PRIu64,
521                               val);
522                 return -EINVAL;;
523         }
524
525         ret = write(fd, &val, sizeof(val));
526         if (ret < 0) {
527                 if (errno == EAGAIN)
528                         llog_dwarning(llog, llog_data,
529                                       "eventfd overflow while writing %" PRIu64,
530                                       val);
531                 else
532                         llog_dwarning(llog, llog_data,
533                                       "eventfd write error (%d): %m", errno);
534                 return -EFAULT;
535         } else if (ret != sizeof(val)) {
536                 llog_dwarning(llog, llog_data,
537                               "wrote %d bytes instead of 8 to eventdfd", ret);
538                 return -EFAULT;
539         }
540
541         return 0;
542 }
543
544 static void eloop_idle_event(struct ev_eloop *loop, unsigned int mask)
545 {
546         int ret;
547         uint64_t val;
548
549         if (mask & (EV_HUP | EV_ERR)) {
550                 llog_warning(loop, "HUP/ERR on eventfd");
551                 goto err_out;
552         }
553
554         if (!(mask & EV_READABLE))
555                 return;
556
557         ret = read(loop->idle_fd, &val, sizeof(val));
558         if (ret < 0) {
559                 if (errno != EAGAIN) {
560                         llog_warning(loop, "reading eventfd failed (%d): %m",
561                                      errno);
562                         goto err_out;
563                 }
564         } else if (ret == 0) {
565                 llog_warning(loop, "EOF on eventfd");
566                 goto err_out;
567         } else if (ret != sizeof(val)) {
568                 llog_warning(loop, "read %d bytes instead of 8 on eventfd",
569                              ret);
570                 goto err_out;
571         } else if (val > 0) {
572                 shl_hook_call(loop->idlers, loop, NULL);
573                 if (shl_hook_num(loop->idlers) > 0)
574                         write_eventfd(loop->llog, loop->llog_data,
575                                       loop->idle_fd, 1);
576         }
577
578         return;
579
580 err_out:
581         ret = epoll_ctl(loop->efd, EPOLL_CTL_DEL, loop->idle_fd, NULL);
582         if (ret)
583                 llog_warning(loop, "cannot remove fd %d from epollset (%d): %m",
584                              loop->idle_fd, errno);
585 }
586
587 /**
588  * ev_eloop_new:
589  * @out: Storage for the result
590  * @log: logging function or NULL
591  * @log_data: logging function user-data
592  *
593  * This creates a new event-loop with ref-count 1. The new event loop is stored
594  * in @out and has no registered events.
595  *
596  * Returns: 0 on success, otherwise negative error code
597  */
598 SHL_EXPORT
599 int ev_eloop_new(struct ev_eloop **out, ev_log_t log, void *log_data)
600 {
601         struct ev_eloop *loop;
602         int ret;
603         struct epoll_event ep;
604
605         if (!out)
606                 return llog_dEINVAL(log, log_data);
607
608         loop = malloc(sizeof(*loop));
609         if (!loop)
610                 return llog_dENOMEM(log, log_data);
611
612         memset(loop, 0, sizeof(*loop));
613         loop->ref = 1;
614         loop->llog = log;
615         loop->llog_data = log_data;
616         shl_dlist_init(&loop->sig_list);
617
618         loop->cur_fds_size = 32;
619         loop->cur_fds = malloc(sizeof(struct epoll_event) *
620                                loop->cur_fds_size);
621         if (!loop->cur_fds) {
622                 ret = llog_ENOMEM(loop);
623                 goto err_free;
624         }
625
626         ret = shl_hook_new(&loop->chlds);
627         if (ret)
628                 goto err_fds;
629
630         ret = shl_hook_new(&loop->idlers);
631         if (ret)
632                 goto err_childs;
633
634         ret = shl_hook_new(&loop->pres);
635         if (ret)
636                 goto err_idlers;
637
638         ret = shl_hook_new(&loop->posts);
639         if (ret)
640                 goto err_pres;
641
642         loop->efd = epoll_create1(EPOLL_CLOEXEC);
643         if (loop->efd < 0) {
644                 ret = -errno;
645                 llog_error(loop, "cannot create epoll-fd");
646                 goto err_posts;
647         }
648
649         ret = ev_fd_new(&loop->fd, loop->efd, EV_READABLE, eloop_event, loop,
650                         loop->llog, loop->llog_data);
651         if (ret)
652                 goto err_close;
653
654         loop->idle_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
655         if (loop->idle_fd < 0) {
656                 llog_error(loop, "cannot create eventfd (%d): %m", errno);
657                 ret = -EFAULT;
658                 goto err_fd;
659         }
660
661         memset(&ep, 0, sizeof(ep));
662         ep.events |= EPOLLIN;
663         ep.data.ptr = loop;
664
665         ret = epoll_ctl(loop->efd, EPOLL_CTL_ADD, loop->idle_fd, &ep);
666         if (ret) {
667                 llog_warning(loop, "cannot add fd %d to epoll set (%d): %m",
668                              loop->idle_fd, errno);
669                 ret = -EFAULT;
670                 goto err_idle_fd;
671         }
672
673         llog_debug(loop, "new eloop object %p", loop);
674         *out = loop;
675         return 0;
676
677 err_idle_fd:
678         close(loop->idle_fd);
679 err_fd:
680         ev_fd_unref(loop->fd);
681 err_close:
682         close(loop->efd);
683 err_posts:
684         shl_hook_free(loop->posts);
685 err_pres:
686         shl_hook_free(loop->pres);
687 err_idlers:
688         shl_hook_free(loop->idlers);
689 err_childs:
690         shl_hook_free(loop->chlds);
691 err_fds:
692         free(loop->cur_fds);
693 err_free:
694         free(loop);
695         return ret;
696 }
697
698 /**
699  * ev_eloop_ref:
700  * @loop: Event loop to be modified or NULL
701  *
702  * This increases the ref-count of @loop by 1.
703  */
704 SHL_EXPORT
705 void ev_eloop_ref(struct ev_eloop *loop)
706 {
707         if (!loop)
708                 return;
709
710         ++loop->ref;
711 }
712
713 /**
714  * ev_eloop_unref:
715  * @loop: Event loop to be modified or NULL
716  *
717  * This decreases the ref-count of @loop by 1. If it drops to zero, the event
718  * loop is destroyed. Note that every registered event source takes a ref-count
719  * of the event loop so this ref-count will never drop to zero while there is an
720  * registered event source.
721  */
722 SHL_EXPORT
723 void ev_eloop_unref(struct ev_eloop *loop)
724 {
725         struct ev_signal_shared *sig;
726         int ret;
727
728         if (!loop)
729                 return;
730         if (!loop->ref)
731                 return llog_vEINVAL(loop);
732         if (--loop->ref)
733                 return;
734
735         llog_debug(loop, "free eloop object %p", loop);
736
737         if (shl_hook_num(loop->chlds))
738                 ev_eloop_unregister_signal_cb(loop, SIGCHLD, sig_child, loop);
739
740         while (loop->sig_list.next != &loop->sig_list) {
741                 sig = shl_dlist_entry(loop->sig_list.next,
742                                         struct ev_signal_shared,
743                                         list);
744                 signal_free(sig);
745         }
746
747         ret = epoll_ctl(loop->efd, EPOLL_CTL_DEL, loop->idle_fd, NULL);
748         if (ret)
749                 llog_warning(loop, "cannot remove fd %d from epollset (%d): %m",
750                              loop->idle_fd, errno);
751         close(loop->idle_fd);
752
753         ev_fd_unref(loop->fd);
754         close(loop->efd);
755         shl_hook_free(loop->posts);
756         shl_hook_free(loop->pres);
757         shl_hook_free(loop->idlers);
758         shl_hook_free(loop->chlds);
759         free(loop->cur_fds);
760         free(loop);
761 }
762
763 /**
764  * ev_eloop_flush_fd:
765  * @loop: The event loop where @fd is registered
766  * @fd: The fd to be flushed
767  *
768  * If @loop is currently dispatching events, this will remove all pending events
769  * of @fd from the current event-list.
770  */
771 SHL_EXPORT
772 void ev_eloop_flush_fd(struct ev_eloop *loop, struct ev_fd *fd)
773 {
774         int i;
775
776         if (!loop)
777                 return;
778         if (!fd)
779                 return llog_vEINVAL(loop);
780
781         if (loop->dispatching) {
782                 for (i = 0; i < loop->cur_fds_cnt; ++i) {
783                         if (loop->cur_fds[i].data.ptr == fd)
784                                 loop->cur_fds[i].data.ptr = NULL;
785                 }
786         }
787 }
788
789 static unsigned int convert_mask(uint32_t mask)
790 {
791         unsigned int res = 0;
792
793         if (mask & EPOLLIN)
794                 res |= EV_READABLE;
795         if (mask & EPOLLOUT)
796                 res |= EV_WRITEABLE;
797         if (mask & EPOLLERR)
798                 res |= EV_ERR;
799         if (mask & EPOLLHUP)
800                 res |= EV_HUP;
801
802         return res;
803 }
804
805 /**
806  * ev_eloop_dispatch:
807  * @loop: Event loop to be dispatched
808  * @timeout: Timeout in milliseconds
809  *
810  * This listens on @loop for incoming events and handles all events that
811  * occurred. This waits at most @timeout milliseconds until returning. If
812  * @timeout is -1, this waits until the first event arrives. If @timeout is 0,
813  * then this returns directly if no event is currently pending.
814  *
815  * This performs only a single dispatch round. That is, if all sources where
816  * checked for events and there are no more pending events, this will return. If
817  * it handled events and the timeout has not elapsed, this will still return.
818  *
819  * If ev_eloop_exit() was called on @loop, then this will return immediately.
820  *
821  * Returns: 0 on success, otherwise negative error code
822  */
823 SHL_EXPORT
824 int ev_eloop_dispatch(struct ev_eloop *loop, int timeout)
825 {
826         struct epoll_event *ep;
827         struct ev_fd *fd;
828         int i, count, mask, ret;
829
830         if (!loop)
831                 return -EINVAL;
832         if (loop->exit)
833                 return llog_EINVAL(loop);
834         if (loop->dispatching) {
835                 llog_warn(loop, "recursive dispatching not allowed");
836                 return -EOPNOTSUPP;
837         }
838
839         loop->dispatching = true;
840
841         shl_hook_call(loop->pres, loop, NULL);
842
843         count = epoll_wait(loop->efd,
844                            loop->cur_fds,
845                            loop->cur_fds_size,
846                            timeout);
847         if (count < 0) {
848                 if (errno == EINTR) {
849                         ret = 0;
850                         goto out_dispatch;
851                 } else {
852                         llog_warn(loop, "epoll_wait dispatching failed: %m");
853                         ret = -errno;
854                         goto out_dispatch;
855                 }
856         } else if (count > loop->cur_fds_size) {
857                 count = loop->cur_fds_size;
858         }
859
860         ep = loop->cur_fds;
861         loop->cur_fds_cnt = count;
862
863         for (i = 0; i < count; ++i) {
864                 if (ep[i].data.ptr == loop) {
865                         mask = convert_mask(ep[i].events);
866                         eloop_idle_event(loop, mask);
867                 } else {
868                         fd = ep[i].data.ptr;
869                         if (!fd || !fd->cb || !fd->enabled)
870                                 continue;
871
872                         mask = convert_mask(ep[i].events);
873                         fd->cb(fd, mask, fd->data);
874                 }
875         }
876
877         if (count == loop->cur_fds_size) {
878                 ep = realloc(loop->cur_fds, sizeof(struct epoll_event) *
879                              loop->cur_fds_size * 2);
880                 if (!ep) {
881                         llog_warning(loop, "cannot reallocate dispatch cache to size %zu",
882                                     loop->cur_fds_size * 2);
883                 } else {
884                         loop->cur_fds = ep;
885                         loop->cur_fds_size *= 2;
886                 }
887         }
888
889         ret = 0;
890
891 out_dispatch:
892         shl_hook_call(loop->posts, loop, NULL);
893         loop->dispatching = false;
894         return ret;
895 }
896
897 /**
898  * ev_eloop_run:
899  * @loop: The event loop to be run
900  * @timeout: Timeout for this operation
901  *
902  * This is similar to ev_eloop_dispatch() but runs _exactly_ for @timeout
903  * milliseconds. It calls ev_eloop_dispatch() as often as it can until the
904  * timeout has elapsed. If @timeout is -1 this will run until you call
905  * ev_eloop_exit(). If @timeout is 0 this is equal to calling
906  * ev_eloop_dispatch() with a timeout of 0.
907  *
908  * Calling ev_eloop_exit() will always interrupt this function and make it
909  * return.
910  *
911  * Returns: 0 on success, otherwise a negative error code
912  */
913 SHL_EXPORT
914 int ev_eloop_run(struct ev_eloop *loop, int timeout)
915 {
916         int ret;
917         struct timeval tv, start;
918         int64_t off, msec;
919
920         if (!loop)
921                 return -EINVAL;
922         loop->exit = false;
923
924         llog_debug(loop, "run for %d msecs", timeout);
925         gettimeofday(&start, NULL);
926
927         while (!loop->exit) {
928                 ret = ev_eloop_dispatch(loop, timeout);
929                 if (ret)
930                         return ret;
931
932                 if (!timeout) {
933                         break;
934                 } else if (timeout > 0) {
935                         gettimeofday(&tv, NULL);
936                         off = tv.tv_sec - start.tv_sec;
937                         msec = (int64_t)tv.tv_usec - (int64_t)start.tv_usec;
938                         if (msec < 0) {
939                                 off -= 1;
940                                 msec = 1000000 + msec;
941                         }
942                         off *= 1000;
943                         off += msec / 1000;
944                         if (off >= timeout)
945                                 break;
946                 }
947         }
948
949         return 0;
950 }
951
952 /**
953  * ev_eloop_exit:
954  * @loop: Event loop that should exit
955  *
956  * This makes a call to ev_eloop_run() stop.
957  */
958 SHL_EXPORT
959 void ev_eloop_exit(struct ev_eloop *loop)
960 {
961         if (!loop)
962                 return;
963
964         llog_debug(loop, "exiting %p", loop);
965
966         loop->exit = true;
967         if (loop->fd->loop)
968                 ev_eloop_exit(loop->fd->loop);
969 }
970
971 /**
972  * ev_eloop_get_fd:
973  * @loop: Event loop
974  *
975  * Returns a single file descriptor for the whole event-loop. If that FD is
976  * readable, then one of the event-sources is active and you should call
977  * ev_eloop_dispatch(loop, 0); to dispatch these events.
978  * If the fd is not readable, then ev_eloop_dispatch() would sleep as there are
979  * no active events.
980  *
981  * Returns: A file descriptor for the event loop or negative error code
982  */
983 SHL_EXPORT
984 int ev_eloop_get_fd(struct ev_eloop *loop)
985 {
986         if (!loop)
987                 return -EINVAL;
988
989         return loop->efd;
990 }
991
992 /**
993  * ev_eloop_new_eloop:
994  * @loop: The parent event-loop where the new event loop is registered
995  * @out: Storage for new event loop
996  *
997  * This creates a new event loop and directly registers it as event source on
998  * the parent event loop \loop.
999  *
1000  * Returns: 0 on success, otherwise negative error code
1001  */
1002 SHL_EXPORT
1003 int ev_eloop_new_eloop(struct ev_eloop *loop, struct ev_eloop **out)
1004 {
1005         struct ev_eloop *el;
1006         int ret;
1007
1008         if (!loop)
1009                 return -EINVAL;
1010         if (!out)
1011                 return llog_EINVAL(loop);
1012
1013         ret = ev_eloop_new(&el, loop->llog, loop->llog_data);
1014         if (ret)
1015                 return ret;
1016
1017         ret = ev_eloop_add_eloop(loop, el);
1018         if (ret) {
1019                 ev_eloop_unref(el);
1020                 return ret;
1021         }
1022
1023         ev_eloop_unref(el);
1024         *out = el;
1025         return 0;
1026 }
1027
1028 /**
1029  * ev_eloop_add_eloop:
1030  * @loop: Parent event loop
1031  * @add: The event loop that is registered as event source on @loop
1032  *
1033  * This registers the existing event loop @add as event source on the parent
1034  * event loop @loop.
1035  *
1036  * Returns: 0 on success, otherwise negative error code
1037  */
1038 SHL_EXPORT
1039 int ev_eloop_add_eloop(struct ev_eloop *loop, struct ev_eloop *add)
1040 {
1041         int ret;
1042
1043         if (!loop)
1044                 return -EINVAL;
1045         if (!add)
1046                 return llog_EINVAL(loop);
1047
1048         if (add->fd->loop)
1049                 return -EALREADY;
1050
1051         /* This adds the epoll-fd into the parent epoll-set. This works
1052          * perfectly well with registered FDs, timers, etc. However, we use
1053          * shared signals in this event-loop so if the parent and child have
1054          * overlapping shared-signals, then the signal will be randomly
1055          * delivered to either the parent-hook or child-hook but never both.
1056          * TODO:
1057          * We may fix this by linking the childs-sig_list into the parent's
1058          * siglist but we didn't need this, yet, so ignore it here.
1059          */
1060
1061         ret = ev_eloop_add_fd(loop, add->fd);
1062         if (ret)
1063                 return ret;
1064
1065         ev_eloop_ref(add);
1066         return 0;
1067 }
1068
1069 /**
1070  * ev_eloop_rm_eloop:
1071  * @rm: Event loop to be unregistered from its parent
1072  *
1073  * This unregisters the event loop @rm as event source from its parent. If this
1074  * event loop was not registered on any other event loop, then this call does
1075  * nothing.
1076  */
1077 SHL_EXPORT
1078 void ev_eloop_rm_eloop(struct ev_eloop *rm)
1079 {
1080         if (!rm || !rm->fd->loop)
1081                 return;
1082
1083         ev_eloop_rm_fd(rm->fd);
1084         ev_eloop_unref(rm);
1085 }
1086
1087 /*
1088  * FD sources
1089  * This allows adding file descriptors to an eloop. A file descriptor is the
1090  * most basic kind of source and used for all other source types.
1091  * By default a source is always enabled but you can easily disable the source
1092  * by calling ev_fd_disable(). This will have the effect, that the source is
1093  * still registered with the eloop but will not wake up the thread or get
1094  * called until you enable it again.
1095  */
1096
1097 /**
1098  * ev_fd_new:
1099  * @out: Storage for result
1100  * @rfd: The actual file descriptor
1101  * @mask: Bitmask of %EV_READABLE and %EV_WRITEABLE flags
1102  * @cb: User callback
1103  * @data: User data
1104  * @log: llog function or NULL
1105  * @log_data: logging function user-data
1106  *
1107  * This creates a new file descriptor source that is watched for the events set
1108  * in @mask. @rfd is the system filedescriptor. The resulting object is stored
1109  * in @out. @cb and @data are the user callback and the user-supplied data that
1110  * is passed to the callback on events.
1111  * The FD is automatically watched for EV_HUP and EV_ERR events, too.
1112  *
1113  * Returns: 0 on success, otherwise negative error code
1114  */
1115 SHL_EXPORT
1116 int ev_fd_new(struct ev_fd **out, int rfd, int mask, ev_fd_cb cb, void *data,
1117               ev_log_t log, void *log_data)
1118 {
1119         struct ev_fd *fd;
1120
1121         if (!out || rfd < 0)
1122                 return llog_dEINVAL(log, log_data);
1123
1124         fd = malloc(sizeof(*fd));
1125         if (!fd)
1126                 return llog_dEINVAL(log, log_data);
1127
1128         memset(fd, 0, sizeof(*fd));
1129         fd->ref = 1;
1130         fd->llog = log;
1131         fd->llog_data = log_data;
1132         fd->fd = rfd;
1133         fd->mask = mask;
1134         fd->cb = cb;
1135         fd->data = data;
1136         fd->enabled = true;
1137
1138         *out = fd;
1139         return 0;
1140 }
1141
1142 /**
1143  * ev_fd_ref:
1144  * @fd: FD object
1145  *
1146  * Increases the ref-count of @fd by 1.
1147  */
1148 SHL_EXPORT
1149 void ev_fd_ref(struct ev_fd *fd)
1150 {
1151         if (!fd)
1152                 return;
1153         if (!fd->ref)
1154                 return llog_vEINVAL(fd);
1155
1156         ++fd->ref;
1157 }
1158
1159 /**
1160  * ev_fd_unref:
1161  * @fd: FD object
1162  *
1163  * Decreases the ref-count of @fd by 1. Destroys the object if the ref-count
1164  * drops to zero.
1165  */
1166 SHL_EXPORT
1167 void ev_fd_unref(struct ev_fd *fd)
1168 {
1169         if (!fd)
1170                 return;
1171         if (!fd->ref)
1172                 return llog_vEINVAL(fd);
1173         if (--fd->ref)
1174                 return;
1175
1176         free(fd);
1177 }
1178
1179 static int fd_epoll_add(struct ev_fd *fd)
1180 {
1181         struct epoll_event ep;
1182         int ret;
1183
1184         if (!fd->loop)
1185                 return 0;
1186
1187         memset(&ep, 0, sizeof(ep));
1188         if (fd->mask & EV_READABLE)
1189                 ep.events |= EPOLLIN;
1190         if (fd->mask & EV_WRITEABLE)
1191                 ep.events |= EPOLLOUT;
1192         if (fd->mask & EV_ET)
1193                 ep.events |= EPOLLET;
1194         ep.data.ptr = fd;
1195
1196         ret = epoll_ctl(fd->loop->efd, EPOLL_CTL_ADD, fd->fd, &ep);
1197         if (ret) {
1198                 llog_warning(fd, "cannot add fd %d to epoll set (%d): %m",
1199                              fd->fd, errno);
1200                 return -EFAULT;
1201         }
1202
1203         return 0;
1204 }
1205
1206 static void fd_epoll_remove(struct ev_fd *fd)
1207 {
1208         int ret;
1209
1210         if (!fd->loop)
1211                 return;
1212
1213         ret = epoll_ctl(fd->loop->efd, EPOLL_CTL_DEL, fd->fd, NULL);
1214         if (ret && errno != EBADF)
1215                 llog_warning(fd, "cannot remove fd %d from epoll set (%d): %m",
1216                              fd->fd, errno);
1217 }
1218
1219 static int fd_epoll_update(struct ev_fd *fd)
1220 {
1221         struct epoll_event ep;
1222         int ret;
1223
1224         if (!fd->loop)
1225                 return 0;
1226
1227         memset(&ep, 0, sizeof(ep));
1228         if (fd->mask & EV_READABLE)
1229                 ep.events |= EPOLLIN;
1230         if (fd->mask & EV_WRITEABLE)
1231                 ep.events |= EPOLLOUT;
1232         if (fd->mask & EV_ET)
1233                 ep.events |= EPOLLET;
1234         ep.data.ptr = fd;
1235
1236         ret = epoll_ctl(fd->loop->efd,  EPOLL_CTL_MOD, fd->fd, &ep);
1237         if (ret) {
1238                 llog_warning(fd, "cannot update epoll fd %d (%d): %m",
1239                              fd->fd, errno);
1240                 return -EFAULT;
1241         }
1242
1243         return 0;
1244 }
1245
1246 /**
1247  * ev_fd_enable:
1248  * @fd: FD object
1249  *
1250  * This enables @fd. By default every fd object is enabled. If you disabled it
1251  * you can re-enable it with this call.
1252  *
1253  * Returns: 0 on success, otherwise negative error code
1254  */
1255 SHL_EXPORT
1256 int ev_fd_enable(struct ev_fd *fd)
1257 {
1258         int ret;
1259
1260         if (!fd)
1261                 return -EINVAL;
1262         if (fd->enabled)
1263                 return 0;
1264
1265         ret = fd_epoll_add(fd);
1266         if (ret)
1267                 return ret;
1268
1269         fd->enabled = true;
1270         return 0;
1271 }
1272
1273 /**
1274  * ev_fd_disable:
1275  * @fd: FD object
1276  *
1277  * Disables @fd. That means, no more events are handled for @fd until you
1278  * re-enable it with ev_fd_enable().
1279  */
1280 SHL_EXPORT
1281 void ev_fd_disable(struct ev_fd *fd)
1282 {
1283         if (!fd || !fd->enabled)
1284                 return;
1285
1286         fd->enabled = false;
1287         fd_epoll_remove(fd);
1288 }
1289
1290 /**
1291  * ev_fd_is_enabled:
1292  * @fd: FD object
1293  *
1294  * Returns whether the fd object is enabled or disabled.
1295  *
1296  * Returns: true if @fd is enabled, otherwise false.
1297  */
1298 SHL_EXPORT
1299 bool ev_fd_is_enabled(struct ev_fd *fd)
1300 {
1301         return fd && fd->enabled;
1302 }
1303
1304 /**
1305  * ev_fd_is_bound:
1306  * @fd: FD object
1307  *
1308  * Returns true if the fd object is bound to an event loop.
1309  *
1310  * Returns: true if @fd is bound, otherwise false
1311  */
1312 SHL_EXPORT
1313 bool ev_fd_is_bound(struct ev_fd *fd)
1314 {
1315         return fd && fd->loop;
1316 }
1317
1318 /**
1319  * ev_fd_set_cb_data:
1320  * @fd: FD object
1321  * @cb: New user callback
1322  * @data: New user data
1323  *
1324  * This changes the user callback and user data that were set in ev_fd_new().
1325  * Both can be set to NULL. If @cb is NULL, then the callback will not be called
1326  * anymore.
1327  */
1328 SHL_EXPORT
1329 void ev_fd_set_cb_data(struct ev_fd *fd, ev_fd_cb cb, void *data)
1330 {
1331         if (!fd)
1332                 return;
1333
1334         fd->cb = cb;
1335         fd->data = data;
1336 }
1337
1338 /**
1339  * ev_fd_update:
1340  * @fd: FD object
1341  * @mask: Bitmask of %EV_READABLE and %EV_WRITEABLE
1342  *
1343  * This resets the event mask of @fd to @mask.
1344  *
1345  * Returns: 0 on success, otherwise negative error code
1346  */
1347 SHL_EXPORT
1348 int ev_fd_update(struct ev_fd *fd, int mask)
1349 {
1350         int ret;
1351         int omask;
1352
1353         if (!fd)
1354                 return -EINVAL;
1355         if (fd->mask == mask && !(mask & EV_ET))
1356                 return 0;
1357
1358         omask = fd->mask;
1359         fd->mask = mask;
1360
1361         if (!fd->enabled)
1362                 return 0;
1363
1364         ret = fd_epoll_update(fd);
1365         if (ret) {
1366                 fd->mask = omask;
1367                 return ret;
1368         }
1369
1370         return 0;
1371 }
1372
1373 /**
1374  * ev_eloop_new_fd:
1375  * @loop: Event loop
1376  * @out: Storage for result
1377  * @rfd: File descriptor
1378  * @mask: Bitmask of %EV_READABLE and %EV_WRITEABLE
1379  * @cb: User callback
1380  * @data: User data
1381  *
1382  * This creates a new fd object like ev_fd_new() and directly registers it in
1383  * the event loop @loop. See ev_fd_new() and ev_eloop_add_fd() for more
1384  * information.
1385  * The ref-count of @out is 1 so you must call ev_eloop_rm_fd() to destroy the
1386  * fd. You must not call ev_fd_unref() unless you called ev_fd_ref() before.
1387  *
1388  * Returns: 0 on success, otherwise negative error code
1389  */
1390 SHL_EXPORT
1391 int ev_eloop_new_fd(struct ev_eloop *loop, struct ev_fd **out, int rfd,
1392                         int mask, ev_fd_cb cb, void *data)
1393 {
1394         struct ev_fd *fd;
1395         int ret;
1396
1397         if (!loop)
1398                 return -EINVAL;
1399         if (!out || rfd < 0)
1400                 return llog_EINVAL(loop);
1401
1402         ret = ev_fd_new(&fd, rfd, mask, cb, data, loop->llog, loop->llog_data);
1403         if (ret)
1404                 return ret;
1405
1406         ret = ev_eloop_add_fd(loop, fd);
1407         if (ret) {
1408                 ev_fd_unref(fd);
1409                 return ret;
1410         }
1411
1412         ev_fd_unref(fd);
1413         *out = fd;
1414         return 0;
1415 }
1416
1417 /**
1418  * ev_eloop_add_fd:
1419  * @loop: Event loop
1420  * @fd: FD Object
1421  *
1422  * Registers @fd in the event loop @loop. This increases the ref-count of both
1423  * @loop and @fd. From now on the user callback of @fd may get called during
1424  * dispatching.
1425  *
1426  * Returns: 0 on success, otherwise negative error code
1427  */
1428 SHL_EXPORT
1429 int ev_eloop_add_fd(struct ev_eloop *loop, struct ev_fd *fd)
1430 {
1431         int ret;
1432
1433         if (!loop)
1434                 return -EINVAL;
1435         if (!fd || fd->loop)
1436                 return llog_EINVAL(loop);
1437
1438         fd->loop = loop;
1439
1440         if (fd->enabled) {
1441                 ret = fd_epoll_add(fd);
1442                 if (ret) {
1443                         fd->loop = NULL;
1444                         return ret;
1445                 }
1446         }
1447
1448         ev_fd_ref(fd);
1449         ev_eloop_ref(loop);
1450         return 0;
1451 }
1452
1453 /**
1454  * ev_eloop_rm_fd:
1455  * @fd: FD object
1456  *
1457  * Removes the fd object @fd from its event loop. If you did not call
1458  * ev_eloop_add_fd() before, this will do nothing.
1459  * This decreases the refcount of @fd and the event loop by 1.
1460  * It is safe to call this in any callback. This makes sure that the current
1461  * dispatcher will not get confused or read invalid memory.
1462  */
1463 SHL_EXPORT
1464 void ev_eloop_rm_fd(struct ev_fd *fd)
1465 {
1466         struct ev_eloop *loop;
1467         size_t i;
1468
1469         if (!fd || !fd->loop)
1470                 return;
1471
1472         loop = fd->loop;
1473         if (fd->enabled)
1474                 fd_epoll_remove(fd);
1475
1476         /*
1477          * If we are currently dispatching events, we need to remove ourself
1478          * from the temporary event list.
1479          */
1480         if (loop->dispatching) {
1481                 for (i = 0; i < loop->cur_fds_cnt; ++i) {
1482                         if (fd == loop->cur_fds[i].data.ptr)
1483                                 loop->cur_fds[i].data.ptr = NULL;
1484                 }
1485         }
1486
1487         fd->loop = NULL;
1488         ev_fd_unref(fd);
1489         ev_eloop_unref(loop);
1490 }
1491
1492 /*
1493  * Timer sources
1494  * Timer sources allow delaying a specific event by an relative timeout. The
1495  * timeout can be set to trigger after a specific time. Optionally, you can
1496  * also make the timeout trigger every next time the timeout elapses so you
1497  * basically get a pulse that reliably calls the callback.
1498  * The callback gets as parameter the number of timeouts that elapsed since it
1499  * was last called (in case the application couldn't call the callback fast
1500  * enough). The timeout can be specified with nano-seconds precision. However,
1501  * real precision depends on the operating-system and hardware.
1502  */
1503
1504 static int timer_drain(struct ev_timer *timer, uint64_t *out)
1505 {
1506         int len;
1507         uint64_t expirations;
1508
1509         if (out)
1510                 *out = 0;
1511
1512         len = read(timer->fd, &expirations, sizeof(expirations));
1513         if (len < 0) {
1514                 if (errno == EAGAIN) {
1515                         return 0;
1516                 } else {
1517                         llog_warning(timer, "cannot read timerfd (%d): %m",
1518                                      errno);
1519                         return errno;
1520                 }
1521         } else if (len == 0) {
1522                 llog_warning(timer, "EOF on timer source");
1523                 return -EFAULT;
1524         } else if (len != sizeof(expirations)) {
1525                 llog_warn(timer, "invalid size %d read on timerfd", len);
1526                 return -EFAULT;
1527         } else {
1528                 if (out)
1529                         *out = expirations;
1530                 return 0;
1531         }
1532 }
1533
1534 static void timer_cb(struct ev_fd *fd, int mask, void *data)
1535 {
1536         struct ev_timer *timer = data;
1537         uint64_t expirations;
1538         int ret;
1539
1540         if (mask & (EV_HUP | EV_ERR)) {
1541                 llog_warn(fd, "HUP/ERR on timer source");
1542                 goto err_cb;
1543         }
1544
1545         if (mask & EV_READABLE) {
1546                 ret = timer_drain(timer, &expirations);
1547                 if (ret)
1548                         goto err_cb;
1549                 if (expirations > 0) {
1550                         if (timer->cb)
1551                                 timer->cb(timer, expirations, timer->data);
1552                 }
1553         }
1554
1555         return;
1556
1557 err_cb:
1558         ev_timer_disable(timer);
1559         if (timer->cb)
1560                 timer->cb(timer, 0, timer->data);
1561 }
1562
1563 static const struct itimerspec ev_timer_zero;
1564
1565 /**
1566  * ev_timer_new:
1567  * @out: Timer pointer where to store the new timer
1568  * @spec: Timespan
1569  * @cb: callback to use for this event-source
1570  * @data: user-specified data
1571  * @log: logging function or NULL
1572  * @log_data: logging function user-data
1573  *
1574  * This creates a new timer-source. See "man timerfd_create" for information on
1575  * the @spec argument. The timer is always relative and uses the
1576  * monotonic-kernel clock.
1577  *
1578  * Returns: 0 on success, negative error on failure
1579  */
1580 SHL_EXPORT
1581 int ev_timer_new(struct ev_timer **out, const struct itimerspec *spec,
1582                  ev_timer_cb cb, void *data, ev_log_t log, void *log_data)
1583 {
1584         struct ev_timer *timer;
1585         int ret;
1586
1587         if (!out)
1588                 return llog_dEINVAL(log, log_data);
1589
1590         if (!spec)
1591                 spec = &ev_timer_zero;
1592
1593         timer = malloc(sizeof(*timer));
1594         if (!timer)
1595                 return llog_dENOMEM(log, log_data);
1596
1597         memset(timer, 0, sizeof(*timer));
1598         timer->ref = 1;
1599         timer->llog = log;
1600         timer->llog_data = log_data;
1601         timer->cb = cb;
1602         timer->data = data;
1603
1604         timer->fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
1605         if (timer->fd < 0) {
1606                 llog_error(timer, "cannot create timerfd (%d): %m", errno);
1607                 ret = -EFAULT;
1608                 goto err_free;
1609         }
1610
1611         ret = timerfd_settime(timer->fd, 0, spec, NULL);
1612         if (ret) {
1613                 llog_warn(timer, "cannot set timerfd (%d): %m", errno);
1614                 ret = -EFAULT;
1615                 goto err_close;
1616         }
1617
1618         ret = ev_fd_new(&timer->efd, timer->fd, EV_READABLE, timer_cb, timer,
1619                         timer->llog, timer->llog_data);
1620         if (ret)
1621                 goto err_close;
1622
1623         *out = timer;
1624         return 0;
1625
1626 err_close:
1627         close(timer->fd);
1628 err_free:
1629         free(timer);
1630         return ret;
1631 }
1632
1633 /**
1634  * ev_timer_ref:
1635  * @timer: Timer object
1636  *
1637  * Increase reference count by 1.
1638  */
1639 SHL_EXPORT
1640 void ev_timer_ref(struct ev_timer *timer)
1641 {
1642         if (!timer)
1643                 return;
1644         if (!timer->ref)
1645                 return llog_vEINVAL(timer);
1646
1647         ++timer->ref;
1648 }
1649
1650 /**
1651  * ev_timer_unref:
1652  * @timer: Timer object
1653  *
1654  * Decrease reference-count by 1 and destroy timer if it drops to 0.
1655  */
1656 SHL_EXPORT
1657 void ev_timer_unref(struct ev_timer *timer)
1658 {
1659         if (!timer)
1660                 return;
1661         if (!timer->ref)
1662                 return llog_vEINVAL(timer);
1663         if (--timer->ref)
1664                 return;
1665
1666         ev_fd_unref(timer->efd);
1667         close(timer->fd);
1668         free(timer);
1669 }
1670
1671 /**
1672  * ev_timer_enable:
1673  * @timer: Timer object
1674  *
1675  * Enable the timer. This calls ev_fd_enable() on the fd that implements this
1676  * timer.
1677  *
1678  * Returns: 0 on success negative error code on failure
1679  */
1680 SHL_EXPORT
1681 int ev_timer_enable(struct ev_timer *timer)
1682 {
1683         if (!timer)
1684                 return -EINVAL;
1685
1686         return ev_fd_enable(timer->efd);
1687 }
1688
1689 /**
1690  * ev_timer_disable:
1691  * @timer: Timer object
1692  *
1693  * Disable the timer. This calls ev_fd_disable() on the fd that implements this
1694  * timer.
1695  *
1696  * Returns: 0 on success and negative error code on failure
1697  */
1698 SHL_EXPORT
1699 void ev_timer_disable(struct ev_timer *timer)
1700 {
1701         if (!timer)
1702                 return;
1703
1704         ev_fd_disable(timer->efd);
1705 }
1706
1707 /**
1708  * ev_timer_is_enabled:
1709  * @timer: Timer object
1710  *
1711  * Checks whether the timer is enabled.
1712  *
1713  * Returns: true if timer is enabled, false otherwise
1714  */
1715 SHL_EXPORT
1716 bool ev_timer_is_enabled(struct ev_timer *timer)
1717 {
1718         return timer && ev_fd_is_enabled(timer->efd);
1719 }
1720
1721 /**
1722  * ev_timer_is_bound:
1723  * @timer: Timer object
1724  *
1725  * Checks whether the timer is bound to an event loop.
1726  *
1727  * Returns: true if the timer is bound, false otherwise.
1728  */
1729 SHL_EXPORT
1730 bool ev_timer_is_bound(struct ev_timer *timer)
1731 {
1732         return timer && ev_fd_is_bound(timer->efd);
1733 }
1734
1735 /**
1736  * ev_timer_set_cb_data:
1737  * @timer: Timer object
1738  * @cb: User callback or NULL
1739  * @data: User data or NULL
1740  *
1741  * This changes the user-supplied callback and data that is used for this timer
1742  * object.
1743  */
1744 SHL_EXPORT
1745 void ev_timer_set_cb_data(struct ev_timer *timer, ev_timer_cb cb, void *data)
1746 {
1747         if (!timer)
1748                 return;
1749
1750         timer->cb = cb;
1751         timer->data = data;
1752 }
1753
1754 /**
1755  * ev_timer_update:
1756  * @timer: Timer object
1757  * @spec: timespan
1758  *
1759  * This changes the timer timespan. See "man timerfd_settime" for information
1760  * on the @spec parameter.
1761  *
1762  * Returns: 0 on success, negative error code on failure.
1763  */
1764 SHL_EXPORT
1765 int ev_timer_update(struct ev_timer *timer, const struct itimerspec *spec)
1766 {
1767         int ret;
1768
1769         if (!timer)
1770                 return -EINVAL;
1771
1772         if (!spec)
1773                 spec = &ev_timer_zero;
1774
1775         ret = timerfd_settime(timer->fd, 0, spec, NULL);
1776         if (ret) {
1777                 llog_warn(timer, "cannot set timerfd (%d): %m", errno);
1778                 return -EFAULT;
1779         }
1780
1781         return 0;
1782 }
1783
1784 /**
1785  * ev_timer_drain:
1786  * @timer: valid timer object
1787  * @expirations: destination to save result or NULL
1788  *
1789  * This reads the current expiration-count from the timer object @timer and
1790  * saves it in @expirations (if it is non-NULL). This can be used to clear the
1791  * timer after an idle-period or similar.
1792  * Note that the timer_cb() callback function automatically calls this before
1793  * calling the user-supplied callback.
1794  *
1795  * Returns: 0 on success, negative error code on failure.
1796  */
1797 SHL_EXPORT
1798 int ev_timer_drain(struct ev_timer *timer, uint64_t *expirations)
1799 {
1800         if (!timer)
1801                 return -EINVAL;
1802
1803         return timer_drain(timer, expirations);
1804 }
1805
1806 /**
1807  * ev_eloop_new_timer:
1808  * @loop: event loop
1809  * @out: output where to store the new timer
1810  * @spec: timespan
1811  * @cb: user callback
1812  * @data: user-supplied data
1813  *
1814  * This is a combination of ev_timer_new() and ev_eloop_add_timer(). See both
1815  * for more information.
1816  *
1817  * Returns: 0 on success, negative error code on failure.
1818  */
1819 SHL_EXPORT
1820 int ev_eloop_new_timer(struct ev_eloop *loop, struct ev_timer **out,
1821                         const struct itimerspec *spec, ev_timer_cb cb,
1822                         void *data)
1823 {
1824         struct ev_timer *timer;
1825         int ret;
1826
1827         if (!loop)
1828                 return -EINVAL;
1829         if (!out)
1830                 return llog_EINVAL(loop);
1831
1832         ret = ev_timer_new(&timer, spec, cb, data, loop->llog, loop->llog_data);
1833         if (ret)
1834                 return ret;
1835
1836         ret = ev_eloop_add_timer(loop, timer);
1837         if (ret) {
1838                 ev_timer_unref(timer);
1839                 return ret;
1840         }
1841
1842         ev_timer_unref(timer);
1843         *out = timer;
1844         return 0;
1845 }
1846
1847 /**
1848  * ev_eloop_add_timer:
1849  * @loop: event loop
1850  * @timer: Timer source
1851  *
1852  * This adds @timer as source to @loop. @timer must be currently unbound,
1853  * otherwise, this will fail with -EALREADY.
1854  *
1855  * Returns: 0 on success, negative error code on failure
1856  */
1857 SHL_EXPORT
1858 int ev_eloop_add_timer(struct ev_eloop *loop, struct ev_timer *timer)
1859 {
1860         int ret;
1861
1862         if (!loop)
1863                 return -EINVAL;
1864         if (!timer)
1865                 return llog_EINVAL(loop);
1866
1867         if (ev_fd_is_bound(timer->efd))
1868                 return -EALREADY;
1869
1870         ret = ev_eloop_add_fd(loop, timer->efd);
1871         if (ret)
1872                 return ret;
1873
1874         ev_timer_ref(timer);
1875         return 0;
1876 }
1877
1878 /**
1879  * ev_eloop_rm_timer:
1880  * @timer: Timer object
1881  *
1882  * If @timer is currently bound to an event loop, this will remove this bondage
1883  * again.
1884  */
1885 SHL_EXPORT
1886 void ev_eloop_rm_timer(struct ev_timer *timer)
1887 {
1888         if (!timer || !ev_fd_is_bound(timer->efd))
1889                 return;
1890
1891         ev_eloop_rm_fd(timer->efd);
1892         ev_timer_unref(timer);
1893 }
1894
1895 /*
1896  * Counter Sources
1897  * Counter sources are a very basic event notification mechanism. It is based
1898  * around the eventfd() system call on linux machines. Internally, there is a
1899  * 64bit unsigned integer that can be increased by the caller. By default it is
1900  * set to 0. If it is non-zero, the event-fd will be notified and the
1901  * user-defined callback is called. The callback gets as argument the current
1902  * state of the counter and the counter is reset to 0.
1903  *
1904  * If the internal counter would overflow, an increase() fails silently so an
1905  * overflow will never occur, however, you may loose events this way. This can
1906  * be ignored when increasing with small values, only.
1907  */
1908
1909 static void counter_event(struct ev_fd *fd, int mask, void *data)
1910 {
1911         struct ev_counter *cnt = data;
1912         int ret;
1913         uint64_t val;
1914
1915         if (mask & (EV_HUP | EV_ERR)) {
1916                 llog_warning(fd, "HUP/ERR on eventfd");
1917                 if (cnt->cb)
1918                         cnt->cb(cnt, 0, cnt->data);
1919                 return;
1920         }
1921
1922         if (!(mask & EV_READABLE))
1923                 return;
1924
1925         ret = read(cnt->fd, &val, sizeof(val));
1926         if (ret < 0) {
1927                 if (errno != EAGAIN) {
1928                         llog_warning(fd, "reading eventfd failed (%d): %m", errno);
1929                         ev_counter_disable(cnt);
1930                         if (cnt->cb)
1931                                 cnt->cb(cnt, 0, cnt->data);
1932                 }
1933         } else if (ret == 0) {
1934                 llog_warning(fd, "EOF on eventfd");
1935                 ev_counter_disable(cnt);
1936                 if (cnt->cb)
1937                         cnt->cb(cnt, 0, cnt->data);
1938         } else if (ret != sizeof(val)) {
1939                 llog_warning(fd, "read %d bytes instead of 8 on eventfd", ret);
1940                 ev_counter_disable(cnt);
1941                 if (cnt->cb)
1942                         cnt->cb(cnt, 0, cnt->data);
1943         } else if (val > 0) {
1944                 if (cnt->cb)
1945                         cnt->cb(cnt, val, cnt->data);
1946         }
1947 }
1948
1949 /**
1950  * ev_counter_new:
1951  * @out: Where to store the new counter
1952  * @cb: user-supplied callback
1953  * @data: user-supplied data
1954  * @log: logging function or NULL
1955  * @log_data: logging function user-data
1956  *
1957  * This creates a new counter object and stores it in @out.
1958  *
1959  * Returns: 0 on success, negative error code on failure.
1960  */
1961 SHL_EXPORT
1962 int ev_counter_new(struct ev_counter **out, ev_counter_cb cb, void *data,
1963                    ev_log_t log, void *log_data)
1964 {
1965         struct ev_counter *cnt;
1966         int ret;
1967
1968         if (!out)
1969                 return llog_dEINVAL(log, log_data);
1970
1971         cnt = malloc(sizeof(*cnt));
1972         if (!cnt)
1973                 return llog_dENOMEM(log, log_data);
1974         memset(cnt, 0, sizeof(*cnt));
1975         cnt->ref = 1;
1976         cnt->llog = log;
1977         cnt->llog_data = log_data;
1978         cnt->cb = cb;
1979         cnt->data = data;
1980
1981         cnt->fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
1982         if (cnt->fd < 0) {
1983                 llog_error(cnt, "cannot create eventfd (%d): %m", errno);
1984                 ret = -EFAULT;
1985                 goto err_free;
1986         }
1987
1988         ret = ev_fd_new(&cnt->efd, cnt->fd, EV_READABLE, counter_event, cnt,
1989                         cnt->llog, cnt->llog_data);
1990         if (ret)
1991                 goto err_close;
1992
1993         *out = cnt;
1994         return 0;
1995
1996 err_close:
1997         close(cnt->fd);
1998 err_free:
1999         free(cnt);
2000         return ret;
2001 }
2002
2003 /**
2004  * ev_counter_ref:
2005  * @cnt: Counter object
2006  *
2007  * This increases the reference-count of @cnt by 1.
2008  */
2009 SHL_EXPORT
2010 void ev_counter_ref(struct ev_counter *cnt)
2011 {
2012         if (!cnt)
2013                 return;
2014         if (!cnt->ref)
2015                 return llog_vEINVAL(cnt);
2016
2017         ++cnt->ref;
2018 }
2019
2020 /**
2021  * ev_counter_unref:
2022  * @cnt: Counter object
2023  *
2024  * This decreases the reference-count of @cnt by 1 and destroys the object if
2025  * it drops to 0.
2026  */
2027 SHL_EXPORT
2028 void ev_counter_unref(struct ev_counter *cnt)
2029 {
2030         if (!cnt)
2031                 return;
2032         if (!cnt->ref)
2033                 return llog_vEINVAL(cnt);
2034         if (--cnt->ref)
2035                 return;
2036
2037         ev_fd_unref(cnt->efd);
2038         close(cnt->fd);
2039         free(cnt);
2040 }
2041
2042 /**
2043  * ev_counter_enable:
2044  * @cnt: Counter object
2045  *
2046  * This enables the counter object. It calls ev_fd_enable() on the underlying
2047  * file-descriptor.
2048  *
2049  * Returns: 0 on success, negative error code on failure
2050  */
2051 SHL_EXPORT
2052 int ev_counter_enable(struct ev_counter *cnt)
2053 {
2054         if (!cnt)
2055                 return -EINVAL;
2056
2057         return ev_fd_enable(cnt->efd);
2058 }
2059
2060 /**
2061  * ev_counter_disable:
2062  * @cnt: Counter object
2063  *
2064  * This disables the counter. It calls ev_fd_disable() on the underlying
2065  * file-descriptor.
2066  */
2067 SHL_EXPORT
2068 void ev_counter_disable(struct ev_counter *cnt)
2069 {
2070         if (!cnt)
2071                 return;
2072
2073         ev_fd_disable(cnt->efd);
2074 }
2075
2076 /**
2077  * ev_counter_is_enabled:
2078  * @cnt: counter object
2079  *
2080  * Checks whether the counter is enabled.
2081  *
2082  * Returns: true if the counter is enabled, otherwise returns false.
2083  */
2084 SHL_EXPORT
2085 bool ev_counter_is_enabled(struct ev_counter *cnt)
2086 {
2087         return cnt && ev_fd_is_enabled(cnt->efd);
2088 }
2089
2090 /**
2091  * ev_counter_is_bound:
2092  * @cnt: Counter object
2093  *
2094  * Checks whether the counter is bound to an event loop.
2095  *
2096  * Returns: true if the counter is bound, otherwise false is returned.
2097  */
2098 SHL_EXPORT
2099 bool ev_counter_is_bound(struct ev_counter *cnt)
2100 {
2101         return cnt && ev_fd_is_bound(cnt->efd);
2102 }
2103
2104 /**
2105  * ev_counter_set_cb_data:
2106  * @cnt: Counter object
2107  * @cb: user-supplied callback
2108  * @data: user-supplied data
2109  *
2110  * This changes the user-supplied callback and data for the given counter
2111  * object.
2112  */
2113 SHL_EXPORT
2114 void ev_counter_set_cb_data(struct ev_counter *cnt, ev_counter_cb cb,
2115                             void *data)
2116 {
2117         if (!cnt)
2118                 return;
2119
2120         cnt->cb = cb;
2121         cnt->data = data;
2122 }
2123
2124 /**
2125  * ev_counter_inc:
2126  * @cnt: Counter object
2127  * @val: Counter increase amount
2128  *
2129  * This increases the counter @cnt by @val.
2130  *
2131  * Returns: 0 on success, negative error code on failure.
2132  */
2133 SHL_EXPORT
2134 int ev_counter_inc(struct ev_counter *cnt, uint64_t val)
2135 {
2136         if (!cnt)
2137                 return -EINVAL;
2138
2139         return write_eventfd(cnt->llog, cnt->llog_data, cnt->fd, val);
2140 }
2141
2142 /**
2143  * ev_eloop_new_counter:
2144  * @eloop: event loop
2145  * @out: output storage for new counter
2146  * @cb: user-supplied callback
2147  * @data: user-supplied data
2148  *
2149  * This combines ev_counter_new() and ev_eloop_add_counter() in one call.
2150  *
2151  * Returns: 0 on success, negative error code on failure.
2152  */
2153 SHL_EXPORT
2154 int ev_eloop_new_counter(struct ev_eloop *eloop, struct ev_counter **out,
2155                          ev_counter_cb cb, void *data)
2156 {
2157         int ret;
2158         struct ev_counter *cnt;
2159
2160         if (!eloop)
2161                 return -EINVAL;
2162         if (!out)
2163                 return llog_EINVAL(eloop);
2164
2165         ret = ev_counter_new(&cnt, cb, data, eloop->llog, eloop->llog_data);
2166         if (ret)
2167                 return ret;
2168
2169         ret = ev_eloop_add_counter(eloop, cnt);
2170         if (ret) {
2171                 ev_counter_unref(cnt);
2172                 return ret;
2173         }
2174
2175         ev_counter_unref(cnt);
2176         *out = cnt;
2177         return 0;
2178 }
2179
2180 /**
2181  * ev_eloop_add_counter:
2182  * @eloop: Event loop
2183  * @cnt: Counter object
2184  *
2185  * This adds @cnt to the given event loop @eloop. If @cnt is already bound,
2186  * this will fail with -EALREADY.
2187  *
2188  * Returns: 0 on success, negative error code on failure.
2189  */
2190 SHL_EXPORT
2191 int ev_eloop_add_counter(struct ev_eloop *eloop, struct ev_counter *cnt)
2192 {
2193         int ret;
2194
2195         if (!eloop)
2196                 return -EINVAL;
2197         if (!cnt)
2198                 return llog_EINVAL(eloop);
2199
2200         if (ev_fd_is_bound(cnt->efd))
2201                 return -EALREADY;
2202
2203         ret = ev_eloop_add_fd(eloop, cnt->efd);
2204         if (ret)
2205                 return ret;
2206
2207         ev_counter_ref(cnt);
2208         return 0;
2209 }
2210
2211 /**
2212  * ev_eloop_rm_counter:
2213  * @cnt: Counter object
2214  *
2215  * If @cnt is bound to an event-loop, then this will remove this bondage again.
2216  */
2217 SHL_EXPORT
2218 void ev_eloop_rm_counter(struct ev_counter *cnt)
2219 {
2220         if (!cnt || !ev_fd_is_bound(cnt->efd))
2221                 return;
2222
2223         ev_eloop_rm_fd(cnt->efd);
2224         ev_counter_unref(cnt);
2225 }
2226
2227 /*
2228  * Shared signals
2229  * This allows registering for shared signal events. See description of the
2230  * shared signal object above for more information how this works. Also see the
2231  * eloop description to see some drawbacks when nesting eloop objects with the
2232  * same shared signal sources.
2233  */
2234
2235 /**
2236  * ev_eloop_register_signal_cb:
2237  * @loop: event loop
2238  * @signum: Signal number
2239  * @cb: user-supplied callback
2240  * @data: user-supplied data
2241  *
2242  * This register a new callback for the given signal @signum. @cb must not be
2243  * NULL!
2244  *
2245  * Returns: 0 on success, negative error code on failure.
2246  */
2247 SHL_EXPORT
2248 int ev_eloop_register_signal_cb(struct ev_eloop *loop, int signum,
2249                                 ev_signal_shared_cb cb, void *data)
2250 {
2251         struct ev_signal_shared *sig = NULL;
2252         int ret;
2253         struct shl_dlist *iter;
2254
2255         if (!loop)
2256                 return -EINVAL;
2257         if (signum < 0 || !cb)
2258                 return llog_EINVAL(loop);
2259
2260         shl_dlist_for_each(iter, &loop->sig_list) {
2261                 sig = shl_dlist_entry(iter, struct ev_signal_shared, list);
2262                 if (sig->signum == signum)
2263                         break;
2264                 sig = NULL;
2265         }
2266
2267         if (!sig) {
2268                 ret = signal_new(&sig, loop, signum);
2269                 if (ret)
2270                         return ret;
2271         }
2272
2273         ret = shl_hook_add_cast(sig->hook, cb, data, false);
2274         if (ret) {
2275                 signal_free(sig);
2276                 return ret;
2277         }
2278
2279         return 0;
2280 }
2281
2282 /**
2283  * ev_eloop_unregister_signal_cb:
2284  * @loop: event loop
2285  * @signum: signal number
2286  * @cb: user-supplied callback
2287  * @data: user-supplied data
2288  *
2289  * This removes a previously registered signal-callback again. The arguments
2290  * must be the same as for the ev_eloop_register_signal_cb() call. If multiple
2291  * callbacks with the same arguments are registered, then only one callback is
2292  * removed. It doesn't matter which callback is removed as both are identical.
2293  */
2294 SHL_EXPORT
2295 void ev_eloop_unregister_signal_cb(struct ev_eloop *loop, int signum,
2296                                         ev_signal_shared_cb cb, void *data)
2297 {
2298         struct ev_signal_shared *sig;
2299         struct shl_dlist *iter;
2300
2301         if (!loop)
2302                 return;
2303
2304         shl_dlist_for_each(iter, &loop->sig_list) {
2305                 sig = shl_dlist_entry(iter, struct ev_signal_shared, list);
2306                 if (sig->signum == signum) {
2307                         shl_hook_rm_cast(sig->hook, cb, data);
2308                         if (!shl_hook_num(sig->hook))
2309                                 signal_free(sig);
2310                         return;
2311                 }
2312         }
2313 }
2314
2315 /*
2316  * Child reaper sources
2317  * If at least one child-reaper callback is registered, then the eloop object
2318  * listens for SIGCHLD and waits for all exiting children. The callbacks are
2319  * then notified for each PID that signaled an event.
2320  * Note that this cannot be done via the shared-signal sources as the waitpid()
2321  * call must not be done in callbacks. Otherwise, only one callback would see
2322  * the events while others will call waitpid() and get EAGAIN.
2323  */
2324
2325 SHL_EXPORT
2326 int ev_eloop_register_child_cb(struct ev_eloop *loop, ev_child_cb cb,
2327                                void *data)
2328 {
2329         int ret;
2330         bool empty;
2331
2332         if (!loop)
2333                 return -EINVAL;
2334
2335         empty = !shl_hook_num(loop->chlds);
2336         ret = shl_hook_add_cast(loop->chlds, cb, data, false);
2337         if (ret)
2338                 return ret;
2339
2340         if (empty) {
2341                 ret = ev_eloop_register_signal_cb(loop, SIGCHLD, sig_child,
2342                                                   loop);
2343                 if (ret) {
2344                         shl_hook_rm_cast(loop->chlds, cb, data);
2345                         return ret;
2346                 }
2347         }
2348
2349         return 0;
2350 }
2351
2352 SHL_EXPORT
2353 void ev_eloop_unregister_child_cb(struct ev_eloop *loop, ev_child_cb cb,
2354                                   void *data)
2355 {
2356         if (!loop || !shl_hook_num(loop->chlds))
2357                 return;
2358
2359         shl_hook_rm_cast(loop->chlds, cb, data);
2360         if (!shl_hook_num(loop->chlds))
2361                 ev_eloop_unregister_signal_cb(loop, SIGCHLD, sig_child, loop);
2362 }
2363
2364 /*
2365  * Idle sources
2366  * Idle sources are called every time when a next dispatch round is started.
2367  * That means, unless there is no idle source registered, the thread will
2368  * _never_ go to sleep. So please unregister your idle source if no longer
2369  * needed.
2370  */
2371
2372 /**
2373  * ev_eloop_register_idle_cb:
2374  * @eloop: event loop
2375  * @cb: user-supplied callback
2376  * @data: user-supplied data
2377  * @flags: flags
2378  *
2379  * This register a new idle-source with the given callback and data. @cb must
2380  * not be NULL!.
2381  *
2382  * Returns: 0 on success, negative error code on failure.
2383  */
2384 SHL_EXPORT
2385 int ev_eloop_register_idle_cb(struct ev_eloop *eloop, ev_idle_cb cb,
2386                               void *data, unsigned int flags)
2387 {
2388         int ret;
2389         bool os = flags & EV_ONESHOT;
2390
2391         if (!eloop || (flags & ~EV_IDLE_ALL))
2392                 return -EINVAL;
2393
2394         if ((flags & EV_SINGLE))
2395                 ret = shl_hook_add_single_cast(eloop->idlers, cb, data, os);
2396         else
2397                 ret = shl_hook_add_cast(eloop->idlers, cb, data, os);
2398
2399         if (ret)
2400                 return ret;
2401
2402         ret = write_eventfd(eloop->llog, eloop->llog_data, eloop->idle_fd, 1);
2403         if (ret) {
2404                 llog_warning(eloop, "cannot increase eloop idle-counter");
2405                 shl_hook_rm_cast(eloop->idlers, cb, data);
2406                 return ret;
2407         }
2408
2409         return 0;
2410 }
2411
2412 /**
2413  * ev_eloop_unregister_idle_cb:
2414  * @eloop: event loop
2415  * @cb: user-supplied callback
2416  * @data: user-supplied data
2417  * @flags: flags
2418  *
2419  * This removes an idle-source. The arguments must be the same as for the
2420  * ev_eloop_register_idle_cb() call. If two identical callbacks are registered,
2421  * then only one is removed. It doesn't matter which one is removed, because
2422  * they are identical.
2423  */
2424 SHL_EXPORT
2425 void ev_eloop_unregister_idle_cb(struct ev_eloop *eloop, ev_idle_cb cb,
2426                                  void *data, unsigned int flags)
2427 {
2428         if (!eloop || (flags & ~EV_IDLE_ALL))
2429                 return;
2430
2431         if (flags & EV_SINGLE)
2432                 shl_hook_rm_all_cast(eloop->idlers, cb, data);
2433         else
2434                 shl_hook_rm_cast(eloop->idlers, cb, data);
2435 }
2436
2437 /*
2438  * Pre-Dispatch Callbacks
2439  * A pre-dispatch cb is called before a single dispatch round is started.
2440  * You should avoid using them and instead not rely on any specific
2441  * dispatch-behavior but expect every event to be received asynchronously.
2442  * However, this hook is useful to integrate other limited APIs into this event
2443  * loop if they do not provide proper FD-abstractions.
2444  */
2445
2446 /**
2447  * ev_eloop_register_pre_cb:
2448  * @eloop: event loop
2449  * @cb: user-supplied callback
2450  * @data: user-supplied data
2451  *
2452  * This register a new pre-cb with the given callback and data. @cb must
2453  * not be NULL!.
2454  *
2455  * Returns: 0 on success, negative error code on failure.
2456  */
2457 SHL_EXPORT
2458 int ev_eloop_register_pre_cb(struct ev_eloop *eloop, ev_idle_cb cb,
2459                              void *data)
2460 {
2461         if (!eloop)
2462                 return -EINVAL;
2463
2464         return shl_hook_add_cast(eloop->pres, cb, data, false);
2465 }
2466
2467 /**
2468  * ev_eloop_unregister_pre_cb:
2469  * @eloop: event loop
2470  * @cb: user-supplied callback
2471  * @data: user-supplied data
2472  *
2473  * This removes a pre-cb. The arguments must be the same as for the
2474  * ev_eloop_register_pre_cb() call. If two identical callbacks are registered,
2475  * then only one is removed. It doesn't matter which one is removed, because
2476  * they are identical.
2477  */
2478 SHL_EXPORT
2479 void ev_eloop_unregister_pre_cb(struct ev_eloop *eloop, ev_idle_cb cb,
2480                                 void *data)
2481 {
2482         if (!eloop)
2483                 return;
2484
2485         shl_hook_rm_cast(eloop->pres, cb, data);
2486 }
2487
2488 /*
2489  * Post-Dispatch Callbacks
2490  * A post-dispatch cb is called whenever a single dispatch round is complete.
2491  * You should avoid using them and instead not rely on any specific
2492  * dispatch-behavior but expect every event to be received asynchronously.
2493  * However, this hook is useful to integrate other limited APIs into this event
2494  * loop if they do not provide proper FD-abstractions.
2495  */
2496
2497 /**
2498  * ev_eloop_register_post_cb:
2499  * @eloop: event loop
2500  * @cb: user-supplied callback
2501  * @data: user-supplied data
2502  *
2503  * This register a new post-cb with the given callback and data. @cb must
2504  * not be NULL!.
2505  *
2506  * Returns: 0 on success, negative error code on failure.
2507  */
2508 SHL_EXPORT
2509 int ev_eloop_register_post_cb(struct ev_eloop *eloop, ev_idle_cb cb,
2510                               void *data)
2511 {
2512         if (!eloop)
2513                 return -EINVAL;
2514
2515         return shl_hook_add_cast(eloop->posts, cb, data, false);
2516 }
2517
2518 /**
2519  * ev_eloop_unregister_post_cb:
2520  * @eloop: event loop
2521  * @cb: user-supplied callback
2522  * @data: user-supplied data
2523  *
2524  * This removes a post-cb. The arguments must be the same as for the
2525  * ev_eloop_register_post_cb() call. If two identical callbacks are registered,
2526  * then only one is removed. It doesn't matter which one is removed, because
2527  * they are identical.
2528  */
2529 SHL_EXPORT
2530 void ev_eloop_unregister_post_cb(struct ev_eloop *eloop, ev_idle_cb cb,
2531                                  void *data)
2532 {
2533         if (!eloop)
2534                 return;
2535
2536         shl_hook_rm_cast(eloop->posts, cb, data);
2537 }