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