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