chiark / gitweb /
cfd5a55457758a7ceadd8ab9d0299af6f7920926
[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                 safe_close(d->fd);
736                 free(d);
737                 return;
738         }
739
740         assert(d->fd >= 0);
741
742         if (signalfd(d->fd, &d->sigset, SFD_NONBLOCK|SFD_CLOEXEC) < 0)
743                 log_debug_errno(errno, "Failed to unset signal bit, ignoring: %m");
744 }
745
746 static void event_gc_signal_data(sd_event *e, const int64_t *priority, int sig) {
747         struct signal_data *d;
748         static const int64_t zero_priority = 0;
749
750         assert(e);
751
752         /* Rechecks if the specified signal is still something we are
753          * interested in. If not, we'll unmask it, and possibly drop
754          * the signalfd for it. */
755
756         if (sig == SIGCHLD &&
757             e->n_enabled_child_sources > 0)
758                 return;
759
760         if (e->signal_sources &&
761             e->signal_sources[sig] &&
762             e->signal_sources[sig]->enabled != SD_EVENT_OFF)
763                 return;
764
765         /*
766          * The specified signal might be enabled in three different queues:
767          *
768          * 1) the one that belongs to the priority passed (if it is non-NULL)
769          * 2) the one that belongs to the priority of the event source of the signal (if there is one)
770          * 3) the 0 priority (to cover the SIGCHLD case)
771          *
772          * Hence, let's remove it from all three here.
773          */
774
775         if (priority) {
776                 d = hashmap_get(e->signal_data, priority);
777                 if (d)
778                         event_unmask_signal_data(e, d, sig);
779         }
780
781         if (e->signal_sources && e->signal_sources[sig]) {
782                 d = hashmap_get(e->signal_data, &e->signal_sources[sig]->priority);
783                 if (d)
784                         event_unmask_signal_data(e, d, sig);
785         }
786
787         d = hashmap_get(e->signal_data, &zero_priority);
788         if (d)
789                 event_unmask_signal_data(e, d, sig);
790 }
791
792 static void source_disconnect(sd_event_source *s) {
793         sd_event *event;
794
795         assert(s);
796
797         if (!s->event)
798                 return;
799
800         assert(s->event->n_sources > 0);
801
802         switch (s->type) {
803
804         case SOURCE_IO:
805                 if (s->io.fd >= 0)
806                         source_io_unregister(s);
807
808                 break;
809
810         case SOURCE_TIME_REALTIME:
811         case SOURCE_TIME_BOOTTIME:
812         case SOURCE_TIME_MONOTONIC:
813         case SOURCE_TIME_REALTIME_ALARM:
814         case SOURCE_TIME_BOOTTIME_ALARM: {
815                 struct clock_data *d;
816
817                 d = event_get_clock_data(s->event, s->type);
818                 assert(d);
819
820                 prioq_remove(d->earliest, s, &s->time.earliest_index);
821                 prioq_remove(d->latest, s, &s->time.latest_index);
822                 d->needs_rearm = true;
823                 break;
824         }
825
826         case SOURCE_SIGNAL:
827                 if (s->signal.sig > 0) {
828
829                         if (s->event->signal_sources)
830                                 s->event->signal_sources[s->signal.sig] = NULL;
831
832                         event_gc_signal_data(s->event, &s->priority, s->signal.sig);
833                 }
834
835                 break;
836
837         case SOURCE_CHILD:
838                 if (s->child.pid > 0) {
839                         if (s->enabled != SD_EVENT_OFF) {
840                                 assert(s->event->n_enabled_child_sources > 0);
841                                 s->event->n_enabled_child_sources--;
842                         }
843
844                         (void) hashmap_remove(s->event->child_sources, PID_TO_PTR(s->child.pid));
845                         event_gc_signal_data(s->event, &s->priority, SIGCHLD);
846                 }
847
848                 break;
849
850         case SOURCE_DEFER:
851                 /* nothing */
852                 break;
853
854         case SOURCE_POST:
855                 set_remove(s->event->post_sources, s);
856                 break;
857
858         case SOURCE_EXIT:
859                 prioq_remove(s->event->exit, s, &s->exit.prioq_index);
860                 break;
861
862         default:
863                 assert_not_reached("Wut? I shouldn't exist.");
864         }
865
866         if (s->pending)
867                 prioq_remove(s->event->pending, s, &s->pending_index);
868
869         if (s->prepare)
870                 prioq_remove(s->event->prepare, s, &s->prepare_index);
871
872         event = s->event;
873
874         s->type = _SOURCE_EVENT_SOURCE_TYPE_INVALID;
875         s->event = NULL;
876         LIST_REMOVE(sources, event->sources, s);
877         event->n_sources--;
878
879         if (!s->floating)
880                 sd_event_unref(event);
881 }
882
883 static void source_free(sd_event_source *s) {
884         assert(s);
885
886         source_disconnect(s);
887         free(s->description);
888         free(s);
889 }
890
891 static int source_set_pending(sd_event_source *s, bool b) {
892         int r;
893
894         assert(s);
895         assert(s->type != SOURCE_EXIT);
896
897         if (s->pending == b)
898                 return 0;
899
900         s->pending = b;
901
902         if (b) {
903                 s->pending_iteration = s->event->iteration;
904
905                 r = prioq_put(s->event->pending, s, &s->pending_index);
906                 if (r < 0) {
907                         s->pending = false;
908                         return r;
909                 }
910         } else
911                 assert_se(prioq_remove(s->event->pending, s, &s->pending_index));
912
913         if (EVENT_SOURCE_IS_TIME(s->type)) {
914                 struct clock_data *d;
915
916                 d = event_get_clock_data(s->event, s->type);
917                 assert(d);
918
919                 prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
920                 prioq_reshuffle(d->latest, s, &s->time.latest_index);
921                 d->needs_rearm = true;
922         }
923
924         if (s->type == SOURCE_SIGNAL && !b) {
925                 struct signal_data *d;
926
927                 d = hashmap_get(s->event->signal_data, &s->priority);
928                 if (d && d->current == s)
929                         d->current = NULL;
930         }
931
932         return 0;
933 }
934
935 static sd_event_source *source_new(sd_event *e, bool floating, EventSourceType type) {
936         sd_event_source *s;
937
938         assert(e);
939
940         s = new0(sd_event_source, 1);
941         if (!s)
942                 return NULL;
943
944         s->n_ref = 1;
945         s->event = e;
946         s->floating = floating;
947         s->type = type;
948         s->pending_index = s->prepare_index = PRIOQ_IDX_NULL;
949
950         if (!floating)
951                 sd_event_ref(e);
952
953         LIST_PREPEND(sources, e->sources, s);
954         e->n_sources++;
955
956         return s;
957 }
958
959 _public_ int sd_event_add_io(
960                 sd_event *e,
961                 sd_event_source **ret,
962                 int fd,
963                 uint32_t events,
964                 sd_event_io_handler_t callback,
965                 void *userdata) {
966
967         sd_event_source *s;
968         int r;
969
970         assert_return(e, -EINVAL);
971         assert_return(fd >= 0, -EBADF);
972         assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
973         assert_return(callback, -EINVAL);
974         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
975         assert_return(!event_pid_changed(e), -ECHILD);
976
977         s = source_new(e, !ret, SOURCE_IO);
978         if (!s)
979                 return -ENOMEM;
980
981         s->wakeup = WAKEUP_EVENT_SOURCE;
982         s->io.fd = fd;
983         s->io.events = events;
984         s->io.callback = callback;
985         s->userdata = userdata;
986         s->enabled = SD_EVENT_ON;
987
988         r = source_io_register(s, s->enabled, events);
989         if (r < 0) {
990                 source_free(s);
991                 return r;
992         }
993
994         if (ret)
995                 *ret = s;
996
997         return 0;
998 }
999
1000 static void initialize_perturb(sd_event *e) {
1001         sd_id128_t bootid = {};
1002
1003         /* When we sleep for longer, we try to realign the wakeup to
1004            the same time wihtin each minute/second/250ms, so that
1005            events all across the system can be coalesced into a single
1006            CPU wakeup. However, let's take some system-specific
1007            randomness for this value, so that in a network of systems
1008            with synced clocks timer events are distributed a
1009            bit. Here, we calculate a perturbation usec offset from the
1010            boot ID. */
1011
1012         if (_likely_(e->perturb != USEC_INFINITY))
1013                 return;
1014
1015         if (sd_id128_get_boot(&bootid) >= 0)
1016                 e->perturb = (bootid.qwords[0] ^ bootid.qwords[1]) % USEC_PER_MINUTE;
1017 }
1018
1019 static int event_setup_timer_fd(
1020                 sd_event *e,
1021                 struct clock_data *d,
1022                 clockid_t clock) {
1023
1024         struct epoll_event ev = {};
1025         int r, fd;
1026
1027         assert(e);
1028         assert(d);
1029
1030         if (_likely_(d->fd >= 0))
1031                 return 0;
1032
1033         fd = timerfd_create(clock, TFD_NONBLOCK|TFD_CLOEXEC);
1034         if (fd < 0)
1035                 return -errno;
1036
1037         ev.events = EPOLLIN;
1038         ev.data.ptr = d;
1039
1040         r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, fd, &ev);
1041         if (r < 0) {
1042                 safe_close(fd);
1043                 return -errno;
1044         }
1045
1046         d->fd = fd;
1047         return 0;
1048 }
1049
1050 static int time_exit_callback(sd_event_source *s, uint64_t usec, void *userdata) {
1051         assert(s);
1052
1053         return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1054 }
1055
1056 _public_ int sd_event_add_time(
1057                 sd_event *e,
1058                 sd_event_source **ret,
1059                 clockid_t clock,
1060                 uint64_t usec,
1061                 uint64_t accuracy,
1062                 sd_event_time_handler_t callback,
1063                 void *userdata) {
1064
1065         EventSourceType type;
1066         sd_event_source *s;
1067         struct clock_data *d;
1068         int r;
1069
1070         assert_return(e, -EINVAL);
1071         assert_return(accuracy != (uint64_t) -1, -EINVAL);
1072         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1073         assert_return(!event_pid_changed(e), -ECHILD);
1074
1075         if (!clock_supported(clock)) /* Checks whether the kernel supports the clock */
1076                 return -EOPNOTSUPP;
1077
1078         type = clock_to_event_source_type(clock); /* checks whether sd-event supports this clock */
1079         if (type < 0)
1080                 return -EOPNOTSUPP;
1081
1082         if (!callback)
1083                 callback = time_exit_callback;
1084
1085         d = event_get_clock_data(e, type);
1086         assert(d);
1087
1088         r = prioq_ensure_allocated(&d->earliest, earliest_time_prioq_compare);
1089         if (r < 0)
1090                 return r;
1091
1092         r = prioq_ensure_allocated(&d->latest, latest_time_prioq_compare);
1093         if (r < 0)
1094                 return r;
1095
1096         if (d->fd < 0) {
1097                 r = event_setup_timer_fd(e, d, clock);
1098                 if (r < 0)
1099                         return r;
1100         }
1101
1102         s = source_new(e, !ret, type);
1103         if (!s)
1104                 return -ENOMEM;
1105
1106         s->time.next = usec;
1107         s->time.accuracy = accuracy == 0 ? DEFAULT_ACCURACY_USEC : accuracy;
1108         s->time.callback = callback;
1109         s->time.earliest_index = s->time.latest_index = PRIOQ_IDX_NULL;
1110         s->userdata = userdata;
1111         s->enabled = SD_EVENT_ONESHOT;
1112
1113         d->needs_rearm = true;
1114
1115         r = prioq_put(d->earliest, s, &s->time.earliest_index);
1116         if (r < 0)
1117                 goto fail;
1118
1119         r = prioq_put(d->latest, s, &s->time.latest_index);
1120         if (r < 0)
1121                 goto fail;
1122
1123         if (ret)
1124                 *ret = s;
1125
1126         return 0;
1127
1128 fail:
1129         source_free(s);
1130         return r;
1131 }
1132
1133 static int signal_exit_callback(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1134         assert(s);
1135
1136         return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1137 }
1138
1139 _public_ int sd_event_add_signal(
1140                 sd_event *e,
1141                 sd_event_source **ret,
1142                 int sig,
1143                 sd_event_signal_handler_t callback,
1144                 void *userdata) {
1145
1146         sd_event_source *s;
1147         struct signal_data *d;
1148         sigset_t ss;
1149         int r;
1150
1151         assert_return(e, -EINVAL);
1152         assert_return(SIGNAL_VALID(sig), -EINVAL);
1153         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1154         assert_return(!event_pid_changed(e), -ECHILD);
1155
1156         if (!callback)
1157                 callback = signal_exit_callback;
1158
1159         r = pthread_sigmask(SIG_SETMASK, NULL, &ss);
1160         if (r != 0)
1161                 return -r;
1162
1163         if (!sigismember(&ss, sig))
1164                 return -EBUSY;
1165
1166         if (!e->signal_sources) {
1167                 e->signal_sources = new0(sd_event_source*, _NSIG);
1168                 if (!e->signal_sources)
1169                         return -ENOMEM;
1170         } else if (e->signal_sources[sig])
1171                 return -EBUSY;
1172
1173         s = source_new(e, !ret, SOURCE_SIGNAL);
1174         if (!s)
1175                 return -ENOMEM;
1176
1177         s->signal.sig = sig;
1178         s->signal.callback = callback;
1179         s->userdata = userdata;
1180         s->enabled = SD_EVENT_ON;
1181
1182         e->signal_sources[sig] = s;
1183
1184         r = event_make_signal_data(e, sig, &d);
1185         if (r < 0) {
1186                 source_free(s);
1187                 return r;
1188         }
1189
1190         /* Use the signal name as description for the event source by default */
1191         (void) sd_event_source_set_description(s, signal_to_string(sig));
1192
1193         if (ret)
1194                 *ret = s;
1195
1196         return 0;
1197 }
1198
1199 #if 0 /// UNNEEDED by elogind
1200 _public_ int sd_event_add_child(
1201                 sd_event *e,
1202                 sd_event_source **ret,
1203                 pid_t pid,
1204                 int options,
1205                 sd_event_child_handler_t callback,
1206                 void *userdata) {
1207
1208         sd_event_source *s;
1209         int r;
1210
1211         assert_return(e, -EINVAL);
1212         assert_return(pid > 1, -EINVAL);
1213         assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED)), -EINVAL);
1214         assert_return(options != 0, -EINVAL);
1215         assert_return(callback, -EINVAL);
1216         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1217         assert_return(!event_pid_changed(e), -ECHILD);
1218
1219         r = hashmap_ensure_allocated(&e->child_sources, NULL);
1220         if (r < 0)
1221                 return r;
1222
1223         if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
1224                 return -EBUSY;
1225
1226         s = source_new(e, !ret, SOURCE_CHILD);
1227         if (!s)
1228                 return -ENOMEM;
1229
1230         s->child.pid = pid;
1231         s->child.options = options;
1232         s->child.callback = callback;
1233         s->userdata = userdata;
1234         s->enabled = SD_EVENT_ONESHOT;
1235
1236         r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
1237         if (r < 0) {
1238                 source_free(s);
1239                 return r;
1240         }
1241
1242         e->n_enabled_child_sources++;
1243
1244         r = event_make_signal_data(e, SIGCHLD, NULL);
1245         if (r < 0) {
1246                 e->n_enabled_child_sources--;
1247                 source_free(s);
1248                 return r;
1249         }
1250
1251         e->need_process_child = true;
1252
1253         if (ret)
1254                 *ret = s;
1255
1256         return 0;
1257 }
1258
1259 _public_ int sd_event_add_defer(
1260                 sd_event *e,
1261                 sd_event_source **ret,
1262                 sd_event_handler_t callback,
1263                 void *userdata) {
1264
1265         sd_event_source *s;
1266         int r;
1267
1268         assert_return(e, -EINVAL);
1269         assert_return(callback, -EINVAL);
1270         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1271         assert_return(!event_pid_changed(e), -ECHILD);
1272
1273         s = source_new(e, !ret, SOURCE_DEFER);
1274         if (!s)
1275                 return -ENOMEM;
1276
1277         s->defer.callback = callback;
1278         s->userdata = userdata;
1279         s->enabled = SD_EVENT_ONESHOT;
1280
1281         r = source_set_pending(s, true);
1282         if (r < 0) {
1283                 source_free(s);
1284                 return r;
1285         }
1286
1287         if (ret)
1288                 *ret = s;
1289
1290         return 0;
1291 }
1292 #endif // 0
1293
1294 _public_ int sd_event_add_post(
1295                 sd_event *e,
1296                 sd_event_source **ret,
1297                 sd_event_handler_t callback,
1298                 void *userdata) {
1299
1300         sd_event_source *s;
1301         int r;
1302
1303         assert_return(e, -EINVAL);
1304         assert_return(callback, -EINVAL);
1305         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1306         assert_return(!event_pid_changed(e), -ECHILD);
1307
1308         r = set_ensure_allocated(&e->post_sources, NULL);
1309         if (r < 0)
1310                 return r;
1311
1312         s = source_new(e, !ret, SOURCE_POST);
1313         if (!s)
1314                 return -ENOMEM;
1315
1316         s->post.callback = callback;
1317         s->userdata = userdata;
1318         s->enabled = SD_EVENT_ON;
1319
1320         r = set_put(e->post_sources, s);
1321         if (r < 0) {
1322                 source_free(s);
1323                 return r;
1324         }
1325
1326         if (ret)
1327                 *ret = s;
1328
1329         return 0;
1330 }
1331
1332 _public_ int sd_event_add_exit(
1333                 sd_event *e,
1334                 sd_event_source **ret,
1335                 sd_event_handler_t callback,
1336                 void *userdata) {
1337
1338         sd_event_source *s;
1339         int r;
1340
1341         assert_return(e, -EINVAL);
1342         assert_return(callback, -EINVAL);
1343         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1344         assert_return(!event_pid_changed(e), -ECHILD);
1345
1346         r = prioq_ensure_allocated(&e->exit, exit_prioq_compare);
1347         if (r < 0)
1348                 return r;
1349
1350         s = source_new(e, !ret, SOURCE_EXIT);
1351         if (!s)
1352                 return -ENOMEM;
1353
1354         s->exit.callback = callback;
1355         s->userdata = userdata;
1356         s->exit.prioq_index = PRIOQ_IDX_NULL;
1357         s->enabled = SD_EVENT_ONESHOT;
1358
1359         r = prioq_put(s->event->exit, s, &s->exit.prioq_index);
1360         if (r < 0) {
1361                 source_free(s);
1362                 return r;
1363         }
1364
1365         if (ret)
1366                 *ret = s;
1367
1368         return 0;
1369 }
1370
1371 #if 0 /// UNNEEDED by elogind
1372 _public_ sd_event_source* sd_event_source_ref(sd_event_source *s) {
1373
1374         if (!s)
1375                 return NULL;
1376
1377         assert(s->n_ref >= 1);
1378         s->n_ref++;
1379
1380         return s;
1381 }
1382 #endif // 0
1383
1384 _public_ sd_event_source* sd_event_source_unref(sd_event_source *s) {
1385
1386         if (!s)
1387                 return NULL;
1388
1389         assert(s->n_ref >= 1);
1390         s->n_ref--;
1391
1392         if (s->n_ref <= 0) {
1393                 /* Here's a special hack: when we are called from a
1394                  * dispatch handler we won't free the event source
1395                  * immediately, but we will detach the fd from the
1396                  * epoll. This way it is safe for the caller to unref
1397                  * the event source and immediately close the fd, but
1398                  * we still retain a valid event source object after
1399                  * the callback. */
1400
1401                 if (s->dispatching) {
1402                         if (s->type == SOURCE_IO)
1403                                 source_io_unregister(s);
1404
1405                         source_disconnect(s);
1406                 } else
1407                         source_free(s);
1408         }
1409
1410         return NULL;
1411 }
1412
1413 _public_ int sd_event_source_set_description(sd_event_source *s, const char *description) {
1414         assert_return(s, -EINVAL);
1415         assert_return(!event_pid_changed(s->event), -ECHILD);
1416
1417         return free_and_strdup(&s->description, description);
1418 }
1419
1420 #if 0 /// UNNEEDED by elogind
1421 _public_ int sd_event_source_get_description(sd_event_source *s, const char **description) {
1422         assert_return(s, -EINVAL);
1423         assert_return(description, -EINVAL);
1424         assert_return(s->description, -ENXIO);
1425         assert_return(!event_pid_changed(s->event), -ECHILD);
1426
1427         *description = s->description;
1428         return 0;
1429 }
1430 #endif // 0
1431
1432 _public_ sd_event *sd_event_source_get_event(sd_event_source *s) {
1433         assert_return(s, NULL);
1434
1435         return s->event;
1436 }
1437
1438 #if 0 /// UNNEEDED by elogind
1439 _public_ int sd_event_source_get_pending(sd_event_source *s) {
1440         assert_return(s, -EINVAL);
1441         assert_return(s->type != SOURCE_EXIT, -EDOM);
1442         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1443         assert_return(!event_pid_changed(s->event), -ECHILD);
1444
1445         return s->pending;
1446 }
1447
1448 _public_ int sd_event_source_get_io_fd(sd_event_source *s) {
1449         assert_return(s, -EINVAL);
1450         assert_return(s->type == SOURCE_IO, -EDOM);
1451         assert_return(!event_pid_changed(s->event), -ECHILD);
1452
1453         return s->io.fd;
1454 }
1455 #endif // 0
1456
1457 _public_ int sd_event_source_set_io_fd(sd_event_source *s, int fd) {
1458         int r;
1459
1460         assert_return(s, -EINVAL);
1461         assert_return(fd >= 0, -EBADF);
1462         assert_return(s->type == SOURCE_IO, -EDOM);
1463         assert_return(!event_pid_changed(s->event), -ECHILD);
1464
1465         if (s->io.fd == fd)
1466                 return 0;
1467
1468         if (s->enabled == SD_EVENT_OFF) {
1469                 s->io.fd = fd;
1470                 s->io.registered = false;
1471         } else {
1472                 int saved_fd;
1473
1474                 saved_fd = s->io.fd;
1475                 assert(s->io.registered);
1476
1477                 s->io.fd = fd;
1478                 s->io.registered = false;
1479
1480                 r = source_io_register(s, s->enabled, s->io.events);
1481                 if (r < 0) {
1482                         s->io.fd = saved_fd;
1483                         s->io.registered = true;
1484                         return r;
1485                 }
1486
1487                 epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, saved_fd, NULL);
1488         }
1489
1490         return 0;
1491 }
1492
1493 #if 0 /// UNNEEDED by elogind
1494 _public_ int sd_event_source_get_io_events(sd_event_source *s, uint32_t* events) {
1495         assert_return(s, -EINVAL);
1496         assert_return(events, -EINVAL);
1497         assert_return(s->type == SOURCE_IO, -EDOM);
1498         assert_return(!event_pid_changed(s->event), -ECHILD);
1499
1500         *events = s->io.events;
1501         return 0;
1502 }
1503 #endif // 0
1504
1505 _public_ int sd_event_source_set_io_events(sd_event_source *s, uint32_t events) {
1506         int r;
1507
1508         assert_return(s, -EINVAL);
1509         assert_return(s->type == SOURCE_IO, -EDOM);
1510         assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
1511         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1512         assert_return(!event_pid_changed(s->event), -ECHILD);
1513
1514         /* edge-triggered updates are never skipped, so we can reset edges */
1515         if (s->io.events == events && !(events & EPOLLET))
1516                 return 0;
1517
1518         if (s->enabled != SD_EVENT_OFF) {
1519                 r = source_io_register(s, s->enabled, events);
1520                 if (r < 0)
1521                         return r;
1522         }
1523
1524         s->io.events = events;
1525         source_set_pending(s, false);
1526
1527         return 0;
1528 }
1529
1530 #if 0 /// UNNEEDED by elogind
1531 _public_ int sd_event_source_get_io_revents(sd_event_source *s, uint32_t* revents) {
1532         assert_return(s, -EINVAL);
1533         assert_return(revents, -EINVAL);
1534         assert_return(s->type == SOURCE_IO, -EDOM);
1535         assert_return(s->pending, -ENODATA);
1536         assert_return(!event_pid_changed(s->event), -ECHILD);
1537
1538         *revents = s->io.revents;
1539         return 0;
1540 }
1541
1542 _public_ int sd_event_source_get_signal(sd_event_source *s) {
1543         assert_return(s, -EINVAL);
1544         assert_return(s->type == SOURCE_SIGNAL, -EDOM);
1545         assert_return(!event_pid_changed(s->event), -ECHILD);
1546
1547         return s->signal.sig;
1548 }
1549
1550 _public_ int sd_event_source_get_priority(sd_event_source *s, int64_t *priority) {
1551         assert_return(s, -EINVAL);
1552         assert_return(!event_pid_changed(s->event), -ECHILD);
1553
1554         return s->priority;
1555 }
1556 #endif // 0
1557
1558 _public_ int sd_event_source_set_priority(sd_event_source *s, int64_t priority) {
1559         int r;
1560
1561         assert_return(s, -EINVAL);
1562         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1563         assert_return(!event_pid_changed(s->event), -ECHILD);
1564
1565         if (s->priority == priority)
1566                 return 0;
1567
1568         if (s->type == SOURCE_SIGNAL && s->enabled != SD_EVENT_OFF) {
1569                 struct signal_data *old, *d;
1570
1571                 /* Move us from the signalfd belonging to the old
1572                  * priority to the signalfd of the new priority */
1573
1574                 assert_se(old = hashmap_get(s->event->signal_data, &s->priority));
1575
1576                 s->priority = priority;
1577
1578                 r = event_make_signal_data(s->event, s->signal.sig, &d);
1579                 if (r < 0) {
1580                         s->priority = old->priority;
1581                         return r;
1582                 }
1583
1584                 event_unmask_signal_data(s->event, old, s->signal.sig);
1585         } else
1586                 s->priority = priority;
1587
1588         if (s->pending)
1589                 prioq_reshuffle(s->event->pending, s, &s->pending_index);
1590
1591         if (s->prepare)
1592                 prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
1593
1594         if (s->type == SOURCE_EXIT)
1595                 prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
1596
1597         return 0;
1598 }
1599
1600 #if 0 /// UNNEEDED by elogind
1601 _public_ int sd_event_source_get_enabled(sd_event_source *s, int *m) {
1602         assert_return(s, -EINVAL);
1603         assert_return(m, -EINVAL);
1604         assert_return(!event_pid_changed(s->event), -ECHILD);
1605
1606         *m = s->enabled;
1607         return 0;
1608 }
1609 #endif // 0
1610
1611 _public_ int sd_event_source_set_enabled(sd_event_source *s, int m) {
1612         int r;
1613
1614         assert_return(s, -EINVAL);
1615         assert_return(m == SD_EVENT_OFF || m == SD_EVENT_ON || m == SD_EVENT_ONESHOT, -EINVAL);
1616         assert_return(!event_pid_changed(s->event), -ECHILD);
1617
1618         /* If we are dead anyway, we are fine with turning off
1619          * sources, but everything else needs to fail. */
1620         if (s->event->state == SD_EVENT_FINISHED)
1621                 return m == SD_EVENT_OFF ? 0 : -ESTALE;
1622
1623         if (s->enabled == m)
1624                 return 0;
1625
1626         if (m == SD_EVENT_OFF) {
1627
1628                 switch (s->type) {
1629
1630                 case SOURCE_IO:
1631                         source_io_unregister(s);
1632                         s->enabled = m;
1633                         break;
1634
1635                 case SOURCE_TIME_REALTIME:
1636                 case SOURCE_TIME_BOOTTIME:
1637                 case SOURCE_TIME_MONOTONIC:
1638                 case SOURCE_TIME_REALTIME_ALARM:
1639                 case SOURCE_TIME_BOOTTIME_ALARM: {
1640                         struct clock_data *d;
1641
1642                         s->enabled = m;
1643                         d = event_get_clock_data(s->event, s->type);
1644                         assert(d);
1645
1646                         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
1647                         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1648                         d->needs_rearm = true;
1649                         break;
1650                 }
1651
1652                 case SOURCE_SIGNAL:
1653                         s->enabled = m;
1654
1655                         event_gc_signal_data(s->event, &s->priority, s->signal.sig);
1656                         break;
1657
1658                 case SOURCE_CHILD:
1659                         s->enabled = m;
1660
1661                         assert(s->event->n_enabled_child_sources > 0);
1662                         s->event->n_enabled_child_sources--;
1663
1664                         event_gc_signal_data(s->event, &s->priority, SIGCHLD);
1665                         break;
1666
1667                 case SOURCE_EXIT:
1668                         s->enabled = m;
1669                         prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
1670                         break;
1671
1672                 case SOURCE_DEFER:
1673                 case SOURCE_POST:
1674                         s->enabled = m;
1675                         break;
1676
1677                 default:
1678                         assert_not_reached("Wut? I shouldn't exist.");
1679                 }
1680
1681         } else {
1682                 switch (s->type) {
1683
1684                 case SOURCE_IO:
1685                         r = source_io_register(s, m, s->io.events);
1686                         if (r < 0)
1687                                 return r;
1688
1689                         s->enabled = m;
1690                         break;
1691
1692                 case SOURCE_TIME_REALTIME:
1693                 case SOURCE_TIME_BOOTTIME:
1694                 case SOURCE_TIME_MONOTONIC:
1695                 case SOURCE_TIME_REALTIME_ALARM:
1696                 case SOURCE_TIME_BOOTTIME_ALARM: {
1697                         struct clock_data *d;
1698
1699                         s->enabled = m;
1700                         d = event_get_clock_data(s->event, s->type);
1701                         assert(d);
1702
1703                         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
1704                         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1705                         d->needs_rearm = true;
1706                         break;
1707                 }
1708
1709                 case SOURCE_SIGNAL:
1710
1711                         s->enabled = m;
1712
1713                         r = event_make_signal_data(s->event, s->signal.sig, NULL);
1714                         if (r < 0) {
1715                                 s->enabled = SD_EVENT_OFF;
1716                                 event_gc_signal_data(s->event, &s->priority, s->signal.sig);
1717                                 return r;
1718                         }
1719
1720                         break;
1721
1722                 case SOURCE_CHILD:
1723
1724                         if (s->enabled == SD_EVENT_OFF)
1725                                 s->event->n_enabled_child_sources++;
1726
1727                         s->enabled = m;
1728
1729                         r = event_make_signal_data(s->event, SIGCHLD, NULL);
1730                         if (r < 0) {
1731                                 s->enabled = SD_EVENT_OFF;
1732                                 s->event->n_enabled_child_sources--;
1733                                 event_gc_signal_data(s->event, &s->priority, SIGCHLD);
1734                                 return r;
1735                         }
1736
1737                         break;
1738
1739                 case SOURCE_EXIT:
1740                         s->enabled = m;
1741                         prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
1742                         break;
1743
1744                 case SOURCE_DEFER:
1745                 case SOURCE_POST:
1746                         s->enabled = m;
1747                         break;
1748
1749                 default:
1750                         assert_not_reached("Wut? I shouldn't exist.");
1751                 }
1752         }
1753
1754         if (s->pending)
1755                 prioq_reshuffle(s->event->pending, s, &s->pending_index);
1756
1757         if (s->prepare)
1758                 prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
1759
1760         return 0;
1761 }
1762
1763 _public_ int sd_event_source_get_time(sd_event_source *s, uint64_t *usec) {
1764         assert_return(s, -EINVAL);
1765         assert_return(usec, -EINVAL);
1766         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1767         assert_return(!event_pid_changed(s->event), -ECHILD);
1768
1769         *usec = s->time.next;
1770         return 0;
1771 }
1772
1773 _public_ int sd_event_source_set_time(sd_event_source *s, uint64_t usec) {
1774         struct clock_data *d;
1775
1776         assert_return(s, -EINVAL);
1777         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1778         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1779         assert_return(!event_pid_changed(s->event), -ECHILD);
1780
1781         s->time.next = usec;
1782
1783         source_set_pending(s, false);
1784
1785         d = event_get_clock_data(s->event, s->type);
1786         assert(d);
1787
1788         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
1789         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1790         d->needs_rearm = true;
1791
1792         return 0;
1793 }
1794
1795 #if 0 /// UNNEEDED by elogind
1796 _public_ int sd_event_source_get_time_accuracy(sd_event_source *s, uint64_t *usec) {
1797         assert_return(s, -EINVAL);
1798         assert_return(usec, -EINVAL);
1799         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1800         assert_return(!event_pid_changed(s->event), -ECHILD);
1801
1802         *usec = s->time.accuracy;
1803         return 0;
1804 }
1805
1806 _public_ int sd_event_source_set_time_accuracy(sd_event_source *s, uint64_t usec) {
1807         struct clock_data *d;
1808
1809         assert_return(s, -EINVAL);
1810         assert_return(usec != (uint64_t) -1, -EINVAL);
1811         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1812         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1813         assert_return(!event_pid_changed(s->event), -ECHILD);
1814
1815         if (usec == 0)
1816                 usec = DEFAULT_ACCURACY_USEC;
1817
1818         s->time.accuracy = usec;
1819
1820         source_set_pending(s, false);
1821
1822         d = event_get_clock_data(s->event, s->type);
1823         assert(d);
1824
1825         prioq_reshuffle(d->latest, s, &s->time.latest_index);
1826         d->needs_rearm = true;
1827
1828         return 0;
1829 }
1830
1831 _public_ int sd_event_source_get_time_clock(sd_event_source *s, clockid_t *clock) {
1832         assert_return(s, -EINVAL);
1833         assert_return(clock, -EINVAL);
1834         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
1835         assert_return(!event_pid_changed(s->event), -ECHILD);
1836
1837         *clock = event_source_type_to_clock(s->type);
1838         return 0;
1839 }
1840
1841 _public_ int sd_event_source_get_child_pid(sd_event_source *s, pid_t *pid) {
1842         assert_return(s, -EINVAL);
1843         assert_return(pid, -EINVAL);
1844         assert_return(s->type == SOURCE_CHILD, -EDOM);
1845         assert_return(!event_pid_changed(s->event), -ECHILD);
1846
1847         *pid = s->child.pid;
1848         return 0;
1849 }
1850 #endif // 0
1851
1852 _public_ int sd_event_source_set_prepare(sd_event_source *s, sd_event_handler_t callback) {
1853         int r;
1854
1855         assert_return(s, -EINVAL);
1856         assert_return(s->type != SOURCE_EXIT, -EDOM);
1857         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1858         assert_return(!event_pid_changed(s->event), -ECHILD);
1859
1860         if (s->prepare == callback)
1861                 return 0;
1862
1863         if (callback && s->prepare) {
1864                 s->prepare = callback;
1865                 return 0;
1866         }
1867
1868         r = prioq_ensure_allocated(&s->event->prepare, prepare_prioq_compare);
1869         if (r < 0)
1870                 return r;
1871
1872         s->prepare = callback;
1873
1874         if (callback) {
1875                 r = prioq_put(s->event->prepare, s, &s->prepare_index);
1876                 if (r < 0)
1877                         return r;
1878         } else
1879                 prioq_remove(s->event->prepare, s, &s->prepare_index);
1880
1881         return 0;
1882 }
1883
1884 #if 0 /// UNNEEDED by elogind
1885 _public_ void* sd_event_source_get_userdata(sd_event_source *s) {
1886         assert_return(s, NULL);
1887
1888         return s->userdata;
1889 }
1890
1891 _public_ void *sd_event_source_set_userdata(sd_event_source *s, void *userdata) {
1892         void *ret;
1893
1894         assert_return(s, NULL);
1895
1896         ret = s->userdata;
1897         s->userdata = userdata;
1898
1899         return ret;
1900 }
1901 #endif // 0
1902
1903 static usec_t sleep_between(sd_event *e, usec_t a, usec_t b) {
1904         usec_t c;
1905         assert(e);
1906         assert(a <= b);
1907
1908         if (a <= 0)
1909                 return 0;
1910         if (a >= USEC_INFINITY)
1911                 return USEC_INFINITY;
1912
1913         if (b <= a + 1)
1914                 return a;
1915
1916         initialize_perturb(e);
1917
1918         /*
1919           Find a good time to wake up again between times a and b. We
1920           have two goals here:
1921
1922           a) We want to wake up as seldom as possible, hence prefer
1923              later times over earlier times.
1924
1925           b) But if we have to wake up, then let's make sure to
1926              dispatch as much as possible on the entire system.
1927
1928           We implement this by waking up everywhere at the same time
1929           within any given minute if we can, synchronised via the
1930           perturbation value determined from the boot ID. If we can't,
1931           then we try to find the same spot in every 10s, then 1s and
1932           then 250ms step. Otherwise, we pick the last possible time
1933           to wake up.
1934         */
1935
1936         c = (b / USEC_PER_MINUTE) * USEC_PER_MINUTE + e->perturb;
1937         if (c >= b) {
1938                 if (_unlikely_(c < USEC_PER_MINUTE))
1939                         return b;
1940
1941                 c -= USEC_PER_MINUTE;
1942         }
1943
1944         if (c >= a)
1945                 return c;
1946
1947         c = (b / (USEC_PER_SEC*10)) * (USEC_PER_SEC*10) + (e->perturb % (USEC_PER_SEC*10));
1948         if (c >= b) {
1949                 if (_unlikely_(c < USEC_PER_SEC*10))
1950                         return b;
1951
1952                 c -= USEC_PER_SEC*10;
1953         }
1954
1955         if (c >= a)
1956                 return c;
1957
1958         c = (b / USEC_PER_SEC) * USEC_PER_SEC + (e->perturb % USEC_PER_SEC);
1959         if (c >= b) {
1960                 if (_unlikely_(c < USEC_PER_SEC))
1961                         return b;
1962
1963                 c -= USEC_PER_SEC;
1964         }
1965
1966         if (c >= a)
1967                 return c;
1968
1969         c = (b / (USEC_PER_MSEC*250)) * (USEC_PER_MSEC*250) + (e->perturb % (USEC_PER_MSEC*250));
1970         if (c >= b) {
1971                 if (_unlikely_(c < USEC_PER_MSEC*250))
1972                         return b;
1973
1974                 c -= USEC_PER_MSEC*250;
1975         }
1976
1977         if (c >= a)
1978                 return c;
1979
1980         return b;
1981 }
1982
1983 static int event_arm_timer(
1984                 sd_event *e,
1985                 struct clock_data *d) {
1986
1987         struct itimerspec its = {};
1988         sd_event_source *a, *b;
1989         usec_t t;
1990         int r;
1991
1992         assert(e);
1993         assert(d);
1994
1995         if (!d->needs_rearm)
1996                 return 0;
1997         else
1998                 d->needs_rearm = false;
1999
2000         a = prioq_peek(d->earliest);
2001         if (!a || a->enabled == SD_EVENT_OFF || a->time.next == USEC_INFINITY) {
2002
2003                 if (d->fd < 0)
2004                         return 0;
2005
2006                 if (d->next == USEC_INFINITY)
2007                         return 0;
2008
2009                 /* disarm */
2010                 r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
2011                 if (r < 0)
2012                         return r;
2013
2014                 d->next = USEC_INFINITY;
2015                 return 0;
2016         }
2017
2018         b = prioq_peek(d->latest);
2019         assert_se(b && b->enabled != SD_EVENT_OFF);
2020
2021         t = sleep_between(e, a->time.next, time_event_source_latest(b));
2022         if (d->next == t)
2023                 return 0;
2024
2025         assert_se(d->fd >= 0);
2026
2027         if (t == 0) {
2028                 /* We don' want to disarm here, just mean some time looooong ago. */
2029                 its.it_value.tv_sec = 0;
2030                 its.it_value.tv_nsec = 1;
2031         } else
2032                 timespec_store(&its.it_value, t);
2033
2034         r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
2035         if (r < 0)
2036                 return -errno;
2037
2038         d->next = t;
2039         return 0;
2040 }
2041
2042 static int process_io(sd_event *e, sd_event_source *s, uint32_t revents) {
2043         assert(e);
2044         assert(s);
2045         assert(s->type == SOURCE_IO);
2046
2047         /* If the event source was already pending, we just OR in the
2048          * new revents, otherwise we reset the value. The ORing is
2049          * necessary to handle EPOLLONESHOT events properly where
2050          * readability might happen independently of writability, and
2051          * we need to keep track of both */
2052
2053         if (s->pending)
2054                 s->io.revents |= revents;
2055         else
2056                 s->io.revents = revents;
2057
2058         return source_set_pending(s, true);
2059 }
2060
2061 static int flush_timer(sd_event *e, int fd, uint32_t events, usec_t *next) {
2062         uint64_t x;
2063         ssize_t ss;
2064
2065         assert(e);
2066         assert(fd >= 0);
2067
2068         assert_return(events == EPOLLIN, -EIO);
2069
2070         ss = read(fd, &x, sizeof(x));
2071         if (ss < 0) {
2072                 if (errno == EAGAIN || errno == EINTR)
2073                         return 0;
2074
2075                 return -errno;
2076         }
2077
2078         if (_unlikely_(ss != sizeof(x)))
2079                 return -EIO;
2080
2081         if (next)
2082                 *next = USEC_INFINITY;
2083
2084         return 0;
2085 }
2086
2087 static int process_timer(
2088                 sd_event *e,
2089                 usec_t n,
2090                 struct clock_data *d) {
2091
2092         sd_event_source *s;
2093         int r;
2094
2095         assert(e);
2096         assert(d);
2097
2098         for (;;) {
2099                 s = prioq_peek(d->earliest);
2100                 if (!s ||
2101                     s->time.next > n ||
2102                     s->enabled == SD_EVENT_OFF ||
2103                     s->pending)
2104                         break;
2105
2106                 r = source_set_pending(s, true);
2107                 if (r < 0)
2108                         return r;
2109
2110                 prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
2111                 prioq_reshuffle(d->latest, s, &s->time.latest_index);
2112                 d->needs_rearm = true;
2113         }
2114
2115         return 0;
2116 }
2117
2118 static int process_child(sd_event *e) {
2119         sd_event_source *s;
2120         Iterator i;
2121         int r;
2122
2123         assert(e);
2124
2125         e->need_process_child = false;
2126
2127         /*
2128            So, this is ugly. We iteratively invoke waitid() with P_PID
2129            + WNOHANG for each PID we wait for, instead of using
2130            P_ALL. This is because we only want to get child
2131            information of very specific child processes, and not all
2132            of them. We might not have processed the SIGCHLD even of a
2133            previous invocation and we don't want to maintain a
2134            unbounded *per-child* event queue, hence we really don't
2135            want anything flushed out of the kernel's queue that we
2136            don't care about. Since this is O(n) this means that if you
2137            have a lot of processes you probably want to handle SIGCHLD
2138            yourself.
2139
2140            We do not reap the children here (by using WNOWAIT), this
2141            is only done after the event source is dispatched so that
2142            the callback still sees the process as a zombie.
2143         */
2144
2145         HASHMAP_FOREACH(s, e->child_sources, i) {
2146                 assert(s->type == SOURCE_CHILD);
2147
2148                 if (s->pending)
2149                         continue;
2150
2151                 if (s->enabled == SD_EVENT_OFF)
2152                         continue;
2153
2154                 zero(s->child.siginfo);
2155                 r = waitid(P_PID, s->child.pid, &s->child.siginfo,
2156                            WNOHANG | (s->child.options & WEXITED ? WNOWAIT : 0) | s->child.options);
2157                 if (r < 0)
2158                         return -errno;
2159
2160                 if (s->child.siginfo.si_pid != 0) {
2161                         bool zombie =
2162                                 s->child.siginfo.si_code == CLD_EXITED ||
2163                                 s->child.siginfo.si_code == CLD_KILLED ||
2164                                 s->child.siginfo.si_code == CLD_DUMPED;
2165
2166                         if (!zombie && (s->child.options & WEXITED)) {
2167                                 /* If the child isn't dead then let's
2168                                  * immediately remove the state change
2169                                  * from the queue, since there's no
2170                                  * benefit in leaving it queued */
2171
2172                                 assert(s->child.options & (WSTOPPED|WCONTINUED));
2173                                 waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|(s->child.options & (WSTOPPED|WCONTINUED)));
2174                         }
2175
2176                         r = source_set_pending(s, true);
2177                         if (r < 0)
2178                                 return r;
2179                 }
2180         }
2181
2182         return 0;
2183 }
2184
2185 static int process_signal(sd_event *e, struct signal_data *d, uint32_t events) {
2186         bool read_one = false;
2187         int r;
2188
2189         assert(e);
2190         assert_return(events == EPOLLIN, -EIO);
2191
2192         /* If there's a signal queued on this priority and SIGCHLD is
2193            on this priority too, then make sure to recheck the
2194            children we watch. This is because we only ever dequeue
2195            the first signal per priority, and if we dequeue one, and
2196            SIGCHLD might be enqueued later we wouldn't know, but we
2197            might have higher priority children we care about hence we
2198            need to check that explicitly. */
2199
2200         if (sigismember(&d->sigset, SIGCHLD))
2201                 e->need_process_child = true;
2202
2203         /* If there's already an event source pending for this
2204          * priority we don't read another */
2205         if (d->current)
2206                 return 0;
2207
2208         for (;;) {
2209                 struct signalfd_siginfo si;
2210                 ssize_t n;
2211                 sd_event_source *s = NULL;
2212
2213                 n = read(d->fd, &si, sizeof(si));
2214                 if (n < 0) {
2215                         if (errno == EAGAIN || errno == EINTR)
2216                                 return read_one;
2217
2218                         return -errno;
2219                 }
2220
2221                 if (_unlikely_(n != sizeof(si)))
2222                         return -EIO;
2223
2224                 assert(SIGNAL_VALID(si.ssi_signo));
2225
2226                 read_one = true;
2227
2228                 if (e->signal_sources)
2229                         s = e->signal_sources[si.ssi_signo];
2230                 if (!s)
2231                         continue;
2232                 if (s->pending)
2233                         continue;
2234
2235                 s->signal.siginfo = si;
2236                 d->current = s;
2237
2238                 r = source_set_pending(s, true);
2239                 if (r < 0)
2240                         return r;
2241
2242                 return 1;
2243         }
2244 }
2245
2246 static int source_dispatch(sd_event_source *s) {
2247         int r = 0;
2248
2249         assert(s);
2250         assert(s->pending || s->type == SOURCE_EXIT);
2251
2252         if (s->type != SOURCE_DEFER && s->type != SOURCE_EXIT) {
2253                 r = source_set_pending(s, false);
2254                 if (r < 0)
2255                         return r;
2256         }
2257
2258         if (s->type != SOURCE_POST) {
2259                 sd_event_source *z;
2260                 Iterator i;
2261
2262                 /* If we execute a non-post source, let's mark all
2263                  * post sources as pending */
2264
2265                 SET_FOREACH(z, s->event->post_sources, i) {
2266                         if (z->enabled == SD_EVENT_OFF)
2267                                 continue;
2268
2269                         r = source_set_pending(z, true);
2270                         if (r < 0)
2271                                 return r;
2272                 }
2273         }
2274
2275         if (s->enabled == SD_EVENT_ONESHOT) {
2276                 r = sd_event_source_set_enabled(s, SD_EVENT_OFF);
2277                 if (r < 0)
2278                         return r;
2279         }
2280
2281         s->dispatching = true;
2282
2283         switch (s->type) {
2284
2285         case SOURCE_IO:
2286                 r = s->io.callback(s, s->io.fd, s->io.revents, s->userdata);
2287                 break;
2288
2289         case SOURCE_TIME_REALTIME:
2290         case SOURCE_TIME_BOOTTIME:
2291         case SOURCE_TIME_MONOTONIC:
2292         case SOURCE_TIME_REALTIME_ALARM:
2293         case SOURCE_TIME_BOOTTIME_ALARM:
2294                 r = s->time.callback(s, s->time.next, s->userdata);
2295                 break;
2296
2297         case SOURCE_SIGNAL:
2298                 r = s->signal.callback(s, &s->signal.siginfo, s->userdata);
2299                 break;
2300
2301         case SOURCE_CHILD: {
2302                 bool zombie;
2303
2304                 zombie = s->child.siginfo.si_code == CLD_EXITED ||
2305                          s->child.siginfo.si_code == CLD_KILLED ||
2306                          s->child.siginfo.si_code == CLD_DUMPED;
2307
2308                 r = s->child.callback(s, &s->child.siginfo, s->userdata);
2309
2310                 /* Now, reap the PID for good. */
2311                 if (zombie)
2312                         waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|WEXITED);
2313
2314                 break;
2315         }
2316
2317         case SOURCE_DEFER:
2318                 r = s->defer.callback(s, s->userdata);
2319                 break;
2320
2321         case SOURCE_POST:
2322                 r = s->post.callback(s, s->userdata);
2323                 break;
2324
2325         case SOURCE_EXIT:
2326                 r = s->exit.callback(s, s->userdata);
2327                 break;
2328
2329         case SOURCE_WATCHDOG:
2330         case _SOURCE_EVENT_SOURCE_TYPE_MAX:
2331         case _SOURCE_EVENT_SOURCE_TYPE_INVALID:
2332                 assert_not_reached("Wut? I shouldn't exist.");
2333         }
2334
2335         s->dispatching = false;
2336
2337         if (r < 0)
2338                 log_debug_errno(r, "Event source %s (type %s) returned error, disabling: %m",
2339                                 strna(s->description), event_source_type_to_string(s->type));
2340
2341         if (s->n_ref == 0)
2342                 source_free(s);
2343         else if (r < 0)
2344                 sd_event_source_set_enabled(s, SD_EVENT_OFF);
2345
2346         return 1;
2347 }
2348
2349 static int event_prepare(sd_event *e) {
2350         int r;
2351
2352         assert(e);
2353
2354         for (;;) {
2355                 sd_event_source *s;
2356
2357                 s = prioq_peek(e->prepare);
2358                 if (!s || s->prepare_iteration == e->iteration || s->enabled == SD_EVENT_OFF)
2359                         break;
2360
2361                 s->prepare_iteration = e->iteration;
2362                 r = prioq_reshuffle(e->prepare, s, &s->prepare_index);
2363                 if (r < 0)
2364                         return r;
2365
2366                 assert(s->prepare);
2367
2368                 s->dispatching = true;
2369                 r = s->prepare(s, s->userdata);
2370                 s->dispatching = false;
2371
2372                 if (r < 0)
2373                         log_debug_errno(r, "Prepare callback of event source %s (type %s) returned error, disabling: %m",
2374                                         strna(s->description), event_source_type_to_string(s->type));
2375
2376                 if (s->n_ref == 0)
2377                         source_free(s);
2378                 else if (r < 0)
2379                         sd_event_source_set_enabled(s, SD_EVENT_OFF);
2380         }
2381
2382         return 0;
2383 }
2384
2385 static int dispatch_exit(sd_event *e) {
2386         sd_event_source *p;
2387         int r;
2388
2389         assert(e);
2390
2391         p = prioq_peek(e->exit);
2392         if (!p || p->enabled == SD_EVENT_OFF) {
2393                 e->state = SD_EVENT_FINISHED;
2394                 return 0;
2395         }
2396
2397         sd_event_ref(e);
2398         e->iteration++;
2399         e->state = SD_EVENT_EXITING;
2400
2401         r = source_dispatch(p);
2402
2403         e->state = SD_EVENT_INITIAL;
2404         sd_event_unref(e);
2405
2406         return r;
2407 }
2408
2409 static sd_event_source* event_next_pending(sd_event *e) {
2410         sd_event_source *p;
2411
2412         assert(e);
2413
2414         p = prioq_peek(e->pending);
2415         if (!p)
2416                 return NULL;
2417
2418         if (p->enabled == SD_EVENT_OFF)
2419                 return NULL;
2420
2421         return p;
2422 }
2423
2424 static int arm_watchdog(sd_event *e) {
2425         struct itimerspec its = {};
2426         usec_t t;
2427         int r;
2428
2429         assert(e);
2430         assert(e->watchdog_fd >= 0);
2431
2432         t = sleep_between(e,
2433                           e->watchdog_last + (e->watchdog_period / 2),
2434                           e->watchdog_last + (e->watchdog_period * 3 / 4));
2435
2436         timespec_store(&its.it_value, t);
2437
2438         /* Make sure we never set the watchdog to 0, which tells the
2439          * kernel to disable it. */
2440         if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0)
2441                 its.it_value.tv_nsec = 1;
2442
2443         r = timerfd_settime(e->watchdog_fd, TFD_TIMER_ABSTIME, &its, NULL);
2444         if (r < 0)
2445                 return -errno;
2446
2447         return 0;
2448 }
2449
2450 static int process_watchdog(sd_event *e) {
2451         assert(e);
2452
2453         if (!e->watchdog)
2454                 return 0;
2455
2456         /* Don't notify watchdog too often */
2457         if (e->watchdog_last + e->watchdog_period / 4 > e->timestamp.monotonic)
2458                 return 0;
2459
2460         sd_notify(false, "WATCHDOG=1");
2461         e->watchdog_last = e->timestamp.monotonic;
2462
2463         return arm_watchdog(e);
2464 }
2465
2466 _public_ int sd_event_prepare(sd_event *e) {
2467         int r;
2468
2469         assert_return(e, -EINVAL);
2470         assert_return(!event_pid_changed(e), -ECHILD);
2471         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2472         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
2473
2474         if (e->exit_requested)
2475                 goto pending;
2476
2477         e->iteration++;
2478
2479         e->state = SD_EVENT_PREPARING;
2480         r = event_prepare(e);
2481         e->state = SD_EVENT_INITIAL;
2482         if (r < 0)
2483                 return r;
2484
2485         r = event_arm_timer(e, &e->realtime);
2486         if (r < 0)
2487                 return r;
2488
2489         r = event_arm_timer(e, &e->boottime);
2490         if (r < 0)
2491                 return r;
2492
2493         r = event_arm_timer(e, &e->monotonic);
2494         if (r < 0)
2495                 return r;
2496
2497         r = event_arm_timer(e, &e->realtime_alarm);
2498         if (r < 0)
2499                 return r;
2500
2501         r = event_arm_timer(e, &e->boottime_alarm);
2502         if (r < 0)
2503                 return r;
2504
2505         if (event_next_pending(e) || e->need_process_child)
2506                 goto pending;
2507
2508         e->state = SD_EVENT_ARMED;
2509
2510         return 0;
2511
2512 pending:
2513         e->state = SD_EVENT_ARMED;
2514         r = sd_event_wait(e, 0);
2515         if (r == 0)
2516                 e->state = SD_EVENT_ARMED;
2517
2518         return r;
2519 }
2520
2521 _public_ int sd_event_wait(sd_event *e, uint64_t timeout) {
2522         struct epoll_event *ev_queue;
2523         unsigned ev_queue_max;
2524         int r, m, i;
2525
2526         assert_return(e, -EINVAL);
2527         assert_return(!event_pid_changed(e), -ECHILD);
2528         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2529         assert_return(e->state == SD_EVENT_ARMED, -EBUSY);
2530
2531         if (e->exit_requested) {
2532                 e->state = SD_EVENT_PENDING;
2533                 return 1;
2534         }
2535
2536         ev_queue_max = MAX(e->n_sources, 1u);
2537         ev_queue = newa(struct epoll_event, ev_queue_max);
2538
2539         m = epoll_wait(e->epoll_fd, ev_queue, ev_queue_max,
2540                        timeout == (uint64_t) -1 ? -1 : (int) ((timeout + USEC_PER_MSEC - 1) / USEC_PER_MSEC));
2541         if (m < 0) {
2542                 if (errno == EINTR) {
2543                         e->state = SD_EVENT_PENDING;
2544                         return 1;
2545                 }
2546
2547                 r = -errno;
2548                 goto finish;
2549         }
2550
2551         triple_timestamp_get(&e->timestamp);
2552
2553         for (i = 0; i < m; i++) {
2554
2555                 if (ev_queue[i].data.ptr == INT_TO_PTR(SOURCE_WATCHDOG))
2556                         r = flush_timer(e, e->watchdog_fd, ev_queue[i].events, NULL);
2557                 else {
2558                         WakeupType *t = ev_queue[i].data.ptr;
2559
2560                         switch (*t) {
2561
2562                         case WAKEUP_EVENT_SOURCE:
2563                                 r = process_io(e, ev_queue[i].data.ptr, ev_queue[i].events);
2564                                 break;
2565
2566                         case WAKEUP_CLOCK_DATA: {
2567                                 struct clock_data *d = ev_queue[i].data.ptr;
2568                                 r = flush_timer(e, d->fd, ev_queue[i].events, &d->next);
2569                                 break;
2570                         }
2571
2572                         case WAKEUP_SIGNAL_DATA:
2573                                 r = process_signal(e, ev_queue[i].data.ptr, ev_queue[i].events);
2574                                 break;
2575
2576                         default:
2577                                 assert_not_reached("Invalid wake-up pointer");
2578                         }
2579                 }
2580                 if (r < 0)
2581                         goto finish;
2582         }
2583
2584         r = process_watchdog(e);
2585         if (r < 0)
2586                 goto finish;
2587
2588         r = process_timer(e, e->timestamp.realtime, &e->realtime);
2589         if (r < 0)
2590                 goto finish;
2591
2592         r = process_timer(e, e->timestamp.boottime, &e->boottime);
2593         if (r < 0)
2594                 goto finish;
2595
2596         r = process_timer(e, e->timestamp.monotonic, &e->monotonic);
2597         if (r < 0)
2598                 goto finish;
2599
2600         r = process_timer(e, e->timestamp.realtime, &e->realtime_alarm);
2601         if (r < 0)
2602                 goto finish;
2603
2604         r = process_timer(e, e->timestamp.boottime, &e->boottime_alarm);
2605         if (r < 0)
2606                 goto finish;
2607
2608         if (e->need_process_child) {
2609                 r = process_child(e);
2610                 if (r < 0)
2611                         goto finish;
2612         }
2613
2614         if (event_next_pending(e)) {
2615                 e->state = SD_EVENT_PENDING;
2616
2617                 return 1;
2618         }
2619
2620         r = 0;
2621
2622 finish:
2623         e->state = SD_EVENT_INITIAL;
2624
2625         return r;
2626 }
2627
2628 _public_ int sd_event_dispatch(sd_event *e) {
2629         sd_event_source *p;
2630         int r;
2631
2632         assert_return(e, -EINVAL);
2633         assert_return(!event_pid_changed(e), -ECHILD);
2634         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2635         assert_return(e->state == SD_EVENT_PENDING, -EBUSY);
2636
2637         if (e->exit_requested)
2638                 return dispatch_exit(e);
2639
2640         p = event_next_pending(e);
2641         if (p) {
2642                 sd_event_ref(e);
2643
2644                 e->state = SD_EVENT_RUNNING;
2645                 r = source_dispatch(p);
2646                 e->state = SD_EVENT_INITIAL;
2647
2648                 sd_event_unref(e);
2649
2650                 return r;
2651         }
2652
2653         e->state = SD_EVENT_INITIAL;
2654
2655         return 1;
2656 }
2657
2658 static void event_log_delays(sd_event *e) {
2659         char b[ELEMENTSOF(e->delays) * DECIMAL_STR_MAX(unsigned) + 1];
2660         unsigned i;
2661         int o;
2662
2663         for (i = o = 0; i < ELEMENTSOF(e->delays); i++) {
2664                 o += snprintf(&b[o], sizeof(b) - o, "%u ", e->delays[i]);
2665                 e->delays[i] = 0;
2666         }
2667         log_debug("Event loop iterations: %.*s", o, b);
2668 }
2669
2670 _public_ int sd_event_run(sd_event *e, uint64_t timeout) {
2671         int r;
2672
2673         assert_return(e, -EINVAL);
2674         assert_return(!event_pid_changed(e), -ECHILD);
2675         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2676         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
2677
2678         if (e->profile_delays && e->last_run) {
2679                 usec_t this_run;
2680                 unsigned l;
2681
2682                 this_run = now(CLOCK_MONOTONIC);
2683
2684                 l = u64log2(this_run - e->last_run);
2685                 assert(l < sizeof(e->delays));
2686                 e->delays[l]++;
2687
2688                 if (this_run - e->last_log >= 5*USEC_PER_SEC) {
2689                         event_log_delays(e);
2690                         e->last_log = this_run;
2691                 }
2692         }
2693
2694         r = sd_event_prepare(e);
2695         if (r == 0)
2696                 /* There was nothing? Then wait... */
2697                 r = sd_event_wait(e, timeout);
2698
2699         if (e->profile_delays)
2700                 e->last_run = now(CLOCK_MONOTONIC);
2701
2702         if (r > 0) {
2703                 /* There's something now, then let's dispatch it */
2704                 r = sd_event_dispatch(e);
2705                 if (r < 0)
2706                         return r;
2707
2708                 return 1;
2709         }
2710
2711         return r;
2712 }
2713
2714 #if 0 /// UNNEEDED by elogind
2715 _public_ int sd_event_loop(sd_event *e) {
2716         int r;
2717
2718         assert_return(e, -EINVAL);
2719         assert_return(!event_pid_changed(e), -ECHILD);
2720         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
2721
2722         sd_event_ref(e);
2723
2724         while (e->state != SD_EVENT_FINISHED) {
2725                 r = sd_event_run(e, (uint64_t) -1);
2726                 if (r < 0)
2727                         goto finish;
2728         }
2729
2730         r = e->exit_code;
2731
2732 finish:
2733         sd_event_unref(e);
2734         return r;
2735 }
2736
2737 _public_ int sd_event_get_fd(sd_event *e) {
2738
2739         assert_return(e, -EINVAL);
2740         assert_return(!event_pid_changed(e), -ECHILD);
2741
2742         return e->epoll_fd;
2743 }
2744 #endif // 0
2745
2746 _public_ int sd_event_get_state(sd_event *e) {
2747         assert_return(e, -EINVAL);
2748         assert_return(!event_pid_changed(e), -ECHILD);
2749
2750         return e->state;
2751 }
2752
2753 #if 0 /// UNNEEDED by elogind
2754 _public_ int sd_event_get_exit_code(sd_event *e, int *code) {
2755         assert_return(e, -EINVAL);
2756         assert_return(code, -EINVAL);
2757         assert_return(!event_pid_changed(e), -ECHILD);
2758
2759         if (!e->exit_requested)
2760                 return -ENODATA;
2761
2762         *code = e->exit_code;
2763         return 0;
2764 }
2765 #endif // 0
2766
2767 _public_ int sd_event_exit(sd_event *e, int code) {
2768         assert_return(e, -EINVAL);
2769         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2770         assert_return(!event_pid_changed(e), -ECHILD);
2771
2772         e->exit_requested = true;
2773         e->exit_code = code;
2774
2775         return 0;
2776 }
2777
2778 #if 0 /// UNNEEDED by elogind
2779 _public_ int sd_event_now(sd_event *e, clockid_t clock, uint64_t *usec) {
2780         assert_return(e, -EINVAL);
2781         assert_return(usec, -EINVAL);
2782         assert_return(!event_pid_changed(e), -ECHILD);
2783
2784         if (!TRIPLE_TIMESTAMP_HAS_CLOCK(clock))
2785                 return -EOPNOTSUPP;
2786
2787         /* Generate a clean error in case CLOCK_BOOTTIME is not available. Note that don't use clock_supported() here,
2788          * for a reason: there are systems where CLOCK_BOOTTIME is supported, but CLOCK_BOOTTIME_ALARM is not, but for
2789          * the purpose of getting the time this doesn't matter. */
2790         if (IN_SET(clock, CLOCK_BOOTTIME, CLOCK_BOOTTIME_ALARM) && !clock_boottime_supported())
2791                 return -EOPNOTSUPP;
2792
2793         if (!triple_timestamp_is_set(&e->timestamp)) {
2794                 /* Implicitly fall back to now() if we never ran
2795                  * before and thus have no cached time. */
2796                 *usec = now(clock);
2797                 return 1;
2798         }
2799
2800         *usec = triple_timestamp_by_clock(&e->timestamp, clock);
2801         return 0;
2802 }
2803 #endif // 0
2804
2805 _public_ int sd_event_default(sd_event **ret) {
2806
2807         static thread_local sd_event *default_event = NULL;
2808         sd_event *e = NULL;
2809         int r;
2810
2811         if (!ret)
2812                 return !!default_event;
2813
2814         if (default_event) {
2815                 *ret = sd_event_ref(default_event);
2816                 return 0;
2817         }
2818
2819         r = sd_event_new(&e);
2820         if (r < 0)
2821                 return r;
2822
2823         e->default_event_ptr = &default_event;
2824         e->tid = gettid();
2825         default_event = e;
2826
2827         *ret = e;
2828         return 1;
2829 }
2830
2831 #if 0 /// UNNEEDED by elogind
2832 _public_ int sd_event_get_tid(sd_event *e, pid_t *tid) {
2833         assert_return(e, -EINVAL);
2834         assert_return(tid, -EINVAL);
2835         assert_return(!event_pid_changed(e), -ECHILD);
2836
2837         if (e->tid != 0) {
2838                 *tid = e->tid;
2839                 return 0;
2840         }
2841
2842         return -ENXIO;
2843 }
2844 #endif // 0
2845
2846 _public_ int sd_event_set_watchdog(sd_event *e, int b) {
2847         int r;
2848
2849         assert_return(e, -EINVAL);
2850         assert_return(!event_pid_changed(e), -ECHILD);
2851
2852         if (e->watchdog == !!b)
2853                 return e->watchdog;
2854
2855         if (b) {
2856                 struct epoll_event ev = {};
2857
2858                 r = sd_watchdog_enabled(false, &e->watchdog_period);
2859                 if (r <= 0)
2860                         return r;
2861
2862                 /* Issue first ping immediately */
2863                 sd_notify(false, "WATCHDOG=1");
2864                 e->watchdog_last = now(CLOCK_MONOTONIC);
2865
2866                 e->watchdog_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
2867                 if (e->watchdog_fd < 0)
2868                         return -errno;
2869
2870                 r = arm_watchdog(e);
2871                 if (r < 0)
2872                         goto fail;
2873
2874                 ev.events = EPOLLIN;
2875                 ev.data.ptr = INT_TO_PTR(SOURCE_WATCHDOG);
2876
2877                 r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, e->watchdog_fd, &ev);
2878                 if (r < 0) {
2879                         r = -errno;
2880                         goto fail;
2881                 }
2882
2883         } else {
2884                 if (e->watchdog_fd >= 0) {
2885                         epoll_ctl(e->epoll_fd, EPOLL_CTL_DEL, e->watchdog_fd, NULL);
2886                         e->watchdog_fd = safe_close(e->watchdog_fd);
2887                 }
2888         }
2889
2890         e->watchdog = !!b;
2891         return e->watchdog;
2892
2893 fail:
2894         e->watchdog_fd = safe_close(e->watchdog_fd);
2895         return r;
2896 }
2897
2898 #if 0 /// UNNEEDED by elogind
2899 _public_ int sd_event_get_watchdog(sd_event *e) {
2900         assert_return(e, -EINVAL);
2901         assert_return(!event_pid_changed(e), -ECHILD);
2902
2903         return e->watchdog;
2904 }
2905 #endif // 0
2906
2907 _public_ int sd_event_get_iteration(sd_event *e, uint64_t *ret) {
2908         assert_return(e, -EINVAL);
2909         assert_return(!event_pid_changed(e), -ECHILD);
2910
2911         *ret = e->iteration;
2912         return 0;
2913 }