chiark / gitweb /
200a2f11730a2654910cd93d33b94084c03b2301
[elogind.git] / src / libelogind / sd-event / sd-event.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2013 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/epoll.h>
23 #include <sys/timerfd.h>
24 #include <sys/wait.h>
25
26 #include "sd-daemon.h"
27 #include "sd-event.h"
28 #include "sd-id128.h"
29
30 #include "alloc-util.h"
31 #include "fd-util.h"
32 #include "hashmap.h"
33 #include "list.h"
34 #include "macro.h"
35 #include "missing.h"
36 #include "prioq.h"
37 #include "process-util.h"
38 #include "set.h"
39 #include "signal-util.h"
40 #include "string-util.h"
41 #include "time-util.h"
42 #include "util.h"
43
44 #define DEFAULT_ACCURACY_USEC (250 * USEC_PER_MSEC)
45
46 typedef enum EventSourceType {
47         SOURCE_IO,
48         SOURCE_TIME_REALTIME,
49         SOURCE_TIME_BOOTTIME,
50         SOURCE_TIME_MONOTONIC,
51         SOURCE_TIME_REALTIME_ALARM,
52         SOURCE_TIME_BOOTTIME_ALARM,
53         SOURCE_SIGNAL,
54         SOURCE_CHILD,
55         SOURCE_DEFER,
56         SOURCE_POST,
57         SOURCE_EXIT,
58         SOURCE_WATCHDOG,
59         _SOURCE_EVENT_SOURCE_TYPE_MAX,
60         _SOURCE_EVENT_SOURCE_TYPE_INVALID = -1
61 } EventSourceType;
62
63 /* All objects we use in epoll events start with this value, so that
64  * we know how to dispatch it */
65 typedef enum WakeupType {
66         WAKEUP_NONE,
67         WAKEUP_EVENT_SOURCE,
68         WAKEUP_CLOCK_DATA,
69         WAKEUP_SIGNAL_DATA,
70         _WAKEUP_TYPE_MAX,
71         _WAKEUP_TYPE_INVALID = -1,
72 } WakeupType;
73
74 #define EVENT_SOURCE_IS_TIME(t) IN_SET((t), SOURCE_TIME_REALTIME, SOURCE_TIME_BOOTTIME, SOURCE_TIME_MONOTONIC, SOURCE_TIME_REALTIME_ALARM, SOURCE_TIME_BOOTTIME_ALARM)
75
76 struct sd_event_source {
77         WakeupType wakeup;
78
79         unsigned n_ref;
80
81         sd_event *event;
82         void *userdata;
83         sd_event_handler_t prepare;
84
85         char *description;
86
87         EventSourceType type:5;
88         int enabled:3;
89         bool pending:1;
90         bool dispatching:1;
91         bool floating:1;
92
93         int64_t priority;
94         unsigned pending_index;
95         unsigned prepare_index;
96         unsigned pending_iteration;
97         unsigned prepare_iteration;
98
99         LIST_FIELDS(sd_event_source, sources);
100
101         union {
102                 struct {
103                         sd_event_io_handler_t callback;
104                         int fd;
105                         uint32_t events;
106                         uint32_t revents;
107                         bool registered:1;
108                 } io;
109                 struct {
110                         sd_event_time_handler_t callback;
111                         usec_t next, accuracy;
112                         unsigned earliest_index;
113                         unsigned latest_index;
114                 } time;
115                 struct {
116                         sd_event_signal_handler_t callback;
117                         struct signalfd_siginfo siginfo;
118                         int sig;
119                 } signal;
120                 struct {
121                         sd_event_child_handler_t callback;
122                         siginfo_t siginfo;
123                         pid_t pid;
124                         int options;
125                 } child;
126                 struct {
127                         sd_event_handler_t callback;
128                 } defer;
129                 struct {
130                         sd_event_handler_t callback;
131                 } post;
132                 struct {
133                         sd_event_handler_t callback;
134                         unsigned prioq_index;
135                 } exit;
136         };
137 };
138
139 struct clock_data {
140         WakeupType wakeup;
141         int fd;
142
143         /* For all clocks we maintain two priority queues each, one
144          * ordered for the earliest times the events may be
145          * dispatched, and one ordered by the latest times they must
146          * have been dispatched. The range between the top entries in
147          * the two prioqs is the time window we can freely schedule
148          * wakeups in */
149
150         Prioq *earliest;
151         Prioq *latest;
152         usec_t next;
153
154         bool needs_rearm:1;
155 };
156
157 struct signal_data {
158         WakeupType wakeup;
159
160         /* For each priority we maintain one signal fd, so that we
161          * only have to dequeue a single event per priority at a
162          * time. */
163
164         int fd;
165         int64_t priority;
166         sigset_t sigset;
167         sd_event_source *current;
168 };
169
170 struct sd_event {
171         unsigned n_ref;
172
173         int epoll_fd;
174         int watchdog_fd;
175
176         Prioq *pending;
177         Prioq *prepare;
178
179         /* timerfd_create() only supports these five clocks so far. We
180          * can add support for more clocks when the kernel learns to
181          * deal with them, too. */
182         struct clock_data realtime;
183         struct clock_data boottime;
184         struct clock_data monotonic;
185         struct clock_data realtime_alarm;
186         struct clock_data boottime_alarm;
187
188         usec_t perturb;
189
190         sd_event_source **signal_sources; /* indexed by signal number */
191         Hashmap *signal_data; /* indexed by priority */
192
193         Hashmap *child_sources;
194         unsigned n_enabled_child_sources;
195
196         Set *post_sources;
197
198         Prioq *exit;
199
200         pid_t original_pid;
201
202         unsigned iteration;
203         dual_timestamp timestamp;
204         usec_t timestamp_boottime;
205         int state;
206
207         bool exit_requested:1;
208         bool need_process_child:1;
209         bool watchdog:1;
210         bool profile_delays:1;
211
212         int exit_code;
213
214         pid_t tid;
215         sd_event **default_event_ptr;
216
217         usec_t watchdog_last, watchdog_period;
218
219         unsigned n_sources;
220
221         LIST_HEAD(sd_event_source, sources);
222
223         usec_t last_run, last_log;
224         unsigned delays[sizeof(usec_t) * 8];
225 };
226
227 static void source_disconnect(sd_event_source *s);
228
229 static int pending_prioq_compare(const void *a, const void *b) {
230         const sd_event_source *x = a, *y = b;
231
232         assert(x->pending);
233         assert(y->pending);
234
235         /* Enabled ones first */
236         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
237                 return -1;
238         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
239                 return 1;
240
241         /* Lower priority values first */
242         if (x->priority < y->priority)
243                 return -1;
244         if (x->priority > y->priority)
245                 return 1;
246
247         /* Older entries first */
248         if (x->pending_iteration < y->pending_iteration)
249                 return -1;
250         if (x->pending_iteration > y->pending_iteration)
251                 return 1;
252
253         return 0;
254 }
255
256 static int prepare_prioq_compare(const void *a, const void *b) {
257         const sd_event_source *x = a, *y = b;
258
259         assert(x->prepare);
260         assert(y->prepare);
261
262         /* Enabled ones first */
263         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
264                 return -1;
265         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
266                 return 1;
267
268         /* Move most recently prepared ones last, so that we can stop
269          * preparing as soon as we hit one that has already been
270          * prepared in the current iteration */
271         if (x->prepare_iteration < y->prepare_iteration)
272                 return -1;
273         if (x->prepare_iteration > y->prepare_iteration)
274                 return 1;
275
276         /* Lower priority values first */
277         if (x->priority < y->priority)
278                 return -1;
279         if (x->priority > y->priority)
280                 return 1;
281
282         return 0;
283 }
284
285 static int earliest_time_prioq_compare(const void *a, const void *b) {
286         const sd_event_source *x = a, *y = b;
287
288         assert(EVENT_SOURCE_IS_TIME(x->type));
289         assert(x->type == y->type);
290
291         /* Enabled ones first */
292         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
293                 return -1;
294         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
295                 return 1;
296
297         /* Move the pending ones to the end */
298         if (!x->pending && y->pending)
299                 return -1;
300         if (x->pending && !y->pending)
301                 return 1;
302
303         /* Order by time */
304         if (x->time.next < y->time.next)
305                 return -1;
306         if (x->time.next > y->time.next)
307                 return 1;
308
309         return 0;
310 }
311
312 static int latest_time_prioq_compare(const void *a, const void *b) {
313         const sd_event_source *x = a, *y = b;
314
315         assert(EVENT_SOURCE_IS_TIME(x->type));
316         assert(x->type == y->type);
317
318         /* Enabled ones first */
319         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
320                 return -1;
321         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
322                 return 1;
323
324         /* Move the pending ones to the end */
325         if (!x->pending && y->pending)
326                 return -1;
327         if (x->pending && !y->pending)
328                 return 1;
329
330         /* Order by time */
331         if (x->time.next + x->time.accuracy < y->time.next + y->time.accuracy)
332                 return -1;
333         if (x->time.next + x->time.accuracy > y->time.next + y->time.accuracy)
334                 return 1;
335
336         return 0;
337 }
338
339 static int exit_prioq_compare(const void *a, const void *b) {
340         const sd_event_source *x = a, *y = b;
341
342         assert(x->type == SOURCE_EXIT);
343         assert(y->type == SOURCE_EXIT);
344
345         /* Enabled ones first */
346         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
347                 return -1;
348         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
349                 return 1;
350
351         /* Lower priority values first */
352         if (x->priority < y->priority)
353                 return -1;
354         if (x->priority > y->priority)
355                 return 1;
356
357         return 0;
358 }
359
360 static void free_clock_data(struct clock_data *d) {
361         assert(d);
362         assert(d->wakeup == WAKEUP_CLOCK_DATA);
363
364         safe_close(d->fd);
365         prioq_free(d->earliest);
366         prioq_free(d->latest);
367 }
368
369 static void event_free(sd_event *e) {
370         sd_event_source *s;
371
372         assert(e);
373
374         while ((s = e->sources)) {
375                 assert(s->floating);
376                 source_disconnect(s);
377                 sd_event_source_unref(s);
378         }
379
380         assert(e->n_sources == 0);
381
382         if (e->default_event_ptr)
383                 *(e->default_event_ptr) = NULL;
384
385         safe_close(e->epoll_fd);
386         safe_close(e->watchdog_fd);
387
388         free_clock_data(&e->realtime);
389         free_clock_data(&e->boottime);
390         free_clock_data(&e->monotonic);
391         free_clock_data(&e->realtime_alarm);
392         free_clock_data(&e->boottime_alarm);
393
394         prioq_free(e->pending);
395         prioq_free(e->prepare);
396         prioq_free(e->exit);
397
398         free(e->signal_sources);
399         hashmap_free(e->signal_data);
400
401         hashmap_free(e->child_sources);
402         set_free(e->post_sources);
403         free(e);
404 }
405
406 _public_ int sd_event_new(sd_event** ret) {
407         sd_event *e;
408         int r;
409
410         assert_return(ret, -EINVAL);
411
412         e = new0(sd_event, 1);
413         if (!e)
414                 return -ENOMEM;
415
416         e->n_ref = 1;
417         e->watchdog_fd = e->epoll_fd = e->realtime.fd = e->boottime.fd = e->monotonic.fd = e->realtime_alarm.fd = e->boottime_alarm.fd = -1;
418         e->realtime.next = e->boottime.next = e->monotonic.next = e->realtime_alarm.next = e->boottime_alarm.next = USEC_INFINITY;
419         e->realtime.wakeup = e->boottime.wakeup = e->monotonic.wakeup = e->realtime_alarm.wakeup = e->boottime_alarm.wakeup = WAKEUP_CLOCK_DATA;
420         e->original_pid = getpid();
421         e->perturb = USEC_INFINITY;
422
423         r = prioq_ensure_allocated(&e->pending, pending_prioq_compare);
424         if (r < 0)
425                 goto fail;
426
427         e->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
428         if (e->epoll_fd < 0) {
429                 r = -errno;
430                 goto fail;
431         }
432
433         if (secure_getenv("SD_EVENT_PROFILE_DELAYS")) {
434                 log_info("Event loop profiling enabled. Logarithmic histogram of event loop iterations in the range 2^0 ... 2^63 us will be logged every 5s.");
435                 e->profile_delays = true;
436         }
437
438         *ret = e;
439         return 0;
440
441 fail:
442         event_free(e);
443         return r;
444 }
445
446 _public_ sd_event* sd_event_ref(sd_event *e) {
447         assert_return(e, NULL);
448
449         assert(e->n_ref >= 1);
450         e->n_ref++;
451
452         return e;
453 }
454
455 _public_ sd_event* sd_event_unref(sd_event *e) {
456
457         if (!e)
458                 return NULL;
459
460         assert(e->n_ref >= 1);
461         e->n_ref--;
462
463         if (e->n_ref <= 0)
464                 event_free(e);
465
466         return NULL;
467 }
468
469 static bool event_pid_changed(sd_event *e) {
470         assert(e);
471
472         /* We don't support people creating an event loop and keeping
473          * it around over a fork(). Let's complain. */
474
475         return e->original_pid != getpid();
476 }
477
478 static void source_io_unregister(sd_event_source *s) {
479         int r;
480
481         assert(s);
482         assert(s->type == SOURCE_IO);
483
484         if (event_pid_changed(s->event))
485                 return;
486
487         if (!s->io.registered)
488                 return;
489
490         r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, s->io.fd, NULL);
491         if (r < 0)
492                 log_debug_errno(errno, "Failed to remove source %s from epoll: %m", strna(s->description));
493
494         s->io.registered = false;
495 }
496
497 static int source_io_register(
498                 sd_event_source *s,
499                 int enabled,
500                 uint32_t events) {
501
502         struct epoll_event ev = {};
503         int r;
504
505         assert(s);
506         assert(s->type == SOURCE_IO);
507         assert(enabled != SD_EVENT_OFF);
508
509         ev.events = events;
510         ev.data.ptr = s;
511
512         if (enabled == SD_EVENT_ONESHOT)
513                 ev.events |= EPOLLONESHOT;
514
515         if (s->io.registered)
516                 r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_MOD, s->io.fd, &ev);
517         else
518                 r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_ADD, s->io.fd, &ev);
519         if (r < 0)
520                 return -errno;
521
522         s->io.registered = true;
523
524         return 0;
525 }
526
527 #if 0 /// UNNEEDED by elogind
528 static clockid_t event_source_type_to_clock(EventSourceType t) {
529
530         switch (t) {
531
532         case SOURCE_TIME_REALTIME:
533                 return CLOCK_REALTIME;
534
535         case SOURCE_TIME_BOOTTIME:
536                 return CLOCK_BOOTTIME;
537
538         case SOURCE_TIME_MONOTONIC:
539                 return CLOCK_MONOTONIC;
540
541         case SOURCE_TIME_REALTIME_ALARM:
542                 return CLOCK_REALTIME_ALARM;
543
544         case SOURCE_TIME_BOOTTIME_ALARM:
545                 return CLOCK_BOOTTIME_ALARM;
546
547         default:
548                 return (clockid_t) -1;
549         }
550 }
551 #endif // 0
552
553 static EventSourceType clock_to_event_source_type(clockid_t clock) {
554
555         switch (clock) {
556
557         case CLOCK_REALTIME:
558                 return SOURCE_TIME_REALTIME;
559
560         case CLOCK_BOOTTIME:
561                 return SOURCE_TIME_BOOTTIME;
562
563         case CLOCK_MONOTONIC:
564                 return SOURCE_TIME_MONOTONIC;
565
566         case CLOCK_REALTIME_ALARM:
567                 return SOURCE_TIME_REALTIME_ALARM;
568
569         case CLOCK_BOOTTIME_ALARM:
570                 return SOURCE_TIME_BOOTTIME_ALARM;
571
572         default:
573                 return _SOURCE_EVENT_SOURCE_TYPE_INVALID;
574         }
575 }
576
577 static struct clock_data* event_get_clock_data(sd_event *e, EventSourceType t) {
578         assert(e);
579
580         switch (t) {
581
582         case SOURCE_TIME_REALTIME:
583                 return &e->realtime;
584
585         case SOURCE_TIME_BOOTTIME:
586                 return &e->boottime;
587
588         case SOURCE_TIME_MONOTONIC:
589                 return &e->monotonic;
590
591         case SOURCE_TIME_REALTIME_ALARM:
592                 return &e->realtime_alarm;
593
594         case SOURCE_TIME_BOOTTIME_ALARM:
595                 return &e->boottime_alarm;
596
597         default:
598                 return NULL;
599         }
600 }
601
602 static int event_make_signal_data(
603                 sd_event *e,
604                 int sig,
605                 struct signal_data **ret) {
606
607         struct epoll_event ev = {};
608         struct signal_data *d;
609         bool added = false;
610         sigset_t ss_copy;
611         int64_t priority;
612         int r;
613
614         assert(e);
615
616         if (event_pid_changed(e))
617                 return -ECHILD;
618
619         if (e->signal_sources && e->signal_sources[sig])
620                 priority = e->signal_sources[sig]->priority;
621         else
622                 priority = 0;
623
624         d = hashmap_get(e->signal_data, &priority);
625         if (d) {
626                 if (sigismember(&d->sigset, sig) > 0) {
627                         if (ret)
628                                 *ret = d;
629                 return 0;
630                 }
631         } else {
632                 r = hashmap_ensure_allocated(&e->signal_data, &uint64_hash_ops);
633                 if (r < 0)
634                         return r;
635
636                 d = new0(struct signal_data, 1);
637                 if (!d)
638                         return -ENOMEM;
639
640                 d->wakeup = WAKEUP_SIGNAL_DATA;
641                 d->fd  = -1;
642                 d->priority = priority;
643
644                 r = hashmap_put(e->signal_data, &d->priority, d);
645         if (r < 0)
646                         return r;
647
648                 added = true;
649         }
650
651         ss_copy = d->sigset;
652         assert_se(sigaddset(&ss_copy, sig) >= 0);
653
654         r = signalfd(d->fd, &ss_copy, SFD_NONBLOCK|SFD_CLOEXEC);
655         if (r < 0) {
656                 r = -errno;
657                 goto fail;
658         }
659
660         d->sigset = ss_copy;
661
662         if (d->fd >= 0) {
663                 if (ret)
664                         *ret = d;
665                 return 0;
666         }
667
668         d->fd = r;
669
670         ev.events = EPOLLIN;
671         ev.data.ptr = d;
672
673         r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, d->fd, &ev);
674         if (r < 0) {
675                 r = -errno;
676                 goto fail;
677         }
678
679         if (ret)
680                 *ret = d;
681
682         return 0;
683
684 fail:
685         if (added) {
686                 d->fd = safe_close(d->fd);
687                 hashmap_remove(e->signal_data, &d->priority);
688                 free(d);
689         }
690
691         return r;
692 }
693
694 static void event_unmask_signal_data(sd_event *e, struct signal_data *d, int sig) {
695         assert(e);
696         assert(d);
697
698         /* Turns off the specified signal in the signal data
699          * object. If the signal mask of the object becomes empty that
700          * way removes it. */
701
702         if (sigismember(&d->sigset, sig) == 0)
703                 return;
704
705         assert_se(sigdelset(&d->sigset, sig) >= 0);
706
707         if (sigisemptyset(&d->sigset)) {
708
709                 /* If all the mask is all-zero we can get rid of the structure */
710                 hashmap_remove(e->signal_data, &d->priority);
711                 assert(!d->current);
712                 safe_close(d->fd);
713                 free(d);
714                 return;
715         }
716
717         assert(d->fd >= 0);
718
719         if (signalfd(d->fd, &d->sigset, SFD_NONBLOCK|SFD_CLOEXEC) < 0)
720                 log_debug_errno(errno, "Failed to unset signal bit, ignoring: %m");
721 }
722
723 static void event_gc_signal_data(sd_event *e, const int64_t *priority, int sig) {
724         struct signal_data *d;
725         static const int64_t zero_priority = 0;
726
727         assert(e);
728
729         /* Rechecks if the specified signal is still something we are
730          * interested in. If not, we'll unmask it, and possibly drop
731          * the signalfd for it. */
732
733         if (sig == SIGCHLD &&
734             e->n_enabled_child_sources > 0)
735                 return;
736
737         if (e->signal_sources &&
738             e->signal_sources[sig] &&
739             e->signal_sources[sig]->enabled != SD_EVENT_OFF)
740                 return;
741
742         /*
743          * The specified signal might be enabled in three different queues:
744          *
745          * 1) the one that belongs to the priority passed (if it is non-NULL)
746          * 2) the one that belongs to the priority of the event source of the signal (if there is one)
747          * 3) the 0 priority (to cover the SIGCHLD case)
748          *
749          * Hence, let's remove it from all three here.
750          */
751
752         if (priority) {
753                 d = hashmap_get(e->signal_data, priority);
754                 if (d)
755                         event_unmask_signal_data(e, d, sig);
756         }
757
758         if (e->signal_sources && e->signal_sources[sig]) {
759                 d = hashmap_get(e->signal_data, &e->signal_sources[sig]->priority);
760                 if (d)
761                         event_unmask_signal_data(e, d, sig);
762         }
763
764         d = hashmap_get(e->signal_data, &zero_priority);
765         if (d)
766                 event_unmask_signal_data(e, d, sig);
767 }
768
769 static void source_disconnect(sd_event_source *s) {
770         sd_event *event;
771
772         assert(s);
773
774         if (!s->event)
775                 return;
776
777         assert(s->event->n_sources > 0);
778
779         switch (s->type) {
780
781         case SOURCE_IO:
782                 if (s->io.fd >= 0)
783                         source_io_unregister(s);
784
785                 break;
786
787         case SOURCE_TIME_REALTIME:
788         case SOURCE_TIME_BOOTTIME:
789         case SOURCE_TIME_MONOTONIC:
790         case SOURCE_TIME_REALTIME_ALARM:
791         case SOURCE_TIME_BOOTTIME_ALARM: {
792                 struct clock_data *d;
793
794                 d = event_get_clock_data(s->event, s->type);
795                 assert(d);
796
797                 prioq_remove(d->earliest, s, &s->time.earliest_index);
798                 prioq_remove(d->latest, s, &s->time.latest_index);
799                 d->needs_rearm = true;
800                 break;
801         }
802
803         case SOURCE_SIGNAL:
804                 if (s->signal.sig > 0) {
805
806                         if (s->event->signal_sources)
807                                 s->event->signal_sources[s->signal.sig] = NULL;
808
809                         event_gc_signal_data(s->event, &s->priority, s->signal.sig);
810                 }
811
812                 break;
813
814         case SOURCE_CHILD:
815                 if (s->child.pid > 0) {
816                         if (s->enabled != SD_EVENT_OFF) {
817                                 assert(s->event->n_enabled_child_sources > 0);
818                                 s->event->n_enabled_child_sources--;
819                         }
820
821                         (void) hashmap_remove(s->event->child_sources, PID_TO_PTR(s->child.pid));
822                         event_gc_signal_data(s->event, &s->priority, SIGCHLD);
823                 }
824
825                 break;
826
827         case SOURCE_DEFER:
828                 /* nothing */
829                 break;
830
831         case SOURCE_POST:
832                 set_remove(s->event->post_sources, s);
833                 break;
834
835         case SOURCE_EXIT:
836                 prioq_remove(s->event->exit, s, &s->exit.prioq_index);
837                 break;
838
839         default:
840                 assert_not_reached("Wut? I shouldn't exist.");
841         }
842
843         if (s->pending)
844                 prioq_remove(s->event->pending, s, &s->pending_index);
845
846         if (s->prepare)
847                 prioq_remove(s->event->prepare, s, &s->prepare_index);
848
849         event = s->event;
850
851         s->type = _SOURCE_EVENT_SOURCE_TYPE_INVALID;
852         s->event = NULL;
853         LIST_REMOVE(sources, event->sources, s);
854         event->n_sources--;
855
856         if (!s->floating)
857                 sd_event_unref(event);
858 }
859
860 static void source_free(sd_event_source *s) {
861         assert(s);
862
863         source_disconnect(s);
864         free(s->description);
865         free(s);
866 }
867
868 static int source_set_pending(sd_event_source *s, bool b) {
869         int r;
870
871         assert(s);
872         assert(s->type != SOURCE_EXIT);
873
874         if (s->pending == b)
875                 return 0;
876
877         s->pending = b;
878
879         if (b) {
880                 s->pending_iteration = s->event->iteration;
881
882                 r = prioq_put(s->event->pending, s, &s->pending_index);
883                 if (r < 0) {
884                         s->pending = false;
885                         return r;
886                 }
887         } else
888                 assert_se(prioq_remove(s->event->pending, s, &s->pending_index));
889
890         if (EVENT_SOURCE_IS_TIME(s->type)) {
891                 struct clock_data *d;
892
893                 d = event_get_clock_data(s->event, s->type);
894                 assert(d);
895
896                 prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
897                 prioq_reshuffle(d->latest, s, &s->time.latest_index);
898                 d->needs_rearm = true;
899         }
900
901         if (s->type == SOURCE_SIGNAL && !b) {
902                 struct signal_data *d;
903
904                 d = hashmap_get(s->event->signal_data, &s->priority);
905                 if (d && d->current == s)
906                         d->current = NULL;
907         }
908
909         return 0;
910 }
911
912 static sd_event_source *source_new(sd_event *e, bool floating, EventSourceType type) {
913         sd_event_source *s;
914
915         assert(e);
916
917         s = new0(sd_event_source, 1);
918         if (!s)
919                 return NULL;
920
921         s->n_ref = 1;
922         s->event = e;
923         s->floating = floating;
924         s->type = type;
925         s->pending_index = s->prepare_index = PRIOQ_IDX_NULL;
926
927         if (!floating)
928                 sd_event_ref(e);
929
930         LIST_PREPEND(sources, e->sources, s);
931         e->n_sources ++;
932
933         return s;
934 }
935
936 _public_ int sd_event_add_io(
937                 sd_event *e,
938                 sd_event_source **ret,
939                 int fd,
940                 uint32_t events,
941                 sd_event_io_handler_t callback,
942                 void *userdata) {
943
944         sd_event_source *s;
945         int r;
946
947         assert_return(e, -EINVAL);
948         assert_return(fd >= 0, -EBADF);
949         assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
950         assert_return(callback, -EINVAL);
951         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
952         assert_return(!event_pid_changed(e), -ECHILD);
953
954         s = source_new(e, !ret, SOURCE_IO);
955         if (!s)
956                 return -ENOMEM;
957
958         s->wakeup = WAKEUP_EVENT_SOURCE;
959         s->io.fd = fd;
960         s->io.events = events;
961         s->io.callback = callback;
962         s->userdata = userdata;
963         s->enabled = SD_EVENT_ON;
964
965         r = source_io_register(s, s->enabled, events);
966         if (r < 0) {
967                 source_free(s);
968                 return r;
969         }
970
971         if (ret)
972                 *ret = s;
973
974         return 0;
975 }
976
977 static void initialize_perturb(sd_event *e) {
978         sd_id128_t bootid = {};
979
980         /* When we sleep for longer, we try to realign the wakeup to
981            the same time wihtin each minute/second/250ms, so that
982            events all across the system can be coalesced into a single
983            CPU wakeup. However, let's take some system-specific
984            randomness for this value, so that in a network of systems
985            with synced clocks timer events are distributed a
986            bit. Here, we calculate a perturbation usec offset from the
987            boot ID. */
988
989         if (_likely_(e->perturb != USEC_INFINITY))
990                 return;
991
992         if (sd_id128_get_boot(&bootid) >= 0)
993                 e->perturb = (bootid.qwords[0] ^ bootid.qwords[1]) % USEC_PER_MINUTE;
994 }
995
996 static int event_setup_timer_fd(
997                 sd_event *e,
998                 struct clock_data *d,
999                 clockid_t clock) {
1000
1001         struct epoll_event ev = {};
1002         int r, fd;
1003
1004         assert(e);
1005         assert(d);
1006
1007         if (_likely_(d->fd >= 0))
1008                 return 0;
1009
1010         fd = timerfd_create(clock, TFD_NONBLOCK|TFD_CLOEXEC);
1011         if (fd < 0)
1012                 return -errno;
1013
1014         ev.events = EPOLLIN;
1015         ev.data.ptr = d;
1016
1017         r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, fd, &ev);
1018         if (r < 0) {
1019                 safe_close(fd);
1020                 return -errno;
1021         }
1022
1023         d->fd = fd;
1024         return 0;
1025 }
1026
1027 static int time_exit_callback(sd_event_source *s, uint64_t usec, void *userdata) {
1028         assert(s);
1029
1030         return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1031 }
1032
1033 _public_ int sd_event_add_time(
1034                 sd_event *e,
1035                 sd_event_source **ret,
1036                 clockid_t clock,
1037                 uint64_t usec,
1038                 uint64_t accuracy,
1039                 sd_event_time_handler_t callback,
1040                 void *userdata) {
1041
1042         EventSourceType type;
1043         sd_event_source *s;
1044         struct clock_data *d;
1045         int r;
1046
1047         assert_return(e, -EINVAL);
1048         assert_return(usec != (uint64_t) -1, -EINVAL);
1049         assert_return(accuracy != (uint64_t) -1, -EINVAL);
1050         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1051         assert_return(!event_pid_changed(e), -ECHILD);
1052
1053         if (!callback)
1054                 callback = time_exit_callback;
1055
1056         type = clock_to_event_source_type(clock);
1057         assert_return(type >= 0, -EOPNOTSUPP);
1058
1059         d = event_get_clock_data(e, type);
1060         assert(d);
1061
1062         r = prioq_ensure_allocated(&d->earliest, earliest_time_prioq_compare);
1063         if (r < 0)
1064                 return r;
1065
1066         r = prioq_ensure_allocated(&d->latest, latest_time_prioq_compare);
1067         if (r < 0)
1068                 return r;
1069
1070         if (d->fd < 0) {
1071                 r = event_setup_timer_fd(e, d, clock);
1072                 if (r < 0)
1073                         return r;
1074         }
1075
1076         s = source_new(e, !ret, type);
1077         if (!s)
1078                 return -ENOMEM;
1079
1080         s->time.next = usec;
1081         s->time.accuracy = accuracy == 0 ? DEFAULT_ACCURACY_USEC : accuracy;
1082         s->time.callback = callback;
1083         s->time.earliest_index = s->time.latest_index = PRIOQ_IDX_NULL;
1084         s->userdata = userdata;
1085         s->enabled = SD_EVENT_ONESHOT;
1086
1087         d->needs_rearm = true;
1088
1089         r = prioq_put(d->earliest, s, &s->time.earliest_index);
1090         if (r < 0)
1091                 goto fail;
1092
1093         r = prioq_put(d->latest, s, &s->time.latest_index);
1094         if (r < 0)
1095                 goto fail;
1096
1097         if (ret)
1098                 *ret = s;
1099
1100         return 0;
1101
1102 fail:
1103         source_free(s);
1104         return r;
1105 }
1106
1107 static int signal_exit_callback(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1108         assert(s);
1109
1110         return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1111 }
1112
1113 _public_ int sd_event_add_signal(
1114                 sd_event *e,
1115                 sd_event_source **ret,
1116                 int sig,
1117                 sd_event_signal_handler_t callback,
1118                 void *userdata) {
1119
1120         sd_event_source *s;
1121         struct signal_data *d;
1122         sigset_t ss;
1123         int r;
1124
1125         assert_return(e, -EINVAL);
1126         assert_return(sig > 0, -EINVAL);
1127         assert_return(sig < _NSIG, -EINVAL);
1128         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1129         assert_return(!event_pid_changed(e), -ECHILD);
1130
1131         if (!callback)
1132                 callback = signal_exit_callback;
1133
1134         r = pthread_sigmask(SIG_SETMASK, NULL, &ss);
1135         if (r != 0)
1136                 return -r;
1137
1138         if (!sigismember(&ss, sig))
1139                 return -EBUSY;
1140
1141         if (!e->signal_sources) {
1142                 e->signal_sources = new0(sd_event_source*, _NSIG);
1143                 if (!e->signal_sources)
1144                         return -ENOMEM;
1145         } else if (e->signal_sources[sig])
1146                 return -EBUSY;
1147
1148         s = source_new(e, !ret, SOURCE_SIGNAL);
1149         if (!s)
1150                 return -ENOMEM;
1151
1152         s->signal.sig = sig;
1153         s->signal.callback = callback;
1154         s->userdata = userdata;
1155         s->enabled = SD_EVENT_ON;
1156
1157         e->signal_sources[sig] = s;
1158
1159         r = event_make_signal_data(e, sig, &d);
1160                 if (r < 0) {
1161                         source_free(s);
1162                         return r;
1163                 }
1164
1165         /* Use the signal name as description for the event source by default */
1166         (void) sd_event_source_set_description(s, signal_to_string(sig));
1167
1168         if (ret)
1169                 *ret = s;
1170
1171         return 0;
1172 }
1173
1174 #if 0 /// UNNEEDED by elogind
1175 _public_ int sd_event_add_child(
1176                 sd_event *e,
1177                 sd_event_source **ret,
1178                 pid_t pid,
1179                 int options,
1180                 sd_event_child_handler_t callback,
1181                 void *userdata) {
1182
1183         sd_event_source *s;
1184         int r;
1185
1186         assert_return(e, -EINVAL);
1187         assert_return(pid > 1, -EINVAL);
1188         assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED)), -EINVAL);
1189         assert_return(options != 0, -EINVAL);
1190         assert_return(callback, -EINVAL);
1191         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1192         assert_return(!event_pid_changed(e), -ECHILD);
1193
1194         r = hashmap_ensure_allocated(&e->child_sources, NULL);
1195         if (r < 0)
1196                 return r;
1197
1198         if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
1199                 return -EBUSY;
1200
1201         s = source_new(e, !ret, SOURCE_CHILD);
1202         if (!s)
1203                 return -ENOMEM;
1204
1205         s->child.pid = pid;
1206         s->child.options = options;
1207         s->child.callback = callback;
1208         s->userdata = userdata;
1209         s->enabled = SD_EVENT_ONESHOT;
1210
1211         r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
1212         if (r < 0) {
1213                 source_free(s);
1214                 return r;
1215         }
1216
1217         e->n_enabled_child_sources ++;
1218
1219         r = event_make_signal_data(e, SIGCHLD, NULL);
1220                 if (r < 0) {
1221                 e->n_enabled_child_sources--;
1222                         source_free(s);
1223                         return r;
1224                 }
1225
1226         e->need_process_child = true;
1227
1228         if (ret)
1229                 *ret = s;
1230
1231         return 0;
1232 }
1233
1234 _public_ int sd_event_add_defer(
1235                 sd_event *e,
1236                 sd_event_source **ret,
1237                 sd_event_handler_t callback,
1238                 void *userdata) {
1239
1240         sd_event_source *s;
1241         int r;
1242
1243         assert_return(e, -EINVAL);
1244         assert_return(callback, -EINVAL);
1245         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1246         assert_return(!event_pid_changed(e), -ECHILD);
1247
1248         s = source_new(e, !ret, SOURCE_DEFER);
1249         if (!s)
1250                 return -ENOMEM;
1251
1252         s->defer.callback = callback;
1253         s->userdata = userdata;
1254         s->enabled = SD_EVENT_ONESHOT;
1255
1256         r = source_set_pending(s, true);
1257         if (r < 0) {
1258                 source_free(s);
1259                 return r;
1260         }
1261
1262         if (ret)
1263                 *ret = s;
1264
1265         return 0;
1266 }
1267 #endif // 0
1268
1269 _public_ int sd_event_add_post(
1270                 sd_event *e,
1271                 sd_event_source **ret,
1272                 sd_event_handler_t callback,
1273                 void *userdata) {
1274
1275         sd_event_source *s;
1276         int r;
1277
1278         assert_return(e, -EINVAL);
1279         assert_return(callback, -EINVAL);
1280         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1281         assert_return(!event_pid_changed(e), -ECHILD);
1282
1283         r = set_ensure_allocated(&e->post_sources, NULL);
1284         if (r < 0)
1285                 return r;
1286
1287         s = source_new(e, !ret, SOURCE_POST);
1288         if (!s)
1289                 return -ENOMEM;
1290
1291         s->post.callback = callback;
1292         s->userdata = userdata;
1293         s->enabled = SD_EVENT_ON;
1294
1295         r = set_put(e->post_sources, s);
1296         if (r < 0) {
1297                 source_free(s);
1298                 return r;
1299         }
1300
1301         if (ret)
1302                 *ret = s;
1303
1304         return 0;
1305 }
1306
1307 _public_ int sd_event_add_exit(
1308                 sd_event *e,
1309                 sd_event_source **ret,
1310                 sd_event_handler_t callback,
1311                 void *userdata) {
1312
1313         sd_event_source *s;
1314         int r;
1315
1316         assert_return(e, -EINVAL);
1317         assert_return(callback, -EINVAL);
1318         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1319         assert_return(!event_pid_changed(e), -ECHILD);
1320
1321         r = prioq_ensure_allocated(&e->exit, exit_prioq_compare);
1322         if (r < 0)
1323                 return r;
1324
1325         s = source_new(e, !ret, SOURCE_EXIT);
1326         if (!s)
1327                 return -ENOMEM;
1328
1329         s->exit.callback = callback;
1330         s->userdata = userdata;
1331         s->exit.prioq_index = PRIOQ_IDX_NULL;
1332         s->enabled = SD_EVENT_ONESHOT;
1333
1334         r = prioq_put(s->event->exit, s, &s->exit.prioq_index);
1335         if (r < 0) {
1336                 source_free(s);
1337                 return r;
1338         }
1339
1340         if (ret)
1341                 *ret = s;
1342
1343         return 0;
1344 }
1345
1346 #if 0 /// UNNEEDED by elogind
1347 _public_ sd_event_source* sd_event_source_ref(sd_event_source *s) {
1348         assert_return(s, NULL);
1349
1350         assert(s->n_ref >= 1);
1351         s->n_ref++;
1352
1353         return s;
1354 }
1355 #endif // 0
1356
1357 _public_ sd_event_source* sd_event_source_unref(sd_event_source *s) {
1358
1359         if (!s)
1360                 return NULL;
1361
1362         assert(s->n_ref >= 1);
1363         s->n_ref--;
1364
1365         if (s->n_ref <= 0) {
1366                 /* Here's a special hack: when we are called from a
1367                  * dispatch handler we won't free the event source
1368                  * immediately, but we will detach the fd from the
1369                  * epoll. This way it is safe for the caller to unref
1370                  * the event source and immediately close the fd, but
1371                  * we still retain a valid event source object after
1372                  * the callback. */
1373
1374                 if (s->dispatching) {
1375                         if (s->type == SOURCE_IO)
1376                                 source_io_unregister(s);
1377
1378                         source_disconnect(s);
1379                 } else
1380                         source_free(s);
1381         }
1382
1383         return NULL;
1384 }
1385
1386 _public_ int sd_event_source_set_description(sd_event_source *s, const char *description) {
1387         assert_return(s, -EINVAL);
1388         assert_return(!event_pid_changed(s->event), -ECHILD);
1389
1390         return free_and_strdup(&s->description, description);
1391 }
1392
1393 #if 0 /// UNNEEDED by elogind
1394 _public_ int sd_event_source_get_description(sd_event_source *s, const char **description) {
1395         assert_return(s, -EINVAL);
1396         assert_return(description, -EINVAL);
1397         assert_return(s->description, -ENXIO);
1398         assert_return(!event_pid_changed(s->event), -ECHILD);
1399
1400         *description = s->description;
1401         return 0;
1402 }
1403 #endif // 0
1404
1405 _public_ sd_event *sd_event_source_get_event(sd_event_source *s) {
1406         assert_return(s, NULL);
1407
1408         return s->event;
1409 }
1410
1411 #if 0 /// UNNEEDED by elogind
1412 _public_ int sd_event_source_get_pending(sd_event_source *s) {
1413         assert_return(s, -EINVAL);
1414         assert_return(s->type != SOURCE_EXIT, -EDOM);
1415         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1416         assert_return(!event_pid_changed(s->event), -ECHILD);
1417
1418         return s->pending;
1419 }
1420
1421 _public_ int sd_event_source_get_io_fd(sd_event_source *s) {
1422         assert_return(s, -EINVAL);
1423         assert_return(s->type == SOURCE_IO, -EDOM);
1424         assert_return(!event_pid_changed(s->event), -ECHILD);
1425
1426         return s->io.fd;
1427 }
1428 #endif // 0
1429
1430 _public_ int sd_event_source_set_io_fd(sd_event_source *s, int fd) {
1431         int r;
1432
1433         assert_return(s, -EINVAL);
1434         assert_return(fd >= 0, -EBADF);
1435         assert_return(s->type == SOURCE_IO, -EDOM);
1436         assert_return(!event_pid_changed(s->event), -ECHILD);
1437
1438         if (s->io.fd == fd)
1439                 return 0;
1440
1441         if (s->enabled == SD_EVENT_OFF) {
1442                 s->io.fd = fd;
1443                 s->io.registered = false;
1444         } else {
1445                 int saved_fd;
1446
1447                 saved_fd = s->io.fd;
1448                 assert(s->io.registered);
1449
1450                 s->io.fd = fd;
1451                 s->io.registered = false;
1452
1453                 r = source_io_register(s, s->enabled, s->io.events);
1454                 if (r < 0) {
1455                         s->io.fd = saved_fd;
1456                         s->io.registered = true;
1457                         return r;
1458                 }
1459
1460                 epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, saved_fd, NULL);
1461         }
1462
1463         return 0;
1464 }
1465
1466 #if 0 /// UNNEEDED by elogind
1467 _public_ int sd_event_source_get_io_events(sd_event_source *s, uint32_t* events) {
1468         assert_return(s, -EINVAL);
1469         assert_return(events, -EINVAL);
1470         assert_return(s->type == SOURCE_IO, -EDOM);
1471         assert_return(!event_pid_changed(s->event), -ECHILD);
1472
1473         *events = s->io.events;
1474         return 0;
1475 }
1476 #endif // 0
1477
1478 _public_ int sd_event_source_set_io_events(sd_event_source *s, uint32_t events) {
1479         int r;
1480
1481         assert_return(s, -EINVAL);
1482         assert_return(s->type == SOURCE_IO, -EDOM);
1483         assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
1484         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1485         assert_return(!event_pid_changed(s->event), -ECHILD);
1486
1487         /* edge-triggered updates are never skipped, so we can reset edges */
1488         if (s->io.events == events && !(events & EPOLLET))
1489                 return 0;
1490
1491         if (s->enabled != SD_EVENT_OFF) {
1492                 r = source_io_register(s, s->enabled, events);
1493                 if (r < 0)
1494                         return r;
1495         }
1496
1497         s->io.events = events;
1498         source_set_pending(s, false);
1499
1500         return 0;
1501 }
1502
1503 #if 0 /// UNNEEDED by elogind
1504 _public_ int sd_event_source_get_io_revents(sd_event_source *s, uint32_t* revents) {
1505         assert_return(s, -EINVAL);
1506         assert_return(revents, -EINVAL);
1507         assert_return(s->type == SOURCE_IO, -EDOM);
1508         assert_return(s->pending, -ENODATA);
1509         assert_return(!event_pid_changed(s->event), -ECHILD);
1510
1511         *revents = s->io.revents;
1512         return 0;
1513 }
1514
1515 _public_ int sd_event_source_get_signal(sd_event_source *s) {
1516         assert_return(s, -EINVAL);
1517         assert_return(s->type == SOURCE_SIGNAL, -EDOM);
1518         assert_return(!event_pid_changed(s->event), -ECHILD);
1519
1520         return s->signal.sig;
1521 }
1522
1523 _public_ int sd_event_source_get_priority(sd_event_source *s, int64_t *priority) {
1524         assert_return(s, -EINVAL);
1525         assert_return(!event_pid_changed(s->event), -ECHILD);
1526
1527         return s->priority;
1528 }
1529 #endif // 0
1530
1531 _public_ int sd_event_source_set_priority(sd_event_source *s, int64_t priority) {
1532         int r;
1533
1534         assert_return(s, -EINVAL);
1535         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1536         assert_return(!event_pid_changed(s->event), -ECHILD);
1537
1538         if (s->priority == priority)
1539                 return 0;
1540
1541         if (s->type == SOURCE_SIGNAL && s->enabled != SD_EVENT_OFF) {
1542                 struct signal_data *old, *d;
1543
1544                 /* Move us from the signalfd belonging to the old
1545                  * priority to the signalfd of the new priority */
1546
1547                 assert_se(old = hashmap_get(s->event->signal_data, &s->priority));
1548
1549                 s->priority = priority;
1550
1551                 r = event_make_signal_data(s->event, s->signal.sig, &d);
1552                 if (r < 0) {
1553                         s->priority = old->priority;
1554                         return r;
1555                 }
1556
1557                 event_unmask_signal_data(s->event, old, s->signal.sig);
1558         } else
1559         s->priority = priority;
1560
1561         if (s->pending)
1562                 prioq_reshuffle(s->event->pending, s, &s->pending_index);
1563
1564         if (s->prepare)
1565                 prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
1566
1567         if (s->type == SOURCE_EXIT)
1568                 prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
1569
1570         return 0;
1571 }
1572
1573 #if 0 /// UNNEEDED by elogind
1574 _public_ int sd_event_source_get_enabled(sd_event_source *s, int *m) {
1575         assert_return(s, -EINVAL);
1576         assert_return(m, -EINVAL);
1577         assert_return(!event_pid_changed(s->event), -ECHILD);
1578
1579         *m = s->enabled;
1580         return 0;
1581 }
1582 #endif // 0
1583
1584 _public_ int sd_event_source_set_enabled(sd_event_source *s, int m) {
1585         int r;
1586
1587         assert_return(s, -EINVAL);
1588         assert_return(m == SD_EVENT_OFF || m == SD_EVENT_ON || m == SD_EVENT_ONESHOT, -EINVAL);
1589         assert_return(!event_pid_changed(s->event), -ECHILD);
1590
1591         /* If we are dead anyway, we are fine with turning off
1592          * sources, but everything else needs to fail. */
1593         if (s->event->state == SD_EVENT_FINISHED)
1594                 return m == SD_EVENT_OFF ? 0 : -ESTALE;
1595
1596         if (s->enabled == m)
1597                 return 0;
1598
1599         if (m == SD_EVENT_OFF) {
1600
1601                 switch (s->type) {
1602
1603                 case SOURCE_IO:
1604                         source_io_unregister(s);
1605                         s->enabled = m;
1606                         break;
1607
1608                 case SOURCE_TIME_REALTIME:
1609                 case SOURCE_TIME_BOOTTIME:
1610                 case SOURCE_TIME_MONOTONIC:
1611                 case SOURCE_TIME_REALTIME_ALARM:
1612                 case SOURCE_TIME_BOOTTIME_ALARM: {
1613                         struct clock_data *d;
1614
1615                         s->enabled = m;
1616                         d = event_get_clock_data(s->event, s->type);
1617                         assert(d);
1618
1619                         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
1620                         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1621                         d->needs_rearm = true;
1622                         break;
1623                 }
1624
1625                 case SOURCE_SIGNAL:
1626                         s->enabled = m;
1627
1628                         event_gc_signal_data(s->event, &s->priority, s->signal.sig);
1629                         break;
1630
1631                 case SOURCE_CHILD:
1632                         s->enabled = m;
1633
1634                         assert(s->event->n_enabled_child_sources > 0);
1635                         s->event->n_enabled_child_sources--;
1636
1637                         event_gc_signal_data(s->event, &s->priority, SIGCHLD);
1638                         break;
1639
1640                 case SOURCE_EXIT:
1641                         s->enabled = m;
1642                         prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
1643                         break;
1644
1645                 case SOURCE_DEFER:
1646                 case SOURCE_POST:
1647                         s->enabled = m;
1648                         break;
1649
1650                 default:
1651                         assert_not_reached("Wut? I shouldn't exist.");
1652                 }
1653
1654         } else {
1655                 switch (s->type) {
1656
1657                 case SOURCE_IO:
1658                         r = source_io_register(s, m, s->io.events);
1659                         if (r < 0)
1660                                 return r;
1661
1662                         s->enabled = m;
1663                         break;
1664
1665                 case SOURCE_TIME_REALTIME:
1666                 case SOURCE_TIME_BOOTTIME:
1667                 case SOURCE_TIME_MONOTONIC:
1668                 case SOURCE_TIME_REALTIME_ALARM:
1669                 case SOURCE_TIME_BOOTTIME_ALARM: {
1670                         struct clock_data *d;
1671
1672                         s->enabled = m;
1673                         d = event_get_clock_data(s->event, s->type);
1674                         assert(d);
1675
1676                         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
1677                         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1678                         d->needs_rearm = true;
1679                         break;
1680                 }
1681
1682                 case SOURCE_SIGNAL:
1683
1684                         s->enabled = m;
1685
1686                         r = event_make_signal_data(s->event, s->signal.sig, NULL);
1687                                 if (r < 0) {
1688                                         s->enabled = SD_EVENT_OFF;
1689                                 event_gc_signal_data(s->event, &s->priority, s->signal.sig);
1690                                         return r;
1691                                 }
1692
1693                         break;
1694
1695                 case SOURCE_CHILD:
1696
1697                         if (s->enabled == SD_EVENT_OFF)
1698                                 s->event->n_enabled_child_sources++;
1699
1700                         s->enabled = m;
1701
1702                         r = event_make_signal_data(s->event, SIGCHLD, NULL);
1703                                         if (r < 0) {
1704                                                 s->enabled = SD_EVENT_OFF;
1705                                 s->event->n_enabled_child_sources--;
1706                                 event_gc_signal_data(s->event, &s->priority, SIGCHLD);
1707                                                 return r;
1708                                         }
1709
1710                         break;
1711
1712                 case SOURCE_EXIT:
1713                         s->enabled = m;
1714                         prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
1715                         break;
1716
1717                 case SOURCE_DEFER:
1718                 case SOURCE_POST:
1719                         s->enabled = m;
1720                         break;
1721
1722                 default:
1723                         assert_not_reached("Wut? I shouldn't exist.");
1724                 }
1725         }
1726
1727         if (s->pending)
1728                 prioq_reshuffle(s->event->pending, s, &s->pending_index);
1729
1730         if (s->prepare)
1731                 prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
1732
1733         return 0;
1734 }
1735
1736 _public_ int sd_event_source_get_time(sd_event_source *s, uint64_t *usec) {
1737         assert_return(s, -EINVAL);
1738         assert_return(usec, -EINVAL);
1739         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1740         assert_return(!event_pid_changed(s->event), -ECHILD);
1741
1742         *usec = s->time.next;
1743         return 0;
1744 }
1745
1746 _public_ int sd_event_source_set_time(sd_event_source *s, uint64_t usec) {
1747         struct clock_data *d;
1748
1749         assert_return(s, -EINVAL);
1750         assert_return(usec != (uint64_t) -1, -EINVAL);
1751         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1752         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1753         assert_return(!event_pid_changed(s->event), -ECHILD);
1754
1755         s->time.next = usec;
1756
1757         source_set_pending(s, false);
1758
1759         d = event_get_clock_data(s->event, s->type);
1760         assert(d);
1761
1762         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
1763         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1764         d->needs_rearm = true;
1765
1766         return 0;
1767 }
1768
1769 #if 0 /// UNNEEDED by elogind
1770 _public_ int sd_event_source_get_time_accuracy(sd_event_source *s, uint64_t *usec) {
1771         assert_return(s, -EINVAL);
1772         assert_return(usec, -EINVAL);
1773         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1774         assert_return(!event_pid_changed(s->event), -ECHILD);
1775
1776         *usec = s->time.accuracy;
1777         return 0;
1778 }
1779
1780 _public_ int sd_event_source_set_time_accuracy(sd_event_source *s, uint64_t usec) {
1781         struct clock_data *d;
1782
1783         assert_return(s, -EINVAL);
1784         assert_return(usec != (uint64_t) -1, -EINVAL);
1785         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1786         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1787         assert_return(!event_pid_changed(s->event), -ECHILD);
1788
1789         if (usec == 0)
1790                 usec = DEFAULT_ACCURACY_USEC;
1791
1792         s->time.accuracy = usec;
1793
1794         source_set_pending(s, false);
1795
1796         d = event_get_clock_data(s->event, s->type);
1797         assert(d);
1798
1799         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1800         d->needs_rearm = true;
1801
1802         return 0;
1803 }
1804
1805 _public_ int sd_event_source_get_time_clock(sd_event_source *s, clockid_t *clock) {
1806         assert_return(s, -EINVAL);
1807         assert_return(clock, -EINVAL);
1808         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1809         assert_return(!event_pid_changed(s->event), -ECHILD);
1810
1811         *clock = event_source_type_to_clock(s->type);
1812         return 0;
1813 }
1814
1815 _public_ int sd_event_source_get_child_pid(sd_event_source *s, pid_t *pid) {
1816         assert_return(s, -EINVAL);
1817         assert_return(pid, -EINVAL);
1818         assert_return(s->type == SOURCE_CHILD, -EDOM);
1819         assert_return(!event_pid_changed(s->event), -ECHILD);
1820
1821         *pid = s->child.pid;
1822         return 0;
1823 }
1824 #endif // 0
1825
1826 _public_ int sd_event_source_set_prepare(sd_event_source *s, sd_event_handler_t callback) {
1827         int r;
1828
1829         assert_return(s, -EINVAL);
1830         assert_return(s->type != SOURCE_EXIT, -EDOM);
1831         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1832         assert_return(!event_pid_changed(s->event), -ECHILD);
1833
1834         if (s->prepare == callback)
1835                 return 0;
1836
1837         if (callback && s->prepare) {
1838                 s->prepare = callback;
1839                 return 0;
1840         }
1841
1842         r = prioq_ensure_allocated(&s->event->prepare, prepare_prioq_compare);
1843         if (r < 0)
1844                 return r;
1845
1846         s->prepare = callback;
1847
1848         if (callback) {
1849                 r = prioq_put(s->event->prepare, s, &s->prepare_index);
1850                 if (r < 0)
1851                         return r;
1852         } else
1853                 prioq_remove(s->event->prepare, s, &s->prepare_index);
1854
1855         return 0;
1856 }
1857
1858 #if 0 /// UNNEEDED by elogind
1859 _public_ void* sd_event_source_get_userdata(sd_event_source *s) {
1860         assert_return(s, NULL);
1861
1862         return s->userdata;
1863 }
1864
1865 _public_ void *sd_event_source_set_userdata(sd_event_source *s, void *userdata) {
1866         void *ret;
1867
1868         assert_return(s, NULL);
1869
1870         ret = s->userdata;
1871         s->userdata = userdata;
1872
1873         return ret;
1874 }
1875 #endif // 0
1876
1877 static usec_t sleep_between(sd_event *e, usec_t a, usec_t b) {
1878         usec_t c;
1879         assert(e);
1880         assert(a <= b);
1881
1882         if (a <= 0)
1883                 return 0;
1884
1885         if (b <= a + 1)
1886                 return a;
1887
1888         initialize_perturb(e);
1889
1890         /*
1891           Find a good time to wake up again between times a and b. We
1892           have two goals here:
1893
1894           a) We want to wake up as seldom as possible, hence prefer
1895              later times over earlier times.
1896
1897           b) But if we have to wake up, then let's make sure to
1898              dispatch as much as possible on the entire system.
1899
1900           We implement this by waking up everywhere at the same time
1901           within any given minute if we can, synchronised via the
1902           perturbation value determined from the boot ID. If we can't,
1903           then we try to find the same spot in every 10s, then 1s and
1904           then 250ms step. Otherwise, we pick the last possible time
1905           to wake up.
1906         */
1907
1908         c = (b / USEC_PER_MINUTE) * USEC_PER_MINUTE + e->perturb;
1909         if (c >= b) {
1910                 if (_unlikely_(c < USEC_PER_MINUTE))
1911                         return b;
1912
1913                 c -= USEC_PER_MINUTE;
1914         }
1915
1916         if (c >= a)
1917                 return c;
1918
1919         c = (b / (USEC_PER_SEC*10)) * (USEC_PER_SEC*10) + (e->perturb % (USEC_PER_SEC*10));
1920         if (c >= b) {
1921                 if (_unlikely_(c < USEC_PER_SEC*10))
1922                         return b;
1923
1924                 c -= USEC_PER_SEC*10;
1925         }
1926
1927         if (c >= a)
1928                 return c;
1929
1930         c = (b / USEC_PER_SEC) * USEC_PER_SEC + (e->perturb % USEC_PER_SEC);
1931         if (c >= b) {
1932                 if (_unlikely_(c < USEC_PER_SEC))
1933                         return b;
1934
1935                 c -= USEC_PER_SEC;
1936         }
1937
1938         if (c >= a)
1939                 return c;
1940
1941         c = (b / (USEC_PER_MSEC*250)) * (USEC_PER_MSEC*250) + (e->perturb % (USEC_PER_MSEC*250));
1942         if (c >= b) {
1943                 if (_unlikely_(c < USEC_PER_MSEC*250))
1944                         return b;
1945
1946                 c -= USEC_PER_MSEC*250;
1947         }
1948
1949         if (c >= a)
1950                 return c;
1951
1952         return b;
1953 }
1954
1955 static int event_arm_timer(
1956                 sd_event *e,
1957                 struct clock_data *d) {
1958
1959         struct itimerspec its = {};
1960         sd_event_source *a, *b;
1961         usec_t t;
1962         int r;
1963
1964         assert(e);
1965         assert(d);
1966
1967         if (!d->needs_rearm)
1968                 return 0;
1969         else
1970                 d->needs_rearm = false;
1971
1972         a = prioq_peek(d->earliest);
1973         if (!a || a->enabled == SD_EVENT_OFF) {
1974
1975                 if (d->fd < 0)
1976                         return 0;
1977
1978                 if (d->next == USEC_INFINITY)
1979                         return 0;
1980
1981                 /* disarm */
1982                 r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
1983                 if (r < 0)
1984                         return r;
1985
1986                 d->next = USEC_INFINITY;
1987                 return 0;
1988         }
1989
1990         b = prioq_peek(d->latest);
1991         assert_se(b && b->enabled != SD_EVENT_OFF);
1992
1993         t = sleep_between(e, a->time.next, b->time.next + b->time.accuracy);
1994         if (d->next == t)
1995                 return 0;
1996
1997         assert_se(d->fd >= 0);
1998
1999         if (t == 0) {
2000                 /* We don' want to disarm here, just mean some time looooong ago. */
2001                 its.it_value.tv_sec = 0;
2002                 its.it_value.tv_nsec = 1;
2003         } else
2004                 timespec_store(&its.it_value, t);
2005
2006         r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
2007         if (r < 0)
2008                 return -errno;
2009
2010         d->next = t;
2011         return 0;
2012 }
2013
2014 static int process_io(sd_event *e, sd_event_source *s, uint32_t revents) {
2015         assert(e);
2016         assert(s);
2017         assert(s->type == SOURCE_IO);
2018
2019         /* If the event source was already pending, we just OR in the
2020          * new revents, otherwise we reset the value. The ORing is
2021          * necessary to handle EPOLLONESHOT events properly where
2022          * readability might happen independently of writability, and
2023          * we need to keep track of both */
2024
2025         if (s->pending)
2026                 s->io.revents |= revents;
2027         else
2028                 s->io.revents = revents;
2029
2030         return source_set_pending(s, true);
2031 }
2032
2033 static int flush_timer(sd_event *e, int fd, uint32_t events, usec_t *next) {
2034         uint64_t x;
2035         ssize_t ss;
2036
2037         assert(e);
2038         assert(fd >= 0);
2039
2040         assert_return(events == EPOLLIN, -EIO);
2041
2042         ss = read(fd, &x, sizeof(x));
2043         if (ss < 0) {
2044                 if (errno == EAGAIN || errno == EINTR)
2045                         return 0;
2046
2047                 return -errno;
2048         }
2049
2050         if (_unlikely_(ss != sizeof(x)))
2051                 return -EIO;
2052
2053         if (next)
2054                 *next = USEC_INFINITY;
2055
2056         return 0;
2057 }
2058
2059 static int process_timer(
2060                 sd_event *e,
2061                 usec_t n,
2062                 struct clock_data *d) {
2063
2064         sd_event_source *s;
2065         int r;
2066
2067         assert(e);
2068         assert(d);
2069
2070         for (;;) {
2071                 s = prioq_peek(d->earliest);
2072                 if (!s ||
2073                     s->time.next > n ||
2074                     s->enabled == SD_EVENT_OFF ||
2075                     s->pending)
2076                         break;
2077
2078                 r = source_set_pending(s, true);
2079                 if (r < 0)
2080                         return r;
2081
2082                 prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
2083                 prioq_reshuffle(d->latest, s, &s->time.latest_index);
2084                 d->needs_rearm = true;
2085         }
2086
2087         return 0;
2088 }
2089
2090 static int process_child(sd_event *e) {
2091         sd_event_source *s;
2092         Iterator i;
2093         int r;
2094
2095         assert(e);
2096
2097         e->need_process_child = false;
2098
2099         /*
2100            So, this is ugly. We iteratively invoke waitid() with P_PID
2101            + WNOHANG for each PID we wait for, instead of using
2102            P_ALL. This is because we only want to get child
2103            information of very specific child processes, and not all
2104            of them. We might not have processed the SIGCHLD even of a
2105            previous invocation and we don't want to maintain a
2106            unbounded *per-child* event queue, hence we really don't
2107            want anything flushed out of the kernel's queue that we
2108            don't care about. Since this is O(n) this means that if you
2109            have a lot of processes you probably want to handle SIGCHLD
2110            yourself.
2111
2112            We do not reap the children here (by using WNOWAIT), this
2113            is only done after the event source is dispatched so that
2114            the callback still sees the process as a zombie.
2115         */
2116
2117         HASHMAP_FOREACH(s, e->child_sources, i) {
2118                 assert(s->type == SOURCE_CHILD);
2119
2120                 if (s->pending)
2121                         continue;
2122
2123                 if (s->enabled == SD_EVENT_OFF)
2124                         continue;
2125
2126                 zero(s->child.siginfo);
2127                 r = waitid(P_PID, s->child.pid, &s->child.siginfo,
2128                            WNOHANG | (s->child.options & WEXITED ? WNOWAIT : 0) | s->child.options);
2129                 if (r < 0)
2130                         return -errno;
2131
2132                 if (s->child.siginfo.si_pid != 0) {
2133                         bool zombie =
2134                                 s->child.siginfo.si_code == CLD_EXITED ||
2135                                 s->child.siginfo.si_code == CLD_KILLED ||
2136                                 s->child.siginfo.si_code == CLD_DUMPED;
2137
2138                         if (!zombie && (s->child.options & WEXITED)) {
2139                                 /* If the child isn't dead then let's
2140                                  * immediately remove the state change
2141                                  * from the queue, since there's no
2142                                  * benefit in leaving it queued */
2143
2144                                 assert(s->child.options & (WSTOPPED|WCONTINUED));
2145                                 waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|(s->child.options & (WSTOPPED|WCONTINUED)));
2146                         }
2147
2148                         r = source_set_pending(s, true);
2149                         if (r < 0)
2150                                 return r;
2151                 }
2152         }
2153
2154         return 0;
2155 }
2156
2157 static int process_signal(sd_event *e, struct signal_data *d, uint32_t events) {
2158         bool read_one = false;
2159         int r;
2160
2161         assert(e);
2162         assert_return(events == EPOLLIN, -EIO);
2163
2164         /* If there's a signal queued on this priority and SIGCHLD is
2165            on this priority too, then make sure to recheck the
2166            children we watch. This is because we only ever dequeue
2167            the first signal per priority, and if we dequeue one, and
2168            SIGCHLD might be enqueued later we wouldn't know, but we
2169            might have higher priority children we care about hence we
2170            need to check that explicitly. */
2171
2172         if (sigismember(&d->sigset, SIGCHLD))
2173                 e->need_process_child = true;
2174
2175         /* If there's already an event source pending for this
2176          * priority we don't read another */
2177         if (d->current)
2178                 return 0;
2179
2180         for (;;) {
2181                 struct signalfd_siginfo si;
2182                 ssize_t n;
2183                 sd_event_source *s = NULL;
2184
2185                 n = read(d->fd, &si, sizeof(si));
2186                 if (n < 0) {
2187                         if (errno == EAGAIN || errno == EINTR)
2188                                 return read_one;
2189
2190                         return -errno;
2191                 }
2192
2193                 if (_unlikely_(n != sizeof(si)))
2194                         return -EIO;
2195
2196                 assert(si.ssi_signo < _NSIG);
2197
2198                 read_one = true;
2199
2200                 if (e->signal_sources)
2201                         s = e->signal_sources[si.ssi_signo];
2202                 if (!s)
2203                         continue;
2204                 if (s->pending)
2205                         continue;
2206
2207                 s->signal.siginfo = si;
2208                 d->current = s;
2209
2210                 r = source_set_pending(s, true);
2211                 if (r < 0)
2212                         return r;
2213
2214                 return 1;
2215         }
2216 }
2217
2218 static int source_dispatch(sd_event_source *s) {
2219         int r = 0;
2220
2221         assert(s);
2222         assert(s->pending || s->type == SOURCE_EXIT);
2223
2224         if (s->type != SOURCE_DEFER && s->type != SOURCE_EXIT) {
2225                 r = source_set_pending(s, false);
2226                 if (r < 0)
2227                         return r;
2228         }
2229
2230         if (s->type != SOURCE_POST) {
2231                 sd_event_source *z;
2232                 Iterator i;
2233
2234                 /* If we execute a non-post source, let's mark all
2235                  * post sources as pending */
2236
2237                 SET_FOREACH(z, s->event->post_sources, i) {
2238                         if (z->enabled == SD_EVENT_OFF)
2239                                 continue;
2240
2241                         r = source_set_pending(z, true);
2242                         if (r < 0)
2243                                 return r;
2244                 }
2245         }
2246
2247         if (s->enabled == SD_EVENT_ONESHOT) {
2248                 r = sd_event_source_set_enabled(s, SD_EVENT_OFF);
2249                 if (r < 0)
2250                         return r;
2251         }
2252
2253         s->dispatching = true;
2254
2255         switch (s->type) {
2256
2257         case SOURCE_IO:
2258                 r = s->io.callback(s, s->io.fd, s->io.revents, s->userdata);
2259                 break;
2260
2261         case SOURCE_TIME_REALTIME:
2262         case SOURCE_TIME_BOOTTIME:
2263         case SOURCE_TIME_MONOTONIC:
2264         case SOURCE_TIME_REALTIME_ALARM:
2265         case SOURCE_TIME_BOOTTIME_ALARM:
2266                 r = s->time.callback(s, s->time.next, s->userdata);
2267                 break;
2268
2269         case SOURCE_SIGNAL:
2270                 r = s->signal.callback(s, &s->signal.siginfo, s->userdata);
2271                 break;
2272
2273         case SOURCE_CHILD: {
2274                 bool zombie;
2275
2276                 zombie = s->child.siginfo.si_code == CLD_EXITED ||
2277                          s->child.siginfo.si_code == CLD_KILLED ||
2278                          s->child.siginfo.si_code == CLD_DUMPED;
2279
2280                 r = s->child.callback(s, &s->child.siginfo, s->userdata);
2281
2282                 /* Now, reap the PID for good. */
2283                 if (zombie)
2284                         waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|WEXITED);
2285
2286                 break;
2287         }
2288
2289         case SOURCE_DEFER:
2290                 r = s->defer.callback(s, s->userdata);
2291                 break;
2292
2293         case SOURCE_POST:
2294                 r = s->post.callback(s, s->userdata);
2295                 break;
2296
2297         case SOURCE_EXIT:
2298                 r = s->exit.callback(s, s->userdata);
2299                 break;
2300
2301         case SOURCE_WATCHDOG:
2302         case _SOURCE_EVENT_SOURCE_TYPE_MAX:
2303         case _SOURCE_EVENT_SOURCE_TYPE_INVALID:
2304                 assert_not_reached("Wut? I shouldn't exist.");
2305         }
2306
2307         s->dispatching = false;
2308
2309         if (r < 0) {
2310                 if (s->description)
2311                         log_debug_errno(r, "Event source '%s' returned error, disabling: %m", s->description);
2312                 else
2313                         log_debug_errno(r, "Event source %p returned error, disabling: %m", s);
2314         }
2315
2316         if (s->n_ref == 0)
2317                 source_free(s);
2318         else if (r < 0)
2319                 sd_event_source_set_enabled(s, SD_EVENT_OFF);
2320
2321         return 1;
2322 }
2323
2324 static int event_prepare(sd_event *e) {
2325         int r;
2326
2327         assert(e);
2328
2329         for (;;) {
2330                 sd_event_source *s;
2331
2332                 s = prioq_peek(e->prepare);
2333                 if (!s || s->prepare_iteration == e->iteration || s->enabled == SD_EVENT_OFF)
2334                         break;
2335
2336                 s->prepare_iteration = e->iteration;
2337                 r = prioq_reshuffle(e->prepare, s, &s->prepare_index);
2338                 if (r < 0)
2339                         return r;
2340
2341                 assert(s->prepare);
2342
2343                 s->dispatching = true;
2344                 r = s->prepare(s, s->userdata);
2345                 s->dispatching = false;
2346
2347                 if (r < 0) {
2348                         if (s->description)
2349                                 log_debug_errno(r, "Prepare callback of event source '%s' returned error, disabling: %m", s->description);
2350                         else
2351                                 log_debug_errno(r, "Prepare callback of event source %p returned error, disabling: %m", s);
2352                 }
2353
2354                 if (s->n_ref == 0)
2355                         source_free(s);
2356                 else if (r < 0)
2357                         sd_event_source_set_enabled(s, SD_EVENT_OFF);
2358         }
2359
2360         return 0;
2361 }
2362
2363 static int dispatch_exit(sd_event *e) {
2364         sd_event_source *p;
2365         int r;
2366
2367         assert(e);
2368
2369         p = prioq_peek(e->exit);
2370         if (!p || p->enabled == SD_EVENT_OFF) {
2371                 e->state = SD_EVENT_FINISHED;
2372                 return 0;
2373         }
2374
2375         sd_event_ref(e);
2376         e->iteration++;
2377         e->state = SD_EVENT_EXITING;
2378
2379         r = source_dispatch(p);
2380
2381         e->state = SD_EVENT_INITIAL;
2382         sd_event_unref(e);
2383
2384         return r;
2385 }
2386
2387 static sd_event_source* event_next_pending(sd_event *e) {
2388         sd_event_source *p;
2389
2390         assert(e);
2391
2392         p = prioq_peek(e->pending);
2393         if (!p)
2394                 return NULL;
2395
2396         if (p->enabled == SD_EVENT_OFF)
2397                 return NULL;
2398
2399         return p;
2400 }
2401
2402 static int arm_watchdog(sd_event *e) {
2403         struct itimerspec its = {};
2404         usec_t t;
2405         int r;
2406
2407         assert(e);
2408         assert(e->watchdog_fd >= 0);
2409
2410         t = sleep_between(e,
2411                           e->watchdog_last + (e->watchdog_period / 2),
2412                           e->watchdog_last + (e->watchdog_period * 3 / 4));
2413
2414         timespec_store(&its.it_value, t);
2415
2416         /* Make sure we never set the watchdog to 0, which tells the
2417          * kernel to disable it. */
2418         if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0)
2419                 its.it_value.tv_nsec = 1;
2420
2421         r = timerfd_settime(e->watchdog_fd, TFD_TIMER_ABSTIME, &its, NULL);
2422         if (r < 0)
2423                 return -errno;
2424
2425         return 0;
2426 }
2427
2428 static int process_watchdog(sd_event *e) {
2429         assert(e);
2430
2431         if (!e->watchdog)
2432                 return 0;
2433
2434         /* Don't notify watchdog too often */
2435         if (e->watchdog_last + e->watchdog_period / 4 > e->timestamp.monotonic)
2436                 return 0;
2437
2438         sd_notify(false, "WATCHDOG=1");
2439         e->watchdog_last = e->timestamp.monotonic;
2440
2441         return arm_watchdog(e);
2442 }
2443
2444 _public_ int sd_event_prepare(sd_event *e) {
2445         int r;
2446
2447         assert_return(e, -EINVAL);
2448         assert_return(!event_pid_changed(e), -ECHILD);
2449         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2450         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
2451
2452         if (e->exit_requested)
2453                 goto pending;
2454
2455         e->iteration++;
2456
2457         e->state = SD_EVENT_PREPARING;
2458         r = event_prepare(e);
2459         e->state = SD_EVENT_INITIAL;
2460         if (r < 0)
2461                 return r;
2462
2463         r = event_arm_timer(e, &e->realtime);
2464         if (r < 0)
2465                 return r;
2466
2467         r = event_arm_timer(e, &e->boottime);
2468         if (r < 0)
2469                 return r;
2470
2471         r = event_arm_timer(e, &e->monotonic);
2472         if (r < 0)
2473                 return r;
2474
2475         r = event_arm_timer(e, &e->realtime_alarm);
2476         if (r < 0)
2477                 return r;
2478
2479         r = event_arm_timer(e, &e->boottime_alarm);
2480         if (r < 0)
2481                 return r;
2482
2483         if (event_next_pending(e) || e->need_process_child)
2484                 goto pending;
2485
2486         e->state = SD_EVENT_ARMED;
2487
2488         return 0;
2489
2490 pending:
2491         e->state = SD_EVENT_ARMED;
2492         r = sd_event_wait(e, 0);
2493         if (r == 0)
2494                 e->state = SD_EVENT_ARMED;
2495
2496         return r;
2497 }
2498
2499 _public_ int sd_event_wait(sd_event *e, uint64_t timeout) {
2500         struct epoll_event *ev_queue;
2501         unsigned ev_queue_max;
2502         int r, m, i;
2503
2504         assert_return(e, -EINVAL);
2505         assert_return(!event_pid_changed(e), -ECHILD);
2506         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2507         assert_return(e->state == SD_EVENT_ARMED, -EBUSY);
2508
2509         if (e->exit_requested) {
2510                 e->state = SD_EVENT_PENDING;
2511                 return 1;
2512         }
2513
2514         ev_queue_max = MAX(e->n_sources, 1u);
2515         ev_queue = newa(struct epoll_event, ev_queue_max);
2516
2517         m = epoll_wait(e->epoll_fd, ev_queue, ev_queue_max,
2518                        timeout == (uint64_t) -1 ? -1 : (int) ((timeout + USEC_PER_MSEC - 1) / USEC_PER_MSEC));
2519         if (m < 0) {
2520                 if (errno == EINTR) {
2521                         e->state = SD_EVENT_PENDING;
2522                         return 1;
2523                 }
2524
2525                 r = -errno;
2526                 goto finish;
2527         }
2528
2529         dual_timestamp_get(&e->timestamp);
2530         e->timestamp_boottime = now(CLOCK_BOOTTIME);
2531
2532         for (i = 0; i < m; i++) {
2533
2534                 if (ev_queue[i].data.ptr == INT_TO_PTR(SOURCE_WATCHDOG))
2535                         r = flush_timer(e, e->watchdog_fd, ev_queue[i].events, NULL);
2536                 else {
2537                         WakeupType *t = ev_queue[i].data.ptr;
2538
2539                         switch (*t) {
2540
2541                         case WAKEUP_EVENT_SOURCE:
2542                         r = process_io(e, ev_queue[i].data.ptr, ev_queue[i].events);
2543                                 break;
2544
2545                         case WAKEUP_CLOCK_DATA: {
2546                                 struct clock_data *d = ev_queue[i].data.ptr;
2547                                 r = flush_timer(e, d->fd, ev_queue[i].events, &d->next);
2548                                 break;
2549                         }
2550
2551                         case WAKEUP_SIGNAL_DATA:
2552                                 r = process_signal(e, ev_queue[i].data.ptr, ev_queue[i].events);
2553                                 break;
2554
2555                         default:
2556                                 assert_not_reached("Invalid wake-up pointer");
2557                         }
2558                 }
2559                 if (r < 0)
2560                         goto finish;
2561         }
2562
2563         r = process_watchdog(e);
2564         if (r < 0)
2565                 goto finish;
2566
2567         r = process_timer(e, e->timestamp.realtime, &e->realtime);
2568         if (r < 0)
2569                 goto finish;
2570
2571         r = process_timer(e, e->timestamp_boottime, &e->boottime);
2572         if (r < 0)
2573                 goto finish;
2574
2575         r = process_timer(e, e->timestamp.monotonic, &e->monotonic);
2576         if (r < 0)
2577                 goto finish;
2578
2579         r = process_timer(e, e->timestamp.realtime, &e->realtime_alarm);
2580         if (r < 0)
2581                 goto finish;
2582
2583         r = process_timer(e, e->timestamp_boottime, &e->boottime_alarm);
2584         if (r < 0)
2585                 goto finish;
2586
2587         if (e->need_process_child) {
2588                 r = process_child(e);
2589                 if (r < 0)
2590                         goto finish;
2591         }
2592
2593         if (event_next_pending(e)) {
2594                 e->state = SD_EVENT_PENDING;
2595
2596                 return 1;
2597         }
2598
2599         r = 0;
2600
2601 finish:
2602         e->state = SD_EVENT_INITIAL;
2603
2604         return r;
2605 }
2606
2607 _public_ int sd_event_dispatch(sd_event *e) {
2608         sd_event_source *p;
2609         int r;
2610
2611         assert_return(e, -EINVAL);
2612         assert_return(!event_pid_changed(e), -ECHILD);
2613         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2614         assert_return(e->state == SD_EVENT_PENDING, -EBUSY);
2615
2616         if (e->exit_requested)
2617                 return dispatch_exit(e);
2618
2619         p = event_next_pending(e);
2620         if (p) {
2621                 sd_event_ref(e);
2622
2623                 e->state = SD_EVENT_RUNNING;
2624                 r = source_dispatch(p);
2625                 e->state = SD_EVENT_INITIAL;
2626
2627                 sd_event_unref(e);
2628
2629                 return r;
2630         }
2631
2632         e->state = SD_EVENT_INITIAL;
2633
2634         return 1;
2635 }
2636
2637 static void event_log_delays(sd_event *e) {
2638         char b[ELEMENTSOF(e->delays) * DECIMAL_STR_MAX(unsigned) + 1];
2639         int i, o;
2640
2641         for (i = o = 0; i < ELEMENTSOF(e->delays); i++) {
2642                 o += snprintf(&b[o], sizeof(b) - o, "%u ", e->delays[i]);
2643                 e->delays[i] = 0;
2644         }
2645         log_info("Event loop iterations: %.*s", o, b);
2646 }
2647
2648 _public_ int sd_event_run(sd_event *e, uint64_t timeout) {
2649         int r;
2650
2651         assert_return(e, -EINVAL);
2652         assert_return(!event_pid_changed(e), -ECHILD);
2653         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2654         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
2655
2656         if (e->profile_delays && e->last_run) {
2657                 usec_t this_run;
2658                 unsigned l;
2659
2660                 this_run = now(CLOCK_MONOTONIC);
2661
2662                 l = u64log2(this_run - e->last_run);
2663                 assert(l < sizeof(e->delays));
2664                 e->delays[l]++;
2665
2666                 if (this_run - e->last_log >= 5*USEC_PER_SEC) {
2667                         event_log_delays(e);
2668                         e->last_log = this_run;
2669                 }
2670         }
2671
2672         r = sd_event_prepare(e);
2673         if (r == 0)
2674                 /* There was nothing? Then wait... */
2675                 r = sd_event_wait(e, timeout);
2676
2677         if (e->profile_delays)
2678                 e->last_run = now(CLOCK_MONOTONIC);
2679
2680         if (r > 0) {
2681                 /* There's something now, then let's dispatch it */
2682                 r = sd_event_dispatch(e);
2683                 if (r < 0)
2684                         return r;
2685
2686                 return 1;
2687         }
2688
2689         return r;
2690 }
2691
2692 #if 0 /// UNNEEDED by elogind
2693 _public_ int sd_event_loop(sd_event *e) {
2694         int r;
2695
2696         assert_return(e, -EINVAL);
2697         assert_return(!event_pid_changed(e), -ECHILD);
2698         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
2699
2700         sd_event_ref(e);
2701
2702         while (e->state != SD_EVENT_FINISHED) {
2703                 r = sd_event_run(e, (uint64_t) -1);
2704                 if (r < 0)
2705                         goto finish;
2706         }
2707
2708         r = e->exit_code;
2709
2710 finish:
2711         sd_event_unref(e);
2712         return r;
2713 }
2714
2715 _public_ int sd_event_get_fd(sd_event *e) {
2716
2717         assert_return(e, -EINVAL);
2718         assert_return(!event_pid_changed(e), -ECHILD);
2719
2720         return e->epoll_fd;
2721 }
2722 #endif // 0
2723
2724 _public_ int sd_event_get_state(sd_event *e) {
2725         assert_return(e, -EINVAL);
2726         assert_return(!event_pid_changed(e), -ECHILD);
2727
2728         return e->state;
2729 }
2730
2731 #if 0 /// UNNEEDED by elogind
2732 _public_ int sd_event_get_exit_code(sd_event *e, int *code) {
2733         assert_return(e, -EINVAL);
2734         assert_return(code, -EINVAL);
2735         assert_return(!event_pid_changed(e), -ECHILD);
2736
2737         if (!e->exit_requested)
2738                 return -ENODATA;
2739
2740         *code = e->exit_code;
2741         return 0;
2742 }
2743 #endif // 0
2744
2745 _public_ int sd_event_exit(sd_event *e, int code) {
2746         assert_return(e, -EINVAL);
2747         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2748         assert_return(!event_pid_changed(e), -ECHILD);
2749
2750         e->exit_requested = true;
2751         e->exit_code = code;
2752
2753         return 0;
2754 }
2755
2756 #if 0 /// UNNEEDED by elogind
2757 _public_ int sd_event_now(sd_event *e, clockid_t clock, uint64_t *usec) {
2758         assert_return(e, -EINVAL);
2759         assert_return(usec, -EINVAL);
2760         assert_return(!event_pid_changed(e), -ECHILD);
2761
2762         if (!dual_timestamp_is_set(&e->timestamp)) {
2763                 /* Implicitly fall back to now() if we never ran
2764                  * before and thus have no cached time. */
2765                 *usec = now(clock);
2766                 return 1;
2767         }
2768
2769         switch (clock) {
2770
2771         case CLOCK_REALTIME:
2772         case CLOCK_REALTIME_ALARM:
2773                 *usec = e->timestamp.realtime;
2774                 break;
2775
2776         case CLOCK_MONOTONIC:
2777                 *usec = e->timestamp.monotonic;
2778                 break;
2779
2780         case CLOCK_BOOTTIME:
2781         case CLOCK_BOOTTIME_ALARM:
2782                 *usec = e->timestamp_boottime;
2783                 break;
2784         }
2785
2786         return 0;
2787 }
2788 #endif // 0
2789
2790 _public_ int sd_event_default(sd_event **ret) {
2791
2792         static thread_local sd_event *default_event = NULL;
2793         sd_event *e = NULL;
2794         int r;
2795
2796         if (!ret)
2797                 return !!default_event;
2798
2799         if (default_event) {
2800                 *ret = sd_event_ref(default_event);
2801                 return 0;
2802         }
2803
2804         r = sd_event_new(&e);
2805         if (r < 0)
2806                 return r;
2807
2808         e->default_event_ptr = &default_event;
2809         e->tid = gettid();
2810         default_event = e;
2811
2812         *ret = e;
2813         return 1;
2814 }
2815
2816 #if 0 /// UNNEEDED by elogind
2817 _public_ int sd_event_get_tid(sd_event *e, pid_t *tid) {
2818         assert_return(e, -EINVAL);
2819         assert_return(tid, -EINVAL);
2820         assert_return(!event_pid_changed(e), -ECHILD);
2821
2822         if (e->tid != 0) {
2823                 *tid = e->tid;
2824                 return 0;
2825         }
2826
2827         return -ENXIO;
2828 }
2829 #endif // 0
2830
2831 _public_ int sd_event_set_watchdog(sd_event *e, int b) {
2832         int r;
2833
2834         assert_return(e, -EINVAL);
2835         assert_return(!event_pid_changed(e), -ECHILD);
2836
2837         if (e->watchdog == !!b)
2838                 return e->watchdog;
2839
2840         if (b) {
2841                 struct epoll_event ev = {};
2842
2843                 r = sd_watchdog_enabled(false, &e->watchdog_period);
2844                 if (r <= 0)
2845                         return r;
2846
2847                 /* Issue first ping immediately */
2848                 sd_notify(false, "WATCHDOG=1");
2849                 e->watchdog_last = now(CLOCK_MONOTONIC);
2850
2851                 e->watchdog_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
2852                 if (e->watchdog_fd < 0)
2853                         return -errno;
2854
2855                 r = arm_watchdog(e);
2856                 if (r < 0)
2857                         goto fail;
2858
2859                 ev.events = EPOLLIN;
2860                 ev.data.ptr = INT_TO_PTR(SOURCE_WATCHDOG);
2861
2862                 r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, e->watchdog_fd, &ev);
2863                 if (r < 0) {
2864                         r = -errno;
2865                         goto fail;
2866                 }
2867
2868         } else {
2869                 if (e->watchdog_fd >= 0) {
2870                         epoll_ctl(e->epoll_fd, EPOLL_CTL_DEL, e->watchdog_fd, NULL);
2871                         e->watchdog_fd = safe_close(e->watchdog_fd);
2872                 }
2873         }
2874
2875         e->watchdog = !!b;
2876         return e->watchdog;
2877
2878 fail:
2879         e->watchdog_fd = safe_close(e->watchdog_fd);
2880         return r;
2881 }
2882
2883 #if 0 /// UNNEEDED by elogind
2884 _public_ int sd_event_get_watchdog(sd_event *e) {
2885         assert_return(e, -EINVAL);
2886         assert_return(!event_pid_changed(e), -ECHILD);
2887
2888         return e->watchdog;
2889 }
2890 #endif // 0