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