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