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