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