chiark / gitweb /
3f9691227d9907f364911c45442d07e09c8cf8fd
[elogind.git] / src / libelogind / sd-event / sd-event.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3   This file is part of systemd.
4
5   Copyright 2013 Lennart Poettering
6 ***/
7
8 #include <sys/epoll.h>
9 #include <sys/timerfd.h>
10 #include <sys/wait.h>
11
12 #include "sd-daemon.h"
13 #include "sd-event.h"
14 #include "sd-id128.h"
15
16 #include "alloc-util.h"
17 #include "fd-util.h"
18 //#include "fs-util.h"
19 #include "hashmap.h"
20 #include "list.h"
21 #include "macro.h"
22 #include "missing.h"
23 #include "prioq.h"
24 #include "process-util.h"
25 #include "set.h"
26 #include "signal-util.h"
27 #include "string-table.h"
28 #include "string-util.h"
29 #include "time-util.h"
30 #include "util.h"
31
32 #define DEFAULT_ACCURACY_USEC (250 * USEC_PER_MSEC)
33
34 typedef enum EventSourceType {
35         SOURCE_IO,
36         SOURCE_TIME_REALTIME,
37         SOURCE_TIME_BOOTTIME,
38         SOURCE_TIME_MONOTONIC,
39         SOURCE_TIME_REALTIME_ALARM,
40         SOURCE_TIME_BOOTTIME_ALARM,
41         SOURCE_SIGNAL,
42         SOURCE_CHILD,
43         SOURCE_DEFER,
44         SOURCE_POST,
45         SOURCE_EXIT,
46         SOURCE_WATCHDOG,
47         SOURCE_INOTIFY,
48         _SOURCE_EVENT_SOURCE_TYPE_MAX,
49         _SOURCE_EVENT_SOURCE_TYPE_INVALID = -1
50 } EventSourceType;
51
52 static const char* const event_source_type_table[_SOURCE_EVENT_SOURCE_TYPE_MAX] = {
53         [SOURCE_IO] = "io",
54         [SOURCE_TIME_REALTIME] = "realtime",
55         [SOURCE_TIME_BOOTTIME] = "bootime",
56         [SOURCE_TIME_MONOTONIC] = "monotonic",
57         [SOURCE_TIME_REALTIME_ALARM] = "realtime-alarm",
58         [SOURCE_TIME_BOOTTIME_ALARM] = "boottime-alarm",
59         [SOURCE_SIGNAL] = "signal",
60         [SOURCE_CHILD] = "child",
61         [SOURCE_DEFER] = "defer",
62         [SOURCE_POST] = "post",
63         [SOURCE_EXIT] = "exit",
64         [SOURCE_WATCHDOG] = "watchdog",
65         [SOURCE_INOTIFY] = "inotify",
66 };
67
68 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(event_source_type, int);
69
70 /* All objects we use in epoll events start with this value, so that
71  * we know how to dispatch it */
72 typedef enum WakeupType {
73         WAKEUP_NONE,
74         WAKEUP_EVENT_SOURCE,
75         WAKEUP_CLOCK_DATA,
76         WAKEUP_SIGNAL_DATA,
77         WAKEUP_INOTIFY_DATA,
78         _WAKEUP_TYPE_MAX,
79         _WAKEUP_TYPE_INVALID = -1,
80 } WakeupType;
81
82 #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)
83
84 struct inode_data;
85
86 struct sd_event_source {
87         WakeupType wakeup;
88
89         unsigned n_ref;
90
91         sd_event *event;
92         void *userdata;
93         sd_event_handler_t prepare;
94
95         char *description;
96
97         EventSourceType type:5;
98         int enabled:3;
99         bool pending:1;
100         bool dispatching:1;
101         bool floating:1;
102
103         int64_t priority;
104         unsigned pending_index;
105         unsigned prepare_index;
106         uint64_t pending_iteration;
107         uint64_t prepare_iteration;
108
109         LIST_FIELDS(sd_event_source, sources);
110
111         union {
112                 struct {
113                         sd_event_io_handler_t callback;
114                         int fd;
115                         uint32_t events;
116                         uint32_t revents;
117                         bool registered:1;
118                         bool owned:1;
119                 } io;
120                 struct {
121                         sd_event_time_handler_t callback;
122                         usec_t next, accuracy;
123                         unsigned earliest_index;
124                         unsigned latest_index;
125                 } time;
126                 struct {
127                         sd_event_signal_handler_t callback;
128                         struct signalfd_siginfo siginfo;
129                         int sig;
130                 } signal;
131                 struct {
132                         sd_event_child_handler_t callback;
133                         siginfo_t siginfo;
134                         pid_t pid;
135                         int options;
136                 } child;
137                 struct {
138                         sd_event_handler_t callback;
139                 } defer;
140                 struct {
141                         sd_event_handler_t callback;
142                 } post;
143                 struct {
144                         sd_event_handler_t callback;
145                         unsigned prioq_index;
146                 } exit;
147                 struct {
148                         sd_event_inotify_handler_t callback;
149                         uint32_t mask;
150                         struct inode_data *inode_data;
151                         LIST_FIELDS(sd_event_source, by_inode_data);
152                 } inotify;
153         };
154 };
155
156 struct clock_data {
157         WakeupType wakeup;
158         int fd;
159
160         /* For all clocks we maintain two priority queues each, one
161          * ordered for the earliest times the events may be
162          * dispatched, and one ordered by the latest times they must
163          * have been dispatched. The range between the top entries in
164          * the two prioqs is the time window we can freely schedule
165          * wakeups in */
166
167         Prioq *earliest;
168         Prioq *latest;
169         usec_t next;
170
171         bool needs_rearm:1;
172 };
173
174 struct signal_data {
175         WakeupType wakeup;
176
177         /* For each priority we maintain one signal fd, so that we
178          * only have to dequeue a single event per priority at a
179          * time. */
180
181         int fd;
182         int64_t priority;
183         sigset_t sigset;
184         sd_event_source *current;
185 };
186
187 /* A structure listing all event sources currently watching a specific inode */
188 struct inode_data {
189         /* The identifier for the inode, the combination of the .st_dev + .st_ino fields of the file */
190         ino_t ino;
191         dev_t dev;
192
193         /* An fd of the inode to watch. The fd is kept open until the next iteration of the loop, so that we can
194          * rearrange the priority still until then, as we need the original inode to change the priority as we need to
195          * add a watch descriptor to the right inotify for the priority which we can only do if we have a handle to the
196          * original inode. We keep a list of all inode_data objects with an open fd in the to_close list (see below) of
197          * the sd-event object, so that it is efficient to close everything, before entering the next event loop
198          * iteration. */
199         int fd;
200
201         /* The inotify "watch descriptor" */
202         int wd;
203
204         /* The combination of the mask of all inotify watches on this inode we manage. This is also the mask that has
205          * most recently been set on the watch descriptor. */
206         uint32_t combined_mask;
207
208         /* All event sources subscribed to this inode */
209         LIST_HEAD(sd_event_source, event_sources);
210
211         /* The inotify object we watch this inode with */
212         struct inotify_data *inotify_data;
213
214         /* A linked list of all inode data objects with fds to close (see above) */
215         LIST_FIELDS(struct inode_data, to_close);
216 };
217
218 /* A structure encapsulating an inotify fd */
219 struct inotify_data {
220         WakeupType wakeup;
221
222         /* For each priority we maintain one inotify fd, so that we only have to dequeue a single event per priority at
223          * a time */
224
225         int fd;
226         int64_t priority;
227
228         Hashmap *inodes; /* The inode_data structures keyed by dev+ino */
229         Hashmap *wd;     /* The inode_data structures keyed by the watch descriptor for each */
230
231         /* The buffer we read inotify events into */
232         union inotify_event_buffer buffer;
233         size_t buffer_filled; /* fill level of the buffer */
234
235         /* How many event sources are currently marked pending for this inotify. We won't read new events off the
236          * inotify fd as long as there are still pending events on the inotify (because we have no strategy of queuing
237          * the events locally if they can't be coalesced). */
238         unsigned n_pending;
239
240         /* A linked list of all inotify objects with data already read, that still need processing. We keep this list
241          * to make it efficient to figure out what inotify objects to process data on next. */
242         LIST_FIELDS(struct inotify_data, buffered);
243 };
244
245 struct sd_event {
246         unsigned n_ref;
247
248         int epoll_fd;
249         int watchdog_fd;
250
251         Prioq *pending;
252         Prioq *prepare;
253
254         /* timerfd_create() only supports these five clocks so far. We
255          * can add support for more clocks when the kernel learns to
256          * deal with them, too. */
257         struct clock_data realtime;
258         struct clock_data boottime;
259         struct clock_data monotonic;
260         struct clock_data realtime_alarm;
261         struct clock_data boottime_alarm;
262
263         usec_t perturb;
264
265         sd_event_source **signal_sources; /* indexed by signal number */
266         Hashmap *signal_data; /* indexed by priority */
267
268         Hashmap *child_sources;
269         unsigned n_enabled_child_sources;
270
271         Set *post_sources;
272
273         Prioq *exit;
274
275         Hashmap *inotify_data; /* indexed by priority */
276
277         /* A list of inode structures that still have an fd open, that we need to close before the next loop iteration */
278         LIST_HEAD(struct inode_data, inode_data_to_close);
279
280         /* A list of inotify objects that already have events buffered which aren't processed yet */
281         LIST_HEAD(struct inotify_data, inotify_data_buffered);
282
283         pid_t original_pid;
284
285         uint64_t iteration;
286         triple_timestamp timestamp;
287         int state;
288
289         bool exit_requested:1;
290         bool need_process_child:1;
291         bool watchdog:1;
292         bool profile_delays:1;
293
294         int exit_code;
295
296         pid_t tid;
297         sd_event **default_event_ptr;
298
299         usec_t watchdog_last, watchdog_period;
300
301         unsigned n_sources;
302
303         LIST_HEAD(sd_event_source, sources);
304
305         usec_t last_run, last_log;
306         unsigned delays[sizeof(usec_t) * 8];
307 };
308
309 static thread_local sd_event *default_event = NULL;
310
311 static void source_disconnect(sd_event_source *s);
312 static void event_gc_inode_data(sd_event *e, struct inode_data *d);
313
314 static sd_event *event_resolve(sd_event *e) {
315         return e == SD_EVENT_DEFAULT ? default_event : e;
316 }
317
318 static int pending_prioq_compare(const void *a, const void *b) {
319         const sd_event_source *x = a, *y = b;
320
321         assert(x->pending);
322         assert(y->pending);
323
324         /* Enabled ones first */
325         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
326                 return -1;
327         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
328                 return 1;
329
330         /* Lower priority values first */
331         if (x->priority < y->priority)
332                 return -1;
333         if (x->priority > y->priority)
334                 return 1;
335
336         /* Older entries first */
337         if (x->pending_iteration < y->pending_iteration)
338                 return -1;
339         if (x->pending_iteration > y->pending_iteration)
340                 return 1;
341
342         return 0;
343 }
344
345 static int prepare_prioq_compare(const void *a, const void *b) {
346         const sd_event_source *x = a, *y = b;
347
348         assert(x->prepare);
349         assert(y->prepare);
350
351         /* Enabled ones first */
352         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
353                 return -1;
354         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
355                 return 1;
356
357         /* Move most recently prepared ones last, so that we can stop
358          * preparing as soon as we hit one that has already been
359          * prepared in the current iteration */
360         if (x->prepare_iteration < y->prepare_iteration)
361                 return -1;
362         if (x->prepare_iteration > y->prepare_iteration)
363                 return 1;
364
365         /* Lower priority values first */
366         if (x->priority < y->priority)
367                 return -1;
368         if (x->priority > y->priority)
369                 return 1;
370
371         return 0;
372 }
373
374 static int earliest_time_prioq_compare(const void *a, const void *b) {
375         const sd_event_source *x = a, *y = b;
376
377         assert(EVENT_SOURCE_IS_TIME(x->type));
378         assert(x->type == y->type);
379
380         /* Enabled ones first */
381         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
382                 return -1;
383         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
384                 return 1;
385
386         /* Move the pending ones to the end */
387         if (!x->pending && y->pending)
388                 return -1;
389         if (x->pending && !y->pending)
390                 return 1;
391
392         /* Order by time */
393         if (x->time.next < y->time.next)
394                 return -1;
395         if (x->time.next > y->time.next)
396                 return 1;
397
398         return 0;
399 }
400
401 static usec_t time_event_source_latest(const sd_event_source *s) {
402         return usec_add(s->time.next, s->time.accuracy);
403 }
404
405 static int latest_time_prioq_compare(const void *a, const void *b) {
406         const sd_event_source *x = a, *y = b;
407
408         assert(EVENT_SOURCE_IS_TIME(x->type));
409         assert(x->type == y->type);
410
411         /* Enabled ones first */
412         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
413                 return -1;
414         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
415                 return 1;
416
417         /* Move the pending ones to the end */
418         if (!x->pending && y->pending)
419                 return -1;
420         if (x->pending && !y->pending)
421                 return 1;
422
423         /* Order by time */
424         if (time_event_source_latest(x) < time_event_source_latest(y))
425                 return -1;
426         if (time_event_source_latest(x) > time_event_source_latest(y))
427                 return 1;
428
429         return 0;
430 }
431
432 static int exit_prioq_compare(const void *a, const void *b) {
433         const sd_event_source *x = a, *y = b;
434
435         assert(x->type == SOURCE_EXIT);
436         assert(y->type == SOURCE_EXIT);
437
438         /* Enabled ones first */
439         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
440                 return -1;
441         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
442                 return 1;
443
444         /* Lower priority values first */
445         if (x->priority < y->priority)
446                 return -1;
447         if (x->priority > y->priority)
448                 return 1;
449
450         return 0;
451 }
452
453 static void free_clock_data(struct clock_data *d) {
454         assert(d);
455         assert(d->wakeup == WAKEUP_CLOCK_DATA);
456
457         safe_close(d->fd);
458         prioq_free(d->earliest);
459         prioq_free(d->latest);
460 }
461
462 static void event_free(sd_event *e) {
463         sd_event_source *s;
464
465         assert(e);
466
467         while ((s = e->sources)) {
468                 assert(s->floating);
469                 source_disconnect(s);
470                 sd_event_source_unref(s);
471         }
472
473         assert(e->n_sources == 0);
474
475         if (e->default_event_ptr)
476                 *(e->default_event_ptr) = NULL;
477
478         safe_close(e->epoll_fd);
479         safe_close(e->watchdog_fd);
480
481         free_clock_data(&e->realtime);
482         free_clock_data(&e->boottime);
483         free_clock_data(&e->monotonic);
484         free_clock_data(&e->realtime_alarm);
485         free_clock_data(&e->boottime_alarm);
486
487         prioq_free(e->pending);
488         prioq_free(e->prepare);
489         prioq_free(e->exit);
490
491         free(e->signal_sources);
492         hashmap_free(e->signal_data);
493
494         hashmap_free(e->inotify_data);
495
496         hashmap_free(e->child_sources);
497         set_free(e->post_sources);
498         free(e);
499 }
500
501 _public_ int sd_event_new(sd_event** ret) {
502         sd_event *e;
503         int r;
504
505         assert_return(ret, -EINVAL);
506
507         e = new(sd_event, 1);
508         if (!e)
509                 return -ENOMEM;
510
511         *e = (sd_event) {
512                 .n_ref = 1,
513                 .epoll_fd = -1,
514                 .watchdog_fd = -1,
515                 .realtime.wakeup = WAKEUP_CLOCK_DATA,
516                 .realtime.fd = -1,
517                 .realtime.next = USEC_INFINITY,
518                 .boottime.wakeup = WAKEUP_CLOCK_DATA,
519                 .boottime.fd = -1,
520                 .boottime.next = USEC_INFINITY,
521                 .monotonic.wakeup = WAKEUP_CLOCK_DATA,
522                 .monotonic.fd = -1,
523                 .monotonic.next = USEC_INFINITY,
524                 .realtime_alarm.wakeup = WAKEUP_CLOCK_DATA,
525                 .realtime_alarm.fd = -1,
526                 .realtime_alarm.next = USEC_INFINITY,
527                 .boottime_alarm.wakeup = WAKEUP_CLOCK_DATA,
528                 .boottime_alarm.fd = -1,
529                 .boottime_alarm.next = USEC_INFINITY,
530                 .perturb = USEC_INFINITY,
531                 .original_pid = getpid_cached(),
532         };
533
534         r = prioq_ensure_allocated(&e->pending, pending_prioq_compare);
535         if (r < 0)
536                 goto fail;
537
538         e->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
539         if (e->epoll_fd < 0) {
540                 r = -errno;
541                 goto fail;
542         }
543
544         e->epoll_fd = fd_move_above_stdio(e->epoll_fd);
545
546         if (secure_getenv("SD_EVENT_PROFILE_DELAYS")) {
547                 log_debug("Event loop profiling enabled. Logarithmic histogram of event loop iterations in the range 2^0 ... 2^63 us will be logged every 5s.");
548                 e->profile_delays = true;
549         }
550
551         *ret = e;
552         return 0;
553
554 fail:
555         event_free(e);
556         return r;
557 }
558
559 _public_ sd_event* sd_event_ref(sd_event *e) {
560
561         if (!e)
562                 return NULL;
563
564         assert(e->n_ref >= 1);
565         e->n_ref++;
566
567         return e;
568 }
569
570 _public_ sd_event* sd_event_unref(sd_event *e) {
571
572         if (!e)
573                 return NULL;
574
575         assert(e->n_ref >= 1);
576         e->n_ref--;
577
578         if (e->n_ref <= 0)
579                 event_free(e);
580
581         return NULL;
582 }
583
584 static bool event_pid_changed(sd_event *e) {
585         assert(e);
586
587         /* We don't support people creating an event loop and keeping
588          * it around over a fork(). Let's complain. */
589
590         return e->original_pid != getpid_cached();
591 }
592
593 static void source_io_unregister(sd_event_source *s) {
594         int r;
595
596         assert(s);
597         assert(s->type == SOURCE_IO);
598
599         if (event_pid_changed(s->event))
600                 return;
601
602         if (!s->io.registered)
603                 return;
604
605         r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, s->io.fd, NULL);
606         if (r < 0)
607                 log_debug_errno(errno, "Failed to remove source %s (type %s) from epoll: %m",
608                                 strna(s->description), event_source_type_to_string(s->type));
609
610         s->io.registered = false;
611 }
612
613 static int source_io_register(
614                 sd_event_source *s,
615                 int enabled,
616                 uint32_t events) {
617
618         struct epoll_event ev;
619         int r;
620
621         assert(s);
622         assert(s->type == SOURCE_IO);
623         assert(enabled != SD_EVENT_OFF);
624
625         ev = (struct epoll_event) {
626                 .events = events | (enabled == SD_EVENT_ONESHOT ? EPOLLONESHOT : 0),
627                 .data.ptr = s,
628         };
629
630         if (s->io.registered)
631                 r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_MOD, s->io.fd, &ev);
632         else
633                 r = epoll_ctl(s->event->epoll_fd, EPOLL_CTL_ADD, s->io.fd, &ev);
634         if (r < 0)
635                 return -errno;
636
637         s->io.registered = true;
638
639         return 0;
640 }
641
642 static clockid_t event_source_type_to_clock(EventSourceType t) {
643
644         switch (t) {
645
646         case SOURCE_TIME_REALTIME:
647                 return CLOCK_REALTIME;
648
649         case SOURCE_TIME_BOOTTIME:
650                 return CLOCK_BOOTTIME;
651
652         case SOURCE_TIME_MONOTONIC:
653                 return CLOCK_MONOTONIC;
654
655         case SOURCE_TIME_REALTIME_ALARM:
656                 return CLOCK_REALTIME_ALARM;
657
658         case SOURCE_TIME_BOOTTIME_ALARM:
659                 return CLOCK_BOOTTIME_ALARM;
660
661         default:
662                 return (clockid_t) -1;
663         }
664 }
665
666 static EventSourceType clock_to_event_source_type(clockid_t clock) {
667
668         switch (clock) {
669
670         case CLOCK_REALTIME:
671                 return SOURCE_TIME_REALTIME;
672
673         case CLOCK_BOOTTIME:
674                 return SOURCE_TIME_BOOTTIME;
675
676         case CLOCK_MONOTONIC:
677                 return SOURCE_TIME_MONOTONIC;
678
679         case CLOCK_REALTIME_ALARM:
680                 return SOURCE_TIME_REALTIME_ALARM;
681
682         case CLOCK_BOOTTIME_ALARM:
683                 return SOURCE_TIME_BOOTTIME_ALARM;
684
685         default:
686                 return _SOURCE_EVENT_SOURCE_TYPE_INVALID;
687         }
688 }
689
690 static struct clock_data* event_get_clock_data(sd_event *e, EventSourceType t) {
691         assert(e);
692
693         switch (t) {
694
695         case SOURCE_TIME_REALTIME:
696                 return &e->realtime;
697
698         case SOURCE_TIME_BOOTTIME:
699                 return &e->boottime;
700
701         case SOURCE_TIME_MONOTONIC:
702                 return &e->monotonic;
703
704         case SOURCE_TIME_REALTIME_ALARM:
705                 return &e->realtime_alarm;
706
707         case SOURCE_TIME_BOOTTIME_ALARM:
708                 return &e->boottime_alarm;
709
710         default:
711                 return NULL;
712         }
713 }
714
715 static int event_make_signal_data(
716                 sd_event *e,
717                 int sig,
718                 struct signal_data **ret) {
719
720         struct epoll_event ev;
721         struct signal_data *d;
722         bool added = false;
723         sigset_t ss_copy;
724         int64_t priority;
725         int r;
726
727         assert(e);
728
729         if (event_pid_changed(e))
730                 return -ECHILD;
731
732         if (e->signal_sources && e->signal_sources[sig])
733                 priority = e->signal_sources[sig]->priority;
734         else
735                 priority = SD_EVENT_PRIORITY_NORMAL;
736
737         d = hashmap_get(e->signal_data, &priority);
738         if (d) {
739                 if (sigismember(&d->sigset, sig) > 0) {
740                         if (ret)
741                                 *ret = d;
742                         return 0;
743                 }
744         } else {
745                 r = hashmap_ensure_allocated(&e->signal_data, &uint64_hash_ops);
746                 if (r < 0)
747                         return r;
748
749                 d = new(struct signal_data, 1);
750                 if (!d)
751                         return -ENOMEM;
752
753                 *d = (struct signal_data) {
754                         .wakeup = WAKEUP_SIGNAL_DATA,
755                         .fd = -1,
756                         .priority = priority,
757                 };
758
759                 r = hashmap_put(e->signal_data, &d->priority, d);
760                 if (r < 0) {
761                         free(d);
762                         return r;
763                 }
764
765                 added = true;
766         }
767
768         ss_copy = d->sigset;
769         assert_se(sigaddset(&ss_copy, sig) >= 0);
770
771         r = signalfd(d->fd, &ss_copy, SFD_NONBLOCK|SFD_CLOEXEC);
772         if (r < 0) {
773                 r = -errno;
774                 goto fail;
775         }
776
777         d->sigset = ss_copy;
778
779         if (d->fd >= 0) {
780                 if (ret)
781                         *ret = d;
782                 return 0;
783         }
784
785         d->fd = fd_move_above_stdio(r);
786
787         ev = (struct epoll_event) {
788                 .events = EPOLLIN,
789                 .data.ptr = d,
790         };
791
792         r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, d->fd, &ev);
793         if (r < 0)  {
794                 r = -errno;
795                 goto fail;
796         }
797
798         if (ret)
799                 *ret = d;
800
801         return 0;
802
803 fail:
804         if (added) {
805                 d->fd = safe_close(d->fd);
806                 hashmap_remove(e->signal_data, &d->priority);
807                 free(d);
808         }
809
810         return r;
811 }
812
813 static void event_unmask_signal_data(sd_event *e, struct signal_data *d, int sig) {
814         assert(e);
815         assert(d);
816
817         /* Turns off the specified signal in the signal data
818          * object. If the signal mask of the object becomes empty that
819          * way removes it. */
820
821         if (sigismember(&d->sigset, sig) == 0)
822                 return;
823
824         assert_se(sigdelset(&d->sigset, sig) >= 0);
825
826         if (sigisemptyset(&d->sigset)) {
827
828                 /* If all the mask is all-zero we can get rid of the structure */
829                 hashmap_remove(e->signal_data, &d->priority);
830                 safe_close(d->fd);
831                 free(d);
832                 return;
833         }
834
835         assert(d->fd >= 0);
836
837         if (signalfd(d->fd, &d->sigset, SFD_NONBLOCK|SFD_CLOEXEC) < 0)
838                 log_debug_errno(errno, "Failed to unset signal bit, ignoring: %m");
839 }
840
841 static void event_gc_signal_data(sd_event *e, const int64_t *priority, int sig) {
842         struct signal_data *d;
843         static const int64_t zero_priority = 0;
844
845         assert(e);
846
847         /* Rechecks if the specified signal is still something we are
848          * interested in. If not, we'll unmask it, and possibly drop
849          * the signalfd for it. */
850
851         if (sig == SIGCHLD &&
852             e->n_enabled_child_sources > 0)
853                 return;
854
855         if (e->signal_sources &&
856             e->signal_sources[sig] &&
857             e->signal_sources[sig]->enabled != SD_EVENT_OFF)
858                 return;
859
860         /*
861          * The specified signal might be enabled in three different queues:
862          *
863          * 1) the one that belongs to the priority passed (if it is non-NULL)
864          * 2) the one that belongs to the priority of the event source of the signal (if there is one)
865          * 3) the 0 priority (to cover the SIGCHLD case)
866          *
867          * Hence, let's remove it from all three here.
868          */
869
870         if (priority) {
871                 d = hashmap_get(e->signal_data, priority);
872                 if (d)
873                         event_unmask_signal_data(e, d, sig);
874         }
875
876         if (e->signal_sources && e->signal_sources[sig]) {
877                 d = hashmap_get(e->signal_data, &e->signal_sources[sig]->priority);
878                 if (d)
879                         event_unmask_signal_data(e, d, sig);
880         }
881
882         d = hashmap_get(e->signal_data, &zero_priority);
883         if (d)
884                 event_unmask_signal_data(e, d, sig);
885 }
886
887 static void source_disconnect(sd_event_source *s) {
888         sd_event *event;
889
890         assert(s);
891
892         if (!s->event)
893                 return;
894
895         assert(s->event->n_sources > 0);
896
897         switch (s->type) {
898
899         case SOURCE_IO:
900                 if (s->io.fd >= 0)
901                         source_io_unregister(s);
902
903                 break;
904
905         case SOURCE_TIME_REALTIME:
906         case SOURCE_TIME_BOOTTIME:
907         case SOURCE_TIME_MONOTONIC:
908         case SOURCE_TIME_REALTIME_ALARM:
909         case SOURCE_TIME_BOOTTIME_ALARM: {
910                 struct clock_data *d;
911
912                 d = event_get_clock_data(s->event, s->type);
913                 assert(d);
914
915                 prioq_remove(d->earliest, s, &s->time.earliest_index);
916                 prioq_remove(d->latest, s, &s->time.latest_index);
917                 d->needs_rearm = true;
918                 break;
919         }
920
921         case SOURCE_SIGNAL:
922                 if (s->signal.sig > 0) {
923
924                         if (s->event->signal_sources)
925                                 s->event->signal_sources[s->signal.sig] = NULL;
926
927                         event_gc_signal_data(s->event, &s->priority, s->signal.sig);
928                 }
929
930                 break;
931
932         case SOURCE_CHILD:
933                 if (s->child.pid > 0) {
934                         if (s->enabled != SD_EVENT_OFF) {
935                                 assert(s->event->n_enabled_child_sources > 0);
936                                 s->event->n_enabled_child_sources--;
937                         }
938
939                         (void) hashmap_remove(s->event->child_sources, PID_TO_PTR(s->child.pid));
940                         event_gc_signal_data(s->event, &s->priority, SIGCHLD);
941                 }
942
943                 break;
944
945         case SOURCE_DEFER:
946                 /* nothing */
947                 break;
948
949         case SOURCE_POST:
950                 set_remove(s->event->post_sources, s);
951                 break;
952
953         case SOURCE_EXIT:
954                 prioq_remove(s->event->exit, s, &s->exit.prioq_index);
955                 break;
956
957         case SOURCE_INOTIFY: {
958                 struct inode_data *inode_data;
959
960                 inode_data = s->inotify.inode_data;
961                 if (inode_data) {
962                         struct inotify_data *inotify_data;
963                         assert_se(inotify_data = inode_data->inotify_data);
964
965                         /* Detach this event source from the inode object */
966                         LIST_REMOVE(inotify.by_inode_data, inode_data->event_sources, s);
967                         s->inotify.inode_data = NULL;
968
969                         if (s->pending) {
970                                 assert(inotify_data->n_pending > 0);
971                                 inotify_data->n_pending--;
972                         }
973
974                         /* Note that we don't reduce the inotify mask for the watch descriptor here if the inode is
975                          * continued to being watched. That's because inotify doesn't really have an API for that: we
976                          * can only change watch masks with access to the original inode either by fd or by path. But
977                          * paths aren't stable, and keeping an O_PATH fd open all the time would mean wasting an fd
978                          * continously and keeping the mount busy which we can't really do. We could reconstruct the
979                          * original inode from /proc/self/fdinfo/$INOTIFY_FD (as all watch descriptors are listed
980                          * there), but given the need for open_by_handle_at() which is privileged and not universally
981                          * available this would be quite an incomplete solution. Hence we go the other way, leave the
982                          * mask set, even if it is not minimized now, and ignore all events we aren't interested in
983                          * anymore after reception. Yes, this sucks, but â€¦ Linux â€¦ */
984
985                         /* Maybe release the inode data (and its inotify) */
986                         event_gc_inode_data(s->event, inode_data);
987                 }
988
989                 break;
990         }
991
992         default:
993                 assert_not_reached("Wut? I shouldn't exist.");
994         }
995
996         if (s->pending)
997                 prioq_remove(s->event->pending, s, &s->pending_index);
998
999         if (s->prepare)
1000                 prioq_remove(s->event->prepare, s, &s->prepare_index);
1001
1002         event = s->event;
1003
1004         s->type = _SOURCE_EVENT_SOURCE_TYPE_INVALID;
1005         s->event = NULL;
1006         LIST_REMOVE(sources, event->sources, s);
1007         event->n_sources--;
1008
1009         if (!s->floating)
1010                 sd_event_unref(event);
1011 }
1012
1013 static void source_free(sd_event_source *s) {
1014         assert(s);
1015
1016         source_disconnect(s);
1017
1018         if (s->type == SOURCE_IO && s->io.owned)
1019                 safe_close(s->io.fd);
1020
1021         free(s->description);
1022         free(s);
1023 }
1024
1025 static int source_set_pending(sd_event_source *s, bool b) {
1026         int r;
1027
1028         assert(s);
1029         assert(s->type != SOURCE_EXIT);
1030
1031         if (s->pending == b)
1032                 return 0;
1033
1034         s->pending = b;
1035
1036         if (b) {
1037                 s->pending_iteration = s->event->iteration;
1038
1039                 r = prioq_put(s->event->pending, s, &s->pending_index);
1040                 if (r < 0) {
1041                         s->pending = false;
1042                         return r;
1043                 }
1044         } else
1045                 assert_se(prioq_remove(s->event->pending, s, &s->pending_index));
1046
1047         if (EVENT_SOURCE_IS_TIME(s->type)) {
1048                 struct clock_data *d;
1049
1050                 d = event_get_clock_data(s->event, s->type);
1051                 assert(d);
1052
1053                 prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
1054                 prioq_reshuffle(d->latest, s, &s->time.latest_index);
1055                 d->needs_rearm = true;
1056         }
1057
1058         if (s->type == SOURCE_SIGNAL && !b) {
1059                 struct signal_data *d;
1060
1061                 d = hashmap_get(s->event->signal_data, &s->priority);
1062                 if (d && d->current == s)
1063                         d->current = NULL;
1064         }
1065
1066         if (s->type == SOURCE_INOTIFY) {
1067
1068                 assert(s->inotify.inode_data);
1069                 assert(s->inotify.inode_data->inotify_data);
1070
1071                 if (b)
1072                         s->inotify.inode_data->inotify_data->n_pending ++;
1073                 else {
1074                         assert(s->inotify.inode_data->inotify_data->n_pending > 0);
1075                         s->inotify.inode_data->inotify_data->n_pending --;
1076                 }
1077         }
1078
1079         return 0;
1080 }
1081
1082 static sd_event_source *source_new(sd_event *e, bool floating, EventSourceType type) {
1083         sd_event_source *s;
1084
1085         assert(e);
1086
1087         s = new(sd_event_source, 1);
1088         if (!s)
1089                 return NULL;
1090
1091         *s = (struct sd_event_source) {
1092                 .n_ref = 1,
1093                 .event = e,
1094                 .floating = floating,
1095                 .type = type,
1096                 .pending_index = PRIOQ_IDX_NULL,
1097                 .prepare_index = PRIOQ_IDX_NULL,
1098         };
1099
1100         if (!floating)
1101                 sd_event_ref(e);
1102
1103         LIST_PREPEND(sources, e->sources, s);
1104         e->n_sources++;
1105
1106         return s;
1107 }
1108
1109 _public_ int sd_event_add_io(
1110                 sd_event *e,
1111                 sd_event_source **ret,
1112                 int fd,
1113                 uint32_t events,
1114                 sd_event_io_handler_t callback,
1115                 void *userdata) {
1116
1117         sd_event_source *s;
1118         int r;
1119
1120         assert_return(e, -EINVAL);
1121         assert_return(e = event_resolve(e), -ENOPKG);
1122         assert_return(fd >= 0, -EBADF);
1123         assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
1124         assert_return(callback, -EINVAL);
1125         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1126         assert_return(!event_pid_changed(e), -ECHILD);
1127
1128         s = source_new(e, !ret, SOURCE_IO);
1129         if (!s)
1130                 return -ENOMEM;
1131
1132         s->wakeup = WAKEUP_EVENT_SOURCE;
1133         s->io.fd = fd;
1134         s->io.events = events;
1135         s->io.callback = callback;
1136         s->userdata = userdata;
1137         s->enabled = SD_EVENT_ON;
1138
1139         r = source_io_register(s, s->enabled, events);
1140         if (r < 0) {
1141                 source_free(s);
1142                 return r;
1143         }
1144
1145         if (ret)
1146                 *ret = s;
1147
1148         return 0;
1149 }
1150
1151 static void initialize_perturb(sd_event *e) {
1152         sd_id128_t bootid = {};
1153
1154         /* When we sleep for longer, we try to realign the wakeup to
1155            the same time wihtin each minute/second/250ms, so that
1156            events all across the system can be coalesced into a single
1157            CPU wakeup. However, let's take some system-specific
1158            randomness for this value, so that in a network of systems
1159            with synced clocks timer events are distributed a
1160            bit. Here, we calculate a perturbation usec offset from the
1161            boot ID. */
1162
1163         if (_likely_(e->perturb != USEC_INFINITY))
1164                 return;
1165
1166         if (sd_id128_get_boot(&bootid) >= 0)
1167                 e->perturb = (bootid.qwords[0] ^ bootid.qwords[1]) % USEC_PER_MINUTE;
1168 }
1169
1170 static int event_setup_timer_fd(
1171                 sd_event *e,
1172                 struct clock_data *d,
1173                 clockid_t clock) {
1174
1175         struct epoll_event ev;
1176         int r, fd;
1177
1178         assert(e);
1179         assert(d);
1180
1181         if (_likely_(d->fd >= 0))
1182                 return 0;
1183
1184         fd = timerfd_create(clock, TFD_NONBLOCK|TFD_CLOEXEC);
1185         if (fd < 0)
1186                 return -errno;
1187
1188         fd = fd_move_above_stdio(fd);
1189
1190         ev = (struct epoll_event) {
1191                 .events = EPOLLIN,
1192                 .data.ptr = d,
1193         };
1194
1195         r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, fd, &ev);
1196         if (r < 0) {
1197                 safe_close(fd);
1198                 return -errno;
1199         }
1200
1201         d->fd = fd;
1202         return 0;
1203 }
1204
1205 static int time_exit_callback(sd_event_source *s, uint64_t usec, void *userdata) {
1206         assert(s);
1207
1208         return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1209 }
1210
1211 _public_ int sd_event_add_time(
1212                 sd_event *e,
1213                 sd_event_source **ret,
1214                 clockid_t clock,
1215                 uint64_t usec,
1216                 uint64_t accuracy,
1217                 sd_event_time_handler_t callback,
1218                 void *userdata) {
1219
1220         EventSourceType type;
1221         sd_event_source *s;
1222         struct clock_data *d;
1223         int r;
1224
1225         assert_return(e, -EINVAL);
1226         assert_return(e = event_resolve(e), -ENOPKG);
1227         assert_return(accuracy != (uint64_t) -1, -EINVAL);
1228         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1229         assert_return(!event_pid_changed(e), -ECHILD);
1230
1231         if (!clock_supported(clock)) /* Checks whether the kernel supports the clock */
1232                 return -EOPNOTSUPP;
1233
1234         type = clock_to_event_source_type(clock); /* checks whether sd-event supports this clock */
1235         if (type < 0)
1236                 return -EOPNOTSUPP;
1237
1238         if (!callback)
1239                 callback = time_exit_callback;
1240
1241         d = event_get_clock_data(e, type);
1242         assert(d);
1243
1244         r = prioq_ensure_allocated(&d->earliest, earliest_time_prioq_compare);
1245         if (r < 0)
1246                 return r;
1247
1248         r = prioq_ensure_allocated(&d->latest, latest_time_prioq_compare);
1249         if (r < 0)
1250                 return r;
1251
1252         if (d->fd < 0) {
1253                 r = event_setup_timer_fd(e, d, clock);
1254                 if (r < 0)
1255                         return r;
1256         }
1257
1258         s = source_new(e, !ret, type);
1259         if (!s)
1260                 return -ENOMEM;
1261
1262         s->time.next = usec;
1263         s->time.accuracy = accuracy == 0 ? DEFAULT_ACCURACY_USEC : accuracy;
1264         s->time.callback = callback;
1265         s->time.earliest_index = s->time.latest_index = PRIOQ_IDX_NULL;
1266         s->userdata = userdata;
1267         s->enabled = SD_EVENT_ONESHOT;
1268
1269         d->needs_rearm = true;
1270
1271         r = prioq_put(d->earliest, s, &s->time.earliest_index);
1272         if (r < 0)
1273                 goto fail;
1274
1275         r = prioq_put(d->latest, s, &s->time.latest_index);
1276         if (r < 0)
1277                 goto fail;
1278
1279         if (ret)
1280                 *ret = s;
1281
1282         return 0;
1283
1284 fail:
1285         source_free(s);
1286         return r;
1287 }
1288
1289 static int signal_exit_callback(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1290         assert(s);
1291
1292         return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1293 }
1294
1295 _public_ int sd_event_add_signal(
1296                 sd_event *e,
1297                 sd_event_source **ret,
1298                 int sig,
1299                 sd_event_signal_handler_t callback,
1300                 void *userdata) {
1301
1302         sd_event_source *s;
1303         struct signal_data *d;
1304         sigset_t ss;
1305         int r;
1306
1307         assert_return(e, -EINVAL);
1308         assert_return(e = event_resolve(e), -ENOPKG);
1309         assert_return(SIGNAL_VALID(sig), -EINVAL);
1310         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1311         assert_return(!event_pid_changed(e), -ECHILD);
1312
1313         if (!callback)
1314                 callback = signal_exit_callback;
1315
1316         r = pthread_sigmask(SIG_SETMASK, NULL, &ss);
1317         if (r != 0)
1318                 return -r;
1319
1320         if (!sigismember(&ss, sig))
1321                 return -EBUSY;
1322
1323         if (!e->signal_sources) {
1324                 e->signal_sources = new0(sd_event_source*, _NSIG);
1325                 if (!e->signal_sources)
1326                         return -ENOMEM;
1327         } else if (e->signal_sources[sig])
1328                 return -EBUSY;
1329
1330         s = source_new(e, !ret, SOURCE_SIGNAL);
1331         if (!s)
1332                 return -ENOMEM;
1333
1334         s->signal.sig = sig;
1335         s->signal.callback = callback;
1336         s->userdata = userdata;
1337         s->enabled = SD_EVENT_ON;
1338
1339         e->signal_sources[sig] = s;
1340
1341         r = event_make_signal_data(e, sig, &d);
1342         if (r < 0) {
1343                 source_free(s);
1344                 return r;
1345         }
1346
1347         /* Use the signal name as description for the event source by default */
1348         (void) sd_event_source_set_description(s, signal_to_string(sig));
1349
1350         if (ret)
1351                 *ret = s;
1352
1353         return 0;
1354 }
1355
1356 _public_ int sd_event_add_child(
1357                 sd_event *e,
1358                 sd_event_source **ret,
1359                 pid_t pid,
1360                 int options,
1361                 sd_event_child_handler_t callback,
1362                 void *userdata) {
1363
1364         sd_event_source *s;
1365         int r;
1366
1367         assert_return(e, -EINVAL);
1368         assert_return(e = event_resolve(e), -ENOPKG);
1369         assert_return(pid > 1, -EINVAL);
1370         assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED)), -EINVAL);
1371         assert_return(options != 0, -EINVAL);
1372         assert_return(callback, -EINVAL);
1373         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1374         assert_return(!event_pid_changed(e), -ECHILD);
1375
1376         r = hashmap_ensure_allocated(&e->child_sources, NULL);
1377         if (r < 0)
1378                 return r;
1379
1380         if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
1381                 return -EBUSY;
1382
1383         s = source_new(e, !ret, SOURCE_CHILD);
1384         if (!s)
1385                 return -ENOMEM;
1386
1387         s->child.pid = pid;
1388         s->child.options = options;
1389         s->child.callback = callback;
1390         s->userdata = userdata;
1391         s->enabled = SD_EVENT_ONESHOT;
1392
1393         r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
1394         if (r < 0) {
1395                 source_free(s);
1396                 return r;
1397         }
1398
1399         e->n_enabled_child_sources++;
1400
1401         r = event_make_signal_data(e, SIGCHLD, NULL);
1402         if (r < 0) {
1403                 e->n_enabled_child_sources--;
1404                 source_free(s);
1405                 return r;
1406         }
1407
1408         e->need_process_child = true;
1409
1410         if (ret)
1411                 *ret = s;
1412
1413         return 0;
1414 }
1415
1416 _public_ int sd_event_add_defer(
1417                 sd_event *e,
1418                 sd_event_source **ret,
1419                 sd_event_handler_t callback,
1420                 void *userdata) {
1421
1422         sd_event_source *s;
1423         int r;
1424
1425         assert_return(e, -EINVAL);
1426         assert_return(e = event_resolve(e), -ENOPKG);
1427         assert_return(callback, -EINVAL);
1428         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1429         assert_return(!event_pid_changed(e), -ECHILD);
1430
1431         s = source_new(e, !ret, SOURCE_DEFER);
1432         if (!s)
1433                 return -ENOMEM;
1434
1435         s->defer.callback = callback;
1436         s->userdata = userdata;
1437         s->enabled = SD_EVENT_ONESHOT;
1438
1439         r = source_set_pending(s, true);
1440         if (r < 0) {
1441                 source_free(s);
1442                 return r;
1443         }
1444
1445         if (ret)
1446                 *ret = s;
1447
1448         return 0;
1449 }
1450
1451 _public_ int sd_event_add_post(
1452                 sd_event *e,
1453                 sd_event_source **ret,
1454                 sd_event_handler_t callback,
1455                 void *userdata) {
1456
1457         sd_event_source *s;
1458         int r;
1459
1460         assert_return(e, -EINVAL);
1461         assert_return(e = event_resolve(e), -ENOPKG);
1462         assert_return(callback, -EINVAL);
1463         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1464         assert_return(!event_pid_changed(e), -ECHILD);
1465
1466         r = set_ensure_allocated(&e->post_sources, NULL);
1467         if (r < 0)
1468                 return r;
1469
1470         s = source_new(e, !ret, SOURCE_POST);
1471         if (!s)
1472                 return -ENOMEM;
1473
1474         s->post.callback = callback;
1475         s->userdata = userdata;
1476         s->enabled = SD_EVENT_ON;
1477
1478         r = set_put(e->post_sources, s);
1479         if (r < 0) {
1480                 source_free(s);
1481                 return r;
1482         }
1483
1484         if (ret)
1485                 *ret = s;
1486
1487         return 0;
1488 }
1489
1490 _public_ int sd_event_add_exit(
1491                 sd_event *e,
1492                 sd_event_source **ret,
1493                 sd_event_handler_t callback,
1494                 void *userdata) {
1495
1496         sd_event_source *s;
1497         int r;
1498
1499         assert_return(e, -EINVAL);
1500         assert_return(e = event_resolve(e), -ENOPKG);
1501         assert_return(callback, -EINVAL);
1502         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1503         assert_return(!event_pid_changed(e), -ECHILD);
1504
1505         r = prioq_ensure_allocated(&e->exit, exit_prioq_compare);
1506         if (r < 0)
1507                 return r;
1508
1509         s = source_new(e, !ret, SOURCE_EXIT);
1510         if (!s)
1511                 return -ENOMEM;
1512
1513         s->exit.callback = callback;
1514         s->userdata = userdata;
1515         s->exit.prioq_index = PRIOQ_IDX_NULL;
1516         s->enabled = SD_EVENT_ONESHOT;
1517
1518         r = prioq_put(s->event->exit, s, &s->exit.prioq_index);
1519         if (r < 0) {
1520                 source_free(s);
1521                 return r;
1522         }
1523
1524         if (ret)
1525                 *ret = s;
1526
1527         return 0;
1528 }
1529
1530 static void event_free_inotify_data(sd_event *e, struct inotify_data *d) {
1531         assert(e);
1532
1533         if (!d)
1534                 return;
1535
1536         assert(hashmap_isempty(d->inodes));
1537         assert(hashmap_isempty(d->wd));
1538
1539         if (d->buffer_filled > 0)
1540                 LIST_REMOVE(buffered, e->inotify_data_buffered, d);
1541
1542         hashmap_free(d->inodes);
1543         hashmap_free(d->wd);
1544
1545         assert_se(hashmap_remove(e->inotify_data, &d->priority) == d);
1546
1547         if (d->fd >= 0) {
1548                 if (epoll_ctl(e->epoll_fd, EPOLL_CTL_DEL, d->fd, NULL) < 0)
1549                         log_debug_errno(errno, "Failed to remove inotify fd from epoll, ignoring: %m");
1550
1551                 safe_close(d->fd);
1552         }
1553         free(d);
1554 }
1555
1556 static int event_make_inotify_data(
1557                 sd_event *e,
1558                 int64_t priority,
1559                 struct inotify_data **ret) {
1560
1561         _cleanup_close_ int fd = -1;
1562         struct inotify_data *d;
1563         struct epoll_event ev;
1564         int r;
1565
1566         assert(e);
1567
1568         d = hashmap_get(e->inotify_data, &priority);
1569         if (d) {
1570                 if (ret)
1571                         *ret = d;
1572                 return 0;
1573         }
1574
1575         fd = inotify_init1(IN_NONBLOCK|O_CLOEXEC);
1576         if (fd < 0)
1577                 return -errno;
1578
1579         fd = fd_move_above_stdio(fd);
1580
1581         r = hashmap_ensure_allocated(&e->inotify_data, &uint64_hash_ops);
1582         if (r < 0)
1583                 return r;
1584
1585         d = new(struct inotify_data, 1);
1586         if (!d)
1587                 return -ENOMEM;
1588
1589         *d = (struct inotify_data) {
1590                 .wakeup = WAKEUP_INOTIFY_DATA,
1591                 .fd = TAKE_FD(fd),
1592                 .priority = priority,
1593         };
1594
1595         r = hashmap_put(e->inotify_data, &d->priority, d);
1596         if (r < 0) {
1597                 d->fd = safe_close(d->fd);
1598                 free(d);
1599                 return r;
1600         }
1601
1602         ev = (struct epoll_event) {
1603                 .events = EPOLLIN,
1604                 .data.ptr = d,
1605         };
1606
1607         if (epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, d->fd, &ev) < 0) {
1608                 r = -errno;
1609                 d->fd = safe_close(d->fd); /* let's close this ourselves, as event_free_inotify_data() would otherwise
1610                                             * remove the fd from the epoll first, which we don't want as we couldn't
1611                                             * add it in the first place. */
1612                 event_free_inotify_data(e, d);
1613                 return r;
1614         }
1615
1616         if (ret)
1617                 *ret = d;
1618
1619         return 1;
1620 }
1621
1622 static int inode_data_compare(const void *a, const void *b) {
1623         const struct inode_data *x = a, *y = b;
1624
1625         assert(x);
1626         assert(y);
1627
1628         if (x->dev < y->dev)
1629                 return -1;
1630         if (x->dev > y->dev)
1631                 return 1;
1632
1633         if (x->ino < y->ino)
1634                 return -1;
1635         if (x->ino > y->ino)
1636                 return 1;
1637
1638         return 0;
1639 }
1640
1641 static void inode_data_hash_func(const void *p, struct siphash *state) {
1642         const struct inode_data *d = p;
1643
1644         assert(p);
1645
1646         siphash24_compress(&d->dev, sizeof(d->dev), state);
1647         siphash24_compress(&d->ino, sizeof(d->ino), state);
1648 }
1649
1650 const struct hash_ops inode_data_hash_ops = {
1651         .hash = inode_data_hash_func,
1652         .compare = inode_data_compare
1653 };
1654
1655 static void event_free_inode_data(
1656                 sd_event *e,
1657                 struct inode_data *d) {
1658
1659         assert(e);
1660
1661         if (!d)
1662                 return;
1663
1664         assert(!d->event_sources);
1665
1666         if (d->fd >= 0) {
1667                 LIST_REMOVE(to_close, e->inode_data_to_close, d);
1668                 safe_close(d->fd);
1669         }
1670
1671         if (d->inotify_data) {
1672
1673                 if (d->wd >= 0) {
1674                         if (d->inotify_data->fd >= 0) {
1675                                 /* So here's a problem. At the time this runs the watch descriptor might already be
1676                                  * invalidated, because an IN_IGNORED event might be queued right the moment we enter
1677                                  * the syscall. Hence, whenever we get EINVAL, ignore it entirely, since it's a very
1678                                  * likely case to happen. */
1679
1680                                 if (inotify_rm_watch(d->inotify_data->fd, d->wd) < 0 && errno != EINVAL)
1681                                         log_debug_errno(errno, "Failed to remove watch descriptor %i from inotify, ignoring: %m", d->wd);
1682                         }
1683
1684                         assert_se(hashmap_remove(d->inotify_data->wd, INT_TO_PTR(d->wd)) == d);
1685                 }
1686
1687                 assert_se(hashmap_remove(d->inotify_data->inodes, d) == d);
1688         }
1689
1690         free(d);
1691 }
1692
1693 static void event_gc_inode_data(
1694                 sd_event *e,
1695                 struct inode_data *d) {
1696
1697         struct inotify_data *inotify_data;
1698
1699         assert(e);
1700
1701         if (!d)
1702                 return;
1703
1704         if (d->event_sources)
1705                 return;
1706
1707         inotify_data = d->inotify_data;
1708         event_free_inode_data(e, d);
1709
1710         if (inotify_data && hashmap_isempty(inotify_data->inodes))
1711                 event_free_inotify_data(e, inotify_data);
1712 }
1713
1714 static int event_make_inode_data(
1715                 sd_event *e,
1716                 struct inotify_data *inotify_data,
1717                 dev_t dev,
1718                 ino_t ino,
1719                 struct inode_data **ret) {
1720
1721         struct inode_data *d, key;
1722         int r;
1723
1724         assert(e);
1725         assert(inotify_data);
1726
1727         key = (struct inode_data) {
1728                 .ino = ino,
1729                 .dev = dev,
1730         };
1731
1732         d = hashmap_get(inotify_data->inodes, &key);
1733         if (d) {
1734                 if (ret)
1735                         *ret = d;
1736
1737                 return 0;
1738         }
1739
1740         r = hashmap_ensure_allocated(&inotify_data->inodes, &inode_data_hash_ops);
1741         if (r < 0)
1742                 return r;
1743
1744         d = new(struct inode_data, 1);
1745         if (!d)
1746                 return -ENOMEM;
1747
1748         *d = (struct inode_data) {
1749                 .dev = dev,
1750                 .ino = ino,
1751                 .wd = -1,
1752                 .fd = -1,
1753                 .inotify_data = inotify_data,
1754         };
1755
1756         r = hashmap_put(inotify_data->inodes, d, d);
1757         if (r < 0) {
1758                 free(d);
1759                 return r;
1760         }
1761
1762         if (ret)
1763                 *ret = d;
1764
1765         return 1;
1766 }
1767
1768 static uint32_t inode_data_determine_mask(struct inode_data *d) {
1769         bool excl_unlink = true;
1770         uint32_t combined = 0;
1771         sd_event_source *s;
1772
1773         assert(d);
1774
1775         /* Combines the watch masks of all event sources watching this inode. We generally just OR them together, but
1776          * the IN_EXCL_UNLINK flag is ANDed instead.
1777          *
1778          * Note that we add all sources to the mask here, regardless whether enabled, disabled or oneshot. That's
1779          * because we cannot change the mask anymore after the event source was created once, since the kernel has no
1780          * API for that. Hence we need to subscribe to the maximum mask we ever might be interested in, and supress
1781          * events we don't care for client-side. */
1782
1783         LIST_FOREACH(inotify.by_inode_data, s, d->event_sources) {
1784
1785                 if ((s->inotify.mask & IN_EXCL_UNLINK) == 0)
1786                         excl_unlink = false;
1787
1788                 combined |= s->inotify.mask;
1789         }
1790
1791         return (combined & ~(IN_ONESHOT|IN_DONT_FOLLOW|IN_ONLYDIR|IN_EXCL_UNLINK)) | (excl_unlink ? IN_EXCL_UNLINK : 0);
1792 }
1793
1794 static int inode_data_realize_watch(sd_event *e, struct inode_data *d) {
1795         uint32_t combined_mask;
1796         int wd, r;
1797
1798         assert(d);
1799         assert(d->fd >= 0);
1800
1801         combined_mask = inode_data_determine_mask(d);
1802
1803         if (d->wd >= 0 && combined_mask == d->combined_mask)
1804                 return 0;
1805
1806         r = hashmap_ensure_allocated(&d->inotify_data->wd, NULL);
1807         if (r < 0)
1808                 return r;
1809
1810         wd = inotify_add_watch_fd(d->inotify_data->fd, d->fd, combined_mask);
1811         if (wd < 0)
1812                 return -errno;
1813
1814         if (d->wd < 0) {
1815                 r = hashmap_put(d->inotify_data->wd, INT_TO_PTR(wd), d);
1816                 if (r < 0) {
1817                         (void) inotify_rm_watch(d->inotify_data->fd, wd);
1818                         return r;
1819                 }
1820
1821                 d->wd = wd;
1822
1823         } else if (d->wd != wd) {
1824
1825                 log_debug("Weird, the watch descriptor we already knew for this inode changed?");
1826                 (void) inotify_rm_watch(d->fd, wd);
1827                 return -EINVAL;
1828         }
1829
1830         d->combined_mask = combined_mask;
1831         return 1;
1832 }
1833
1834 _public_ int sd_event_add_inotify(
1835                 sd_event *e,
1836                 sd_event_source **ret,
1837                 const char *path,
1838                 uint32_t mask,
1839                 sd_event_inotify_handler_t callback,
1840                 void *userdata) {
1841
1842         bool rm_inotify = false, rm_inode = false;
1843         struct inotify_data *inotify_data = NULL;
1844         struct inode_data *inode_data = NULL;
1845         _cleanup_close_ int fd = -1;
1846         sd_event_source *s;
1847         struct stat st;
1848         int r;
1849
1850         assert_return(e, -EINVAL);
1851         assert_return(e = event_resolve(e), -ENOPKG);
1852         assert_return(path, -EINVAL);
1853         assert_return(callback, -EINVAL);
1854         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1855         assert_return(!event_pid_changed(e), -ECHILD);
1856
1857         /* Refuse IN_MASK_ADD since we coalesce watches on the same inode, and hence really don't want to merge
1858          * masks. Or in other words, this whole code exists only to manage IN_MASK_ADD type operations for you, hence
1859          * the user can't use them for us. */
1860         if (mask & IN_MASK_ADD)
1861                 return -EINVAL;
1862
1863         fd = open(path, O_PATH|O_CLOEXEC|
1864                   (mask & IN_ONLYDIR ? O_DIRECTORY : 0)|
1865                   (mask & IN_DONT_FOLLOW ? O_NOFOLLOW : 0));
1866         if (fd < 0)
1867                 return -errno;
1868
1869         if (fstat(fd, &st) < 0)
1870                 return -errno;
1871
1872         s = source_new(e, !ret, SOURCE_INOTIFY);
1873         if (!s)
1874                 return -ENOMEM;
1875
1876         s->enabled = mask & IN_ONESHOT ? SD_EVENT_ONESHOT : SD_EVENT_ON;
1877         s->inotify.mask = mask;
1878         s->inotify.callback = callback;
1879         s->userdata = userdata;
1880
1881         /* Allocate an inotify object for this priority, and an inode object within it */
1882         r = event_make_inotify_data(e, SD_EVENT_PRIORITY_NORMAL, &inotify_data);
1883         if (r < 0)
1884                 goto fail;
1885         rm_inotify = r > 0;
1886
1887         r = event_make_inode_data(e, inotify_data, st.st_dev, st.st_ino, &inode_data);
1888         if (r < 0)
1889                 goto fail;
1890         rm_inode = r > 0;
1891
1892         /* Keep the O_PATH fd around until the first iteration of the loop, so that we can still change the priority of
1893          * the event source, until then, for which we need the original inode. */
1894         if (inode_data->fd < 0) {
1895                 inode_data->fd = TAKE_FD(fd);
1896                 LIST_PREPEND(to_close, e->inode_data_to_close, inode_data);
1897         }
1898
1899         /* Link our event source to the inode data object */
1900         LIST_PREPEND(inotify.by_inode_data, inode_data->event_sources, s);
1901         s->inotify.inode_data = inode_data;
1902
1903         rm_inode = rm_inotify = false;
1904
1905         /* Actually realize the watch now */
1906         r = inode_data_realize_watch(e, inode_data);
1907         if (r < 0)
1908                 goto fail;
1909
1910         (void) sd_event_source_set_description(s, path);
1911
1912         if (ret)
1913                 *ret = s;
1914
1915         return 0;
1916
1917 fail:
1918         source_free(s);
1919
1920         if (rm_inode)
1921                 event_free_inode_data(e, inode_data);
1922
1923         if (rm_inotify)
1924                 event_free_inotify_data(e, inotify_data);
1925
1926         return r;
1927 }
1928
1929 _public_ sd_event_source* sd_event_source_ref(sd_event_source *s) {
1930
1931         if (!s)
1932                 return NULL;
1933
1934         assert(s->n_ref >= 1);
1935         s->n_ref++;
1936
1937         return s;
1938 }
1939
1940 _public_ sd_event_source* sd_event_source_unref(sd_event_source *s) {
1941
1942         if (!s)
1943                 return NULL;
1944
1945         assert(s->n_ref >= 1);
1946         s->n_ref--;
1947
1948         if (s->n_ref <= 0) {
1949                 /* Here's a special hack: when we are called from a
1950                  * dispatch handler we won't free the event source
1951                  * immediately, but we will detach the fd from the
1952                  * epoll. This way it is safe for the caller to unref
1953                  * the event source and immediately close the fd, but
1954                  * we still retain a valid event source object after
1955                  * the callback. */
1956
1957                 if (s->dispatching) {
1958                         if (s->type == SOURCE_IO)
1959                                 source_io_unregister(s);
1960
1961                         source_disconnect(s);
1962                 } else
1963                         source_free(s);
1964         }
1965
1966         return NULL;
1967 }
1968
1969 _public_ int sd_event_source_set_description(sd_event_source *s, const char *description) {
1970         assert_return(s, -EINVAL);
1971         assert_return(!event_pid_changed(s->event), -ECHILD);
1972
1973         return free_and_strdup(&s->description, description);
1974 }
1975
1976 _public_ int sd_event_source_get_description(sd_event_source *s, const char **description) {
1977         assert_return(s, -EINVAL);
1978         assert_return(description, -EINVAL);
1979         assert_return(s->description, -ENXIO);
1980         assert_return(!event_pid_changed(s->event), -ECHILD);
1981
1982         *description = s->description;
1983         return 0;
1984 }
1985
1986 _public_ sd_event *sd_event_source_get_event(sd_event_source *s) {
1987         assert_return(s, NULL);
1988
1989         return s->event;
1990 }
1991
1992 _public_ int sd_event_source_get_pending(sd_event_source *s) {
1993         assert_return(s, -EINVAL);
1994         assert_return(s->type != SOURCE_EXIT, -EDOM);
1995         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
1996         assert_return(!event_pid_changed(s->event), -ECHILD);
1997
1998         return s->pending;
1999 }
2000
2001 _public_ int sd_event_source_get_io_fd(sd_event_source *s) {
2002         assert_return(s, -EINVAL);
2003         assert_return(s->type == SOURCE_IO, -EDOM);
2004         assert_return(!event_pid_changed(s->event), -ECHILD);
2005
2006         return s->io.fd;
2007 }
2008
2009 _public_ int sd_event_source_set_io_fd(sd_event_source *s, int fd) {
2010         int r;
2011
2012         assert_return(s, -EINVAL);
2013         assert_return(fd >= 0, -EBADF);
2014         assert_return(s->type == SOURCE_IO, -EDOM);
2015         assert_return(!event_pid_changed(s->event), -ECHILD);
2016
2017         if (s->io.fd == fd)
2018                 return 0;
2019
2020         if (s->enabled == SD_EVENT_OFF) {
2021                 s->io.fd = fd;
2022                 s->io.registered = false;
2023         } else {
2024                 int saved_fd;
2025
2026                 saved_fd = s->io.fd;
2027                 assert(s->io.registered);
2028
2029                 s->io.fd = fd;
2030                 s->io.registered = false;
2031
2032                 r = source_io_register(s, s->enabled, s->io.events);
2033                 if (r < 0) {
2034                         s->io.fd = saved_fd;
2035                         s->io.registered = true;
2036                         return r;
2037                 }
2038
2039                 epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, saved_fd, NULL);
2040         }
2041
2042         return 0;
2043 }
2044
2045 _public_ int sd_event_source_get_io_fd_own(sd_event_source *s) {
2046         assert_return(s, -EINVAL);
2047         assert_return(s->type == SOURCE_IO, -EDOM);
2048
2049         return s->io.owned;
2050 }
2051
2052 _public_ int sd_event_source_set_io_fd_own(sd_event_source *s, int own) {
2053         assert_return(s, -EINVAL);
2054         assert_return(s->type == SOURCE_IO, -EDOM);
2055
2056         s->io.owned = own;
2057         return 0;
2058 }
2059
2060 _public_ int sd_event_source_get_io_events(sd_event_source *s, uint32_t* events) {
2061         assert_return(s, -EINVAL);
2062         assert_return(events, -EINVAL);
2063         assert_return(s->type == SOURCE_IO, -EDOM);
2064         assert_return(!event_pid_changed(s->event), -ECHILD);
2065
2066         *events = s->io.events;
2067         return 0;
2068 }
2069
2070 _public_ int sd_event_source_set_io_events(sd_event_source *s, uint32_t events) {
2071         int r;
2072
2073         assert_return(s, -EINVAL);
2074         assert_return(s->type == SOURCE_IO, -EDOM);
2075         assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
2076         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2077         assert_return(!event_pid_changed(s->event), -ECHILD);
2078
2079         /* edge-triggered updates are never skipped, so we can reset edges */
2080         if (s->io.events == events && !(events & EPOLLET))
2081                 return 0;
2082
2083         r = source_set_pending(s, false);
2084         if (r < 0)
2085                 return r;
2086
2087         if (s->enabled != SD_EVENT_OFF) {
2088                 r = source_io_register(s, s->enabled, events);
2089                 if (r < 0)
2090                         return r;
2091         }
2092
2093         s->io.events = events;
2094
2095         return 0;
2096 }
2097
2098 _public_ int sd_event_source_get_io_revents(sd_event_source *s, uint32_t* revents) {
2099         assert_return(s, -EINVAL);
2100         assert_return(revents, -EINVAL);
2101         assert_return(s->type == SOURCE_IO, -EDOM);
2102         assert_return(s->pending, -ENODATA);
2103         assert_return(!event_pid_changed(s->event), -ECHILD);
2104
2105         *revents = s->io.revents;
2106         return 0;
2107 }
2108
2109 _public_ int sd_event_source_get_signal(sd_event_source *s) {
2110         assert_return(s, -EINVAL);
2111         assert_return(s->type == SOURCE_SIGNAL, -EDOM);
2112         assert_return(!event_pid_changed(s->event), -ECHILD);
2113
2114         return s->signal.sig;
2115 }
2116
2117 _public_ int sd_event_source_get_priority(sd_event_source *s, int64_t *priority) {
2118         assert_return(s, -EINVAL);
2119         assert_return(!event_pid_changed(s->event), -ECHILD);
2120
2121         *priority = s->priority;
2122         return 0;
2123 }
2124
2125 _public_ int sd_event_source_set_priority(sd_event_source *s, int64_t priority) {
2126         bool rm_inotify = false, rm_inode = false;
2127         struct inotify_data *new_inotify_data = NULL;
2128         struct inode_data *new_inode_data = NULL;
2129         int r;
2130
2131         assert_return(s, -EINVAL);
2132         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2133         assert_return(!event_pid_changed(s->event), -ECHILD);
2134
2135         if (s->priority == priority)
2136                 return 0;
2137
2138         if (s->type == SOURCE_INOTIFY) {
2139                 struct inode_data *old_inode_data;
2140
2141                 assert(s->inotify.inode_data);
2142                 old_inode_data = s->inotify.inode_data;
2143
2144                 /* We need the original fd to change the priority. If we don't have it we can't change the priority,
2145                  * anymore. Note that we close any fds when entering the next event loop iteration, i.e. for inotify
2146                  * events we allow priority changes only until the first following iteration. */
2147                 if (old_inode_data->fd < 0)
2148                         return -EOPNOTSUPP;
2149
2150                 r = event_make_inotify_data(s->event, priority, &new_inotify_data);
2151                 if (r < 0)
2152                         return r;
2153                 rm_inotify = r > 0;
2154
2155                 r = event_make_inode_data(s->event, new_inotify_data, old_inode_data->dev, old_inode_data->ino, &new_inode_data);
2156                 if (r < 0)
2157                         goto fail;
2158                 rm_inode = r > 0;
2159
2160                 if (new_inode_data->fd < 0) {
2161                         /* Duplicate the fd for the new inode object if we don't have any yet */
2162                         new_inode_data->fd = fcntl(old_inode_data->fd, F_DUPFD_CLOEXEC, 3);
2163                         if (new_inode_data->fd < 0) {
2164                                 r = -errno;
2165                                 goto fail;
2166                         }
2167
2168                         LIST_PREPEND(to_close, s->event->inode_data_to_close, new_inode_data);
2169                 }
2170
2171                 /* Move the event source to the new inode data structure */
2172                 LIST_REMOVE(inotify.by_inode_data, old_inode_data->event_sources, s);
2173                 LIST_PREPEND(inotify.by_inode_data, new_inode_data->event_sources, s);
2174                 s->inotify.inode_data = new_inode_data;
2175
2176                 /* Now create the new watch */
2177                 r = inode_data_realize_watch(s->event, new_inode_data);
2178                 if (r < 0) {
2179                         /* Move it back */
2180                         LIST_REMOVE(inotify.by_inode_data, new_inode_data->event_sources, s);
2181                         LIST_PREPEND(inotify.by_inode_data, old_inode_data->event_sources, s);
2182                         s->inotify.inode_data = old_inode_data;
2183                         goto fail;
2184                 }
2185
2186                 s->priority = priority;
2187
2188                 event_gc_inode_data(s->event, old_inode_data);
2189
2190         } else if (s->type == SOURCE_SIGNAL && s->enabled != SD_EVENT_OFF) {
2191                 struct signal_data *old, *d;
2192
2193                 /* Move us from the signalfd belonging to the old
2194                  * priority to the signalfd of the new priority */
2195
2196                 assert_se(old = hashmap_get(s->event->signal_data, &s->priority));
2197
2198                 s->priority = priority;
2199
2200                 r = event_make_signal_data(s->event, s->signal.sig, &d);
2201                 if (r < 0) {
2202                         s->priority = old->priority;
2203                         return r;
2204                 }
2205
2206                 event_unmask_signal_data(s->event, old, s->signal.sig);
2207         } else
2208                 s->priority = priority;
2209
2210         if (s->pending)
2211                 prioq_reshuffle(s->event->pending, s, &s->pending_index);
2212
2213         if (s->prepare)
2214                 prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
2215
2216         if (s->type == SOURCE_EXIT)
2217                 prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
2218
2219         return 0;
2220
2221 fail:
2222         if (rm_inode)
2223                 event_free_inode_data(s->event, new_inode_data);
2224
2225         if (rm_inotify)
2226                 event_free_inotify_data(s->event, new_inotify_data);
2227
2228         return r;
2229 }
2230
2231 _public_ int sd_event_source_get_enabled(sd_event_source *s, int *m) {
2232         assert_return(s, -EINVAL);
2233         assert_return(m, -EINVAL);
2234         assert_return(!event_pid_changed(s->event), -ECHILD);
2235
2236         *m = s->enabled;
2237         return 0;
2238 }
2239
2240 _public_ int sd_event_source_set_enabled(sd_event_source *s, int m) {
2241         int r;
2242
2243         assert_return(s, -EINVAL);
2244         assert_return(IN_SET(m, SD_EVENT_OFF, SD_EVENT_ON, SD_EVENT_ONESHOT), -EINVAL);
2245         assert_return(!event_pid_changed(s->event), -ECHILD);
2246
2247         /* If we are dead anyway, we are fine with turning off
2248          * sources, but everything else needs to fail. */
2249         if (s->event->state == SD_EVENT_FINISHED)
2250                 return m == SD_EVENT_OFF ? 0 : -ESTALE;
2251
2252         if (s->enabled == m)
2253                 return 0;
2254
2255         if (m == SD_EVENT_OFF) {
2256
2257                 /* Unset the pending flag when this event source is disabled */
2258                 if (!IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
2259                         r = source_set_pending(s, false);
2260                         if (r < 0)
2261                                 return r;
2262                 }
2263
2264                 switch (s->type) {
2265
2266                 case SOURCE_IO:
2267                         source_io_unregister(s);
2268                         s->enabled = m;
2269                         break;
2270
2271                 case SOURCE_TIME_REALTIME:
2272                 case SOURCE_TIME_BOOTTIME:
2273                 case SOURCE_TIME_MONOTONIC:
2274                 case SOURCE_TIME_REALTIME_ALARM:
2275                 case SOURCE_TIME_BOOTTIME_ALARM: {
2276                         struct clock_data *d;
2277
2278                         s->enabled = m;
2279                         d = event_get_clock_data(s->event, s->type);
2280                         assert(d);
2281
2282                         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
2283                         prioq_reshuffle(d->latest, s, &s->time.latest_index);
2284                         d->needs_rearm = true;
2285                         break;
2286                 }
2287
2288                 case SOURCE_SIGNAL:
2289                         s->enabled = m;
2290
2291                         event_gc_signal_data(s->event, &s->priority, s->signal.sig);
2292                         break;
2293
2294                 case SOURCE_CHILD:
2295                         s->enabled = m;
2296
2297                         assert(s->event->n_enabled_child_sources > 0);
2298                         s->event->n_enabled_child_sources--;
2299
2300                         event_gc_signal_data(s->event, &s->priority, SIGCHLD);
2301                         break;
2302
2303                 case SOURCE_EXIT:
2304                         s->enabled = m;
2305                         prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
2306                         break;
2307
2308                 case SOURCE_DEFER:
2309                 case SOURCE_POST:
2310                 case SOURCE_INOTIFY:
2311                         s->enabled = m;
2312                         break;
2313
2314                 default:
2315                         assert_not_reached("Wut? I shouldn't exist.");
2316                 }
2317
2318         } else {
2319
2320                 /* Unset the pending flag when this event source is enabled */
2321                 if (s->enabled == SD_EVENT_OFF && !IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
2322                         r = source_set_pending(s, false);
2323                         if (r < 0)
2324                                 return r;
2325                 }
2326
2327                 switch (s->type) {
2328
2329                 case SOURCE_IO:
2330                         r = source_io_register(s, m, s->io.events);
2331                         if (r < 0)
2332                                 return r;
2333
2334                         s->enabled = m;
2335                         break;
2336
2337                 case SOURCE_TIME_REALTIME:
2338                 case SOURCE_TIME_BOOTTIME:
2339                 case SOURCE_TIME_MONOTONIC:
2340                 case SOURCE_TIME_REALTIME_ALARM:
2341                 case SOURCE_TIME_BOOTTIME_ALARM: {
2342                         struct clock_data *d;
2343
2344                         s->enabled = m;
2345                         d = event_get_clock_data(s->event, s->type);
2346                         assert(d);
2347
2348                         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
2349                         prioq_reshuffle(d->latest, s, &s->time.latest_index);
2350                         d->needs_rearm = true;
2351                         break;
2352                 }
2353
2354                 case SOURCE_SIGNAL:
2355
2356                         s->enabled = m;
2357
2358                         r = event_make_signal_data(s->event, s->signal.sig, NULL);
2359                         if (r < 0) {
2360                                 s->enabled = SD_EVENT_OFF;
2361                                 event_gc_signal_data(s->event, &s->priority, s->signal.sig);
2362                                 return r;
2363                         }
2364
2365                         break;
2366
2367                 case SOURCE_CHILD:
2368
2369                         if (s->enabled == SD_EVENT_OFF)
2370                                 s->event->n_enabled_child_sources++;
2371
2372                         s->enabled = m;
2373
2374                         r = event_make_signal_data(s->event, SIGCHLD, NULL);
2375                         if (r < 0) {
2376                                 s->enabled = SD_EVENT_OFF;
2377                                 s->event->n_enabled_child_sources--;
2378                                 event_gc_signal_data(s->event, &s->priority, SIGCHLD);
2379                                 return r;
2380                         }
2381
2382                         break;
2383
2384                 case SOURCE_EXIT:
2385                         s->enabled = m;
2386                         prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
2387                         break;
2388
2389                 case SOURCE_DEFER:
2390                 case SOURCE_POST:
2391                 case SOURCE_INOTIFY:
2392                         s->enabled = m;
2393                         break;
2394
2395                 default:
2396                         assert_not_reached("Wut? I shouldn't exist.");
2397                 }
2398         }
2399
2400         if (s->pending)
2401                 prioq_reshuffle(s->event->pending, s, &s->pending_index);
2402
2403         if (s->prepare)
2404                 prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
2405
2406         return 0;
2407 }
2408
2409 _public_ int sd_event_source_get_time(sd_event_source *s, uint64_t *usec) {
2410         assert_return(s, -EINVAL);
2411         assert_return(usec, -EINVAL);
2412         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
2413         assert_return(!event_pid_changed(s->event), -ECHILD);
2414
2415         *usec = s->time.next;
2416         return 0;
2417 }
2418
2419 _public_ int sd_event_source_set_time(sd_event_source *s, uint64_t usec) {
2420         struct clock_data *d;
2421         int r;
2422
2423         assert_return(s, -EINVAL);
2424         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
2425         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2426         assert_return(!event_pid_changed(s->event), -ECHILD);
2427
2428         r = source_set_pending(s, false);
2429         if (r < 0)
2430                 return r;
2431
2432         s->time.next = usec;
2433
2434         d = event_get_clock_data(s->event, s->type);
2435         assert(d);
2436
2437         prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
2438         prioq_reshuffle(d->latest, s, &s->time.latest_index);
2439         d->needs_rearm = true;
2440
2441         return 0;
2442 }
2443
2444 _public_ int sd_event_source_get_time_accuracy(sd_event_source *s, uint64_t *usec) {
2445         assert_return(s, -EINVAL);
2446         assert_return(usec, -EINVAL);
2447         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
2448         assert_return(!event_pid_changed(s->event), -ECHILD);
2449
2450         *usec = s->time.accuracy;
2451         return 0;
2452 }
2453
2454 _public_ int sd_event_source_set_time_accuracy(sd_event_source *s, uint64_t usec) {
2455         struct clock_data *d;
2456         int r;
2457
2458         assert_return(s, -EINVAL);
2459         assert_return(usec != (uint64_t) -1, -EINVAL);
2460         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
2461         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2462         assert_return(!event_pid_changed(s->event), -ECHILD);
2463
2464         r = source_set_pending(s, false);
2465         if (r < 0)
2466                 return r;
2467
2468         if (usec == 0)
2469                 usec = DEFAULT_ACCURACY_USEC;
2470
2471         s->time.accuracy = usec;
2472
2473         d = event_get_clock_data(s->event, s->type);
2474         assert(d);
2475
2476         prioq_reshuffle(d->latest, s, &s->time.latest_index);
2477         d->needs_rearm = true;
2478
2479         return 0;
2480 }
2481
2482 _public_ int sd_event_source_get_time_clock(sd_event_source *s, clockid_t *clock) {
2483         assert_return(s, -EINVAL);
2484         assert_return(clock, -EINVAL);
2485         assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
2486         assert_return(!event_pid_changed(s->event), -ECHILD);
2487
2488         *clock = event_source_type_to_clock(s->type);
2489         return 0;
2490 }
2491
2492 _public_ int sd_event_source_get_child_pid(sd_event_source *s, pid_t *pid) {
2493         assert_return(s, -EINVAL);
2494         assert_return(pid, -EINVAL);
2495         assert_return(s->type == SOURCE_CHILD, -EDOM);
2496         assert_return(!event_pid_changed(s->event), -ECHILD);
2497
2498         *pid = s->child.pid;
2499         return 0;
2500 }
2501
2502 _public_ int sd_event_source_get_inotify_mask(sd_event_source *s, uint32_t *mask) {
2503         assert_return(s, -EINVAL);
2504         assert_return(mask, -EINVAL);
2505         assert_return(s->type == SOURCE_INOTIFY, -EDOM);
2506         assert_return(!event_pid_changed(s->event), -ECHILD);
2507
2508         *mask = s->inotify.mask;
2509         return 0;
2510 }
2511
2512 _public_ int sd_event_source_set_prepare(sd_event_source *s, sd_event_handler_t callback) {
2513         int r;
2514
2515         assert_return(s, -EINVAL);
2516         assert_return(s->type != SOURCE_EXIT, -EDOM);
2517         assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2518         assert_return(!event_pid_changed(s->event), -ECHILD);
2519
2520         if (s->prepare == callback)
2521                 return 0;
2522
2523         if (callback && s->prepare) {
2524                 s->prepare = callback;
2525                 return 0;
2526         }
2527
2528         r = prioq_ensure_allocated(&s->event->prepare, prepare_prioq_compare);
2529         if (r < 0)
2530                 return r;
2531
2532         s->prepare = callback;
2533
2534         if (callback) {
2535                 r = prioq_put(s->event->prepare, s, &s->prepare_index);
2536                 if (r < 0)
2537                         return r;
2538         } else
2539                 prioq_remove(s->event->prepare, s, &s->prepare_index);
2540
2541         return 0;
2542 }
2543
2544 _public_ void* sd_event_source_get_userdata(sd_event_source *s) {
2545         assert_return(s, NULL);
2546
2547         return s->userdata;
2548 }
2549
2550 _public_ void *sd_event_source_set_userdata(sd_event_source *s, void *userdata) {
2551         void *ret;
2552
2553         assert_return(s, NULL);
2554
2555         ret = s->userdata;
2556         s->userdata = userdata;
2557
2558         return ret;
2559 }
2560
2561 static usec_t sleep_between(sd_event *e, usec_t a, usec_t b) {
2562         usec_t c;
2563         assert(e);
2564         assert(a <= b);
2565
2566         if (a <= 0)
2567                 return 0;
2568         if (a >= USEC_INFINITY)
2569                 return USEC_INFINITY;
2570
2571         if (b <= a + 1)
2572                 return a;
2573
2574         initialize_perturb(e);
2575
2576         /*
2577           Find a good time to wake up again between times a and b. We
2578           have two goals here:
2579
2580           a) We want to wake up as seldom as possible, hence prefer
2581              later times over earlier times.
2582
2583           b) But if we have to wake up, then let's make sure to
2584              dispatch as much as possible on the entire system.
2585
2586           We implement this by waking up everywhere at the same time
2587           within any given minute if we can, synchronised via the
2588           perturbation value determined from the boot ID. If we can't,
2589           then we try to find the same spot in every 10s, then 1s and
2590           then 250ms step. Otherwise, we pick the last possible time
2591           to wake up.
2592         */
2593
2594         c = (b / USEC_PER_MINUTE) * USEC_PER_MINUTE + e->perturb;
2595         if (c >= b) {
2596                 if (_unlikely_(c < USEC_PER_MINUTE))
2597                         return b;
2598
2599                 c -= USEC_PER_MINUTE;
2600         }
2601
2602         if (c >= a)
2603                 return c;
2604
2605         c = (b / (USEC_PER_SEC*10)) * (USEC_PER_SEC*10) + (e->perturb % (USEC_PER_SEC*10));
2606         if (c >= b) {
2607                 if (_unlikely_(c < USEC_PER_SEC*10))
2608                         return b;
2609
2610                 c -= USEC_PER_SEC*10;
2611         }
2612
2613         if (c >= a)
2614                 return c;
2615
2616         c = (b / USEC_PER_SEC) * USEC_PER_SEC + (e->perturb % USEC_PER_SEC);
2617         if (c >= b) {
2618                 if (_unlikely_(c < USEC_PER_SEC))
2619                         return b;
2620
2621                 c -= USEC_PER_SEC;
2622         }
2623
2624         if (c >= a)
2625                 return c;
2626
2627         c = (b / (USEC_PER_MSEC*250)) * (USEC_PER_MSEC*250) + (e->perturb % (USEC_PER_MSEC*250));
2628         if (c >= b) {
2629                 if (_unlikely_(c < USEC_PER_MSEC*250))
2630                         return b;
2631
2632                 c -= USEC_PER_MSEC*250;
2633         }
2634
2635         if (c >= a)
2636                 return c;
2637
2638         return b;
2639 }
2640
2641 static int event_arm_timer(
2642                 sd_event *e,
2643                 struct clock_data *d) {
2644
2645         struct itimerspec its = {};
2646         sd_event_source *a, *b;
2647         usec_t t;
2648         int r;
2649
2650         assert(e);
2651         assert(d);
2652
2653         if (!d->needs_rearm)
2654                 return 0;
2655         else
2656                 d->needs_rearm = false;
2657
2658         a = prioq_peek(d->earliest);
2659         if (!a || a->enabled == SD_EVENT_OFF || a->time.next == USEC_INFINITY) {
2660
2661                 if (d->fd < 0)
2662                         return 0;
2663
2664                 if (d->next == USEC_INFINITY)
2665                         return 0;
2666
2667                 /* disarm */
2668                 r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
2669                 if (r < 0)
2670                         return r;
2671
2672                 d->next = USEC_INFINITY;
2673                 return 0;
2674         }
2675
2676         b = prioq_peek(d->latest);
2677         assert_se(b && b->enabled != SD_EVENT_OFF);
2678
2679         t = sleep_between(e, a->time.next, time_event_source_latest(b));
2680         if (d->next == t)
2681                 return 0;
2682
2683         assert_se(d->fd >= 0);
2684
2685         if (t == 0) {
2686                 /* We don' want to disarm here, just mean some time looooong ago. */
2687                 its.it_value.tv_sec = 0;
2688                 its.it_value.tv_nsec = 1;
2689         } else
2690                 timespec_store(&its.it_value, t);
2691
2692         r = timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL);
2693         if (r < 0)
2694                 return -errno;
2695
2696         d->next = t;
2697         return 0;
2698 }
2699
2700 static int process_io(sd_event *e, sd_event_source *s, uint32_t revents) {
2701         assert(e);
2702         assert(s);
2703         assert(s->type == SOURCE_IO);
2704
2705         /* If the event source was already pending, we just OR in the
2706          * new revents, otherwise we reset the value. The ORing is
2707          * necessary to handle EPOLLONESHOT events properly where
2708          * readability might happen independently of writability, and
2709          * we need to keep track of both */
2710
2711         if (s->pending)
2712                 s->io.revents |= revents;
2713         else
2714                 s->io.revents = revents;
2715
2716         return source_set_pending(s, true);
2717 }
2718
2719 static int flush_timer(sd_event *e, int fd, uint32_t events, usec_t *next) {
2720         uint64_t x;
2721         ssize_t ss;
2722
2723         assert(e);
2724         assert(fd >= 0);
2725
2726         assert_return(events == EPOLLIN, -EIO);
2727
2728         ss = read(fd, &x, sizeof(x));
2729         if (ss < 0) {
2730                 if (IN_SET(errno, EAGAIN, EINTR))
2731                         return 0;
2732
2733                 return -errno;
2734         }
2735
2736         if (_unlikely_(ss != sizeof(x)))
2737                 return -EIO;
2738
2739         if (next)
2740                 *next = USEC_INFINITY;
2741
2742         return 0;
2743 }
2744
2745 static int process_timer(
2746                 sd_event *e,
2747                 usec_t n,
2748                 struct clock_data *d) {
2749
2750         sd_event_source *s;
2751         int r;
2752
2753         assert(e);
2754         assert(d);
2755
2756         for (;;) {
2757                 s = prioq_peek(d->earliest);
2758                 if (!s ||
2759                     s->time.next > n ||
2760                     s->enabled == SD_EVENT_OFF ||
2761                     s->pending)
2762                         break;
2763
2764                 r = source_set_pending(s, true);
2765                 if (r < 0)
2766                         return r;
2767
2768                 prioq_reshuffle(d->earliest, s, &s->time.earliest_index);
2769                 prioq_reshuffle(d->latest, s, &s->time.latest_index);
2770                 d->needs_rearm = true;
2771         }
2772
2773         return 0;
2774 }
2775
2776 static int process_child(sd_event *e) {
2777         sd_event_source *s;
2778         Iterator i;
2779         int r;
2780
2781         assert(e);
2782
2783         e->need_process_child = false;
2784
2785         /*
2786            So, this is ugly. We iteratively invoke waitid() with P_PID
2787            + WNOHANG for each PID we wait for, instead of using
2788            P_ALL. This is because we only want to get child
2789            information of very specific child processes, and not all
2790            of them. We might not have processed the SIGCHLD even of a
2791            previous invocation and we don't want to maintain a
2792            unbounded *per-child* event queue, hence we really don't
2793            want anything flushed out of the kernel's queue that we
2794            don't care about. Since this is O(n) this means that if you
2795            have a lot of processes you probably want to handle SIGCHLD
2796            yourself.
2797
2798            We do not reap the children here (by using WNOWAIT), this
2799            is only done after the event source is dispatched so that
2800            the callback still sees the process as a zombie.
2801         */
2802
2803         HASHMAP_FOREACH(s, e->child_sources, i) {
2804                 assert(s->type == SOURCE_CHILD);
2805
2806                 if (s->pending)
2807                         continue;
2808
2809                 if (s->enabled == SD_EVENT_OFF)
2810                         continue;
2811
2812                 zero(s->child.siginfo);
2813                 r = waitid(P_PID, s->child.pid, &s->child.siginfo,
2814                            WNOHANG | (s->child.options & WEXITED ? WNOWAIT : 0) | s->child.options);
2815                 if (r < 0)
2816                         return -errno;
2817
2818                 if (s->child.siginfo.si_pid != 0) {
2819                         bool zombie = IN_SET(s->child.siginfo.si_code, CLD_EXITED, CLD_KILLED, CLD_DUMPED);
2820
2821                         if (!zombie && (s->child.options & WEXITED)) {
2822                                 /* If the child isn't dead then let's
2823                                  * immediately remove the state change
2824                                  * from the queue, since there's no
2825                                  * benefit in leaving it queued */
2826
2827                                 assert(s->child.options & (WSTOPPED|WCONTINUED));
2828                                 waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|(s->child.options & (WSTOPPED|WCONTINUED)));
2829                         }
2830
2831                         r = source_set_pending(s, true);
2832                         if (r < 0)
2833                                 return r;
2834                 }
2835         }
2836
2837         return 0;
2838 }
2839
2840 static int process_signal(sd_event *e, struct signal_data *d, uint32_t events) {
2841         bool read_one = false;
2842         int r;
2843
2844         assert(e);
2845         assert(d);
2846         assert_return(events == EPOLLIN, -EIO);
2847
2848         /* If there's a signal queued on this priority and SIGCHLD is
2849            on this priority too, then make sure to recheck the
2850            children we watch. This is because we only ever dequeue
2851            the first signal per priority, and if we dequeue one, and
2852            SIGCHLD might be enqueued later we wouldn't know, but we
2853            might have higher priority children we care about hence we
2854            need to check that explicitly. */
2855
2856         if (sigismember(&d->sigset, SIGCHLD))
2857                 e->need_process_child = true;
2858
2859         /* If there's already an event source pending for this
2860          * priority we don't read another */
2861         if (d->current)
2862                 return 0;
2863
2864         for (;;) {
2865                 struct signalfd_siginfo si;
2866                 ssize_t n;
2867                 sd_event_source *s = NULL;
2868
2869                 n = read(d->fd, &si, sizeof(si));
2870                 if (n < 0) {
2871                         if (IN_SET(errno, EAGAIN, EINTR))
2872                                 return read_one;
2873
2874                         return -errno;
2875                 }
2876
2877                 if (_unlikely_(n != sizeof(si)))
2878                         return -EIO;
2879
2880                 assert(SIGNAL_VALID(si.ssi_signo));
2881
2882                 read_one = true;
2883
2884                 if (e->signal_sources)
2885                         s = e->signal_sources[si.ssi_signo];
2886                 if (!s)
2887                         continue;
2888                 if (s->pending)
2889                         continue;
2890
2891                 s->signal.siginfo = si;
2892                 d->current = s;
2893
2894                 r = source_set_pending(s, true);
2895                 if (r < 0)
2896                         return r;
2897
2898                 return 1;
2899         }
2900 }
2901
2902 static int event_inotify_data_read(sd_event *e, struct inotify_data *d, uint32_t revents) {
2903         ssize_t n;
2904
2905         assert(e);
2906         assert(d);
2907
2908         assert_return(revents == EPOLLIN, -EIO);
2909
2910         /* If there's already an event source pending for this priority, don't read another */
2911         if (d->n_pending > 0)
2912                 return 0;
2913
2914         /* Is the read buffer non-empty? If so, let's not read more */
2915         if (d->buffer_filled > 0)
2916                 return 0;
2917
2918         n = read(d->fd, &d->buffer, sizeof(d->buffer));
2919         if (n < 0) {
2920                 if (IN_SET(errno, EAGAIN, EINTR))
2921                         return 0;
2922
2923                 return -errno;
2924         }
2925
2926         assert(n > 0);
2927         d->buffer_filled = (size_t) n;
2928         LIST_PREPEND(buffered, e->inotify_data_buffered, d);
2929
2930         return 1;
2931 }
2932
2933 static void event_inotify_data_drop(sd_event *e, struct inotify_data *d, size_t sz) {
2934         assert(e);
2935         assert(d);
2936         assert(sz <= d->buffer_filled);
2937
2938         if (sz == 0)
2939                 return;
2940
2941         /* Move the rest to the buffer to the front, in order to get things properly aligned again */
2942         memmove(d->buffer.raw, d->buffer.raw + sz, d->buffer_filled - sz);
2943         d->buffer_filled -= sz;
2944
2945         if (d->buffer_filled == 0)
2946                 LIST_REMOVE(buffered, e->inotify_data_buffered, d);
2947 }
2948
2949 static int event_inotify_data_process(sd_event *e, struct inotify_data *d) {
2950         int r;
2951
2952         assert(e);
2953         assert(d);
2954
2955         /* If there's already an event source pending for this priority, don't read another */
2956         if (d->n_pending > 0)
2957                 return 0;
2958
2959         while (d->buffer_filled > 0) {
2960                 size_t sz;
2961
2962                 /* Let's validate that the event structures are complete */
2963                 if (d->buffer_filled < offsetof(struct inotify_event, name))
2964                         return -EIO;
2965
2966                 sz = offsetof(struct inotify_event, name) + d->buffer.ev.len;
2967                 if (d->buffer_filled < sz)
2968                         return -EIO;
2969
2970                 if (d->buffer.ev.mask & IN_Q_OVERFLOW) {
2971                         struct inode_data *inode_data;
2972                         Iterator i;
2973
2974                         /* The queue overran, let's pass this event to all event sources connected to this inotify
2975                          * object */
2976
2977                         HASHMAP_FOREACH(inode_data, d->inodes, i) {
2978                                 sd_event_source *s;
2979
2980                                 LIST_FOREACH(inotify.by_inode_data, s, inode_data->event_sources) {
2981
2982                                         if (s->enabled == SD_EVENT_OFF)
2983                                                 continue;
2984
2985                                         r = source_set_pending(s, true);
2986                                         if (r < 0)
2987                                                 return r;
2988                                 }
2989                         }
2990                 } else {
2991                         struct inode_data *inode_data;
2992                         sd_event_source *s;
2993
2994                         /* Find the inode object for this watch descriptor. If IN_IGNORED is set we also remove it from
2995                          * our watch descriptor table. */
2996                         if (d->buffer.ev.mask & IN_IGNORED) {
2997
2998                                 inode_data = hashmap_remove(d->wd, INT_TO_PTR(d->buffer.ev.wd));
2999                                 if (!inode_data) {
3000                                         event_inotify_data_drop(e, d, sz);
3001                                         continue;
3002                                 }
3003
3004                                 /* The watch descriptor was removed by the kernel, let's drop it here too */
3005                                 inode_data->wd = -1;
3006                         } else {
3007                                 inode_data = hashmap_get(d->wd, INT_TO_PTR(d->buffer.ev.wd));
3008                                 if (!inode_data) {
3009                                         event_inotify_data_drop(e, d, sz);
3010                                         continue;
3011                                 }
3012                         }
3013
3014                         /* Trigger all event sources that are interested in these events. Also trigger all event
3015                          * sources if IN_IGNORED or IN_UNMOUNT is set. */
3016                         LIST_FOREACH(inotify.by_inode_data, s, inode_data->event_sources) {
3017
3018                                 if (s->enabled == SD_EVENT_OFF)
3019                                         continue;
3020
3021                                 if ((d->buffer.ev.mask & (IN_IGNORED|IN_UNMOUNT)) == 0 &&
3022                                     (s->inotify.mask & d->buffer.ev.mask & IN_ALL_EVENTS) == 0)
3023                                         continue;
3024
3025                                 r = source_set_pending(s, true);
3026                                 if (r < 0)
3027                                         return r;
3028                         }
3029                 }
3030
3031                 /* Something pending now? If so, let's finish, otherwise let's read more. */
3032                 if (d->n_pending > 0)
3033                         return 1;
3034         }
3035
3036         return 0;
3037 }
3038
3039 static int process_inotify(sd_event *e) {
3040         struct inotify_data *d;
3041         int r, done = 0;
3042
3043         assert(e);
3044
3045         LIST_FOREACH(buffered, d, e->inotify_data_buffered) {
3046                 r = event_inotify_data_process(e, d);
3047                 if (r < 0)
3048                         return r;
3049                 if (r > 0)
3050                         done ++;
3051         }
3052
3053         return done;
3054 }
3055
3056 static int source_dispatch(sd_event_source *s) {
3057         EventSourceType saved_type;
3058         int r = 0;
3059
3060         assert(s);
3061         assert(s->pending || s->type == SOURCE_EXIT);
3062
3063         /* Save the event source type, here, so that we still know it after the event callback which might invalidate
3064          * the event. */
3065         saved_type = s->type;
3066
3067         if (!IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
3068                 r = source_set_pending(s, false);
3069                 if (r < 0)
3070                         return r;
3071         }
3072
3073         if (s->type != SOURCE_POST) {
3074                 sd_event_source *z;
3075                 Iterator i;
3076
3077                 /* If we execute a non-post source, let's mark all
3078                  * post sources as pending */
3079
3080                 SET_FOREACH(z, s->event->post_sources, i) {
3081                         if (z->enabled == SD_EVENT_OFF)
3082                                 continue;
3083
3084                         r = source_set_pending(z, true);
3085                         if (r < 0)
3086                                 return r;
3087                 }
3088         }
3089
3090         if (s->enabled == SD_EVENT_ONESHOT) {
3091                 r = sd_event_source_set_enabled(s, SD_EVENT_OFF);
3092                 if (r < 0)
3093                         return r;
3094         }
3095
3096         s->dispatching = true;
3097
3098         switch (s->type) {
3099
3100         case SOURCE_IO:
3101                 r = s->io.callback(s, s->io.fd, s->io.revents, s->userdata);
3102                 break;
3103
3104         case SOURCE_TIME_REALTIME:
3105         case SOURCE_TIME_BOOTTIME:
3106         case SOURCE_TIME_MONOTONIC:
3107         case SOURCE_TIME_REALTIME_ALARM:
3108         case SOURCE_TIME_BOOTTIME_ALARM:
3109                 r = s->time.callback(s, s->time.next, s->userdata);
3110                 break;
3111
3112         case SOURCE_SIGNAL:
3113                 r = s->signal.callback(s, &s->signal.siginfo, s->userdata);
3114                 break;
3115
3116         case SOURCE_CHILD: {
3117                 bool zombie;
3118
3119                 zombie = IN_SET(s->child.siginfo.si_code, CLD_EXITED, CLD_KILLED, CLD_DUMPED);
3120
3121                 r = s->child.callback(s, &s->child.siginfo, s->userdata);
3122
3123                 /* Now, reap the PID for good. */
3124                 if (zombie)
3125                         (void) waitid(P_PID, s->child.pid, &s->child.siginfo, WNOHANG|WEXITED);
3126
3127                 break;
3128         }
3129
3130         case SOURCE_DEFER:
3131                 r = s->defer.callback(s, s->userdata);
3132                 break;
3133
3134         case SOURCE_POST:
3135                 r = s->post.callback(s, s->userdata);
3136                 break;
3137
3138         case SOURCE_EXIT:
3139                 r = s->exit.callback(s, s->userdata);
3140                 break;
3141
3142         case SOURCE_INOTIFY: {
3143                 struct sd_event *e = s->event;
3144                 struct inotify_data *d;
3145                 size_t sz;
3146
3147                 assert(s->inotify.inode_data);
3148                 assert_se(d = s->inotify.inode_data->inotify_data);
3149
3150                 assert(d->buffer_filled >= offsetof(struct inotify_event, name));
3151                 sz = offsetof(struct inotify_event, name) + d->buffer.ev.len;
3152                 assert(d->buffer_filled >= sz);
3153
3154                 r = s->inotify.callback(s, &d->buffer.ev, s->userdata);
3155
3156                 /* When no event is pending anymore on this inotify object, then let's drop the event from the
3157                  * buffer. */
3158                 if (d->n_pending == 0)
3159                         event_inotify_data_drop(e, d, sz);
3160
3161                 break;
3162         }
3163
3164         case SOURCE_WATCHDOG:
3165         case _SOURCE_EVENT_SOURCE_TYPE_MAX:
3166         case _SOURCE_EVENT_SOURCE_TYPE_INVALID:
3167                 assert_not_reached("Wut? I shouldn't exist.");
3168         }
3169
3170         s->dispatching = false;
3171
3172         if (r < 0)
3173                 log_debug_errno(r, "Event source %s (type %s) returned error, disabling: %m",
3174                                 strna(s->description), event_source_type_to_string(saved_type));
3175
3176         if (s->n_ref == 0)
3177                 source_free(s);
3178         else if (r < 0)
3179                 sd_event_source_set_enabled(s, SD_EVENT_OFF);
3180
3181         return 1;
3182 }
3183
3184 static int event_prepare(sd_event *e) {
3185         int r;
3186
3187         assert(e);
3188
3189         for (;;) {
3190                 sd_event_source *s;
3191
3192                 s = prioq_peek(e->prepare);
3193                 if (!s || s->prepare_iteration == e->iteration || s->enabled == SD_EVENT_OFF)
3194                         break;
3195
3196                 s->prepare_iteration = e->iteration;
3197                 r = prioq_reshuffle(e->prepare, s, &s->prepare_index);
3198                 if (r < 0)
3199                         return r;
3200
3201                 assert(s->prepare);
3202
3203                 s->dispatching = true;
3204                 r = s->prepare(s, s->userdata);
3205                 s->dispatching = false;
3206
3207                 if (r < 0)
3208                         log_debug_errno(r, "Prepare callback of event source %s (type %s) returned error, disabling: %m",
3209                                         strna(s->description), event_source_type_to_string(s->type));
3210
3211                 if (s->n_ref == 0)
3212                         source_free(s);
3213                 else if (r < 0)
3214                         sd_event_source_set_enabled(s, SD_EVENT_OFF);
3215         }
3216
3217         return 0;
3218 }
3219
3220 static int dispatch_exit(sd_event *e) {
3221         sd_event_source *p;
3222         _cleanup_(sd_event_unrefp) sd_event *ref = NULL;
3223         int r;
3224
3225         assert(e);
3226
3227         p = prioq_peek(e->exit);
3228         if (!p || p->enabled == SD_EVENT_OFF) {
3229                 e->state = SD_EVENT_FINISHED;
3230                 return 0;
3231         }
3232
3233         ref = sd_event_ref(e);
3234         e->iteration++;
3235         e->state = SD_EVENT_EXITING;
3236         r = source_dispatch(p);
3237         e->state = SD_EVENT_INITIAL;
3238         return r;
3239 }
3240
3241 static sd_event_source* event_next_pending(sd_event *e) {
3242         sd_event_source *p;
3243
3244         assert(e);
3245
3246         p = prioq_peek(e->pending);
3247         if (!p)
3248                 return NULL;
3249
3250         if (p->enabled == SD_EVENT_OFF)
3251                 return NULL;
3252
3253         return p;
3254 }
3255
3256 static int arm_watchdog(sd_event *e) {
3257         struct itimerspec its = {};
3258         usec_t t;
3259         int r;
3260
3261         assert(e);
3262         assert(e->watchdog_fd >= 0);
3263
3264         t = sleep_between(e,
3265                           e->watchdog_last + (e->watchdog_period / 2),
3266                           e->watchdog_last + (e->watchdog_period * 3 / 4));
3267
3268         timespec_store(&its.it_value, t);
3269
3270         /* Make sure we never set the watchdog to 0, which tells the
3271          * kernel to disable it. */
3272         if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0)
3273                 its.it_value.tv_nsec = 1;
3274
3275         r = timerfd_settime(e->watchdog_fd, TFD_TIMER_ABSTIME, &its, NULL);
3276         if (r < 0)
3277                 return -errno;
3278
3279         return 0;
3280 }
3281
3282 static int process_watchdog(sd_event *e) {
3283         assert(e);
3284
3285         if (!e->watchdog)
3286                 return 0;
3287
3288         /* Don't notify watchdog too often */
3289         if (e->watchdog_last + e->watchdog_period / 4 > e->timestamp.monotonic)
3290                 return 0;
3291
3292         sd_notify(false, "WATCHDOG=1");
3293         e->watchdog_last = e->timestamp.monotonic;
3294
3295         return arm_watchdog(e);
3296 }
3297
3298 static void event_close_inode_data_fds(sd_event *e) {
3299         struct inode_data *d;
3300
3301         assert(e);
3302
3303         /* Close the fds pointing to the inodes to watch now. We need to close them as they might otherwise pin
3304          * filesystems. But we can't close them right-away as we need them as long as the user still wants to make
3305          * adjustments to the even source, such as changing the priority (which requires us to remove and readd a watch
3306          * for the inode). Hence, let's close them when entering the first iteration after they were added, as a
3307          * compromise. */
3308
3309         while ((d = e->inode_data_to_close)) {
3310                 assert(d->fd >= 0);
3311                 d->fd = safe_close(d->fd);
3312
3313                 LIST_REMOVE(to_close, e->inode_data_to_close, d);
3314         }
3315 }
3316
3317 _public_ int sd_event_prepare(sd_event *e) {
3318         int r;
3319
3320         assert_return(e, -EINVAL);
3321         assert_return(e = event_resolve(e), -ENOPKG);
3322         assert_return(!event_pid_changed(e), -ECHILD);
3323         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
3324         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
3325
3326         if (e->exit_requested)
3327                 goto pending;
3328
3329         e->iteration++;
3330
3331         e->state = SD_EVENT_PREPARING;
3332         r = event_prepare(e);
3333         e->state = SD_EVENT_INITIAL;
3334         if (r < 0)
3335                 return r;
3336
3337         r = event_arm_timer(e, &e->realtime);
3338         if (r < 0)
3339                 return r;
3340
3341         r = event_arm_timer(e, &e->boottime);
3342         if (r < 0)
3343                 return r;
3344
3345         r = event_arm_timer(e, &e->monotonic);
3346         if (r < 0)
3347                 return r;
3348
3349         r = event_arm_timer(e, &e->realtime_alarm);
3350         if (r < 0)
3351                 return r;
3352
3353         r = event_arm_timer(e, &e->boottime_alarm);
3354         if (r < 0)
3355                 return r;
3356
3357         event_close_inode_data_fds(e);
3358
3359         if (event_next_pending(e) || e->need_process_child)
3360                 goto pending;
3361
3362         e->state = SD_EVENT_ARMED;
3363
3364         return 0;
3365
3366 pending:
3367         e->state = SD_EVENT_ARMED;
3368         r = sd_event_wait(e, 0);
3369         if (r == 0)
3370                 e->state = SD_EVENT_ARMED;
3371
3372         return r;
3373 }
3374
3375 _public_ int sd_event_wait(sd_event *e, uint64_t timeout) {
3376         struct epoll_event *ev_queue;
3377         unsigned ev_queue_max;
3378         int r, m, i;
3379
3380         assert_return(e, -EINVAL);
3381         assert_return(e = event_resolve(e), -ENOPKG);
3382         assert_return(!event_pid_changed(e), -ECHILD);
3383         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
3384         assert_return(e->state == SD_EVENT_ARMED, -EBUSY);
3385
3386         if (e->exit_requested) {
3387                 e->state = SD_EVENT_PENDING;
3388                 return 1;
3389         }
3390
3391         ev_queue_max = MAX(e->n_sources, 1u);
3392         ev_queue = newa(struct epoll_event, ev_queue_max);
3393
3394         /* If we still have inotify data buffered, then query the other fds, but don't wait on it */
3395         if (e->inotify_data_buffered)
3396                 timeout = 0;
3397
3398         m = epoll_wait(e->epoll_fd, ev_queue, ev_queue_max,
3399                        timeout == (uint64_t) -1 ? -1 : (int) ((timeout + USEC_PER_MSEC - 1) / USEC_PER_MSEC));
3400         if (m < 0) {
3401                 if (errno == EINTR) {
3402                         e->state = SD_EVENT_PENDING;
3403                         return 1;
3404                 }
3405
3406                 r = -errno;
3407                 goto finish;
3408         }
3409
3410         triple_timestamp_get(&e->timestamp);
3411
3412         for (i = 0; i < m; i++) {
3413
3414                 if (ev_queue[i].data.ptr == INT_TO_PTR(SOURCE_WATCHDOG))
3415                         r = flush_timer(e, e->watchdog_fd, ev_queue[i].events, NULL);
3416                 else {
3417                         WakeupType *t = ev_queue[i].data.ptr;
3418
3419                         switch (*t) {
3420
3421                         case WAKEUP_EVENT_SOURCE:
3422                                 r = process_io(e, ev_queue[i].data.ptr, ev_queue[i].events);
3423                                 break;
3424
3425                         case WAKEUP_CLOCK_DATA: {
3426                                 struct clock_data *d = ev_queue[i].data.ptr;
3427                                 r = flush_timer(e, d->fd, ev_queue[i].events, &d->next);
3428                                 break;
3429                         }
3430
3431                         case WAKEUP_SIGNAL_DATA:
3432                                 r = process_signal(e, ev_queue[i].data.ptr, ev_queue[i].events);
3433                                 break;
3434
3435                         case WAKEUP_INOTIFY_DATA:
3436                                 r = event_inotify_data_read(e, ev_queue[i].data.ptr, ev_queue[i].events);
3437                                 break;
3438
3439                         default:
3440                                 assert_not_reached("Invalid wake-up pointer");
3441                         }
3442                 }
3443                 if (r < 0)
3444                         goto finish;
3445         }
3446
3447         r = process_watchdog(e);
3448         if (r < 0)
3449                 goto finish;
3450
3451         r = process_timer(e, e->timestamp.realtime, &e->realtime);
3452         if (r < 0)
3453                 goto finish;
3454
3455         r = process_timer(e, e->timestamp.boottime, &e->boottime);
3456         if (r < 0)
3457                 goto finish;
3458
3459         r = process_timer(e, e->timestamp.monotonic, &e->monotonic);
3460         if (r < 0)
3461                 goto finish;
3462
3463         r = process_timer(e, e->timestamp.realtime, &e->realtime_alarm);
3464         if (r < 0)
3465                 goto finish;
3466
3467         r = process_timer(e, e->timestamp.boottime, &e->boottime_alarm);
3468         if (r < 0)
3469                 goto finish;
3470
3471         if (e->need_process_child) {
3472                 r = process_child(e);
3473                 if (r < 0)
3474                         goto finish;
3475         }
3476
3477         r = process_inotify(e);
3478         if (r < 0)
3479                 goto finish;
3480
3481         if (event_next_pending(e)) {
3482                 e->state = SD_EVENT_PENDING;
3483
3484                 return 1;
3485         }
3486
3487         r = 0;
3488
3489 finish:
3490         e->state = SD_EVENT_INITIAL;
3491
3492         return r;
3493 }
3494
3495 _public_ int sd_event_dispatch(sd_event *e) {
3496         sd_event_source *p;
3497         int r;
3498
3499         assert_return(e, -EINVAL);
3500         assert_return(e = event_resolve(e), -ENOPKG);
3501         assert_return(!event_pid_changed(e), -ECHILD);
3502         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
3503         assert_return(e->state == SD_EVENT_PENDING, -EBUSY);
3504
3505         if (e->exit_requested)
3506                 return dispatch_exit(e);
3507
3508         p = event_next_pending(e);
3509         if (p) {
3510                 _cleanup_(sd_event_unrefp) sd_event *ref = NULL;
3511
3512                 ref = sd_event_ref(e);
3513                 e->state = SD_EVENT_RUNNING;
3514                 r = source_dispatch(p);
3515                 e->state = SD_EVENT_INITIAL;
3516                 return r;
3517         }
3518
3519         e->state = SD_EVENT_INITIAL;
3520
3521         return 1;
3522 }
3523
3524 static void event_log_delays(sd_event *e) {
3525         char b[ELEMENTSOF(e->delays) * DECIMAL_STR_MAX(unsigned) + 1];
3526         unsigned i;
3527         int o;
3528
3529         for (i = o = 0; i < ELEMENTSOF(e->delays); i++) {
3530                 o += snprintf(&b[o], sizeof(b) - o, "%u ", e->delays[i]);
3531                 e->delays[i] = 0;
3532         }
3533         log_debug("Event loop iterations: %.*s", o, b);
3534 }
3535
3536 _public_ int sd_event_run(sd_event *e, uint64_t timeout) {
3537         int r;
3538
3539         assert_return(e, -EINVAL);
3540         assert_return(e = event_resolve(e), -ENOPKG);
3541         assert_return(!event_pid_changed(e), -ECHILD);
3542         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
3543         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
3544
3545         if (e->profile_delays && e->last_run) {
3546                 usec_t this_run;
3547                 unsigned l;
3548
3549                 this_run = now(CLOCK_MONOTONIC);
3550
3551                 l = u64log2(this_run - e->last_run);
3552                 assert(l < sizeof(e->delays));
3553                 e->delays[l]++;
3554
3555                 if (this_run - e->last_log >= 5*USEC_PER_SEC) {
3556                         event_log_delays(e);
3557                         e->last_log = this_run;
3558                 }
3559         }
3560
3561         r = sd_event_prepare(e);
3562         if (r == 0)
3563                 /* There was nothing? Then wait... */
3564                 r = sd_event_wait(e, timeout);
3565
3566         if (e->profile_delays)
3567                 e->last_run = now(CLOCK_MONOTONIC);
3568
3569         if (r > 0) {
3570                 /* There's something now, then let's dispatch it */
3571                 r = sd_event_dispatch(e);
3572                 if (r < 0)
3573                         return r;
3574
3575                 return 1;
3576         }
3577
3578         return r;
3579 }
3580
3581 _public_ int sd_event_loop(sd_event *e) {
3582         _cleanup_(sd_event_unrefp) sd_event *ref = NULL;
3583         int r;
3584
3585         assert_return(e, -EINVAL);
3586         assert_return(e = event_resolve(e), -ENOPKG);
3587         assert_return(!event_pid_changed(e), -ECHILD);
3588         assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
3589
3590         ref = sd_event_ref(e);
3591
3592         while (e->state != SD_EVENT_FINISHED) {
3593                 r = sd_event_run(e, (uint64_t) -1);
3594                 if (r < 0)
3595                         return r;
3596         }
3597
3598         return e->exit_code;
3599 }
3600
3601 _public_ int sd_event_get_fd(sd_event *e) {
3602
3603         assert_return(e, -EINVAL);
3604         assert_return(e = event_resolve(e), -ENOPKG);
3605         assert_return(!event_pid_changed(e), -ECHILD);
3606
3607         return e->epoll_fd;
3608 }
3609
3610 _public_ int sd_event_get_state(sd_event *e) {
3611         assert_return(e, -EINVAL);
3612         assert_return(e = event_resolve(e), -ENOPKG);
3613         assert_return(!event_pid_changed(e), -ECHILD);
3614
3615         return e->state;
3616 }
3617
3618 _public_ int sd_event_get_exit_code(sd_event *e, int *code) {
3619         assert_return(e, -EINVAL);
3620         assert_return(e = event_resolve(e), -ENOPKG);
3621         assert_return(code, -EINVAL);
3622         assert_return(!event_pid_changed(e), -ECHILD);
3623
3624         if (!e->exit_requested)
3625                 return -ENODATA;
3626
3627         *code = e->exit_code;
3628         return 0;
3629 }
3630
3631 _public_ int sd_event_exit(sd_event *e, int code) {
3632         assert_return(e, -EINVAL);
3633         assert_return(e = event_resolve(e), -ENOPKG);
3634         assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
3635         assert_return(!event_pid_changed(e), -ECHILD);
3636
3637         e->exit_requested = true;
3638         e->exit_code = code;
3639
3640         return 0;
3641 }
3642
3643 _public_ int sd_event_now(sd_event *e, clockid_t clock, uint64_t *usec) {
3644         assert_return(e, -EINVAL);
3645         assert_return(e = event_resolve(e), -ENOPKG);
3646         assert_return(usec, -EINVAL);
3647         assert_return(!event_pid_changed(e), -ECHILD);
3648
3649         if (!TRIPLE_TIMESTAMP_HAS_CLOCK(clock))
3650                 return -EOPNOTSUPP;
3651
3652         /* Generate a clean error in case CLOCK_BOOTTIME is not available. Note that don't use clock_supported() here,
3653          * for a reason: there are systems where CLOCK_BOOTTIME is supported, but CLOCK_BOOTTIME_ALARM is not, but for
3654          * the purpose of getting the time this doesn't matter. */
3655         if (IN_SET(clock, CLOCK_BOOTTIME, CLOCK_BOOTTIME_ALARM) && !clock_boottime_supported())
3656                 return -EOPNOTSUPP;
3657
3658         if (!triple_timestamp_is_set(&e->timestamp)) {
3659                 /* Implicitly fall back to now() if we never ran
3660                  * before and thus have no cached time. */
3661                 *usec = now(clock);
3662                 return 1;
3663         }
3664
3665         *usec = triple_timestamp_by_clock(&e->timestamp, clock);
3666         return 0;
3667 }
3668
3669 _public_ int sd_event_default(sd_event **ret) {
3670         sd_event *e = NULL;
3671         int r;
3672
3673         if (!ret)
3674                 return !!default_event;
3675
3676         if (default_event) {
3677                 *ret = sd_event_ref(default_event);
3678                 return 0;
3679         }
3680
3681         r = sd_event_new(&e);
3682         if (r < 0)
3683                 return r;
3684
3685         e->default_event_ptr = &default_event;
3686         e->tid = gettid();
3687         default_event = e;
3688
3689         *ret = e;
3690         return 1;
3691 }
3692
3693 _public_ int sd_event_get_tid(sd_event *e, pid_t *tid) {
3694         assert_return(e, -EINVAL);
3695         assert_return(e = event_resolve(e), -ENOPKG);
3696         assert_return(tid, -EINVAL);
3697         assert_return(!event_pid_changed(e), -ECHILD);
3698
3699         if (e->tid != 0) {
3700                 *tid = e->tid;
3701                 return 0;
3702         }
3703
3704         return -ENXIO;
3705 }
3706
3707 _public_ int sd_event_set_watchdog(sd_event *e, int b) {
3708         int r;
3709
3710         assert_return(e, -EINVAL);
3711         assert_return(e = event_resolve(e), -ENOPKG);
3712         assert_return(!event_pid_changed(e), -ECHILD);
3713
3714         if (e->watchdog == !!b)
3715                 return e->watchdog;
3716
3717         if (b) {
3718                 struct epoll_event ev;
3719
3720                 r = sd_watchdog_enabled(false, &e->watchdog_period);
3721                 if (r <= 0)
3722                         return r;
3723
3724                 /* Issue first ping immediately */
3725                 sd_notify(false, "WATCHDOG=1");
3726                 e->watchdog_last = now(CLOCK_MONOTONIC);
3727
3728                 e->watchdog_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
3729                 if (e->watchdog_fd < 0)
3730                         return -errno;
3731
3732                 r = arm_watchdog(e);
3733                 if (r < 0)
3734                         goto fail;
3735
3736                 ev = (struct epoll_event) {
3737                         .events = EPOLLIN,
3738                         .data.ptr = INT_TO_PTR(SOURCE_WATCHDOG),
3739                 };
3740
3741                 r = epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, e->watchdog_fd, &ev);
3742                 if (r < 0) {
3743                         r = -errno;
3744                         goto fail;
3745                 }
3746
3747         } else {
3748                 if (e->watchdog_fd >= 0) {
3749                         epoll_ctl(e->epoll_fd, EPOLL_CTL_DEL, e->watchdog_fd, NULL);
3750                         e->watchdog_fd = safe_close(e->watchdog_fd);
3751                 }
3752         }
3753
3754         e->watchdog = !!b;
3755         return e->watchdog;
3756
3757 fail:
3758         e->watchdog_fd = safe_close(e->watchdog_fd);
3759         return r;
3760 }
3761
3762 _public_ int sd_event_get_watchdog(sd_event *e) {
3763         assert_return(e, -EINVAL);
3764         assert_return(e = event_resolve(e), -ENOPKG);
3765         assert_return(!event_pid_changed(e), -ECHILD);
3766
3767         return e->watchdog;
3768 }
3769
3770 _public_ int sd_event_get_iteration(sd_event *e, uint64_t *ret) {
3771         assert_return(e, -EINVAL);
3772         assert_return(e = event_resolve(e), -ENOPKG);
3773         assert_return(!event_pid_changed(e), -ECHILD);
3774
3775         *ret = e->iteration;
3776         return 0;
3777 }