Debian Codegraph @

src/libsystemd/sd-event/sd-event.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/magic.h>
4 #include <malloc.h>
5 #include <stdlib.h>
6 #include <sys/timerfd.h>
7 #include <sys/wait.h>
8 #include <threads.h>
9 #include <unistd.h>
10
11 #include "sd-daemon.h"
12 #include "sd-event.h"
13 #include "sd-future.h"
14 #include "sd-id128.h"
15 #include "sd-messages.h"
16
17 #include "alloc-util.h"
18 #include "errno-util.h"
19 #include "event-future.h"
20 #include "event-source.h"
21 #include "event-util.h"
22 #include "fd-util.h"
23 #include "format-util.h"
24 #include "glyph-util.h"
25 #include "hashmap.h"
26 #include "hexdecoct.h"
27 #include "list.h"
28 #include "log.h"
29 #include "logarithm.h"
30 #include "memory-util.h"
31 #include "origin-id.h"
32 #include "path-util.h"
33 #include "pidfd-util.h"
34 #include "prioq.h"
35 #include "process-util.h"
36 #include "psi-util.h"
37 #include "set.h"
38 #include "signal-util.h"
39 #include "siphash24.h"
40 #include "socket-util.h"
41 #include "stat-util.h"
42 #include "string-table.h"
43 #include "string-util.h"
44 #include "strv.h"
45 #include "strxcpyx.h"
46 #include "time-util.h"
47
48 #define DEFAULT_ACCURACY_USEC (250 * USEC_PER_MSEC)
49
50 static bool EVENT_SOURCE_WATCH_PIDFD(const sd_event_source *s) {
51 /* Returns true if this is a PID event source and can be implemented by watching EPOLLIN */
52 return s &&
53 s->type == SOURCE_CHILD &&
54 (s->child.options & ~WNOWAIT) == WEXITED;
55 }
56
57 static bool event_source_is_online(sd_event_source *s) {
58 assert(s);
59 return s->enabled != SD_EVENT_OFF && !s->ratelimited;
60 }
61
62 static bool event_source_is_offline(sd_event_source *s) {
63 assert(s);
64 return s->enabled == SD_EVENT_OFF || s->ratelimited;
65 }
66
67 static const char* const event_source_type_table[_SOURCE_EVENT_SOURCE_TYPE_MAX] = {
68 [SOURCE_IO] = "io",
69 [SOURCE_TIME_REALTIME] = "realtime",
70 [SOURCE_TIME_BOOTTIME] = "boottime",
71 [SOURCE_TIME_MONOTONIC] = "monotonic",
72 [SOURCE_TIME_REALTIME_ALARM] = "realtime-alarm",
73 [SOURCE_TIME_BOOTTIME_ALARM] = "boottime-alarm",
74 [SOURCE_SIGNAL] = "signal",
75 [SOURCE_CHILD] = "child",
76 [SOURCE_DEFER] = "defer",
77 [SOURCE_POST] = "post",
78 [SOURCE_EXIT] = "exit",
79 [SOURCE_WATCHDOG] = "watchdog",
80 [SOURCE_INOTIFY] = "inotify",
81 [SOURCE_MEMORY_PRESSURE] = "memory-pressure",
82 [SOURCE_CPU_PRESSURE] = "cpu-pressure",
83 [SOURCE_IO_PRESSURE] = "io-pressure",
84 };
85
86 DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(event_source_type, int);
87
88 #define EVENT_SOURCE_IS_TIME(t) \
89 IN_SET((t), \
90 SOURCE_TIME_REALTIME, \
91 SOURCE_TIME_BOOTTIME, \
92 SOURCE_TIME_MONOTONIC, \
93 SOURCE_TIME_REALTIME_ALARM, \
94 SOURCE_TIME_BOOTTIME_ALARM)
95
96 #define EVENT_SOURCE_CAN_RATE_LIMIT(t) \
97 IN_SET((t), \
98 SOURCE_IO, \
99 SOURCE_TIME_REALTIME, \
100 SOURCE_TIME_BOOTTIME, \
101 SOURCE_TIME_MONOTONIC, \
102 SOURCE_TIME_REALTIME_ALARM, \
103 SOURCE_TIME_BOOTTIME_ALARM, \
104 SOURCE_SIGNAL, \
105 SOURCE_DEFER, \
106 SOURCE_INOTIFY, \
107 SOURCE_MEMORY_PRESSURE, \
108 SOURCE_CPU_PRESSURE, \
109 SOURCE_IO_PRESSURE)
110
111 /* This is used to assert that we didn't pass an unexpected source type to event_source_time_prioq_put().
112 * Time sources and ratelimited sources can be passed, so effectively this is the same as the
113 * EVENT_SOURCE_CAN_RATE_LIMIT() macro. */
114 #define EVENT_SOURCE_USES_TIME_PRIOQ(t) EVENT_SOURCE_CAN_RATE_LIMIT(t)
115
116 struct sd_event {
117 unsigned n_ref;
118
119 int epoll_fd;
120 int watchdog_fd;
121
122 Prioq *pending;
123 Prioq *prepare;
124
125 /* timerfd_create() only supports these five clocks so far. We
126 * can add support for more clocks when the kernel learns to
127 * deal with them, too. */
128 struct clock_data realtime;
129 struct clock_data boottime;
130 struct clock_data monotonic;
131 struct clock_data realtime_alarm;
132 struct clock_data boottime_alarm;
133
134 usec_t perturb;
135
136 sd_event_source **signal_sources; /* indexed by signal number */
137 Hashmap *signal_data; /* indexed by priority */
138
139 Hashmap *child_sources;
140 unsigned n_online_child_sources;
141
142 Set *post_sources;
143
144 Prioq *exit;
145
146 Hashmap *inotify_data; /* indexed by priority */
147
148 /* A list of inode structures that still have an fd open, that we need to close before the next loop iteration */
149 LIST_HEAD(InodeData, inode_data_to_close_list);
150
151 /* A list of inotify objects that already have events buffered which aren't processed yet */
152 LIST_HEAD(InotifyData, buffered_inotify_data_list);
153
154 /* A list of pressure event sources that still need their subscription string written */
155 LIST_HEAD(sd_event_source, pressure_write_list);
156
157 uint64_t origin_id;
158
159 uint64_t iteration;
160 triple_timestamp timestamp;
161 int state;
162
163 bool exit_requested:1;
164 bool need_process_child:1;
165 bool watchdog:1;
166 bool profile_delays:1;
167 bool exit_on_idle:1;
168
169 int exit_code;
170
171 pid_t tid;
172 sd_event **default_event_ptr;
173
174 usec_t watchdog_last, watchdog_period;
175
176 unsigned n_sources;
177
178 struct epoll_event *event_queue;
179
180 LIST_HEAD(sd_event_source, sources);
181
182 sd_event_source *sigint_event_source, *sigterm_event_source;
183
184 usec_t last_run_usec, last_log_usec;
185 unsigned delays[sizeof(usec_t) * 8];
186 };
187
188 DEFINE_PRIVATE_ORIGIN_ID_HELPERS(sd_event, event);
189
190 static thread_local sd_event *default_event = NULL;
191
192 static void source_disconnect(sd_event_source *s);
193 static void event_gc_inode_data(sd_event *e, InodeData *d);
194
195 static sd_event* event_resolve(sd_event *e) {
196 return e == SD_EVENT_DEFAULT ? default_event : e;
197 }
198
199 static int pending_prioq_compare(const void *a, const void *b) {
200 const sd_event_source *x = a, *y = b;
201 int r;
202
203 assert(x->pending);
204 assert(y->pending);
205
206 /* Enabled ones first */
207 r = CMP(x->enabled == SD_EVENT_OFF, y->enabled == SD_EVENT_OFF);
208 if (r != 0)
209 return r;
210
211 /* Non rate-limited ones first. */
212 r = CMP(!!x->ratelimited, !!y->ratelimited);
213 if (r != 0)
214 return r;
215
216 /* Lower priority values first */
217 r = CMP(x->priority, y->priority);
218 if (r != 0)
219 return r;
220
221 /* Older entries first */
222 return CMP(x->pending_iteration, y->pending_iteration);
223 }
224
225 static int prepare_prioq_compare(const void *a, const void *b) {
226 const sd_event_source *x = a, *y = b;
227 int r;
228
229 assert(x->prepare);
230 assert(y->prepare);
231
232 /* Enabled ones first */
233 r = CMP(x->enabled == SD_EVENT_OFF, y->enabled == SD_EVENT_OFF);
234 if (r != 0)
235 return r;
236
237 /* Non rate-limited ones first. */
238 r = CMP(!!x->ratelimited, !!y->ratelimited);
239 if (r != 0)
240 return r;
241
242 /* Move most recently prepared ones last, so that we can stop
243 * preparing as soon as we hit one that has already been
244 * prepared in the current iteration */
245 r = CMP(x->prepare_iteration, y->prepare_iteration);
246 if (r != 0)
247 return r;
248
249 /* Lower priority values first */
250 return CMP(x->priority, y->priority);
251 }
252
253 static usec_t time_event_source_next(const sd_event_source *s) {
254 assert(s);
255
256 /* We have two kinds of event sources that have elapsation times associated with them: the actual
257 * time based ones and the ones for which a ratelimit can be in effect (where we want to be notified
258 * once the ratelimit time window ends). Let's return the next elapsing time depending on what we are
259 * looking at here. */
260
261 if (s->ratelimited) { /* If rate-limited the next elapsation is when the ratelimit time window ends */
262 assert(s->rate_limit.begin != 0);
263 assert(s->rate_limit.interval != 0);
264 return usec_add(s->rate_limit.begin, s->rate_limit.interval);
265 }
266
267 /* Otherwise this must be a time event source, if not ratelimited */
268 if (EVENT_SOURCE_IS_TIME(s->type))
269 return s->time.next;
270
271 return USEC_INFINITY;
272 }
273
274 static usec_t time_event_source_latest(const sd_event_source *s) {
275 assert(s);
276
277 if (s->ratelimited) { /* For ratelimited stuff the earliest and the latest time shall actually be the
278 * same, as we should avoid adding additional inaccuracy on an inaccuracy time
279 * window */
280 assert(s->rate_limit.begin != 0);
281 assert(s->rate_limit.interval != 0);
282 return usec_add(s->rate_limit.begin, s->rate_limit.interval);
283 }
284
285 /* Must be a time event source, if not ratelimited */
286 if (EVENT_SOURCE_IS_TIME(s->type))
287 return usec_add(s->time.next, s->time.accuracy);
288
289 return USEC_INFINITY;
290 }
291
292 static bool event_source_timer_candidate(const sd_event_source *s) {
293 assert(s);
294
295 /* Returns true for event sources that either are not pending yet (i.e. where it's worth to mark them pending)
296 * or which are currently ratelimited (i.e. where it's worth leaving the ratelimited state) */
297 return !s->pending || s->ratelimited;
298 }
299
300 static int time_prioq_compare(const void *a, const void *b, usec_t (*time_func)(const sd_event_source *s)) {
301 const sd_event_source *x = a, *y = b;
302 int r;
303
304 /* Enabled ones first */
305 r = CMP(x->enabled == SD_EVENT_OFF, y->enabled == SD_EVENT_OFF);
306 if (r != 0)
307 return r;
308
309 /* Order "non-pending OR ratelimited" before "pending AND not-ratelimited" */
310 r = CMP(!event_source_timer_candidate(x), !event_source_timer_candidate(y));
311 if (r != 0)
312 return r;
313
314 /* Order by time */
315 return CMP(time_func(x), time_func(y));
316 }
317
318 static int earliest_time_prioq_compare(const void *a, const void *b) {
319 return time_prioq_compare(a, b, time_event_source_next);
320 }
321
322 static int latest_time_prioq_compare(const void *a, const void *b) {
323 return time_prioq_compare(a, b, time_event_source_latest);
324 }
325
326 static int exit_prioq_compare(const void *a, const void *b) {
327 const sd_event_source *x = a, *y = b;
328 int r;
329
330 assert(x->type == SOURCE_EXIT);
331 assert(y->type == SOURCE_EXIT);
332
333 /* Enabled ones first */
334 r = CMP(x->enabled == SD_EVENT_OFF, y->enabled == SD_EVENT_OFF);
335 if (r != 0)
336 return r;
337
338 /* Lower priority values first */
339 return CMP(x->priority, y->priority);
340 }
341
342 static void free_clock_data(struct clock_data *d) {
343 assert(d);
344 assert(d->wakeup == WAKEUP_CLOCK_DATA);
345
346 safe_close(d->fd);
347 prioq_free(d->earliest);
348 prioq_free(d->latest);
349 }
350
351 static sd_event* event_free(sd_event *e) {
352 sd_event_source *s;
353
354 assert(e);
355
356 e->sigterm_event_source = sd_event_source_unref(e->sigterm_event_source);
357 e->sigint_event_source = sd_event_source_unref(e->sigint_event_source);
358
359 while ((s = e->sources)) {
360 assert(s->floating);
361 source_disconnect(s);
362 sd_event_source_unref(s);
363 }
364
365 assert(e->n_sources == 0);
366
367 if (e->default_event_ptr)
368 *(e->default_event_ptr) = NULL;
369
370 safe_close(e->epoll_fd);
371 safe_close(e->watchdog_fd);
372
373 free_clock_data(&e->realtime);
374 free_clock_data(&e->boottime);
375 free_clock_data(&e->monotonic);
376 free_clock_data(&e->realtime_alarm);
377 free_clock_data(&e->boottime_alarm);
378
379 prioq_free(e->pending);
380 prioq_free(e->prepare);
381 prioq_free(e->exit);
382
383 free(e->signal_sources);
384 hashmap_free(e->signal_data);
385
386 hashmap_free(e->inotify_data);
387
388 hashmap_free(e->child_sources);
389 set_free(e->post_sources);
390
391 free(e->event_queue);
392
393 return mfree(e);
394 }
395
396 _public_ int sd_event_new(sd_event** ret) {
397 sd_event *e;
398 int r;
399
400 assert_return(ret, -EINVAL);
401
402 e = new(sd_event, 1);
403 if (!e)
404 return -ENOMEM;
405
406 *e = (sd_event) {
407 .n_ref = 1,
408 .epoll_fd = -EBADF,
409 .watchdog_fd = -EBADF,
410 .realtime.wakeup = WAKEUP_CLOCK_DATA,
411 .realtime.fd = -EBADF,
412 .realtime.next = USEC_INFINITY,
413 .boottime.wakeup = WAKEUP_CLOCK_DATA,
414 .boottime.fd = -EBADF,
415 .boottime.next = USEC_INFINITY,
416 .monotonic.wakeup = WAKEUP_CLOCK_DATA,
417 .monotonic.fd = -EBADF,
418 .monotonic.next = USEC_INFINITY,
419 .realtime_alarm.wakeup = WAKEUP_CLOCK_DATA,
420 .realtime_alarm.fd = -EBADF,
421 .realtime_alarm.next = USEC_INFINITY,
422 .boottime_alarm.wakeup = WAKEUP_CLOCK_DATA,
423 .boottime_alarm.fd = -EBADF,
424 .boottime_alarm.next = USEC_INFINITY,
425 .perturb = USEC_INFINITY,
426 .origin_id = origin_id_query(),
427 };
428
429 r = prioq_ensure_allocated(&e->pending, pending_prioq_compare);
430 if (r < 0)
431 goto fail;
432
433 e->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
434 if (e->epoll_fd < 0) {
435 r = -errno;
436 goto fail;
437 }
438
439 e->epoll_fd = fd_move_above_stdio(e->epoll_fd);
440
441 if (secure_getenv("SD_EVENT_PROFILE_DELAYS")) {
442 log_debug("Event loop profiling enabled. Logarithmic histogram of event loop iterations in the range 2^0 %s 2^63 us will be logged every 5s.",
443 glyph(GLYPH_ELLIPSIS));
444 e->profile_delays = true;
445 }
446
447 *ret = e;
448 return 0;
449
450 fail:
451 event_free(e);
452 return r;
453 }
454
455 /* Define manually so we can add the origin check */
456 _public_ sd_event* sd_event_ref(sd_event *e) {
457 if (!e)
458 return NULL;
459 if (event_origin_changed(e))
460 return NULL;
461
462 e->n_ref++;
463
464 return e;
465 }
466
467 _public_ sd_event* sd_event_unref(sd_event *e) {
468 if (!e)
469 return NULL;
470 if (event_origin_changed(e))
471 return NULL;
472
473 assert(e->n_ref > 0);
474 if (--e->n_ref > 0)
475 return NULL;
476
477 return event_free(e);
478 }
479
480 _public_ sd_event_source* sd_event_source_disable_unref(sd_event_source *s) {
481 int r;
482
483 r = sd_event_source_set_enabled(s, SD_EVENT_OFF);
484 if (r < 0)
485 log_debug_errno(r, "Failed to disable event source %p (%s): %m",
486 s, strna(s->description));
487
488 return sd_event_source_unref(s);
489 }
490
491 static void source_io_unregister(sd_event_source *s) {
492 assert(s);
493 assert(s->type == SOURCE_IO);
494
495 if (event_origin_changed(s->event))
496 return;
497
498 if (!s->io.registered)
499 return;
500
501 if (epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, s->io.fd, NULL) < 0)
502 log_debug_errno(errno, "Failed to remove source %s (type %s) from epoll, ignoring: %m",
503 strna(s->description), event_source_type_to_string(s->type));
504
505 s->io.registered = false;
506 }
507
508 static int source_io_register(
509 sd_event_source *s,
510 int enabled,
511 uint32_t events) {
512
513 assert(s);
514 assert(s->type == SOURCE_IO);
515 assert(enabled != SD_EVENT_OFF);
516
517 struct epoll_event ev = {
518 .events = events | (enabled == SD_EVENT_ONESHOT ? EPOLLONESHOT : 0),
519 .data.ptr = s,
520 };
521
522 if (epoll_ctl(s->event->epoll_fd,
523 s->io.registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD,
524 s->io.fd, &ev) < 0)
525 return -errno;
526
527 s->io.registered = true;
528
529 return 0;
530 }
531
532 static void source_child_pidfd_unregister(sd_event_source *s) {
533 assert(s);
534 assert(s->type == SOURCE_CHILD);
535
536 if (event_origin_changed(s->event))
537 return;
538
539 if (!s->child.registered)
540 return;
541
542 if (EVENT_SOURCE_WATCH_PIDFD(s))
543 if (epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, s->child.pidfd, NULL) < 0)
544 log_debug_errno(errno, "Failed to remove source %s (type %s) from epoll, ignoring: %m",
545 strna(s->description), event_source_type_to_string(s->type));
546
547 s->child.registered = false;
548 }
549
550 static int source_child_pidfd_register(sd_event_source *s, int enabled) {
551 assert(s);
552 assert(s->type == SOURCE_CHILD);
553 assert(enabled != SD_EVENT_OFF);
554
555 if (EVENT_SOURCE_WATCH_PIDFD(s)) {
556 struct epoll_event ev = {
557 .events = EPOLLIN | (enabled == SD_EVENT_ONESHOT ? EPOLLONESHOT : 0),
558 .data.ptr = s,
559 };
560
561 if (epoll_ctl(s->event->epoll_fd,
562 s->child.registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD,
563 s->child.pidfd, &ev) < 0)
564 return -errno;
565 }
566
567 s->child.registered = true;
568 return 0;
569 }
570
571 #define EVENT_SOURCE_IS_PRESSURE(s) IN_SET((s)->type, SOURCE_MEMORY_PRESSURE, SOURCE_CPU_PRESSURE, SOURCE_IO_PRESSURE)
572
573 static void source_pressure_unregister(sd_event_source *s) {
574 assert(s);
575 assert(EVENT_SOURCE_IS_PRESSURE(s));
576
577 if (event_origin_changed(s->event))
578 return;
579
580 if (!s->pressure.registered)
581 return;
582
583 if (epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, s->pressure.fd, NULL) < 0)
584 log_debug_errno(errno, "Failed to remove source %s (type %s) from epoll, ignoring: %m",
585 strna(s->description), event_source_type_to_string(s->type));
586
587 s->pressure.registered = false;
588 }
589
590 static int source_pressure_register(sd_event_source *s, int enabled) {
591 assert(s);
592 assert(EVENT_SOURCE_IS_PRESSURE(s));
593 assert(enabled != SD_EVENT_OFF);
594
595 struct epoll_event ev = {
596 .events = s->pressure.write_buffer_size > 0 ? EPOLLOUT :
597 (s->pressure.events | (enabled == SD_EVENT_ONESHOT ? EPOLLONESHOT : 0)),
598 .data.ptr = s,
599 };
600
601 if (epoll_ctl(s->event->epoll_fd,
602 s->pressure.registered ? EPOLL_CTL_MOD : EPOLL_CTL_ADD,
603 s->pressure.fd, &ev) < 0)
604 return -errno;
605
606 s->pressure.registered = true;
607 return 0;
608 }
609
610 static void source_pressure_add_to_write_list(sd_event_source *s) {
611 assert(s);
612 assert(EVENT_SOURCE_IS_PRESSURE(s));
613
614 if (s->pressure.in_write_list)
615 return;
616
617 LIST_PREPEND(pressure.write_list, s->event->pressure_write_list, s);
618 s->pressure.in_write_list = true;
619 }
620
621 static void source_pressure_remove_from_write_list(sd_event_source *s) {
622 assert(s);
623 assert(EVENT_SOURCE_IS_PRESSURE(s));
624
625 if (!s->pressure.in_write_list)
626 return;
627
628 LIST_REMOVE(pressure.write_list, s->event->pressure_write_list, s);
629 s->pressure.in_write_list = false;
630 }
631
632 static clockid_t event_source_type_to_clock(EventSourceType t) {
633
634 switch (t) {
635
636 case SOURCE_TIME_REALTIME:
637 return CLOCK_REALTIME;
638
639 case SOURCE_TIME_BOOTTIME:
640 return CLOCK_BOOTTIME;
641
642 case SOURCE_TIME_MONOTONIC:
643 return CLOCK_MONOTONIC;
644
645 case SOURCE_TIME_REALTIME_ALARM:
646 return CLOCK_REALTIME_ALARM;
647
648 case SOURCE_TIME_BOOTTIME_ALARM:
649 return CLOCK_BOOTTIME_ALARM;
650
651 default:
652 return (clockid_t) -1;
653 }
654 }
655
656 static EventSourceType clock_to_event_source_type(clockid_t clock) {
657
658 switch (clock) {
659
660 case CLOCK_REALTIME:
661 return SOURCE_TIME_REALTIME;
662
663 case CLOCK_BOOTTIME:
664 return SOURCE_TIME_BOOTTIME;
665
666 case CLOCK_MONOTONIC:
667 return SOURCE_TIME_MONOTONIC;
668
669 case CLOCK_REALTIME_ALARM:
670 return SOURCE_TIME_REALTIME_ALARM;
671
672 case CLOCK_BOOTTIME_ALARM:
673 return SOURCE_TIME_BOOTTIME_ALARM;
674
675 default:
676 return _SOURCE_EVENT_SOURCE_TYPE_INVALID;
677 }
678 }
679
680 static struct clock_data* event_get_clock_data(sd_event *e, EventSourceType t) {
681 assert(e);
682
683 switch (t) {
684
685 case SOURCE_TIME_REALTIME:
686 return &e->realtime;
687
688 case SOURCE_TIME_BOOTTIME:
689 return &e->boottime;
690
691 case SOURCE_TIME_MONOTONIC:
692 return &e->monotonic;
693
694 case SOURCE_TIME_REALTIME_ALARM:
695 return &e->realtime_alarm;
696
697 case SOURCE_TIME_BOOTTIME_ALARM:
698 return &e->boottime_alarm;
699
700 default:
701 return NULL;
702 }
703 }
704
705 static void event_free_signal_data(sd_event *e, struct signal_data *d) {
706 assert(e);
707
708 if (!d)
709 return;
710
711 hashmap_remove(e->signal_data, &d->priority);
712 safe_close(d->fd);
713 free(d);
714 }
715
716 static int event_make_signal_data(
717 sd_event *e,
718 int sig,
719 struct signal_data **ret) {
720
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_origin_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 d = new(struct signal_data, 1);
746 if (!d)
747 return -ENOMEM;
748
749 *d = (struct signal_data) {
750 .wakeup = WAKEUP_SIGNAL_DATA,
751 .fd = -EBADF,
752 .priority = priority,
753 };
754
755 r = hashmap_ensure_put(&e->signal_data, &uint64_hash_ops, &d->priority, d);
756 if (r < 0) {
757 free(d);
758 return r;
759 }
760
761 added = true;
762 }
763
764 ss_copy = d->sigset;
765 assert_se(sigaddset(&ss_copy, sig) >= 0);
766
767 r = signalfd(d->fd >= 0 ? d->fd : -1, /* the first arg must be -1 or a valid signalfd */
768 &ss_copy,
769 SFD_NONBLOCK|SFD_CLOEXEC);
770 if (r < 0) {
771 r = -errno;
772 goto fail;
773 }
774
775 d->sigset = ss_copy;
776
777 if (d->fd >= 0) {
778 if (ret)
779 *ret = d;
780 return 0;
781 }
782
783 d->fd = fd_move_above_stdio(r);
784
785 struct epoll_event ev = {
786 .events = EPOLLIN,
787 .data.ptr = d,
788 };
789
790 if (epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, d->fd, &ev) < 0) {
791 r = -errno;
792 goto fail;
793 }
794
795 if (ret)
796 *ret = d;
797
798 return 0;
799
800 fail:
801 if (added)
802 event_free_signal_data(e, d);
803
804 return r;
805 }
806
807 static void event_unmask_signal_data(sd_event *e, struct signal_data *d, int sig) {
808 assert(e);
809 assert(d);
810
811 /* Turns off the specified signal in the signal data
812 * object. If the signal mask of the object becomes empty that
813 * way removes it. */
814
815 if (sigismember(&d->sigset, sig) == 0)
816 return;
817
818 assert_se(sigdelset(&d->sigset, sig) >= 0);
819
820 if (sigisemptyset(&d->sigset)) {
821 /* If all the mask is all-zero we can get rid of the structure */
822 event_free_signal_data(e, d);
823 return;
824 }
825
826 if (event_origin_changed(e))
827 return;
828
829 assert(d->fd >= 0);
830
831 if (signalfd(d->fd, &d->sigset, SFD_NONBLOCK|SFD_CLOEXEC) < 0)
832 log_debug_errno(errno, "Failed to unset signal bit, ignoring: %m");
833 }
834
835 static void event_gc_signal_data(sd_event *e, const int64_t *priority, int sig) {
836 struct signal_data *d;
837 static const int64_t zero_priority = 0;
838
839 assert(e);
840
841 /* Rechecks if the specified signal is still something we are interested in. If not, we'll unmask it,
842 * and possibly drop the signalfd for it. */
843
844 if (sig == SIGCHLD &&
845 e->n_online_child_sources > 0)
846 return;
847
848 if (e->signal_sources &&
849 e->signal_sources[sig] &&
850 event_source_is_online(e->signal_sources[sig]))
851 return;
852
853 /*
854 * The specified signal might be enabled in three different queues:
855 *
856 * 1) the one that belongs to the priority passed (if it is non-NULL)
857 * 2) the one that belongs to the priority of the event source of the signal (if there is one)
858 * 3) the 0 priority (to cover the SIGCHLD case)
859 *
860 * Hence, let's remove it from all three here.
861 */
862
863 if (priority) {
864 d = hashmap_get(e->signal_data, priority);
865 if (d)
866 event_unmask_signal_data(e, d, sig);
867 }
868
869 if (e->signal_sources && e->signal_sources[sig]) {
870 d = hashmap_get(e->signal_data, &e->signal_sources[sig]->priority);
871 if (d)
872 event_unmask_signal_data(e, d, sig);
873 }
874
875 d = hashmap_get(e->signal_data, &zero_priority);
876 if (d)
877 event_unmask_signal_data(e, d, sig);
878 }
879
880 static void event_source_pp_prioq_reshuffle(sd_event_source *s) {
881 assert(s);
882
883 /* Reshuffles the pending + prepare prioqs. Called whenever the dispatch order changes, i.e. when
884 * they are enabled/disabled or marked pending and such. */
885
886 if (s->pending)
887 prioq_reshuffle(s->event->pending, s, &s->pending_index);
888
889 if (s->prepare)
890 prioq_reshuffle(s->event->prepare, s, &s->prepare_index);
891 }
892
893 static void event_source_time_prioq_reshuffle(sd_event_source *s) {
894 struct clock_data *d;
895
896 assert(s);
897
898 /* Called whenever the event source's timer ordering properties changed, i.e. time, accuracy,
899 * pending, enable state, and ratelimiting state. Makes sure the two prioq's are ordered
900 * properly again. */
901
902 if (s->ratelimited)
903 d = &s->event->monotonic;
904 else if (EVENT_SOURCE_IS_TIME(s->type))
905 assert_se(d = event_get_clock_data(s->event, s->type));
906 else
907 return; /* no-op for an event source which is neither a timer nor ratelimited. */
908
909 prioq_reshuffle(d->earliest, s, &s->earliest_index);
910 prioq_reshuffle(d->latest, s, &s->latest_index);
911 d->needs_rearm = true;
912 }
913
914 static void event_source_time_prioq_remove(
915 sd_event_source *s,
916 struct clock_data *d) {
917
918 assert(s);
919 assert(d);
920
921 prioq_remove(d->earliest, s, &s->earliest_index);
922 prioq_remove(d->latest, s, &s->latest_index);
923 s->earliest_index = s->latest_index = PRIOQ_IDX_NULL;
924 d->needs_rearm = true;
925 }
926
927 static void source_disconnect(sd_event_source *s) {
928 sd_event *event;
929 int r;
930
931 assert(s);
932
933 if (!s->event)
934 return;
935
936 assert(s->event->n_sources > 0);
937
938 switch (s->type) {
939
940 case SOURCE_IO:
941 if (s->io.fd >= 0)
942 source_io_unregister(s);
943
944 break;
945
946 case SOURCE_TIME_REALTIME:
947 case SOURCE_TIME_BOOTTIME:
948 case SOURCE_TIME_MONOTONIC:
949 case SOURCE_TIME_REALTIME_ALARM:
950 case SOURCE_TIME_BOOTTIME_ALARM:
951 /* Only remove this event source from the time event source here if it is not ratelimited. If
952 * it is ratelimited, we'll remove it below, separately. Why? Because the clock used might
953 * differ: ratelimiting always uses CLOCK_MONOTONIC, but timer events might use any clock */
954
955 if (!s->ratelimited) {
956 struct clock_data *d;
957 assert_se(d = event_get_clock_data(s->event, s->type));
958 event_source_time_prioq_remove(s, d);
959 }
960
961 break;
962
963 case SOURCE_SIGNAL:
964 if (s->signal.sig > 0) {
965
966 if (s->event->signal_sources)
967 s->event->signal_sources[s->signal.sig] = NULL;
968
969 event_gc_signal_data(s->event, &s->priority, s->signal.sig);
970
971 if (s->signal.unblock) {
972 sigset_t new_ss;
973
974 if (sigemptyset(&new_ss) < 0)
975 log_debug_errno(errno, "Failed to reset signal set, ignoring: %m");
976 else if (sigaddset(&new_ss, s->signal.sig) < 0)
977 log_debug_errno(errno, "Failed to add signal %i to signal mask, ignoring: %m", s->signal.sig);
978 else {
979 r = pthread_sigmask(SIG_UNBLOCK, &new_ss, NULL);
980 if (r != 0)
981 log_debug_errno(r, "Failed to unblock signal %i, ignoring: %m", s->signal.sig);
982 }
983 }
984 }
985
986 break;
987
988 case SOURCE_CHILD:
989 if (event_origin_changed(s->event))
990 s->child.process_owned = false;
991
992 if (s->child.pid > 0) {
993 if (event_source_is_online(s)) {
994 assert(s->event->n_online_child_sources > 0);
995 s->event->n_online_child_sources--;
996 }
997
998 assert_se(hashmap_remove(s->event->child_sources, PID_TO_PTR(s->child.pid)));
999 }
1000
1001 if (EVENT_SOURCE_WATCH_PIDFD(s))
1002 source_child_pidfd_unregister(s);
1003 else
1004 event_gc_signal_data(s->event, &s->priority, SIGCHLD);
1005
1006 break;
1007
1008 case SOURCE_DEFER:
1009 /* nothing */
1010 break;
1011
1012 case SOURCE_POST:
1013 set_remove(s->event->post_sources, s);
1014 break;
1015
1016 case SOURCE_EXIT:
1017 prioq_remove(s->event->exit, s, &s->exit.prioq_index);
1018 break;
1019
1020 case SOURCE_INOTIFY: {
1021 InodeData *inode_data;
1022
1023 inode_data = s->inotify.inode_data;
1024 if (inode_data) {
1025 InotifyData *inotify_data;
1026 assert_se(inotify_data = inode_data->inotify_data);
1027
1028 /* Detach this event source from the inode object */
1029 LIST_REMOVE(inotify.by_inode_data, inode_data->event_sources, s);
1030 s->inotify.inode_data = NULL;
1031
1032 if (s->pending) {
1033 assert(inotify_data->n_pending > 0);
1034 inotify_data->n_pending--;
1035 }
1036
1037 /* Note that we don't reduce the inotify mask for the watch descriptor here if the inode is
1038 * continued to being watched. That's because inotify doesn't really have an API for that: we
1039 * can only change watch masks with access to the original inode either by fd or by path. But
1040 * paths aren't stable, and keeping an O_PATH fd open all the time would mean wasting an fd
1041 * continuously and keeping the mount busy which we can't really do. We could reconstruct the
1042 * original inode from /proc/self/fdinfo/$INOTIFY_FD (as all watch descriptors are listed
1043 * there), but given the need for open_by_handle_at() which is privileged and not universally
1044 * available this would be quite an incomplete solution. Hence we go the other way, leave the
1045 * mask set, even if it is not minimized now, and ignore all events we aren't interested in
1046 * anymore after reception. Yes, this sucks, but … Linux … */
1047
1048 /* Maybe release the inode data (and its inotify) */
1049 event_gc_inode_data(s->event, inode_data);
1050 }
1051
1052 break;
1053 }
1054
1055 case SOURCE_MEMORY_PRESSURE:
1056 case SOURCE_CPU_PRESSURE:
1057 case SOURCE_IO_PRESSURE:
1058 source_pressure_remove_from_write_list(s);
1059 source_pressure_unregister(s);
1060 break;
1061
1062 default:
1063 assert_not_reached();
1064 }
1065
1066 if (s->pending)
1067 prioq_remove(s->event->pending, s, &s->pending_index);
1068
1069 if (s->prepare)
1070 prioq_remove(s->event->prepare, s, &s->prepare_index);
1071
1072 if (s->ratelimited)
1073 event_source_time_prioq_remove(s, &s->event->monotonic);
1074
1075 event = TAKE_PTR(s->event);
1076 LIST_REMOVE(sources, event->sources, s);
1077 event->n_sources--;
1078
1079 /* Note that we don't invalidate the type here, since we still need it in order to close the fd or
1080 * pidfd associated with this event source, which we'll do only on source_free(). */
1081
1082 if (!s->floating)
1083 sd_event_unref(event);
1084 }
1085
1086 static sd_event_source* source_free(sd_event_source *s) {
1087 int r;
1088
1089 assert(s);
1090
1091 source_disconnect(s);
1092
1093 if (s->type == SOURCE_IO && s->io.owned)
1094 s->io.fd = safe_close(s->io.fd);
1095
1096 if (s->type == SOURCE_CHILD) {
1097 /* Eventually the kernel will do this automatically for us, but for now let's emulate this (unreliably) in userspace. */
1098
1099 if (s->child.process_owned) {
1100 assert(s->child.pid > 0);
1101 assert(s->child.pidfd >= 0);
1102
1103 if (!s->child.exited) {
1104 r = RET_NERRNO(pidfd_send_signal(s->child.pidfd, SIGKILL, NULL, 0));
1105 if (r < 0 && r != -ESRCH)
1106 log_debug_errno(r, "Failed to kill process " PID_FMT ", ignoring: %m",
1107 s->child.pid);
1108 }
1109
1110 if (!s->child.waited) {
1111 siginfo_t si = {};
1112
1113 /* Reap the child if we can */
1114 (void) waitid(P_PIDFD, s->child.pidfd, &si, WEXITED);
1115 }
1116 }
1117
1118 if (s->child.pidfd_owned)
1119 s->child.pidfd = safe_close(s->child.pidfd);
1120 }
1121
1122 if (EVENT_SOURCE_IS_PRESSURE(s)) {
1123 s->pressure.fd = safe_close(s->pressure.fd);
1124 s->pressure.write_buffer = mfree(s->pressure.write_buffer);
1125 }
1126
1127 if (s->destroy_callback)
1128 s->destroy_callback(s->userdata);
1129
1130 free(s->description);
1131 return mfree(s);
1132 }
1133 DEFINE_TRIVIAL_CLEANUP_FUNC(sd_event_source*, source_free);
1134
1135 static int source_set_pending(sd_event_source *s, bool b) {
1136 int r;
1137
1138 assert(s);
1139 assert(s->type != SOURCE_EXIT);
1140
1141 if (s->pending == b)
1142 return 0;
1143
1144 s->pending = b;
1145
1146 if (b) {
1147 s->pending_iteration = s->event->iteration;
1148
1149 r = prioq_put(s->event->pending, s, &s->pending_index);
1150 if (r < 0) {
1151 s->pending = false;
1152 return r;
1153 }
1154 } else
1155 assert_se(prioq_remove(s->event->pending, s, &s->pending_index));
1156
1157 if (EVENT_SOURCE_IS_TIME(s->type))
1158 event_source_time_prioq_reshuffle(s);
1159
1160 if (s->type == SOURCE_SIGNAL && !b) {
1161 struct signal_data *d;
1162
1163 d = hashmap_get(s->event->signal_data, &s->priority);
1164 if (d && d->current == s)
1165 d->current = NULL;
1166 }
1167
1168 if (s->type == SOURCE_INOTIFY) {
1169
1170 assert(s->inotify.inode_data);
1171 assert(s->inotify.inode_data->inotify_data);
1172
1173 if (b)
1174 s->inotify.inode_data->inotify_data->n_pending++;
1175 else {
1176 assert(s->inotify.inode_data->inotify_data->n_pending > 0);
1177 s->inotify.inode_data->inotify_data->n_pending--;
1178 }
1179 }
1180
1181 return 1;
1182 }
1183
1184 static sd_event_source* source_new(sd_event *e, bool floating, EventSourceType type) {
1185
1186 /* Let's allocate exactly what we need. Note that the difference of the smallest event source
1187 * structure to the largest is 144 bytes on x86-64 at the time of writing, i.e. more than two cache
1188 * lines. */
1189 static const size_t size_table[_SOURCE_EVENT_SOURCE_TYPE_MAX] = {
1190 [SOURCE_IO] = endoffsetof_field(sd_event_source, io),
1191 [SOURCE_TIME_REALTIME] = endoffsetof_field(sd_event_source, time),
1192 [SOURCE_TIME_BOOTTIME] = endoffsetof_field(sd_event_source, time),
1193 [SOURCE_TIME_MONOTONIC] = endoffsetof_field(sd_event_source, time),
1194 [SOURCE_TIME_REALTIME_ALARM] = endoffsetof_field(sd_event_source, time),
1195 [SOURCE_TIME_BOOTTIME_ALARM] = endoffsetof_field(sd_event_source, time),
1196 [SOURCE_SIGNAL] = endoffsetof_field(sd_event_source, signal),
1197 [SOURCE_CHILD] = endoffsetof_field(sd_event_source, child),
1198 [SOURCE_DEFER] = endoffsetof_field(sd_event_source, defer),
1199 [SOURCE_POST] = endoffsetof_field(sd_event_source, post),
1200 [SOURCE_EXIT] = endoffsetof_field(sd_event_source, exit),
1201 [SOURCE_INOTIFY] = endoffsetof_field(sd_event_source, inotify),
1202 [SOURCE_MEMORY_PRESSURE] = endoffsetof_field(sd_event_source, pressure),
1203 [SOURCE_CPU_PRESSURE] = endoffsetof_field(sd_event_source, pressure),
1204 [SOURCE_IO_PRESSURE] = endoffsetof_field(sd_event_source, pressure),
1205 };
1206
1207 sd_event_source *s;
1208
1209 assert(e);
1210 assert(type >= 0);
1211 assert(type < _SOURCE_EVENT_SOURCE_TYPE_MAX);
1212 assert(size_table[type] > 0);
1213
1214 s = malloc0(size_table[type]);
1215 if (!s)
1216 return NULL;
1217 /* We use expand_to_usable() here to tell gcc that it should consider this an object of the full
1218 * size, even if we only allocate the initial part we need. */
1219 s = expand_to_usable(s, sizeof(sd_event_source));
1220
1221 /* Note: we cannot use compound initialization here, because sizeof(sd_event_source) is likely larger
1222 * than what we allocated here. */
1223 s->n_ref = 1;
1224 s->event = e;
1225 s->floating = floating;
1226 s->type = type;
1227 s->pending_index = PRIOQ_IDX_NULL;
1228 s->prepare_index = PRIOQ_IDX_NULL;
1229
1230 if (!floating)
1231 sd_event_ref(e);
1232
1233 LIST_PREPEND(sources, e->sources, s);
1234 e->n_sources++;
1235
1236 return s;
1237 }
1238
1239 static int io_exit_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1240 assert(s);
1241
1242 return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1243 }
1244
1245 _public_ int sd_event_add_io(
1246 sd_event *e,
1247 sd_event_source **ret,
1248 int fd,
1249 uint32_t events,
1250 sd_event_io_handler_t callback,
1251 void *userdata) {
1252
1253 _cleanup_(source_freep) sd_event_source *s = NULL;
1254 int r;
1255
1256 assert_return(e, -EINVAL);
1257 assert_return(e = event_resolve(e), -ENOPKG);
1258 assert_return(fd >= 0, -EBADF);
1259 assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
1260 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1261 assert_return(!event_origin_changed(e), -ECHILD);
1262
1263 if (!callback)
1264 callback = io_exit_callback;
1265
1266 s = source_new(e, !ret, SOURCE_IO);
1267 if (!s)
1268 return -ENOMEM;
1269
1270 s->wakeup = WAKEUP_EVENT_SOURCE;
1271 s->io.fd = fd;
1272 s->io.events = events;
1273 s->io.callback = callback;
1274 s->userdata = userdata;
1275 s->enabled = SD_EVENT_ON;
1276
1277 r = source_io_register(s, s->enabled, events);
1278 if (r < 0)
1279 return r;
1280
1281 if (ret)
1282 *ret = s;
1283 TAKE_PTR(s);
1284
1285 return 0;
1286 }
1287
1288 static void initialize_perturb(sd_event *e) {
1289 sd_id128_t id = {};
1290
1291 /* When we sleep for longer, we try to realign the wakeup to the same time within each
1292 * minute/second/250ms, so that events all across the system can be coalesced into a single CPU
1293 * wakeup. However, let's take some system-specific randomness for this value, so that in a network
1294 * of systems with synced clocks timer events are distributed a bit. Here, we calculate a
1295 * perturbation usec offset from the boot ID (or machine ID if failed, e.g. /proc is not mounted). */
1296
1297 if (_likely_(e->perturb != USEC_INFINITY))
1298 return;
1299
1300 if (sd_id128_get_boot(&id) >= 0 || sd_id128_get_machine(&id) >= 0)
1301 e->perturb = (id.qwords[0] ^ id.qwords[1]) % USEC_PER_MINUTE;
1302 else
1303 e->perturb = 0; /* This is a super early process without /proc and /etc ?? */
1304 }
1305
1306 static int event_setup_timer_fd(
1307 sd_event *e,
1308 struct clock_data *d,
1309 clockid_t clock) {
1310
1311 assert(e);
1312 assert(d);
1313
1314 if (_likely_(d->fd >= 0))
1315 return 0;
1316
1317 _cleanup_close_ int fd = -EBADF;
1318
1319 fd = timerfd_create(clock, TFD_NONBLOCK|TFD_CLOEXEC);
1320 if (fd < 0)
1321 return -errno;
1322
1323 fd = fd_move_above_stdio(fd);
1324
1325 struct epoll_event ev = {
1326 .events = EPOLLIN,
1327 .data.ptr = d,
1328 };
1329
1330 if (epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1331 return -errno;
1332
1333 d->fd = TAKE_FD(fd);
1334 return 0;
1335 }
1336
1337 static int time_exit_callback(sd_event_source *s, uint64_t usec, void *userdata) {
1338 assert(s);
1339
1340 return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1341 }
1342
1343 static int setup_clock_data(sd_event *e, struct clock_data *d, clockid_t clock) {
1344 int r;
1345
1346 assert(d);
1347
1348 if (d->fd < 0) {
1349 r = event_setup_timer_fd(e, d, clock);
1350 if (r < 0)
1351 return r;
1352 }
1353
1354 r = prioq_ensure_allocated(&d->earliest, earliest_time_prioq_compare);
1355 if (r < 0)
1356 return r;
1357
1358 r = prioq_ensure_allocated(&d->latest, latest_time_prioq_compare);
1359 if (r < 0)
1360 return r;
1361
1362 return 0;
1363 }
1364
1365 static int event_source_time_prioq_put(
1366 sd_event_source *s,
1367 struct clock_data *d) {
1368
1369 int r;
1370
1371 assert(s);
1372 assert(d);
1373 assert(EVENT_SOURCE_USES_TIME_PRIOQ(s->type));
1374
1375 r = prioq_put(d->earliest, s, &s->earliest_index);
1376 if (r < 0)
1377 return r;
1378
1379 r = prioq_put(d->latest, s, &s->latest_index);
1380 if (r < 0) {
1381 assert_se(prioq_remove(d->earliest, s, &s->earliest_index) > 0);
1382 s->earliest_index = PRIOQ_IDX_NULL;
1383 return r;
1384 }
1385
1386 d->needs_rearm = true;
1387 return 0;
1388 }
1389
1390 _public_ int sd_event_add_time(
1391 sd_event *e,
1392 sd_event_source **ret,
1393 clockid_t clock,
1394 uint64_t usec,
1395 uint64_t accuracy,
1396 sd_event_time_handler_t callback,
1397 void *userdata) {
1398
1399 EventSourceType type;
1400 _cleanup_(source_freep) sd_event_source *s = NULL;
1401 struct clock_data *d;
1402 int r;
1403
1404 assert_return(e, -EINVAL);
1405 assert_return(e = event_resolve(e), -ENOPKG);
1406 assert_return(accuracy != UINT64_MAX, -EINVAL);
1407 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1408 assert_return(!event_origin_changed(e), -ECHILD);
1409
1410 if (!clock_supported(clock)) /* Checks whether the kernel supports the clock */
1411 return -EOPNOTSUPP;
1412
1413 type = clock_to_event_source_type(clock); /* checks whether sd-event supports this clock */
1414 if (type < 0)
1415 return -EOPNOTSUPP;
1416
1417 if (!callback)
1418 callback = time_exit_callback;
1419
1420 assert_se(d = event_get_clock_data(e, type));
1421
1422 r = setup_clock_data(e, d, clock);
1423 if (r < 0)
1424 return r;
1425
1426 s = source_new(e, !ret, type);
1427 if (!s)
1428 return -ENOMEM;
1429
1430 s->time.next = usec;
1431 s->time.accuracy = accuracy == 0 ? DEFAULT_ACCURACY_USEC : accuracy;
1432 s->time.callback = callback;
1433 s->earliest_index = s->latest_index = PRIOQ_IDX_NULL;
1434 s->userdata = userdata;
1435 s->enabled = SD_EVENT_ONESHOT;
1436
1437 r = event_source_time_prioq_put(s, d);
1438 if (r < 0)
1439 return r;
1440
1441 if (ret)
1442 *ret = s;
1443 TAKE_PTR(s);
1444
1445 return 0;
1446 }
1447
1448 _public_ int sd_event_add_time_relative(
1449 sd_event *e,
1450 sd_event_source **ret,
1451 clockid_t clock,
1452 uint64_t usec,
1453 uint64_t accuracy,
1454 sd_event_time_handler_t callback,
1455 void *userdata) {
1456
1457 usec_t t;
1458 int r;
1459
1460 /* Same as sd_event_add_time() but operates relative to the event loop's current point in time, and
1461 * checks for overflow. */
1462
1463 r = sd_event_now(e, clock, &t);
1464 if (r < 0)
1465 return r;
1466
1467 if (usec >= USEC_INFINITY - t)
1468 return -EOVERFLOW;
1469
1470 return sd_event_add_time(e, ret, clock, t + usec, accuracy, callback, userdata);
1471 }
1472
1473 static int signal_exit_callback(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
1474 assert(s);
1475
1476 return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1477 }
1478
1479 _public_ int sd_event_add_signal(
1480 sd_event *e,
1481 sd_event_source **ret,
1482 int sig,
1483 sd_event_signal_handler_t callback,
1484 void *userdata) {
1485
1486 _cleanup_(source_freep) sd_event_source *s = NULL;
1487 struct signal_data *d;
1488 sigset_t new_ss;
1489 bool block_it;
1490 int r;
1491
1492 assert_return(e, -EINVAL);
1493 assert_return(e = event_resolve(e), -ENOPKG);
1494 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1495 assert_return(!event_origin_changed(e), -ECHILD);
1496
1497 /* Let's make sure our special flag stays outside of the valid signal range */
1498 assert_cc(_NSIG < SD_EVENT_SIGNAL_PROCMASK);
1499
1500 if (sig & SD_EVENT_SIGNAL_PROCMASK) {
1501 sig &= ~SD_EVENT_SIGNAL_PROCMASK;
1502 assert_return(SIGNAL_VALID(sig), -EINVAL);
1503
1504 block_it = true;
1505 } else {
1506 assert_return(SIGNAL_VALID(sig), -EINVAL);
1507
1508 r = signal_is_blocked(sig);
1509 if (r < 0)
1510 return r;
1511 if (r == 0)
1512 return -EBUSY;
1513
1514 block_it = false;
1515 }
1516
1517 if (!callback)
1518 callback = signal_exit_callback;
1519
1520 if (!e->signal_sources) {
1521 e->signal_sources = new0(sd_event_source*, _NSIG);
1522 if (!e->signal_sources)
1523 return -ENOMEM;
1524 } else if (e->signal_sources[sig])
1525 return -EBUSY;
1526
1527 s = source_new(e, !ret, SOURCE_SIGNAL);
1528 if (!s)
1529 return -ENOMEM;
1530
1531 s->signal.sig = sig;
1532 s->signal.callback = callback;
1533 s->userdata = userdata;
1534 s->enabled = SD_EVENT_ON;
1535
1536 e->signal_sources[sig] = s;
1537
1538 if (block_it) {
1539 sigset_t old_ss;
1540
1541 if (sigemptyset(&new_ss) < 0)
1542 return -errno;
1543
1544 if (sigaddset(&new_ss, sig) < 0)
1545 return -errno;
1546
1547 r = pthread_sigmask(SIG_BLOCK, &new_ss, &old_ss);
1548 if (r != 0)
1549 return -r;
1550
1551 r = sigismember(&old_ss, sig);
1552 if (r < 0)
1553 return -errno;
1554
1555 s->signal.unblock = !r;
1556 } else
1557 s->signal.unblock = false;
1558
1559 r = event_make_signal_data(e, sig, &d);
1560 if (r < 0) {
1561 if (s->signal.unblock)
1562 (void) pthread_sigmask(SIG_UNBLOCK, &new_ss, NULL);
1563
1564 return r;
1565 }
1566
1567 /* Use the signal name as description for the event source by default */
1568 (void) sd_event_source_set_description(s, signal_to_string(sig));
1569
1570 if (ret)
1571 *ret = s;
1572 TAKE_PTR(s);
1573
1574 return 0;
1575 }
1576
1577 static int child_exit_callback(sd_event_source *s, const siginfo_t *si, void *userdata) {
1578 assert(s);
1579
1580 return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1581 }
1582
1583 static int verify_sigchld(int options) {
1584 int r;
1585
1586 if ((options & (WSTOPPED|WCONTINUED)) != 0) {
1587 /* Caller must block SIGCHLD before using us to watch for WSTOPPED or WCONTINUED. */
1588
1589 r = signal_is_blocked(SIGCHLD);
1590 if (r < 0)
1591 return r;
1592 if (r == 0)
1593 return -EBUSY;
1594 }
1595
1596 /* We don't want the Linux autoreaping logic to take effect when we're watching for process exit, so
1597 * check if it is enabled. */
1598
1599 if (options & WEXITED) {
1600 r = autoreaping_enabled();
1601 if (r < 0)
1602 return r;
1603 if (r > 0)
1604 return -EBUSY;
1605 }
1606
1607 return 0;
1608 }
1609
1610 _public_ int sd_event_add_child(
1611 sd_event *e,
1612 sd_event_source **ret,
1613 pid_t pid,
1614 int options,
1615 sd_event_child_handler_t callback,
1616 void *userdata) {
1617
1618 _cleanup_(source_freep) sd_event_source *s = NULL;
1619 int r;
1620
1621 assert_return(e, -EINVAL);
1622 assert_return(e = event_resolve(e), -ENOPKG);
1623 assert_return(pid > 1, -EINVAL);
1624 assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED|WNOWAIT)), -EINVAL);
1625 assert_return(options != 0, -EINVAL);
1626 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1627 assert_return(!event_origin_changed(e), -ECHILD);
1628
1629 if (!callback)
1630 callback = child_exit_callback;
1631
1632 r = verify_sigchld(options);
1633 if (r < 0)
1634 return r;
1635
1636 r = hashmap_ensure_allocated(&e->child_sources, NULL);
1637 if (r < 0)
1638 return r;
1639
1640 if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
1641 return -EBUSY;
1642
1643 s = source_new(e, !ret, SOURCE_CHILD);
1644 if (!s)
1645 return -ENOMEM;
1646
1647 /* We always take a pidfd here, even if we wait for anything else than WEXITED, so that we pin the
1648 * PID, and make regular waitid() handling race-free. */
1649
1650 s->child.pidfd = pidfd_open(pid, 0);
1651 if (s->child.pidfd < 0)
1652 return -errno;
1653
1654 s->child.pidfd_owned = true; /* If we allocate the pidfd we own it by default */
1655
1656 s->wakeup = WAKEUP_EVENT_SOURCE;
1657 s->child.options = options;
1658 s->child.callback = callback;
1659 s->userdata = userdata;
1660 s->enabled = SD_EVENT_ONESHOT;
1661
1662 if (EVENT_SOURCE_WATCH_PIDFD(s)) {
1663 /* We only want to watch for exit */
1664 r = source_child_pidfd_register(s, s->enabled);
1665 if (r < 0)
1666 return r;
1667
1668 } else {
1669 /* We shall wait for some other event than WEXITED */
1670 r = event_make_signal_data(e, SIGCHLD, NULL);
1671 if (r < 0)
1672 return r;
1673
1674 e->need_process_child = true;
1675 }
1676
1677 r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
1678 if (r < 0)
1679 return r;
1680
1681 /* These must be done after everything succeeds. */
1682 s->child.pid = pid;
1683 e->n_online_child_sources++;
1684
1685 if (ret)
1686 *ret = s;
1687 TAKE_PTR(s);
1688 return 0;
1689 }
1690
1691 _public_ int sd_event_add_child_pidfd(
1692 sd_event *e,
1693 sd_event_source **ret,
1694 int pidfd,
1695 int options,
1696 sd_event_child_handler_t callback,
1697 void *userdata) {
1698
1699 _cleanup_(source_freep) sd_event_source *s = NULL;
1700 pid_t pid;
1701 int r;
1702
1703 assert_return(e, -EINVAL);
1704 assert_return(e = event_resolve(e), -ENOPKG);
1705 assert_return(pidfd >= 0, -EBADF);
1706 assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED|WNOWAIT)), -EINVAL);
1707 assert_return(options != 0, -EINVAL);
1708 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1709 assert_return(!event_origin_changed(e), -ECHILD);
1710
1711 if (!callback)
1712 callback = child_exit_callback;
1713
1714 r = verify_sigchld(options);
1715 if (r < 0)
1716 return r;
1717
1718 r = hashmap_ensure_allocated(&e->child_sources, NULL);
1719 if (r < 0)
1720 return r;
1721
1722 r = pidfd_get_pid(pidfd, &pid);
1723 if (r < 0)
1724 return r;
1725
1726 if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
1727 return -EBUSY;
1728
1729 s = source_new(e, !ret, SOURCE_CHILD);
1730 if (!s)
1731 return -ENOMEM;
1732
1733 s->wakeup = WAKEUP_EVENT_SOURCE;
1734 s->child.pidfd = pidfd;
1735 s->child.options = options;
1736 s->child.callback = callback;
1737 s->child.pidfd_owned = false; /* If we got the pidfd passed in we don't own it by default (similar to the IO fd case) */
1738 s->userdata = userdata;
1739 s->enabled = SD_EVENT_ONESHOT;
1740
1741 if (EVENT_SOURCE_WATCH_PIDFD(s)) {
1742 /* We only want to watch for WEXITED */
1743 r = source_child_pidfd_register(s, s->enabled);
1744 if (r < 0)
1745 return r;
1746 } else {
1747 /* We shall wait for some other event than WEXITED */
1748 r = event_make_signal_data(e, SIGCHLD, NULL);
1749 if (r < 0)
1750 return r;
1751
1752 e->need_process_child = true;
1753 }
1754
1755 r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
1756 if (r < 0)
1757 return r;
1758
1759 s->child.pid = pid;
1760 e->n_online_child_sources++;
1761
1762 if (ret)
1763 *ret = s;
1764 TAKE_PTR(s);
1765 return 0;
1766 }
1767
1768 static int generic_exit_callback(sd_event_source *s, void *userdata) {
1769 assert(s);
1770
1771 return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
1772 }
1773
1774 _public_ int sd_event_add_defer(
1775 sd_event *e,
1776 sd_event_source **ret,
1777 sd_event_handler_t callback,
1778 void *userdata) {
1779
1780 _cleanup_(source_freep) sd_event_source *s = NULL;
1781 int r;
1782
1783 assert_return(e, -EINVAL);
1784 assert_return(e = event_resolve(e), -ENOPKG);
1785 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1786 assert_return(!event_origin_changed(e), -ECHILD);
1787
1788 if (!callback)
1789 callback = generic_exit_callback;
1790
1791 s = source_new(e, !ret, SOURCE_DEFER);
1792 if (!s)
1793 return -ENOMEM;
1794
1795 s->defer.callback = callback;
1796 s->userdata = userdata;
1797 s->enabled = SD_EVENT_ONESHOT;
1798
1799 r = source_set_pending(s, true);
1800 if (r < 0)
1801 return r;
1802
1803 if (ret)
1804 *ret = s;
1805 TAKE_PTR(s);
1806
1807 return 0;
1808 }
1809
1810 _public_ int sd_event_add_post(
1811 sd_event *e,
1812 sd_event_source **ret,
1813 sd_event_handler_t callback,
1814 void *userdata) {
1815
1816 _cleanup_(source_freep) sd_event_source *s = NULL;
1817 int r;
1818
1819 assert_return(e, -EINVAL);
1820 assert_return(e = event_resolve(e), -ENOPKG);
1821 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1822 assert_return(!event_origin_changed(e), -ECHILD);
1823
1824 if (!callback)
1825 callback = generic_exit_callback;
1826
1827 s = source_new(e, !ret, SOURCE_POST);
1828 if (!s)
1829 return -ENOMEM;
1830
1831 s->post.callback = callback;
1832 s->userdata = userdata;
1833 s->enabled = SD_EVENT_ON;
1834
1835 r = set_ensure_put(&e->post_sources, NULL, s);
1836 if (r < 0)
1837 return r;
1838 assert(r > 0);
1839
1840 if (ret)
1841 *ret = s;
1842 TAKE_PTR(s);
1843
1844 return 0;
1845 }
1846
1847 _public_ int sd_event_add_exit(
1848 sd_event *e,
1849 sd_event_source **ret,
1850 sd_event_handler_t callback,
1851 void *userdata) {
1852
1853 _cleanup_(source_freep) sd_event_source *s = NULL;
1854 int r;
1855
1856 assert_return(e, -EINVAL);
1857 assert_return(e = event_resolve(e), -ENOPKG);
1858 assert_return(callback, -EINVAL);
1859 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1860 assert_return(!event_origin_changed(e), -ECHILD);
1861
1862 r = prioq_ensure_allocated(&e->exit, exit_prioq_compare);
1863 if (r < 0)
1864 return r;
1865
1866 s = source_new(e, !ret, SOURCE_EXIT);
1867 if (!s)
1868 return -ENOMEM;
1869
1870 s->exit.callback = callback;
1871 s->userdata = userdata;
1872 s->exit.prioq_index = PRIOQ_IDX_NULL;
1873 s->enabled = SD_EVENT_ONESHOT;
1874
1875 r = prioq_put(s->event->exit, s, &s->exit.prioq_index);
1876 if (r < 0)
1877 return r;
1878
1879 if (ret)
1880 *ret = s;
1881 TAKE_PTR(s);
1882
1883 return 0;
1884 }
1885
1886 _public_ int sd_event_trim_memory(void) {
1887 int r;
1888
1889 /* A default implementation of a memory pressure callback. Simply releases our own allocation caches
1890 * and glibc's. This is automatically used when people call sd_event_add_memory_pressure() with a
1891 * NULL callback parameter. */
1892
1893 log_debug("Memory pressure event, trimming malloc() memory.");
1894
1895 struct mallinfo2 before_mallinfo = mallinfo2();
1896
1897 usec_t before_timestamp = now(CLOCK_MONOTONIC);
1898 hashmap_trim_pools();
1899 r = malloc_trim(0);
1900 usec_t after_timestamp = now(CLOCK_MONOTONIC);
1901
1902 if (r > 0)
1903 log_debug("Successfully trimmed some memory.");
1904 else
1905 log_debug("Couldn't trim any memory.");
1906
1907 usec_t period = after_timestamp - before_timestamp;
1908
1909 struct mallinfo2 after_mallinfo = mallinfo2();
1910 size_t l = LESS_BY(before_mallinfo.hblkhd, after_mallinfo.hblkhd) +
1911 LESS_BY(before_mallinfo.arena, after_mallinfo.arena);
1912 log_struct(LOG_DEBUG,
1913 LOG_MESSAGE("Memory trimming took %s, returned %s to OS.",
1914 FORMAT_TIMESPAN(period, 0),
1915 FORMAT_BYTES(l)),
1916 LOG_MESSAGE_ID(SD_MESSAGE_MEMORY_TRIM_STR),
1917 LOG_ITEM("TRIMMED_BYTES=%zu", l),
1918 LOG_ITEM("TRIMMED_USEC=" USEC_FMT, period));
1919
1920 return 0;
1921 }
1922
1923 static int memory_pressure_callback(sd_event_source *s, void *userdata) {
1924 assert(s);
1925
1926 sd_event_trim_memory();
1927 return 0;
1928 }
1929
1930 static int event_add_pressure(
1931 sd_event *e,
1932 sd_event_source **ret,
1933 sd_event_handler_t callback,
1934 void *userdata,
1935 EventSourceType type,
1936 sd_event_handler_t default_callback,
1937 PressureResource resource) {
1938
1939 _cleanup_free_ char *w = NULL;
1940 _cleanup_(source_freep) sd_event_source *s = NULL;
1941 _cleanup_close_ int path_fd = -EBADF, fd = -EBADF;
1942 _cleanup_free_ void *write_buffer = NULL;
1943 _cleanup_free_ char *watch_fallback = NULL;
1944 const char *watch, *env;
1945 size_t write_buffer_size = 0;
1946 struct stat st;
1947 uint32_t events;
1948 bool locked;
1949 int r;
1950
1951 assert_return(e, -EINVAL);
1952 assert_return(e = event_resolve(e), -ENOPKG);
1953 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
1954 assert_return(!event_origin_changed(e), -ECHILD);
1955
1956 const PressureResourceInfo *info = pressure_resource_get_info(resource);
1957
1958 if (!callback)
1959 callback = default_callback;
1960
1961 s = source_new(e, !ret, type);
1962 if (!s)
1963 return -ENOMEM;
1964
1965 s->wakeup = WAKEUP_EVENT_SOURCE;
1966 s->pressure.callback = callback;
1967 s->userdata = userdata;
1968 s->enabled = SD_EVENT_ON;
1969 s->pressure.fd = -EBADF;
1970
1971 env = secure_getenv(info->env_watch);
1972 if (env) {
1973 if (isempty(env) || path_equal(env, "/dev/null"))
1974 return log_debug_errno(SYNTHETIC_ERRNO(EHOSTDOWN),
1975 "Pressure logic is explicitly disabled via $%s.", info->env_watch);
1976
1977 if (!path_is_absolute(env) || !path_is_normalized(env))
1978 return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
1979 "$%s set to invalid path: %s", info->env_watch, env);
1980
1981 watch = env;
1982
1983 env = secure_getenv(info->env_write);
1984 if (env) {
1985 r = unbase64mem(env, &write_buffer, &write_buffer_size);
1986 if (r < 0)
1987 return r;
1988 }
1989
1990 locked = true;
1991 } else {
1992
1993 r = is_pressure_supported();
1994 if (r < 0)
1995 return r;
1996 if (r == 0)
1997 return -EOPNOTSUPP;
1998
1999 /* By default we want to watch pressure on the local cgroup, but we'll fall back on
2000 * the system wide pressure if for some reason we cannot (which could be: controller
2001 * not delegated to us, or PSI simply not available in the kernel). */
2002
2003 _cleanup_free_ char *cg = NULL;
2004 r = cg_pid_get_path(0, &cg);
2005 if (r < 0)
2006 return r;
2007
2008 _cleanup_free_ char *cgroup_file = strjoin(info->name, ".pressure");
2009 if (!cgroup_file)
2010 return -ENOMEM;
2011
2012 w = path_join("/sys/fs/cgroup", cg, cgroup_file);
2013 if (!w)
2014 return -ENOMEM;
2015
2016 watch = w;
2017
2018 watch_fallback = strjoin("/proc/pressure/", info->name);
2019 if (!watch_fallback)
2020 return -ENOMEM;
2021
2022 /* Android uses three levels in its userspace low memory killer logic:
2023 * some 70000 1000000
2024 * some 100000 1000000
2025 * full 70000 1000000
2026 *
2027 * GNOME's low memory monitor uses:
2028 * some 70000 1000000
2029 * some 100000 1000000
2030 * full 100000 1000000
2031 *
2032 * We'll default to the middle level that both agree on. Except we do it on a 2s window
2033 * (i.e. 200ms per 2s, rather than 100ms per 1s), because that's the window duration the
2034 * kernel will allow us to do unprivileged, also in the future. */
2035 if (asprintf((char**) &write_buffer,
2036 "%s " USEC_FMT " " USEC_FMT,
2037 PRESSURE_DEFAULT_TYPE,
2038 PRESSURE_DEFAULT_THRESHOLD_USEC,
2039 PRESSURE_DEFAULT_WINDOW_USEC) < 0)
2040 return -ENOMEM;
2041
2042 write_buffer_size = strlen(write_buffer) + 1;
2043 locked = false;
2044 }
2045
2046 path_fd = open(watch, O_PATH|O_CLOEXEC);
2047 if (path_fd < 0) {
2048 if (errno != ENOENT)
2049 return -errno;
2050
2051 /* We got ENOENT. Two options now: try the fallback if we have one, or return the error as is
2052 * (when based on user/env config). */
2053
2054 if (!watch_fallback) {
2055 assert(locked);
2056 return -ENOENT;
2057 }
2058
2059 path_fd = open(watch_fallback, O_PATH|O_CLOEXEC);
2060 if (path_fd < 0) {
2061 if (errno == ENOENT) /* PSI is not available in the kernel even under the fallback path? */
2062 return -EOPNOTSUPP;
2063 return -errno;
2064 }
2065 }
2066
2067 if (fstat(path_fd, &st) < 0)
2068 return -errno;
2069
2070 if (S_ISSOCK(st.st_mode)) {
2071 fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
2072 if (fd < 0)
2073 return -errno;
2074
2075 r = connect_unix_path(fd, path_fd, NULL);
2076 if (r < 0)
2077 return r;
2078
2079 events = EPOLLIN;
2080
2081 } else if (S_ISREG(st.st_mode) || S_ISFIFO(st.st_mode) || S_ISCHR(st.st_mode)) {
2082 fd = fd_reopen(path_fd, (write_buffer_size > 0 ? O_RDWR : O_RDONLY) |O_CLOEXEC|O_NONBLOCK|O_NOCTTY);
2083 if (fd < 0)
2084 return fd;
2085
2086 if (S_ISREG(st.st_mode)) {
2087 struct statfs sfs;
2088
2089 /* If this is a regular file validate this is a procfs or cgroupfs file, where we look for EPOLLPRI */
2090
2091 if (fstatfs(fd, &sfs) < 0)
2092 return -errno;
2093
2094 if (!is_fs_type(&sfs, PROC_SUPER_MAGIC) &&
2095 !is_fs_type(&sfs, CGROUP2_SUPER_MAGIC))
2096 return -ENOTTY;
2097
2098 events = EPOLLPRI;
2099 } else
2100 /* For fifos and char devices just watch for EPOLLIN */
2101 events = EPOLLIN;
2102
2103 } else if (S_ISDIR(st.st_mode))
2104 return -EISDIR;
2105 else
2106 return -EBADF;
2107
2108 s->pressure.fd = TAKE_FD(fd);
2109 s->pressure.write_buffer = TAKE_PTR(write_buffer);
2110 s->pressure.write_buffer_size = write_buffer_size;
2111 s->pressure.events = events;
2112 s->pressure.locked = locked;
2113
2114 /* So here's the thing: if we are talking to PSI we need to write the watch string before adding the
2115 * fd to epoll (if we ignore this, then the watch won't work). Hence we'll not actually register the
2116 * fd with the epoll right-away. Instead, we just add the event source to a list of pressure event
2117 * sources on which writes must be executed before the first event loop iteration is executed. (We
2118 * could also write the data here, right away, but we want to give the caller the freedom to call
2119 * sd_event_source_set_{memory,cpu,io}_pressure_type() and
2120 * sd_event_source_set_{memory,cpu,io}_pressure_period() before we write it. */
2121
2122 if (s->pressure.write_buffer_size > 0)
2123 source_pressure_add_to_write_list(s);
2124 else {
2125 r = source_pressure_register(s, s->enabled);
2126 if (r < 0)
2127 return r;
2128 }
2129
2130 if (ret)
2131 *ret = s;
2132 TAKE_PTR(s);
2133
2134 return 0;
2135 }
2136
2137 _public_ int sd_event_add_memory_pressure(
2138 sd_event *e,
2139 sd_event_source **ret,
2140 sd_event_handler_t callback,
2141 void *userdata) {
2142
2143 return event_add_pressure(
2144 e, ret, callback, userdata,
2145 SOURCE_MEMORY_PRESSURE,
2146 memory_pressure_callback,
2147 PRESSURE_MEMORY);
2148 }
2149
2150 static int cpu_pressure_callback(sd_event_source *s, void *userdata) {
2151 assert(s);
2152
2153 return 0;
2154 }
2155
2156 _public_ int sd_event_add_cpu_pressure(
2157 sd_event *e,
2158 sd_event_source **ret,
2159 sd_event_handler_t callback,
2160 void *userdata) {
2161
2162 return event_add_pressure(
2163 e, ret, callback, userdata,
2164 SOURCE_CPU_PRESSURE,
2165 cpu_pressure_callback,
2166 PRESSURE_CPU);
2167 }
2168
2169 static int io_pressure_callback(sd_event_source *s, void *userdata) {
2170 assert(s);
2171
2172 return 0;
2173 }
2174
2175 _public_ int sd_event_add_io_pressure(
2176 sd_event *e,
2177 sd_event_source **ret,
2178 sd_event_handler_t callback,
2179 void *userdata) {
2180
2181 return event_add_pressure(
2182 e, ret, callback, userdata,
2183 SOURCE_IO_PRESSURE,
2184 io_pressure_callback,
2185 PRESSURE_IO);
2186 }
2187
2188 static void event_free_inotify_data(sd_event *e, InotifyData *d) {
2189 assert(e);
2190
2191 if (!d)
2192 return;
2193
2194 assert(hashmap_isempty(d->inodes));
2195 assert(hashmap_isempty(d->wd));
2196
2197 if (d->buffer_filled > 0)
2198 LIST_REMOVE(buffered, e->buffered_inotify_data_list, d);
2199
2200 hashmap_free(d->inodes);
2201 hashmap_free(d->wd);
2202
2203 assert_se(hashmap_remove(e->inotify_data, &d->priority) == d);
2204
2205 if (d->fd >= 0) {
2206 if (!event_origin_changed(e) &&
2207 epoll_ctl(e->epoll_fd, EPOLL_CTL_DEL, d->fd, NULL) < 0)
2208 log_debug_errno(errno, "Failed to remove inotify fd from epoll, ignoring: %m");
2209
2210 safe_close(d->fd);
2211 }
2212 free(d);
2213 }
2214
2215 static int event_make_inotify_data(sd_event *e, int64_t priority, InotifyData **ret) {
2216 _cleanup_close_ int fd = -EBADF;
2217 InotifyData *d;
2218 int r;
2219
2220 assert(e);
2221
2222 d = hashmap_get(e->inotify_data, &priority);
2223 if (d) {
2224 if (ret)
2225 *ret = d;
2226 return 0;
2227 }
2228
2229 fd = inotify_init1(IN_NONBLOCK|O_CLOEXEC);
2230 if (fd < 0)
2231 return -errno;
2232
2233 fd = fd_move_above_stdio(fd);
2234
2235 d = new(InotifyData, 1);
2236 if (!d)
2237 return -ENOMEM;
2238
2239 *d = (InotifyData) {
2240 .wakeup = WAKEUP_INOTIFY_DATA,
2241 .fd = TAKE_FD(fd),
2242 .priority = priority,
2243 };
2244
2245 r = hashmap_ensure_put(&e->inotify_data, &uint64_hash_ops, &d->priority, d);
2246 if (r < 0) {
2247 d->fd = safe_close(d->fd);
2248 free(d);
2249 return r;
2250 }
2251
2252 struct epoll_event ev = {
2253 .events = EPOLLIN,
2254 .data.ptr = d,
2255 };
2256
2257 if (epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, d->fd, &ev) < 0) {
2258 r = -errno;
2259 d->fd = safe_close(d->fd); /* let's close this ourselves, as event_free_inotify_data() would otherwise
2260 * remove the fd from the epoll first, which we don't want as we couldn't
2261 * add it in the first place. */
2262 event_free_inotify_data(e, d);
2263 return r;
2264 }
2265
2266 if (ret)
2267 *ret = d;
2268
2269 return 1;
2270 }
2271
2272 static int inode_data_compare(const InodeData *x, const InodeData *y) {
2273 int r;
2274
2275 assert(x);
2276 assert(y);
2277
2278 r = CMP(x->dev, y->dev);
2279 if (r != 0)
2280 return r;
2281
2282 return CMP(x->ino, y->ino);
2283 }
2284
2285 static void inode_data_hash_func(const InodeData *d, struct siphash *state) {
2286 assert(d);
2287
2288 siphash24_compress_typesafe(d->dev, state);
2289 siphash24_compress_typesafe(d->ino, state);
2290 }
2291
2292 DEFINE_PRIVATE_HASH_OPS(inode_data_hash_ops, InodeData, inode_data_hash_func, inode_data_compare);
2293
2294 static void event_free_inode_data(sd_event *e, InodeData *d) {
2295 assert(e);
2296
2297 if (!d)
2298 return;
2299
2300 assert(!d->event_sources);
2301
2302 if (d->fd >= 0) {
2303 LIST_REMOVE(to_close, e->inode_data_to_close_list, d);
2304 safe_close(d->fd);
2305 }
2306
2307 if (d->inotify_data) {
2308
2309 if (d->wd >= 0) {
2310 if (d->inotify_data->fd >= 0 && !event_origin_changed(e)) {
2311 /* So here's a problem. At the time this runs the watch descriptor might already be
2312 * invalidated, because an IN_IGNORED event might be queued right the moment we enter
2313 * the syscall. Hence, whenever we get EINVAL, ignore it entirely, since it's a very
2314 * likely case to happen. */
2315
2316 if (inotify_rm_watch(d->inotify_data->fd, d->wd) < 0 && errno != EINVAL)
2317 log_debug_errno(errno, "Failed to remove watch descriptor %i from inotify, ignoring: %m", d->wd);
2318 }
2319
2320 assert_se(hashmap_remove(d->inotify_data->wd, INT_TO_PTR(d->wd)) == d);
2321 }
2322
2323 assert_se(hashmap_remove(d->inotify_data->inodes, d) == d);
2324 }
2325
2326 free(d->path);
2327 free(d);
2328 }
2329
2330 static void event_gc_inotify_data(sd_event *e, InotifyData *d) {
2331 assert(e);
2332
2333 /* Collects the InotifyData object if we don't need it anymore. That's the case if we don't want to
2334 * watch any inode with it anymore, which in turn happens if no event source of this priority is
2335 * interested in any inode any longer. That said, we maintain an extra busy counter: if non-zero
2336 * we'll delay GC (under the expectation that the GC is called again once the counter is
2337 * decremented). */
2338
2339 if (!d)
2340 return;
2341
2342 if (!hashmap_isempty(d->inodes))
2343 return;
2344
2345 if (d->n_busy > 0)
2346 return;
2347
2348 event_free_inotify_data(e, d);
2349 }
2350
2351 static void event_gc_inode_data(sd_event *e, InodeData *d) {
2352 InotifyData *inotify_data;
2353
2354 assert(e);
2355
2356 if (!d)
2357 return;
2358
2359 if (d->event_sources)
2360 return;
2361
2362 inotify_data = d->inotify_data;
2363 event_free_inode_data(e, d);
2364
2365 event_gc_inotify_data(e, inotify_data);
2366 }
2367
2368 static int event_make_inode_data(
2369 sd_event *e,
2370 InotifyData *inotify_data,
2371 dev_t dev,
2372 ino_t ino,
2373 InodeData **ret) {
2374
2375 InodeData *d, key;
2376 int r;
2377
2378 assert(e);
2379 assert(inotify_data);
2380
2381 key = (InodeData) {
2382 .ino = ino,
2383 .dev = dev,
2384 };
2385
2386 d = hashmap_get(inotify_data->inodes, &key);
2387 if (d) {
2388 if (ret)
2389 *ret = d;
2390
2391 return 0;
2392 }
2393
2394 r = hashmap_ensure_allocated(&inotify_data->inodes, &inode_data_hash_ops);
2395 if (r < 0)
2396 return r;
2397
2398 d = new(InodeData, 1);
2399 if (!d)
2400 return -ENOMEM;
2401
2402 *d = (InodeData) {
2403 .dev = dev,
2404 .ino = ino,
2405 .wd = -1,
2406 .fd = -EBADF,
2407 .inotify_data = inotify_data,
2408 };
2409
2410 r = hashmap_put(inotify_data->inodes, d, d);
2411 if (r < 0) {
2412 free(d);
2413 return r;
2414 }
2415
2416 if (ret)
2417 *ret = d;
2418
2419 return 1;
2420 }
2421
2422 static uint32_t inode_data_determine_mask(InodeData *d) {
2423 bool excl_unlink = true;
2424 uint32_t combined = 0;
2425
2426 assert(d);
2427
2428 /* Combines the watch masks of all event sources watching this inode. We generally just OR them together, but
2429 * the IN_EXCL_UNLINK flag is ANDed instead.
2430 *
2431 * Note that we add all sources to the mask here, regardless whether enabled, disabled or oneshot. That's
2432 * because we cannot change the mask anymore after the event source was created once, since the kernel has no
2433 * API for that. Hence we need to subscribe to the maximum mask we ever might be interested in, and suppress
2434 * events we don't care for client-side. */
2435
2436 LIST_FOREACH(inotify.by_inode_data, s, d->event_sources) {
2437
2438 if ((s->inotify.mask & IN_EXCL_UNLINK) == 0)
2439 excl_unlink = false;
2440
2441 combined |= s->inotify.mask;
2442 }
2443
2444 return (combined & ~(IN_ONESHOT|IN_DONT_FOLLOW|IN_ONLYDIR|IN_EXCL_UNLINK)) | (excl_unlink ? IN_EXCL_UNLINK : 0);
2445 }
2446
2447 static int inode_data_realize_watch(sd_event *e, InodeData *d) {
2448 uint32_t combined_mask;
2449 int wd, r;
2450
2451 assert(d);
2452 assert(d->fd >= 0);
2453
2454 combined_mask = inode_data_determine_mask(d);
2455
2456 if (d->wd >= 0 && combined_mask == d->combined_mask)
2457 return 0;
2458
2459 r = hashmap_ensure_allocated(&d->inotify_data->wd, NULL);
2460 if (r < 0)
2461 return r;
2462
2463 wd = inotify_add_watch_fd(d->inotify_data->fd, d->fd, combined_mask);
2464 if (wd < 0)
2465 return wd;
2466
2467 if (d->wd < 0) {
2468 r = hashmap_put(d->inotify_data->wd, INT_TO_PTR(wd), d);
2469 if (r < 0) {
2470 (void) inotify_rm_watch(d->inotify_data->fd, wd);
2471 return r;
2472 }
2473
2474 d->wd = wd;
2475
2476 } else if (d->wd != wd) {
2477
2478 log_debug("Weird, the watch descriptor we already knew for this inode changed?");
2479 (void) inotify_rm_watch(d->fd, wd);
2480 return -EINVAL;
2481 }
2482
2483 d->combined_mask = combined_mask;
2484 return 1;
2485 }
2486
2487 static int inotify_exit_callback(sd_event_source *s, const struct inotify_event *event, void *userdata) {
2488 assert(s);
2489
2490 return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
2491 }
2492
2493 static int event_add_inotify_fd_internal(
2494 sd_event *e,
2495 sd_event_source **ret,
2496 int fd,
2497 bool donate,
2498 uint32_t mask,
2499 sd_event_inotify_handler_t callback,
2500 void *userdata) {
2501
2502 _cleanup_close_ int donated_fd = donate ? fd : -EBADF;
2503 _cleanup_(source_freep) sd_event_source *s = NULL;
2504 InotifyData *inotify_data = NULL;
2505 InodeData *inode_data = NULL;
2506 struct stat st;
2507 int r;
2508
2509 assert_return(e, -EINVAL);
2510 assert_return(e = event_resolve(e), -ENOPKG);
2511 assert_return(fd >= 0, -EBADF);
2512 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
2513 assert_return(!event_origin_changed(e), -ECHILD);
2514
2515 if (!callback)
2516 callback = inotify_exit_callback;
2517
2518 /* Refuse IN_MASK_ADD since we coalesce watches on the same inode, and hence really don't want to merge
2519 * masks. Or in other words, this whole code exists only to manage IN_MASK_ADD type operations for you, hence
2520 * the user can't use them for us. */
2521 if (mask & IN_MASK_ADD)
2522 return -EINVAL;
2523
2524 if (fstat(fd, &st) < 0)
2525 return -errno;
2526
2527 s = source_new(e, !ret, SOURCE_INOTIFY);
2528 if (!s)
2529 return -ENOMEM;
2530
2531 s->enabled = mask & IN_ONESHOT ? SD_EVENT_ONESHOT : SD_EVENT_ON;
2532 s->inotify.mask = mask;
2533 s->inotify.callback = callback;
2534 s->userdata = userdata;
2535
2536 /* Allocate an inotify object for this priority, and an inode object within it */
2537 r = event_make_inotify_data(e, SD_EVENT_PRIORITY_NORMAL, &inotify_data);
2538 if (r < 0)
2539 return r;
2540
2541 r = event_make_inode_data(e, inotify_data, st.st_dev, st.st_ino, &inode_data);
2542 if (r < 0) {
2543 event_gc_inotify_data(e, inotify_data);
2544 return r;
2545 }
2546
2547 /* Keep the O_PATH fd around until the first iteration of the loop, so that we can still change the priority of
2548 * the event source, until then, for which we need the original inode. */
2549 if (inode_data->fd < 0) {
2550 if (donated_fd >= 0)
2551 inode_data->fd = TAKE_FD(donated_fd);
2552 else {
2553 inode_data->fd = fcntl(fd, F_DUPFD_CLOEXEC, 3);
2554 if (inode_data->fd < 0) {
2555 r = -errno;
2556 event_gc_inode_data(e, inode_data);
2557 return r;
2558 }
2559 }
2560
2561 LIST_PREPEND(to_close, e->inode_data_to_close_list, inode_data);
2562
2563 _cleanup_free_ char *path = NULL;
2564 r = fd_get_path(inode_data->fd, &path);
2565 if (r < 0 && r != -ENOSYS) { /* The path is optional, hence ignore -ENOSYS. */
2566 event_gc_inode_data(e, inode_data);
2567 return r;
2568 }
2569
2570 free_and_replace(inode_data->path, path);
2571 }
2572
2573 /* Link our event source to the inode data object */
2574 LIST_PREPEND(inotify.by_inode_data, inode_data->event_sources, s);
2575 s->inotify.inode_data = inode_data;
2576
2577 /* Actually realize the watch now */
2578 r = inode_data_realize_watch(e, inode_data);
2579 if (r < 0)
2580 return r;
2581
2582 if (ret)
2583 *ret = s;
2584 TAKE_PTR(s);
2585
2586 return 0;
2587 }
2588
2589 _public_ int sd_event_add_inotify_fd(
2590 sd_event *e,
2591 sd_event_source **ret,
2592 int fd,
2593 uint32_t mask,
2594 sd_event_inotify_handler_t callback,
2595 void *userdata) {
2596
2597 return event_add_inotify_fd_internal(e, ret, fd, /* donate= */ false, mask, callback, userdata);
2598 }
2599
2600 _public_ int sd_event_add_inotify(
2601 sd_event *e,
2602 sd_event_source **ret,
2603 const char *path,
2604 uint32_t mask,
2605 sd_event_inotify_handler_t callback,
2606 void *userdata) {
2607
2608 sd_event_source *s = NULL; /* avoid false maybe-uninitialized warning */
2609 int fd, r;
2610
2611 assert_return(path, -EINVAL);
2612
2613 fd = open(path, O_PATH | O_CLOEXEC |
2614 (mask & IN_ONLYDIR ? O_DIRECTORY : 0) |
2615 (mask & IN_DONT_FOLLOW ? O_NOFOLLOW : 0));
2616 if (fd < 0)
2617 return -errno;
2618
2619 r = event_add_inotify_fd_internal(e, &s, fd, /* donate= */ true, mask, callback, userdata);
2620 if (r < 0)
2621 return r;
2622
2623 (void) sd_event_source_set_description(s, path);
2624
2625 if (ret)
2626 *ret = s;
2627
2628 return r;
2629 }
2630
2631 static sd_event_source* event_source_free(sd_event_source *s) {
2632 if (!s)
2633 return NULL;
2634
2635 /* Here's a special hack: when we are called from a
2636 * dispatch handler we won't free the event source
2637 * immediately, but we will detach the fd from the
2638 * epoll. This way it is safe for the caller to unref
2639 * the event source and immediately close the fd, but
2640 * we still retain a valid event source object after
2641 * the callback. */
2642
2643 if (s->dispatching)
2644 source_disconnect(s);
2645 else
2646 source_free(s);
2647
2648 return NULL;
2649 }
2650
2651 DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(sd_event_source, sd_event_source, event_source_free);
2652
2653 _public_ int sd_event_source_set_description(sd_event_source *s, const char *description) {
2654 assert_return(s, -EINVAL);
2655 assert_return(!event_origin_changed(s->event), -ECHILD);
2656
2657 return free_and_strdup(&s->description, description);
2658 }
2659
2660 _public_ int sd_event_source_get_description(sd_event_source *s, const char **ret) {
2661 assert_return(s, -EINVAL);
2662 assert_return(ret, -EINVAL);
2663
2664 if (!s->description)
2665 return -ENXIO;
2666
2667 *ret = s->description;
2668 return 0;
2669 }
2670
2671 _public_ sd_event* sd_event_source_get_event(sd_event_source *s) {
2672 assert_return(s, NULL);
2673 assert_return(!event_origin_changed(s->event), NULL);
2674
2675 return s->event;
2676 }
2677
2678 _public_ int sd_event_source_get_pending(sd_event_source *s) {
2679 assert_return(s, -EINVAL);
2680 assert_return(s->type != SOURCE_EXIT, -EDOM);
2681 assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2682 assert_return(!event_origin_changed(s->event), -ECHILD);
2683
2684 return s->pending;
2685 }
2686
2687 _public_ int sd_event_source_get_io_fd(sd_event_source *s) {
2688 assert_return(s, -EINVAL);
2689 assert_return(s->type == SOURCE_IO, -EDOM);
2690 assert_return(!event_origin_changed(s->event), -ECHILD);
2691
2692 return s->io.fd;
2693 }
2694
2695 _public_ int sd_event_source_set_io_fd(sd_event_source *s, int fd) {
2696 int saved_fd, r;
2697
2698 assert_return(s, -EINVAL);
2699 assert_return(fd >= 0, -EBADF);
2700 assert_return(s->type == SOURCE_IO, -EDOM);
2701 assert_return(!event_origin_changed(s->event), -ECHILD);
2702
2703 if (s->io.fd == fd)
2704 return 0;
2705
2706 saved_fd = s->io.fd;
2707 s->io.fd = fd;
2708
2709 assert(event_source_is_offline(s) == !s->io.registered);
2710
2711 if (s->io.registered) {
2712 s->io.registered = false;
2713
2714 r = source_io_register(s, s->enabled, s->io.events);
2715 if (r < 0) {
2716 s->io.fd = saved_fd;
2717 s->io.registered = true;
2718 return r;
2719 }
2720
2721 (void) epoll_ctl(s->event->epoll_fd, EPOLL_CTL_DEL, saved_fd, NULL);
2722 }
2723
2724 if (s->io.owned)
2725 safe_close(saved_fd);
2726
2727 return 0;
2728 }
2729
2730 _public_ int sd_event_source_get_io_fd_own(sd_event_source *s) {
2731 assert_return(s, -EINVAL);
2732 assert_return(s->type == SOURCE_IO, -EDOM);
2733 assert_return(!event_origin_changed(s->event), -ECHILD);
2734
2735 return s->io.owned;
2736 }
2737
2738 _public_ int sd_event_source_set_io_fd_own(sd_event_source *s, int own) {
2739 assert_return(s, -EINVAL);
2740 assert_return(s->type == SOURCE_IO, -EDOM);
2741 assert_return(!event_origin_changed(s->event), -ECHILD);
2742
2743 s->io.owned = own;
2744 return 0;
2745 }
2746
2747 _public_ int sd_event_source_get_io_events(sd_event_source *s, uint32_t *ret) {
2748 assert_return(s, -EINVAL);
2749 assert_return(ret, -EINVAL);
2750 assert_return(s->type == SOURCE_IO, -EDOM);
2751 assert_return(!event_origin_changed(s->event), -ECHILD);
2752
2753 *ret = s->io.events;
2754 return 0;
2755 }
2756
2757 _public_ int sd_event_source_set_io_events(sd_event_source *s, uint32_t events) {
2758 int r;
2759
2760 assert_return(s, -EINVAL);
2761 assert_return(s->type == SOURCE_IO, -EDOM);
2762 assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
2763 assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2764 assert_return(!event_origin_changed(s->event), -ECHILD);
2765
2766 /* edge-triggered updates are never skipped, so we can reset edges */
2767 if (s->io.events == events && !(events & EPOLLET))
2768 return 0;
2769
2770 r = source_set_pending(s, false);
2771 if (r < 0)
2772 return r;
2773
2774 if (event_source_is_online(s)) {
2775 r = source_io_register(s, s->enabled, events);
2776 if (r < 0)
2777 return r;
2778 }
2779
2780 s->io.events = events;
2781
2782 return 0;
2783 }
2784
2785 _public_ int sd_event_source_get_io_revents(sd_event_source *s, uint32_t *ret) {
2786 assert_return(s, -EINVAL);
2787 assert_return(ret, -EINVAL);
2788 assert_return(s->type == SOURCE_IO, -EDOM);
2789 assert_return(!event_origin_changed(s->event), -ECHILD);
2790
2791 if (!s->pending)
2792 return -ENODATA;
2793
2794 *ret = s->io.revents;
2795 return 0;
2796 }
2797
2798 _public_ int sd_event_source_get_signal(sd_event_source *s) {
2799 assert_return(s, -EINVAL);
2800 assert_return(s->type == SOURCE_SIGNAL, -EDOM);
2801 assert_return(!event_origin_changed(s->event), -ECHILD);
2802
2803 return s->signal.sig;
2804 }
2805
2806 _public_ int sd_event_source_get_priority(sd_event_source *s, int64_t *ret) {
2807 assert_return(s, -EINVAL);
2808 assert_return(ret, -EINVAL);
2809 assert_return(!event_origin_changed(s->event), -ECHILD);
2810
2811 *ret = s->priority;
2812 return 0;
2813 }
2814
2815 _public_ int sd_event_source_set_priority(sd_event_source *s, int64_t priority) {
2816 bool rm_inotify = false, rm_inode = false;
2817 InotifyData *new_inotify_data = NULL;
2818 InodeData *new_inode_data = NULL;
2819 int r;
2820
2821 assert_return(s, -EINVAL);
2822 assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
2823 assert_return(!event_origin_changed(s->event), -ECHILD);
2824
2825 if (s->priority == priority)
2826 return 0;
2827
2828 if (s->type == SOURCE_INOTIFY) {
2829 InodeData *old_inode_data;
2830
2831 assert(s->inotify.inode_data);
2832 old_inode_data = s->inotify.inode_data;
2833
2834 /* We need the original fd to change the priority. If we don't have it we can't change the priority,
2835 * anymore. Note that we close any fds when entering the next event loop iteration, i.e. for inotify
2836 * events we allow priority changes only until the first following iteration. */
2837 if (old_inode_data->fd < 0)
2838 return -EOPNOTSUPP;
2839
2840 r = event_make_inotify_data(s->event, priority, &new_inotify_data);
2841 if (r < 0)
2842 return r;
2843 rm_inotify = r > 0;
2844
2845 r = event_make_inode_data(s->event, new_inotify_data, old_inode_data->dev, old_inode_data->ino, &new_inode_data);
2846 if (r < 0)
2847 goto fail;
2848 rm_inode = r > 0;
2849
2850 if (new_inode_data->fd < 0) {
2851 /* Duplicate the fd for the new inode object if we don't have any yet */
2852 new_inode_data->fd = fcntl(old_inode_data->fd, F_DUPFD_CLOEXEC, 3);
2853 if (new_inode_data->fd < 0) {
2854 r = -errno;
2855 goto fail;
2856 }
2857
2858 LIST_PREPEND(to_close, s->event->inode_data_to_close_list, new_inode_data);
2859
2860 _cleanup_free_ char *path = NULL;
2861 r = fd_get_path(new_inode_data->fd, &path);
2862 if (r < 0 && r != -ENOSYS)
2863 goto fail;
2864
2865 free_and_replace(new_inode_data->path, path);
2866 }
2867
2868 /* Move the event source to the new inode data structure */
2869 LIST_REMOVE(inotify.by_inode_data, old_inode_data->event_sources, s);
2870 LIST_PREPEND(inotify.by_inode_data, new_inode_data->event_sources, s);
2871 s->inotify.inode_data = new_inode_data;
2872
2873 /* Now create the new watch */
2874 r = inode_data_realize_watch(s->event, new_inode_data);
2875 if (r < 0) {
2876 /* Move it back */
2877 LIST_REMOVE(inotify.by_inode_data, new_inode_data->event_sources, s);
2878 LIST_PREPEND(inotify.by_inode_data, old_inode_data->event_sources, s);
2879 s->inotify.inode_data = old_inode_data;
2880 goto fail;
2881 }
2882
2883 s->priority = priority;
2884
2885 event_gc_inode_data(s->event, old_inode_data);
2886
2887 } else if (s->type == SOURCE_SIGNAL && event_source_is_online(s)) {
2888 struct signal_data *old, *d;
2889
2890 /* Move us from the signalfd belonging to the old
2891 * priority to the signalfd of the new priority */
2892
2893 assert_se(old = hashmap_get(s->event->signal_data, &s->priority));
2894
2895 s->priority = priority;
2896
2897 r = event_make_signal_data(s->event, s->signal.sig, &d);
2898 if (r < 0) {
2899 s->priority = old->priority;
2900 return r;
2901 }
2902
2903 event_unmask_signal_data(s->event, old, s->signal.sig);
2904 } else
2905 s->priority = priority;
2906
2907 event_source_pp_prioq_reshuffle(s);
2908
2909 if (s->type == SOURCE_EXIT)
2910 prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
2911
2912 return 0;
2913
2914 fail:
2915 if (rm_inode)
2916 event_free_inode_data(s->event, new_inode_data);
2917
2918 if (rm_inotify)
2919 event_free_inotify_data(s->event, new_inotify_data);
2920
2921 return r;
2922 }
2923
2924 _public_ int sd_event_source_get_enabled(sd_event_source *s, int *ret) {
2925 /* Quick mode: the event source doesn't exist and we only want to query boolean enablement state. */
2926 if (!s && !ret)
2927 return false;
2928
2929 assert_return(s, -EINVAL);
2930 assert_return(!event_origin_changed(s->event), -ECHILD);
2931
2932 if (ret)
2933 *ret = s->enabled;
2934
2935 return s->enabled != SD_EVENT_OFF;
2936 }
2937
2938 static int event_source_offline(
2939 sd_event_source *s,
2940 int enabled,
2941 bool ratelimited) {
2942
2943 bool was_offline;
2944 int r;
2945
2946 assert(s);
2947 assert(enabled == SD_EVENT_OFF || ratelimited);
2948
2949 /* Unset the pending flag when this event source is disabled */
2950 if (s->enabled != SD_EVENT_OFF &&
2951 enabled == SD_EVENT_OFF &&
2952 !IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
2953 r = source_set_pending(s, false);
2954 if (r < 0)
2955 return r;
2956 }
2957
2958 was_offline = event_source_is_offline(s);
2959 s->enabled = enabled;
2960 s->ratelimited = ratelimited;
2961
2962 switch (s->type) {
2963
2964 case SOURCE_IO:
2965 source_io_unregister(s);
2966 break;
2967
2968 case SOURCE_SIGNAL:
2969 event_gc_signal_data(s->event, &s->priority, s->signal.sig);
2970 break;
2971
2972 case SOURCE_CHILD:
2973 if (!was_offline) {
2974 assert(s->event->n_online_child_sources > 0);
2975 s->event->n_online_child_sources--;
2976 }
2977
2978 if (EVENT_SOURCE_WATCH_PIDFD(s))
2979 source_child_pidfd_unregister(s);
2980 else
2981 event_gc_signal_data(s->event, &s->priority, SIGCHLD);
2982 break;
2983
2984 case SOURCE_EXIT:
2985 prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
2986 break;
2987
2988 case SOURCE_MEMORY_PRESSURE:
2989 case SOURCE_CPU_PRESSURE:
2990 case SOURCE_IO_PRESSURE:
2991 source_pressure_unregister(s);
2992 break;
2993
2994 case SOURCE_TIME_REALTIME:
2995 case SOURCE_TIME_BOOTTIME:
2996 case SOURCE_TIME_MONOTONIC:
2997 case SOURCE_TIME_REALTIME_ALARM:
2998 case SOURCE_TIME_BOOTTIME_ALARM:
2999 case SOURCE_DEFER:
3000 case SOURCE_POST:
3001 case SOURCE_INOTIFY:
3002 break;
3003
3004 default:
3005 assert_not_reached();
3006 }
3007
3008 /* Always reshuffle time prioq, as the ratelimited flag may be changed. */
3009 event_source_time_prioq_reshuffle(s);
3010
3011 return 1;
3012 }
3013
3014 static int event_source_online(
3015 sd_event_source *s,
3016 int enabled,
3017 bool ratelimited) {
3018
3019 bool was_online;
3020 int r;
3021
3022 assert(s);
3023 assert(enabled != SD_EVENT_OFF || !ratelimited);
3024
3025 /* Unset the pending flag when this event source is enabled */
3026 if (s->enabled == SD_EVENT_OFF &&
3027 enabled != SD_EVENT_OFF &&
3028 !IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
3029 r = source_set_pending(s, false);
3030 if (r < 0)
3031 return r;
3032 }
3033
3034 /* Are we really ready for onlining? */
3035 if (enabled == SD_EVENT_OFF || ratelimited) {
3036 /* Nope, we are not ready for onlining, then just update the precise state and exit */
3037 s->enabled = enabled;
3038 s->ratelimited = ratelimited;
3039 return 0;
3040 }
3041
3042 was_online = event_source_is_online(s);
3043
3044 switch (s->type) {
3045 case SOURCE_IO:
3046 r = source_io_register(s, enabled, s->io.events);
3047 if (r < 0)
3048 return r;
3049 break;
3050
3051 case SOURCE_SIGNAL:
3052 r = event_make_signal_data(s->event, s->signal.sig, NULL);
3053 if (r < 0) {
3054 event_gc_signal_data(s->event, &s->priority, s->signal.sig);
3055 return r;
3056 }
3057
3058 break;
3059
3060 case SOURCE_CHILD:
3061 if (EVENT_SOURCE_WATCH_PIDFD(s)) {
3062 /* yes, we can rely on pidfd */
3063
3064 r = source_child_pidfd_register(s, enabled);
3065 if (r < 0)
3066 return r;
3067 } else {
3068 /* something other to watch for than WEXITED */
3069
3070 r = event_make_signal_data(s->event, SIGCHLD, NULL);
3071 if (r < 0) {
3072 event_gc_signal_data(s->event, &s->priority, SIGCHLD);
3073 return r;
3074 }
3075 }
3076
3077 if (!was_online)
3078 s->event->n_online_child_sources++;
3079 break;
3080
3081 case SOURCE_MEMORY_PRESSURE:
3082 case SOURCE_CPU_PRESSURE:
3083 case SOURCE_IO_PRESSURE:
3084 /* As documented in sd_event_add_{memory,cpu,io}_pressure(), we can only register the PSI fd
3085 * with epoll after writing the watch string. */
3086 if (s->pressure.write_buffer_size == 0) {
3087 r = source_pressure_register(s, enabled);
3088 if (r < 0)
3089 return r;
3090 }
3091
3092 break;
3093
3094 case SOURCE_TIME_REALTIME:
3095 case SOURCE_TIME_BOOTTIME:
3096 case SOURCE_TIME_MONOTONIC:
3097 case SOURCE_TIME_REALTIME_ALARM:
3098 case SOURCE_TIME_BOOTTIME_ALARM:
3099 case SOURCE_EXIT:
3100 case SOURCE_DEFER:
3101 case SOURCE_POST:
3102 case SOURCE_INOTIFY:
3103 break;
3104
3105 default:
3106 assert_not_reached();
3107 }
3108
3109 s->enabled = enabled;
3110 s->ratelimited = ratelimited;
3111
3112 /* Non-failing operations below */
3113 if (s->type == SOURCE_EXIT)
3114 prioq_reshuffle(s->event->exit, s, &s->exit.prioq_index);
3115
3116 /* Always reshuffle time prioq, as the ratelimited flag may be changed. */
3117 event_source_time_prioq_reshuffle(s);
3118
3119 return 1;
3120 }
3121
3122 _public_ int sd_event_source_set_enabled(sd_event_source *s, int enabled) {
3123 int r;
3124
3125 assert_return(IN_SET(enabled, SD_EVENT_OFF, SD_EVENT_ON, SD_EVENT_ONESHOT), -EINVAL);
3126
3127 /* Quick mode: if the source doesn't exist, SD_EVENT_OFF is a noop. */
3128 if (enabled == SD_EVENT_OFF && !s)
3129 return 0;
3130
3131 assert_return(s, -EINVAL);
3132 assert_return(!event_origin_changed(s->event), -ECHILD);
3133
3134 /* If we are dead anyway, we are fine with turning off sources, but everything else needs to fail. */
3135 if (s->event->state == SD_EVENT_FINISHED)
3136 return enabled == SD_EVENT_OFF ? 0 : -ESTALE;
3137
3138 if (s->enabled == enabled) /* No change? */
3139 return 0;
3140
3141 if (enabled == SD_EVENT_OFF)
3142 r = event_source_offline(s, enabled, s->ratelimited);
3143 else
3144 r = event_source_online(s, enabled, s->ratelimited);
3145 if (r < 0)
3146 return r;
3147
3148 event_source_pp_prioq_reshuffle(s);
3149 return 0;
3150 }
3151
3152 _public_ int sd_event_source_get_time(sd_event_source *s, uint64_t *ret) {
3153 assert_return(s, -EINVAL);
3154 assert_return(ret, -EINVAL);
3155 assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
3156 assert_return(!event_origin_changed(s->event), -ECHILD);
3157
3158 *ret = s->time.next;
3159 return 0;
3160 }
3161
3162 _public_ int sd_event_source_set_time(sd_event_source *s, uint64_t usec) {
3163 int r;
3164
3165 assert_return(s, -EINVAL);
3166 assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
3167 assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
3168 assert_return(!event_origin_changed(s->event), -ECHILD);
3169
3170 r = source_set_pending(s, false);
3171 if (r < 0)
3172 return r;
3173
3174 s->time.next = usec;
3175
3176 event_source_time_prioq_reshuffle(s);
3177 return 0;
3178 }
3179
3180 _public_ int sd_event_source_set_time_relative(sd_event_source *s, uint64_t usec) {
3181 usec_t t;
3182 int r;
3183
3184 assert_return(s, -EINVAL);
3185 assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
3186 assert_return(!event_origin_changed(s->event), -ECHILD);
3187
3188 if (usec == USEC_INFINITY)
3189 return sd_event_source_set_time(s, USEC_INFINITY);
3190
3191 r = sd_event_now(s->event, event_source_type_to_clock(s->type), &t);
3192 if (r < 0)
3193 return r;
3194
3195 usec = usec_add(t, usec);
3196 if (usec == USEC_INFINITY)
3197 return -EOVERFLOW;
3198
3199 return sd_event_source_set_time(s, usec);
3200 }
3201
3202 _public_ int sd_event_source_get_time_accuracy(sd_event_source *s, uint64_t *ret) {
3203 assert_return(s, -EINVAL);
3204 assert_return(ret, -EINVAL);
3205 assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
3206 assert_return(!event_origin_changed(s->event), -ECHILD);
3207
3208 *ret = s->time.accuracy;
3209 return 0;
3210 }
3211
3212 _public_ int sd_event_source_set_time_accuracy(sd_event_source *s, uint64_t usec) {
3213 int r;
3214
3215 assert_return(s, -EINVAL);
3216 assert_return(usec != UINT64_MAX, -EINVAL);
3217 assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
3218 assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
3219 assert_return(!event_origin_changed(s->event), -ECHILD);
3220
3221 r = source_set_pending(s, false);
3222 if (r < 0)
3223 return r;
3224
3225 if (usec == 0)
3226 usec = DEFAULT_ACCURACY_USEC;
3227
3228 s->time.accuracy = usec;
3229
3230 event_source_time_prioq_reshuffle(s);
3231 return 0;
3232 }
3233
3234 _public_ int sd_event_source_get_time_clock(sd_event_source *s, clockid_t *ret) {
3235 assert_return(s, -EINVAL);
3236 assert_return(ret, -EINVAL);
3237 assert_return(EVENT_SOURCE_IS_TIME(s->type), -EDOM);
3238 assert_return(!event_origin_changed(s->event), -ECHILD);
3239
3240 *ret = event_source_type_to_clock(s->type);
3241 return 0;
3242 }
3243
3244 _public_ int sd_event_source_get_child_pid(sd_event_source *s, pid_t *ret) {
3245 assert_return(s, -EINVAL);
3246 assert_return(ret, -EINVAL);
3247 assert_return(s->type == SOURCE_CHILD, -EDOM);
3248 assert_return(!event_origin_changed(s->event), -ECHILD);
3249
3250 *ret = s->child.pid;
3251 return 0;
3252 }
3253
3254 _public_ int sd_event_source_get_child_pidfd(sd_event_source *s) {
3255 assert_return(s, -EINVAL);
3256 assert_return(s->type == SOURCE_CHILD, -EDOM);
3257 assert_return(!event_origin_changed(s->event), -ECHILD);
3258
3259 return s->child.pidfd;
3260 }
3261
3262 _public_ int sd_event_source_send_child_signal(sd_event_source *s, int sig, const siginfo_t *si, unsigned flags) {
3263 assert_return(s, -EINVAL);
3264 assert_return(s->type == SOURCE_CHILD, -EDOM);
3265 assert_return(!event_origin_changed(s->event), -ECHILD);
3266 assert_return(SIGNAL_VALID(sig), -EINVAL);
3267 assert(s->child.pidfd >= 0);
3268
3269 /* If we already have seen indication the process exited refuse sending a signal early. */
3270 if (s->child.exited)
3271 return -ESRCH;
3272 assert(!s->child.waited);
3273
3274 /* pidfd_send_signal() changes the siginfo_t argument. This is weird, let's hence copy the structure here. */
3275 siginfo_t copy;
3276 if (si)
3277 copy = *si;
3278
3279 return RET_NERRNO(pidfd_send_signal(s->child.pidfd, sig, si ? &copy : NULL, flags));
3280 }
3281
3282 _public_ int sd_event_source_get_child_pidfd_own(sd_event_source *s) {
3283 assert_return(s, -EINVAL);
3284 assert_return(s->type == SOURCE_CHILD, -EDOM);
3285 assert_return(!event_origin_changed(s->event), -ECHILD);
3286 assert(s->child.pidfd >= 0);
3287
3288 return s->child.pidfd_owned;
3289 }
3290
3291 _public_ int sd_event_source_set_child_pidfd_own(sd_event_source *s, int own) {
3292 assert_return(s, -EINVAL);
3293 assert_return(s->type == SOURCE_CHILD, -EDOM);
3294 assert_return(!event_origin_changed(s->event), -ECHILD);
3295 assert(s->child.pidfd >= 0);
3296
3297 s->child.pidfd_owned = own;
3298 return 0;
3299 }
3300
3301 _public_ int sd_event_source_get_child_process_own(sd_event_source *s) {
3302 assert_return(s, -EINVAL);
3303 assert_return(s->type == SOURCE_CHILD, -EDOM);
3304 assert_return(!event_origin_changed(s->event), -ECHILD);
3305
3306 return s->child.process_owned;
3307 }
3308
3309 _public_ int sd_event_source_set_child_process_own(sd_event_source *s, int own) {
3310 assert_return(s, -EINVAL);
3311 assert_return(s->type == SOURCE_CHILD, -EDOM);
3312 assert_return(!event_origin_changed(s->event), -ECHILD);
3313
3314 s->child.process_owned = own;
3315 return 0;
3316 }
3317
3318 _public_ int sd_event_source_get_inotify_mask(sd_event_source *s, uint32_t *ret) {
3319 assert_return(s, -EINVAL);
3320 assert_return(ret, -EINVAL);
3321 assert_return(s->type == SOURCE_INOTIFY, -EDOM);
3322 assert_return(!event_origin_changed(s->event), -ECHILD);
3323
3324 *ret = s->inotify.mask;
3325 return 0;
3326 }
3327
3328 _public_ int sd_event_source_get_inotify_path(sd_event_source *s, const char **ret) {
3329 assert_return(s, -EINVAL);
3330 assert_return(ret, -EINVAL);
3331 assert_return(s->type == SOURCE_INOTIFY, -EDOM);
3332 assert_return(!event_origin_changed(s->event), -ECHILD);
3333
3334 if (!s->inotify.inode_data)
3335 return -ESTALE; /* already disconnected. */
3336
3337 if (!s->inotify.inode_data->path)
3338 return -ENOSYS; /* /proc was not mounted? */
3339
3340 *ret = s->inotify.inode_data->path;
3341 return 0;
3342 }
3343
3344 _public_ int sd_event_source_set_prepare(sd_event_source *s, sd_event_handler_t callback) {
3345 int r;
3346
3347 assert_return(s, -EINVAL);
3348 assert_return(s->type != SOURCE_EXIT, -EDOM);
3349 assert_return(s->event->state != SD_EVENT_FINISHED, -ESTALE);
3350 assert_return(!event_origin_changed(s->event), -ECHILD);
3351
3352 if (s->prepare == callback)
3353 return 0;
3354
3355 if (callback && s->prepare) {
3356 s->prepare = callback;
3357 return 0;
3358 }
3359
3360 r = prioq_ensure_allocated(&s->event->prepare, prepare_prioq_compare);
3361 if (r < 0)
3362 return r;
3363
3364 s->prepare = callback;
3365
3366 if (callback) {
3367 r = prioq_put(s->event->prepare, s, &s->prepare_index);
3368 if (r < 0)
3369 return r;
3370 } else
3371 prioq_remove(s->event->prepare, s, &s->prepare_index);
3372
3373 return 0;
3374 }
3375
3376 _public_ void* sd_event_source_get_userdata(sd_event_source *s) {
3377 assert_return(s, NULL);
3378 assert_return(!event_origin_changed(s->event), NULL);
3379
3380 return s->userdata;
3381 }
3382
3383 _public_ void *sd_event_source_set_userdata(sd_event_source *s, void *userdata) {
3384 void *ret;
3385
3386 assert_return(s, NULL);
3387 assert_return(!event_origin_changed(s->event), NULL);
3388
3389 ret = s->userdata;
3390 s->userdata = userdata;
3391
3392 return ret;
3393 }
3394
3395 static int event_source_enter_ratelimited(sd_event_source *s) {
3396 int r;
3397
3398 assert(s);
3399
3400 /* When an event source becomes ratelimited, we place it in the CLOCK_MONOTONIC priority queue, with
3401 * the end of the rate limit time window, much as if it was a timer event source. */
3402
3403 if (s->ratelimited)
3404 return 0; /* Already ratelimited, this is a NOP hence */
3405
3406 /* Make sure we can install a CLOCK_MONOTONIC event further down. */
3407 r = setup_clock_data(s->event, &s->event->monotonic, CLOCK_MONOTONIC);
3408 if (r < 0)
3409 return r;
3410
3411 /* Timer event sources are already using the earliest/latest queues for the timer scheduling. Let's
3412 * first remove them from the prioq appropriate for their own clock, so that we can use the prioq
3413 * fields of the event source then for adding it to the CLOCK_MONOTONIC prioq instead. */
3414 if (EVENT_SOURCE_IS_TIME(s->type))
3415 event_source_time_prioq_remove(s, event_get_clock_data(s->event, s->type));
3416
3417 /* Now, let's add the event source to the monotonic clock instead */
3418 r = event_source_time_prioq_put(s, &s->event->monotonic);
3419 if (r < 0)
3420 goto fail;
3421
3422 /* And let's take the event source officially offline */
3423 r = event_source_offline(s, s->enabled, /* ratelimited= */ true);
3424 if (r < 0) {
3425 event_source_time_prioq_remove(s, &s->event->monotonic);
3426 goto fail;
3427 }
3428
3429 event_source_pp_prioq_reshuffle(s);
3430
3431 log_debug("Event source %p (%s) entered rate limit state.", s, strna(s->description));
3432 return 0;
3433
3434 fail:
3435 /* Reinstall time event sources in the priority queue as before. This shouldn't fail, since the queue
3436 * space for it should already be allocated. */
3437 if (EVENT_SOURCE_IS_TIME(s->type))
3438 assert_se(event_source_time_prioq_put(s, event_get_clock_data(s->event, s->type)) >= 0);
3439
3440 return r;
3441 }
3442
3443 static int event_source_leave_ratelimit(sd_event_source *s, bool run_callback) {
3444 int r;
3445
3446 assert(s);
3447
3448 if (!s->ratelimited)
3449 return 0;
3450
3451 /* Let's take the event source out of the monotonic prioq first. */
3452 event_source_time_prioq_remove(s, &s->event->monotonic);
3453
3454 /* Let's then add the event source to its native clock prioq again — if this is a timer event source */
3455 if (EVENT_SOURCE_IS_TIME(s->type)) {
3456 r = event_source_time_prioq_put(s, event_get_clock_data(s->event, s->type));
3457 if (r < 0)
3458 goto fail;
3459 }
3460
3461 /* Let's try to take it online again. */
3462 r = event_source_online(s, s->enabled, /* ratelimited= */ false);
3463 if (r < 0) {
3464 /* Do something roughly sensible when this failed: undo the two prioq ops above */
3465 if (EVENT_SOURCE_IS_TIME(s->type))
3466 event_source_time_prioq_remove(s, event_get_clock_data(s->event, s->type));
3467
3468 goto fail;
3469 }
3470
3471 event_source_pp_prioq_reshuffle(s);
3472 ratelimit_reset(&s->rate_limit);
3473
3474 log_debug("Event source %p (%s) left rate limit state.", s, strna(s->description));
3475
3476 if (run_callback && s->ratelimit_expire_callback) {
3477 s->dispatching = true;
3478 r = s->ratelimit_expire_callback(s, s->userdata);
3479 s->dispatching = false;
3480
3481 if (r < 0) {
3482 log_debug_errno(r, "Ratelimit expiry callback of event source %s (type %s) returned error, %s: %m",
3483 strna(s->description),
3484 event_source_type_to_string(s->type),
3485 s->exit_on_failure ? "exiting" : "disabling");
3486
3487 if (s->exit_on_failure)
3488 (void) sd_event_exit(s->event, r);
3489 }
3490
3491 if (s->n_ref == 0)
3492 source_free(s);
3493 else if (r < 0)
3494 assert_se(sd_event_source_set_enabled(s, SD_EVENT_OFF) >= 0);
3495
3496 return 1;
3497 }
3498
3499 return 0;
3500
3501 fail:
3502 /* Do something somewhat reasonable when we cannot move an event sources out of ratelimited mode:
3503 * simply put it back in it, maybe we can then process it more successfully next iteration. */
3504 assert_se(event_source_time_prioq_put(s, &s->event->monotonic) >= 0);
3505
3506 return r;
3507 }
3508
3509 static usec_t sleep_between(sd_event *e, usec_t a, usec_t b) {
3510 usec_t c;
3511 assert(e);
3512 assert(a <= b);
3513
3514 if (a <= 0)
3515 return 0;
3516 if (a >= USEC_INFINITY)
3517 return USEC_INFINITY;
3518
3519 if (b <= a + 1)
3520 return a;
3521
3522 initialize_perturb(e);
3523
3524 /*
3525 Find a good time to wake up again between times a and b. We
3526 have two goals here:
3527
3528 a) We want to wake up as seldom as possible, hence prefer
3529 later times over earlier times.
3530
3531 b) But if we have to wake up, then let's make sure to
3532 dispatch as much as possible on the entire system.
3533
3534 We implement this by waking up everywhere at the same time
3535 within any given minute if we can, synchronised via the
3536 perturbation value determined from the boot ID. If we can't,
3537 then we try to find the same spot in every 10s, then 1s and
3538 then 250ms step. Otherwise, we pick the last possible time
3539 to wake up.
3540 */
3541
3542 c = (b / USEC_PER_MINUTE) * USEC_PER_MINUTE + e->perturb;
3543 if (c >= b) {
3544 if (_unlikely_(c < USEC_PER_MINUTE))
3545 return b;
3546
3547 c -= USEC_PER_MINUTE;
3548 }
3549
3550 if (c >= a)
3551 return c;
3552
3553 c = (b / (USEC_PER_SEC*10)) * (USEC_PER_SEC*10) + (e->perturb % (USEC_PER_SEC*10));
3554 if (c >= b) {
3555 if (_unlikely_(c < USEC_PER_SEC*10))
3556 return b;
3557
3558 c -= USEC_PER_SEC*10;
3559 }
3560
3561 if (c >= a)
3562 return c;
3563
3564 c = (b / USEC_PER_SEC) * USEC_PER_SEC + (e->perturb % USEC_PER_SEC);
3565 if (c >= b) {
3566 if (_unlikely_(c < USEC_PER_SEC))
3567 return b;
3568
3569 c -= USEC_PER_SEC;
3570 }
3571
3572 if (c >= a)
3573 return c;
3574
3575 c = (b / (USEC_PER_MSEC*250)) * (USEC_PER_MSEC*250) + (e->perturb % (USEC_PER_MSEC*250));
3576 if (c >= b) {
3577 if (_unlikely_(c < USEC_PER_MSEC*250))
3578 return b;
3579
3580 c -= USEC_PER_MSEC*250;
3581 }
3582
3583 if (c >= a)
3584 return c;
3585
3586 return b;
3587 }
3588
3589 static int event_arm_timer(
3590 sd_event *e,
3591 struct clock_data *d) {
3592
3593 struct itimerspec its = {};
3594 sd_event_source *a, *b;
3595 usec_t t;
3596
3597 assert(e);
3598 assert(d);
3599
3600 if (!d->needs_rearm)
3601 return 0;
3602
3603 d->needs_rearm = false;
3604
3605 a = prioq_peek(d->earliest);
3606 assert(!a || EVENT_SOURCE_USES_TIME_PRIOQ(a->type));
3607 if (!a || a->enabled == SD_EVENT_OFF || time_event_source_next(a) == USEC_INFINITY) {
3608
3609 if (d->fd < 0)
3610 return 0;
3611
3612 if (d->next == USEC_INFINITY)
3613 return 0;
3614
3615 /* disarm */
3616 if (timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL) < 0)
3617 return -errno;
3618
3619 d->next = USEC_INFINITY;
3620 return 0;
3621 }
3622
3623 b = prioq_peek(d->latest);
3624 assert(!b || EVENT_SOURCE_USES_TIME_PRIOQ(b->type));
3625 assert(b && b->enabled != SD_EVENT_OFF);
3626
3627 t = sleep_between(e, time_event_source_next(a), time_event_source_latest(b));
3628 if (d->next == t)
3629 return 0;
3630
3631 assert_se(d->fd >= 0);
3632
3633 if (t == 0) {
3634 /* We don't want to disarm here, just mean some time looooong ago. */
3635 its.it_value.tv_sec = 0;
3636 its.it_value.tv_nsec = 1;
3637 } else
3638 timespec_store(&its.it_value, t);
3639
3640 if (timerfd_settime(d->fd, TFD_TIMER_ABSTIME, &its, NULL) < 0)
3641 return -errno;
3642
3643 d->next = t;
3644 return 0;
3645 }
3646
3647 static int process_io(sd_event *e, sd_event_source *s, uint32_t revents) {
3648 assert(e);
3649 assert(s);
3650 assert(s->type == SOURCE_IO);
3651
3652 /* If the event source was already pending, we just OR in the
3653 * new revents, otherwise we reset the value. The ORing is
3654 * necessary to handle EPOLLONESHOT events properly where
3655 * readability might happen independently of writability, and
3656 * we need to keep track of both */
3657
3658 if (s->pending)
3659 s->io.revents |= revents;
3660 else
3661 s->io.revents = revents;
3662
3663 return source_set_pending(s, true);
3664 }
3665
3666 static int flush_timer(sd_event *e, int fd, uint32_t events, usec_t *next) {
3667 uint64_t x;
3668 ssize_t ss;
3669
3670 assert(e);
3671 assert(fd >= 0);
3672
3673 assert_return(events == EPOLLIN, -EIO);
3674
3675 ss = read(fd, &x, sizeof(x));
3676 if (ss < 0) {
3677 if (ERRNO_IS_TRANSIENT(errno))
3678 return 0;
3679
3680 return -errno;
3681 }
3682
3683 if (_unlikely_(ss != sizeof(x)))
3684 return -EIO;
3685
3686 if (next)
3687 *next = USEC_INFINITY;
3688
3689 return 0;
3690 }
3691
3692 static int process_timer(
3693 sd_event *e,
3694 usec_t n,
3695 struct clock_data *d) {
3696
3697 sd_event_source *s;
3698 bool callback_invoked = false;
3699 int r;
3700
3701 assert(e);
3702 assert(d);
3703
3704 for (;;) {
3705 s = prioq_peek(d->earliest);
3706 assert(!s || EVENT_SOURCE_USES_TIME_PRIOQ(s->type));
3707
3708 if (!s || time_event_source_next(s) > n)
3709 break;
3710
3711 if (s->ratelimited) {
3712 /* This is an event sources whose ratelimit window has ended. Let's turn it on
3713 * again. */
3714 assert(s->ratelimited);
3715
3716 r = event_source_leave_ratelimit(s, /* run_callback= */ true);
3717 if (r < 0)
3718 return r;
3719 else if (r == 1)
3720 callback_invoked = true;
3721
3722 continue;
3723 }
3724
3725 if (s->enabled == SD_EVENT_OFF || s->pending)
3726 break;
3727
3728 r = source_set_pending(s, true);
3729 if (r < 0)
3730 return r;
3731
3732 event_source_time_prioq_reshuffle(s);
3733 }
3734
3735 return callback_invoked;
3736 }
3737
3738 static int process_child(sd_event *e, int64_t threshold, int64_t *ret_min_priority) {
3739 int64_t min_priority = threshold;
3740 bool something_new = false;
3741 sd_event_source *s;
3742 int r;
3743
3744 assert(e);
3745 assert(ret_min_priority);
3746
3747 if (!e->need_process_child) {
3748 *ret_min_priority = min_priority;
3749 return 0;
3750 }
3751
3752 e->need_process_child = false;
3753
3754 /* So, this is ugly. We iteratively invoke waitid() + WNOHANG with each child process we shall wait for,
3755 * instead of using P_ALL. This is because we only want to get child information of very specific
3756 * child processes, and not all of them. We might not have processed the SIGCHLD event
3757 * of a previous invocation and we don't want to maintain a unbounded *per-child* event queue,
3758 * hence we really don't want anything flushed out of the kernel's queue that we don't care
3759 * about. Since this is O(n) this means that if you have a lot of processes you probably want
3760 * to handle SIGCHLD yourself.
3761 *
3762 * We do not reap the children here (by using WNOWAIT), this is only done after the event
3763 * source is dispatched so that the callback still sees the process as a zombie. */
3764
3765 HASHMAP_FOREACH(s, e->child_sources) {
3766 assert(s->type == SOURCE_CHILD);
3767 assert(s->child.pidfd >= 0);
3768
3769 if (s->priority > threshold)
3770 continue;
3771
3772 if (s->pending)
3773 continue;
3774
3775 if (event_source_is_offline(s))
3776 continue;
3777
3778 if (s->child.exited)
3779 continue;
3780
3781 if (EVENT_SOURCE_WATCH_PIDFD(s))
3782 /* There's a usable pidfd known for this event source? Then don't waitid() for
3783 * it here */
3784 continue;
3785
3786 zero(s->child.siginfo);
3787 if (waitid(P_PIDFD, s->child.pidfd, &s->child.siginfo,
3788 WNOHANG | (s->child.options & WEXITED ? WNOWAIT : 0) | (s->child.options & ~WNOWAIT)) < 0)
3789 return negative_errno();
3790
3791 if (s->child.siginfo.si_pid != 0) {
3792 bool zombie = SIGINFO_CODE_IS_DEAD(s->child.siginfo.si_code);
3793
3794 if (zombie)
3795 s->child.exited = true;
3796 else if (s->child.options & WEXITED) {
3797 /* If the child isn't dead then let's immediately remove the state change
3798 * from the queue, since there's no benefit in leaving it queued. */
3799
3800 assert(s->child.options & (WSTOPPED|WCONTINUED));
3801 (void) waitid(P_PIDFD, s->child.pidfd, &s->child.siginfo, WNOHANG|(s->child.options & (WSTOPPED|WCONTINUED)));
3802 }
3803
3804 r = source_set_pending(s, true);
3805 if (r < 0)
3806 return r;
3807 if (r > 0) {
3808 something_new = true;
3809 min_priority = MIN(min_priority, s->priority);
3810 }
3811 }
3812 }
3813
3814 *ret_min_priority = min_priority;
3815 return something_new;
3816 }
3817
3818 static int process_pidfd(sd_event *e, sd_event_source *s, uint32_t revents) {
3819 assert(e);
3820 assert(s);
3821 assert(s->type == SOURCE_CHILD);
3822 assert(s->child.pidfd >= 0);
3823
3824 if (s->pending)
3825 return 0;
3826
3827 if (event_source_is_offline(s))
3828 return 0;
3829
3830 if (!EVENT_SOURCE_WATCH_PIDFD(s))
3831 return 0;
3832
3833 /* Note that pidfd would also generate EPOLLHUP when the process gets reaped. But at this point we
3834 * only permit EPOLLIN, under the assumption that upon EPOLLHUP the child source should already
3835 * be set to pending, and we would have returned early above. */
3836
3837 zero(s->child.siginfo);
3838 if (waitid(P_PIDFD, s->child.pidfd, &s->child.siginfo, WNOHANG | WNOWAIT | s->child.options) < 0)
3839 return -errno;
3840
3841 if (s->child.siginfo.si_pid == 0)
3842 return 0;
3843
3844 if (SIGINFO_CODE_IS_DEAD(s->child.siginfo.si_code))
3845 s->child.exited = true;
3846
3847 return source_set_pending(s, true);
3848 }
3849
3850 static int process_signal(sd_event *e, struct signal_data *d, uint32_t events, int64_t *min_priority) {
3851 int r;
3852
3853 assert(e);
3854 assert(d);
3855 assert_return(events == EPOLLIN, -EIO);
3856 assert(min_priority);
3857
3858 /* If there's a signal queued on this priority and SIGCHLD is on this priority too, then make
3859 * sure to recheck the children we watch. This is because we only ever dequeue the first signal
3860 * per priority, and if we dequeue one, and SIGCHLD might be enqueued later we wouldn't know,
3861 * but we might have higher priority children we care about hence we need to check that
3862 * explicitly. */
3863
3864 if (sigismember(&d->sigset, SIGCHLD))
3865 e->need_process_child = true;
3866
3867 /* If there's already an event source pending for this priority we don't read another */
3868 if (d->current)
3869 return 0;
3870
3871 for (;;) {
3872 struct signalfd_siginfo si;
3873 ssize_t n;
3874 sd_event_source *s = NULL;
3875
3876 n = read(d->fd, &si, sizeof(si));
3877 if (n < 0) {
3878 if (ERRNO_IS_TRANSIENT(errno))
3879 return 0;
3880
3881 return -errno;
3882 }
3883
3884 if (_unlikely_(n != sizeof(si)))
3885 return -EIO;
3886
3887 if (_unlikely_(si.ssi_signo > INT_MAX)) /* Ensure value fits in int before casting */
3888 return -EIO;
3889
3890 if (_unlikely_(!SIGNAL_VALID(si.ssi_signo)))
3891 return -EIO;
3892
3893 if (e->signal_sources)
3894 s = e->signal_sources[si.ssi_signo];
3895 if (!s)
3896 continue;
3897 if (s->pending)
3898 continue;
3899
3900 s->signal.siginfo = si;
3901 d->current = s;
3902
3903 r = source_set_pending(s, true);
3904 if (r < 0)
3905 return r;
3906 if (r > 0 && *min_priority >= s->priority) {
3907 *min_priority = s->priority;
3908 return 1; /* an event source with smaller priority is queued. */
3909 }
3910
3911 return 0;
3912 }
3913 }
3914
3915 static int event_inotify_data_read(sd_event *e, InotifyData *d, uint32_t revents, int64_t threshold) {
3916 ssize_t n;
3917
3918 assert(e);
3919 assert(d);
3920
3921 assert_return(revents == EPOLLIN, -EIO);
3922
3923 /* If there's already an event source pending for this priority, don't read another */
3924 if (d->n_pending > 0)
3925 return 0;
3926
3927 /* Is the read buffer non-empty? If so, let's not read more */
3928 if (d->buffer_filled > 0)
3929 return 0;
3930
3931 if (d->priority > threshold)
3932 return 0;
3933
3934 n = read(d->fd, &d->buffer, sizeof(d->buffer));
3935 if (n < 0) {
3936 if (ERRNO_IS_TRANSIENT(errno))
3937 return 0;
3938
3939 return -errno;
3940 }
3941
3942 assert(n > 0);
3943 d->buffer_filled = (size_t) n;
3944 LIST_PREPEND(buffered, e->buffered_inotify_data_list, d);
3945
3946 return 1;
3947 }
3948
3949 static void event_inotify_data_drop(sd_event *e, InotifyData *d, size_t sz) {
3950 assert(e);
3951 assert(d);
3952 assert(sz <= d->buffer_filled);
3953
3954 if (sz == 0)
3955 return;
3956
3957 /* Move the rest to the buffer to the front, in order to get things properly aligned again */
3958 memmove(d->buffer.raw, d->buffer.raw + sz, d->buffer_filled - sz);
3959 d->buffer_filled -= sz;
3960
3961 if (d->buffer_filled == 0)
3962 LIST_REMOVE(buffered, e->buffered_inotify_data_list, d);
3963 }
3964
3965 static int event_inotify_data_process(sd_event *e, InotifyData *d) {
3966 int r;
3967
3968 assert(e);
3969 assert(d);
3970
3971 /* If there's already an event source pending for this priority, don't read another */
3972 if (d->n_pending > 0)
3973 return 0;
3974
3975 while (d->buffer_filled > 0) {
3976 size_t sz;
3977
3978 /* Let's validate that the event structures are complete */
3979 if (d->buffer_filled < offsetof(struct inotify_event, name))
3980 return -EIO;
3981
3982 sz = offsetof(struct inotify_event, name) + d->buffer.ev.len;
3983 if (d->buffer_filled < sz)
3984 return -EIO;
3985
3986 if (d->buffer.ev.mask & IN_Q_OVERFLOW) {
3987 InodeData *inode_data;
3988
3989 /* The queue overran, let's pass this event to all event sources connected to this inotify
3990 * object */
3991
3992 HASHMAP_FOREACH(inode_data, d->inodes)
3993 LIST_FOREACH(inotify.by_inode_data, s, inode_data->event_sources) {
3994
3995 if (event_source_is_offline(s))
3996 continue;
3997
3998 r = source_set_pending(s, true);
3999 if (r < 0)
4000 return r;
4001 }
4002 } else {
4003 InodeData *inode_data;
4004
4005 /* Find the inode object for this watch descriptor. If IN_IGNORED is set we also remove it from
4006 * our watch descriptor table. */
4007 if (d->buffer.ev.mask & IN_IGNORED) {
4008
4009 inode_data = hashmap_remove(d->wd, INT_TO_PTR(d->buffer.ev.wd));
4010 if (!inode_data) {
4011 event_inotify_data_drop(e, d, sz);
4012 continue;
4013 }
4014
4015 /* The watch descriptor was removed by the kernel, let's drop it here too */
4016 inode_data->wd = -1;
4017 } else {
4018 inode_data = hashmap_get(d->wd, INT_TO_PTR(d->buffer.ev.wd));
4019 if (!inode_data) {
4020 event_inotify_data_drop(e, d, sz);
4021 continue;
4022 }
4023 }
4024
4025 /* Trigger all event sources that are interested in these events. Also trigger all event
4026 * sources if IN_IGNORED or IN_UNMOUNT is set. */
4027 LIST_FOREACH(inotify.by_inode_data, s, inode_data->event_sources) {
4028
4029 if (event_source_is_offline(s))
4030 continue;
4031
4032 if ((d->buffer.ev.mask & (IN_IGNORED|IN_UNMOUNT)) == 0 &&
4033 (s->inotify.mask & d->buffer.ev.mask & IN_ALL_EVENTS) == 0)
4034 continue;
4035
4036 r = source_set_pending(s, true);
4037 if (r < 0)
4038 return r;
4039 }
4040 }
4041
4042 /* Something pending now? If so, let's finish. */
4043 if (d->n_pending > 0)
4044 return 1;
4045
4046 /* otherwise, drop the event and let's read more */
4047 event_inotify_data_drop(e, d, sz);
4048 }
4049
4050 return 0;
4051 }
4052
4053 static int process_inotify(sd_event *e) {
4054 int r, done = 0;
4055
4056 assert(e);
4057
4058 LIST_FOREACH(buffered, d, e->buffered_inotify_data_list) {
4059 r = event_inotify_data_process(e, d);
4060 if (r < 0)
4061 return r;
4062 if (r > 0)
4063 done++;
4064 }
4065
4066 return done;
4067 }
4068
4069 static int process_pressure(sd_event_source *s, uint32_t revents) {
4070 assert(s);
4071 assert(EVENT_SOURCE_IS_PRESSURE(s));
4072
4073 if (s->pending)
4074 s->pressure.revents |= revents;
4075 else
4076 s->pressure.revents = revents;
4077
4078 return source_set_pending(s, true);
4079 }
4080
4081 static int source_pressure_write(sd_event_source *s) {
4082 ssize_t n;
4083 int r;
4084
4085 assert(s);
4086 assert(EVENT_SOURCE_IS_PRESSURE(s));
4087
4088 /* once we start writing, the buffer is locked, we allow no further changes. */
4089 s->pressure.locked = true;
4090
4091 if (s->pressure.write_buffer_size > 0) {
4092 n = write(s->pressure.fd, s->pressure.write_buffer, s->pressure.write_buffer_size);
4093 if (n < 0) {
4094 if (!ERRNO_IS_TRANSIENT(errno)) {
4095 /* If kernel is built with CONFIG_PSI_DEFAULT_DISABLED it will expose PSI
4096 * files, but then generates EOPNOSUPP on read() and write() (instead of on
4097 * open()!). This sucks hard, since we can only detect this kind of failure
4098 * so late. Let's make the best of it, and turn off the event source like we
4099 * do for failed event source handlers. */
4100
4101 log_debug_errno(errno, "Writing pressure settings to kernel failed, disabling pressure event source: %m");
4102 assert_se(sd_event_source_set_enabled(s, SD_EVENT_OFF) >= 0);
4103 return 0;
4104 }
4105
4106 n = 0;
4107 }
4108 } else
4109 n = 0;
4110
4111 assert(n >= 0);
4112
4113 if ((size_t) n == s->pressure.write_buffer_size) {
4114 s->pressure.write_buffer = mfree(s->pressure.write_buffer);
4115
4116 if (n > 0) {
4117 s->pressure.write_buffer_size = 0;
4118
4119 /* Update epoll events mask, since we have now written everything and don't care for EPOLLOUT anymore */
4120 r = source_pressure_register(s, s->enabled);
4121 if (r < 0)
4122 return r;
4123 }
4124 } else if (n > 0) {
4125 _cleanup_free_ void *c = NULL;
4126
4127 assert((size_t) n < s->pressure.write_buffer_size);
4128
4129 c = memdup((uint8_t*) s->pressure.write_buffer + n, s->pressure.write_buffer_size - n);
4130 if (!c)
4131 return -ENOMEM;
4132
4133 free_and_replace(s->pressure.write_buffer, c);
4134 s->pressure.write_buffer_size -= n;
4135 return 1;
4136 }
4137
4138 return 0;
4139 }
4140
4141 static int source_pressure_initiate_dispatch(sd_event_source *s) {
4142 int r;
4143
4144 assert(s);
4145 assert(EVENT_SOURCE_IS_PRESSURE(s));
4146
4147 r = source_pressure_write(s);
4148 if (r < 0)
4149 return r;
4150 if (r > 0)
4151 return 1; /* if we wrote something, then don't continue with dispatching user dispatch
4152 * function. Instead, shortcut it so that we wait for next EPOLLOUT immediately. */
4153
4154 /* No pending incoming IO? Then let's not continue further */
4155 if ((s->pressure.revents & (EPOLLIN|EPOLLPRI)) == 0) {
4156
4157 /* Treat IO errors on the notifier the same ways errors returned from a callback */
4158 if ((s->pressure.revents & (EPOLLHUP|EPOLLERR|EPOLLRDHUP)) != 0)
4159 return -EIO;
4160
4161 return 1; /* leave dispatch, we already processed everything */
4162 }
4163
4164 if (s->pressure.revents & EPOLLIN) {
4165 uint8_t pipe_buf[PIPE_BUF];
4166 ssize_t n;
4167
4168 /* If the fd is readable, then flush out anything that might be queued */
4169
4170 n = read(s->pressure.fd, pipe_buf, sizeof(pipe_buf));
4171 if (n < 0 && !ERRNO_IS_TRANSIENT(errno))
4172 return -errno;
4173 }
4174
4175 return 0; /* go on, dispatch to user callback */
4176 }
4177
4178 static int maybe_mark_post_sources_pending(EventSourceType t, sd_event *e) {
4179 sd_event_source *z;
4180 int r;
4181
4182 if (t == SOURCE_POST)
4183 return 0;
4184
4185 SET_FOREACH(z, e->post_sources) {
4186 if (event_source_is_offline(z))
4187 continue;
4188
4189 r = source_set_pending(z, true);
4190 if (r < 0)
4191 return r;
4192 }
4193
4194 return 0;
4195 }
4196
4197 static int source_dispatch(sd_event_source *s) {
4198 EventSourceType saved_type;
4199 sd_event *saved_event;
4200 int r = 0;
4201
4202 assert(s);
4203 assert(s->pending || s->type == SOURCE_EXIT);
4204
4205 /* Save the event source type, here, so that we still know it after the event callback which might
4206 * invalidate the event. */
4207 saved_type = s->type;
4208
4209 /* Similarly, store a reference to the event loop object, so that we can still access it after the
4210 * callback might have invalidated/disconnected the event source. */
4211 saved_event = s->event;
4212 PROTECT_EVENT(saved_event);
4213
4214 /* Check if we hit the ratelimit for this event source, and if so, let's disable it. */
4215 assert(!s->ratelimited);
4216 if (!ratelimit_below(&s->rate_limit)) {
4217 r = event_source_enter_ratelimited(s);
4218 if (r < 0)
4219 return r;
4220
4221 return 1;
4222 }
4223
4224 if (IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
4225 /* Make sure this event source is moved to the end of the priority list now. We do this here
4226 * because defer and exit event sources are always pending from the moment they're added so
4227 * the same logic in source_set_pending() is never triggered. */
4228 s->pending_iteration = s->event->iteration;
4229 event_source_pp_prioq_reshuffle(s);
4230 } else {
4231 r = source_set_pending(s, false);
4232 if (r < 0)
4233 return r;
4234 }
4235
4236 /* If we execute a non-post source, let's mark all post sources as pending. */
4237 r = maybe_mark_post_sources_pending(s->type, s->event);
4238 if (r < 0)
4239 return r;
4240
4241 if (EVENT_SOURCE_IS_PRESSURE(s)) {
4242 r = source_pressure_initiate_dispatch(s);
4243 if (r == -EIO) /* handle EIO errors similar to callback errors */
4244 goto finish;
4245 if (r < 0)
4246 return r;
4247 if (r > 0) /* already handled */
4248 return 1;
4249 }
4250
4251 if (s->enabled == SD_EVENT_ONESHOT) {
4252 r = sd_event_source_set_enabled(s, SD_EVENT_OFF);
4253 if (r < 0)
4254 return r;
4255 }
4256
4257 s->dispatching = true;
4258
4259 switch (s->type) {
4260
4261 case SOURCE_IO:
4262 r = s->io.callback(s, s->io.fd, s->io.revents, s->userdata);
4263 break;
4264
4265 case SOURCE_TIME_REALTIME:
4266 case SOURCE_TIME_BOOTTIME:
4267 case SOURCE_TIME_MONOTONIC:
4268 case SOURCE_TIME_REALTIME_ALARM:
4269 case SOURCE_TIME_BOOTTIME_ALARM:
4270 r = s->time.callback(s, s->time.next, s->userdata);
4271 break;
4272
4273 case SOURCE_SIGNAL:
4274 r = s->signal.callback(s, &s->signal.siginfo, s->userdata);
4275 break;
4276
4277 case SOURCE_CHILD: {
4278 bool zombie = SIGINFO_CODE_IS_DEAD(s->child.siginfo.si_code);
4279
4280 r = s->child.callback(s, &s->child.siginfo, s->userdata);
4281
4282 /* Now, reap the PID for good (unless WNOWAIT was specified by the caller). */
4283 if (zombie) {
4284 (void) waitid(P_PIDFD, s->child.pidfd, &s->child.siginfo, WNOHANG|WEXITED|(s->child.options & WNOWAIT));
4285 if (!FLAGS_SET(s->child.options, WNOWAIT))
4286 s->child.waited = true;
4287 }
4288
4289 break;
4290 }
4291
4292 case SOURCE_DEFER:
4293 r = s->defer.callback(s, s->userdata);
4294 break;
4295
4296 case SOURCE_POST:
4297 r = s->post.callback(s, s->userdata);
4298 break;
4299
4300 case SOURCE_EXIT:
4301 r = s->exit.callback(s, s->userdata);
4302 break;
4303
4304 case SOURCE_INOTIFY: {
4305 struct sd_event *e = s->event;
4306 InotifyData *d;
4307 size_t sz;
4308
4309 assert(s->inotify.inode_data);
4310 assert_se(d = s->inotify.inode_data->inotify_data);
4311
4312 assert(d->buffer_filled >= offsetof(struct inotify_event, name));
4313 sz = offsetof(struct inotify_event, name) + d->buffer.ev.len;
4314 assert(d->buffer_filled >= sz);
4315
4316 /* If the inotify callback destroys the event source then this likely means we don't need to
4317 * watch the inode anymore, and thus also won't need the inotify object anymore. But if we'd
4318 * free it immediately, then we couldn't drop the event from the inotify event queue without
4319 * memory corruption anymore, as below. Hence, let's not free it immediately, but mark it
4320 * "busy" with a counter (which will ensure it's not GC'ed away prematurely). Let's then
4321 * explicitly GC it after we are done dropping the inotify event from the buffer. */
4322 d->n_busy++;
4323 r = s->inotify.callback(s, &d->buffer.ev, s->userdata);
4324 d->n_busy--;
4325
4326 /* When no event is pending anymore on this inotify object, then let's drop the event from
4327 * the inotify event queue buffer. */
4328 if (d->n_pending == 0)
4329 event_inotify_data_drop(e, d, sz);
4330
4331 /* Now we don't want to access 'd' anymore, it's OK to GC now. */
4332 event_gc_inotify_data(e, d);
4333 break;
4334 }
4335
4336 case SOURCE_MEMORY_PRESSURE:
4337 case SOURCE_CPU_PRESSURE:
4338 case SOURCE_IO_PRESSURE:
4339 r = s->pressure.callback(s, s->userdata);
4340 break;
4341
4342 case SOURCE_WATCHDOG:
4343 case _SOURCE_EVENT_SOURCE_TYPE_MAX:
4344 case _SOURCE_EVENT_SOURCE_TYPE_INVALID:
4345 assert_not_reached();
4346 }
4347
4348 s->dispatching = false;
4349
4350 finish:
4351 if (r < 0) {
4352 log_debug_errno(r, "Event source %s (type %s) returned error, %s: %m",
4353 strna(s->description),
4354 event_source_type_to_string(saved_type),
4355 s->exit_on_failure ? "exiting" : "disabling");
4356
4357 if (s->exit_on_failure)
4358 (void) sd_event_exit(saved_event, r);
4359 }
4360
4361 if (s->n_ref == 0)
4362 source_free(s);
4363 else if (r < 0)
4364 assert_se(sd_event_source_set_enabled(s, SD_EVENT_OFF) >= 0);
4365
4366 /* More post sources might have been added while executing the callback, let's make sure
4367 * those are marked pending as well. */
4368 r = maybe_mark_post_sources_pending(saved_type, saved_event);
4369 if (r < 0)
4370 return r;
4371
4372 return 1;
4373 }
4374
4375 static int event_prepare(sd_event *e) {
4376 int r;
4377
4378 assert(e);
4379
4380 for (;;) {
4381 sd_event_source *s;
4382
4383 s = prioq_peek(e->prepare);
4384 if (!s || s->prepare_iteration == e->iteration || event_source_is_offline(s))
4385 break;
4386
4387 s->prepare_iteration = e->iteration;
4388 prioq_reshuffle(e->prepare, s, &s->prepare_index);
4389
4390 assert(s->prepare);
4391 s->dispatching = true;
4392 r = s->prepare(s, s->userdata);
4393 s->dispatching = false;
4394
4395 if (r < 0) {
4396 log_debug_errno(r, "Prepare callback of event source %s (type %s) returned error, %s: %m",
4397 strna(s->description),
4398 event_source_type_to_string(s->type),
4399 s->exit_on_failure ? "exiting" : "disabling");
4400
4401 if (s->exit_on_failure)
4402 (void) sd_event_exit(e, r);
4403 }
4404
4405 if (s->n_ref == 0)
4406 source_free(s);
4407 else if (r < 0)
4408 assert_se(sd_event_source_set_enabled(s, SD_EVENT_OFF) >= 0);
4409 }
4410
4411 return 0;
4412 }
4413
4414 static int dispatch_exit(sd_event *e) {
4415 sd_event_source *p;
4416 int r;
4417
4418 assert(e);
4419
4420 p = prioq_peek(e->exit);
4421 assert(!p || p->type == SOURCE_EXIT);
4422
4423 if (!p || event_source_is_offline(p)) {
4424 e->state = SD_EVENT_FINISHED;
4425 return 0;
4426 }
4427
4428 PROTECT_EVENT(e);
4429 e->iteration++;
4430 e->state = SD_EVENT_EXITING;
4431 r = source_dispatch(p);
4432 e->state = SD_EVENT_INITIAL;
4433 return r;
4434 }
4435
4436 static sd_event_source* event_next_pending(sd_event *e) {
4437 sd_event_source *p;
4438
4439 assert(e);
4440
4441 p = prioq_peek(e->pending);
4442 if (!p)
4443 return NULL;
4444
4445 if (event_source_is_offline(p))
4446 return NULL;
4447
4448 return p;
4449 }
4450
4451 static int arm_watchdog(sd_event *e) {
4452 struct itimerspec its = {};
4453 usec_t t;
4454
4455 assert(e);
4456 assert(e->watchdog_fd >= 0);
4457
4458 t = sleep_between(e,
4459 usec_add(e->watchdog_last, (e->watchdog_period / 2)),
4460 usec_add(e->watchdog_last, (e->watchdog_period * 3 / 4)));
4461
4462 timespec_store(&its.it_value, t);
4463
4464 /* Make sure we never set the watchdog to 0, which tells the
4465 * kernel to disable it. */
4466 if (its.it_value.tv_sec == 0 && its.it_value.tv_nsec == 0)
4467 its.it_value.tv_nsec = 1;
4468
4469 return RET_NERRNO(timerfd_settime(e->watchdog_fd, TFD_TIMER_ABSTIME, &its, NULL));
4470 }
4471
4472 static int process_watchdog(sd_event *e) {
4473 assert(e);
4474
4475 if (!e->watchdog)
4476 return 0;
4477
4478 /* Don't notify watchdog too often */
4479 if (e->watchdog_last + e->watchdog_period / 4 > e->timestamp.monotonic)
4480 return 0;
4481
4482 sd_notify(false, "WATCHDOG=1");
4483 e->watchdog_last = e->timestamp.monotonic;
4484
4485 return arm_watchdog(e);
4486 }
4487
4488 static void event_close_inode_data_fds(sd_event *e) {
4489 InodeData *d;
4490
4491 assert(e);
4492
4493 /* Close the fds pointing to the inodes to watch now. We need to close them as they might otherwise pin
4494 * filesystems. But we can't close them right-away as we need them as long as the user still wants to make
4495 * adjustments to the event source, such as changing the priority (which requires us to remove and re-add a watch
4496 * for the inode). Hence, let's close them when entering the first iteration after they were added, as a
4497 * compromise. */
4498
4499 while ((d = e->inode_data_to_close_list)) {
4500 assert(d->fd >= 0);
4501 d->fd = safe_close(d->fd);
4502
4503 LIST_REMOVE(to_close, e->inode_data_to_close_list, d);
4504 }
4505 }
4506
4507 static int event_pressure_write_list(sd_event *e) {
4508 int r;
4509
4510 assert(e);
4511
4512 for (;;) {
4513 sd_event_source *s;
4514
4515 s = LIST_POP(pressure.write_list, e->pressure_write_list);
4516 if (!s)
4517 break;
4518
4519 assert(EVENT_SOURCE_IS_PRESSURE(s));
4520 assert(s->pressure.write_buffer_size > 0);
4521 s->pressure.in_write_list = false;
4522
4523 r = source_pressure_write(s);
4524 if (r < 0)
4525 return r;
4526 }
4527
4528 return 0;
4529 }
4530
4531 static bool event_loop_idle(sd_event *e) {
4532 assert(e);
4533
4534 LIST_FOREACH(sources, s, e->sources) {
4535 /* Exit sources only trigger on exit, so whether they're enabled or not doesn't matter when
4536 * we're deciding if the event loop is idle or not. */
4537 if (s->type == SOURCE_EXIT)
4538 continue;
4539
4540 if (s->enabled == SD_EVENT_OFF)
4541 continue;
4542
4543 /* Post event sources always need another active event source to become pending. */
4544 if (s->type == SOURCE_POST && !s->pending)
4545 continue;
4546
4547 return false;
4548 }
4549
4550 return true;
4551 }
4552
4553 _public_ int sd_event_prepare(sd_event *e) {
4554 int r;
4555
4556 assert_return(e, -EINVAL);
4557 assert_return(e = event_resolve(e), -ENOPKG);
4558 assert_return(!event_origin_changed(e), -ECHILD);
4559 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
4560 assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
4561
4562 /* Let's check that if we are a default event loop we are executed in the correct thread. We only do
4563 * this check here once, since gettid() is typically not cached, and thus want to minimize
4564 * syscalls */
4565 assert_return(!e->default_event_ptr || e->tid == gettid(), -EREMOTEIO);
4566
4567 /* Make sure that none of the preparation callbacks ends up freeing the event source under our feet */
4568 PROTECT_EVENT(e);
4569
4570 if (!e->exit_requested && e->exit_on_idle && event_loop_idle(e))
4571 (void) sd_event_exit(e, 0);
4572
4573 if (e->exit_requested)
4574 goto pending;
4575
4576 e->iteration++;
4577
4578 e->state = SD_EVENT_PREPARING;
4579 r = event_prepare(e);
4580 e->state = SD_EVENT_INITIAL;
4581 if (r < 0)
4582 return r;
4583
4584 r = event_pressure_write_list(e);
4585 if (r < 0)
4586 return r;
4587
4588 r = event_arm_timer(e, &e->realtime);
4589 if (r < 0)
4590 return r;
4591
4592 r = event_arm_timer(e, &e->boottime);
4593 if (r < 0)
4594 return r;
4595
4596 r = event_arm_timer(e, &e->monotonic);
4597 if (r < 0)
4598 return r;
4599
4600 r = event_arm_timer(e, &e->realtime_alarm);
4601 if (r < 0)
4602 return r;
4603
4604 r = event_arm_timer(e, &e->boottime_alarm);
4605 if (r < 0)
4606 return r;
4607
4608 event_close_inode_data_fds(e);
4609
4610 if (event_next_pending(e) || e->need_process_child || e->buffered_inotify_data_list)
4611 goto pending;
4612
4613 e->state = SD_EVENT_ARMED;
4614
4615 return 0;
4616
4617 pending:
4618 e->state = SD_EVENT_ARMED;
4619 r = sd_event_wait(e, 0);
4620 if (r == 0)
4621 e->state = SD_EVENT_ARMED;
4622
4623 return r;
4624 }
4625
4626 static int epoll_wait_usec(
4627 int fd,
4628 struct epoll_event *events,
4629 int maxevents,
4630 usec_t timeout) {
4631
4632 static bool epoll_pwait2_absent = false;
4633 int r, msec;
4634 /* A wrapper that uses epoll_pwait2() if available, and falls back to epoll_wait() if not. */
4635
4636 if (!epoll_pwait2_absent && timeout != USEC_INFINITY) {
4637 r = epoll_pwait2(fd,
4638 events,
4639 maxevents,
4640 TIMESPEC_STORE(timeout),
4641 NULL);
4642 if (r >= 0)
4643 return r;
4644 if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno))
4645 return -errno; /* Only fallback to old epoll_wait() if the syscall is masked or not
4646 * supported. */
4647
4648 epoll_pwait2_absent = true;
4649 }
4650
4651 if (timeout == USEC_INFINITY)
4652 msec = -1;
4653 else {
4654 usec_t k;
4655
4656 k = DIV_ROUND_UP(timeout, USEC_PER_MSEC);
4657 if (k >= INT_MAX)
4658 msec = INT_MAX; /* Saturate */
4659 else
4660 msec = (int) k;
4661 }
4662
4663 return RET_NERRNO(epoll_wait(fd, events, maxevents, msec));
4664 }
4665
4666 static int process_epoll(sd_event *e, usec_t timeout, int64_t threshold, int64_t *ret_min_priority) {
4667 size_t n_event_queue, m, n_event_max;
4668 int64_t min_priority = threshold;
4669 bool something_new = false;
4670 int r;
4671
4672 assert(e);
4673 assert(ret_min_priority);
4674
4675 n_event_queue = MAX(e->n_sources, 1u);
4676 if (!GREEDY_REALLOC(e->event_queue, n_event_queue))
4677 return -ENOMEM;
4678
4679 n_event_max = MALLOC_ELEMENTSOF(e->event_queue);
4680
4681 /* If we still have inotify data buffered, then query the other fds, but don't wait on it */
4682 if (e->buffered_inotify_data_list)
4683 timeout = 0;
4684
4685 for (;;) {
4686 r = epoll_wait_usec(
4687 e->epoll_fd,
4688 e->event_queue,
4689 n_event_max,
4690 timeout);
4691 if (r < 0)
4692 return r;
4693
4694 m = (size_t) r;
4695 msan_unpoison(e->event_queue, m * sizeof(struct epoll_event));
4696
4697 if (m < n_event_max)
4698 break;
4699
4700 if (n_event_max >= n_event_queue * 10)
4701 break;
4702
4703 if (!GREEDY_REALLOC(e->event_queue, n_event_max + n_event_queue))
4704 return -ENOMEM;
4705
4706 n_event_max = MALLOC_ELEMENTSOF(e->event_queue);
4707 timeout = 0;
4708 }
4709
4710 /* Set timestamp only when this is called first time. */
4711 if (threshold == INT64_MAX)
4712 triple_timestamp_now(&e->timestamp);
4713
4714 FOREACH_ARRAY(i, e->event_queue, m) {
4715
4716 if (i->data.ptr == INT_TO_PTR(SOURCE_WATCHDOG))
4717 r = flush_timer(e, e->watchdog_fd, i->events, NULL);
4718 else {
4719 WakeupType *t = ASSERT_PTR(i->data.ptr);
4720
4721 switch (*t) {
4722
4723 case WAKEUP_EVENT_SOURCE: {
4724 sd_event_source *s = i->data.ptr;
4725
4726 if (s->priority > threshold)
4727 continue;
4728
4729 min_priority = MIN(min_priority, s->priority);
4730
4731 switch (s->type) {
4732
4733 case SOURCE_IO:
4734 r = process_io(e, s, i->events);
4735 break;
4736
4737 case SOURCE_CHILD:
4738 r = process_pidfd(e, s, i->events);
4739 break;
4740
4741 case SOURCE_MEMORY_PRESSURE:
4742 case SOURCE_CPU_PRESSURE:
4743 case SOURCE_IO_PRESSURE:
4744 r = process_pressure(s, i->events);
4745 break;
4746
4747 default:
4748 assert_not_reached();
4749 }
4750
4751 break;
4752 }
4753
4754 case WAKEUP_CLOCK_DATA: {
4755 struct clock_data *d = i->data.ptr;
4756
4757 r = flush_timer(e, d->fd, i->events, &d->next);
4758 break;
4759 }
4760
4761 case WAKEUP_SIGNAL_DATA:
4762 r = process_signal(e, i->data.ptr, i->events, &min_priority);
4763 break;
4764
4765 case WAKEUP_INOTIFY_DATA:
4766 r = event_inotify_data_read(e, i->data.ptr, i->events, threshold);
4767 break;
4768
4769 default:
4770 assert_not_reached();
4771 }
4772 }
4773 if (r < 0)
4774 return r;
4775 if (r > 0)
4776 something_new = true;
4777 }
4778
4779 *ret_min_priority = min_priority;
4780 return something_new;
4781 }
4782
4783 _public_ int sd_event_wait(sd_event *e, uint64_t timeout) {
4784 int r;
4785
4786 assert_return(e, -EINVAL);
4787 assert_return(e = event_resolve(e), -ENOPKG);
4788 assert_return(!event_origin_changed(e), -ECHILD);
4789 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
4790 assert_return(e->state == SD_EVENT_ARMED, -EBUSY);
4791
4792 if (e->exit_requested) {
4793 e->state = SD_EVENT_PENDING;
4794 return 1;
4795 }
4796
4797 for (int64_t threshold = INT64_MAX; ; threshold--) {
4798 int64_t epoll_min_priority, child_min_priority;
4799
4800 /* There may be a possibility that new epoll (especially IO) and child events are
4801 * triggered just after process_epoll() call but before process_child(), and the new IO
4802 * events may have higher priority than the child events. To salvage these events,
4803 * let's call epoll_wait() again, but accepts only events with higher priority than the
4804 * previous. See issue https://github.com/systemd/systemd/issues/18190 and comments
4805 * https://github.com/systemd/systemd/pull/18750#issuecomment-785801085
4806 * https://github.com/systemd/systemd/pull/18922#issuecomment-792825226 */
4807
4808 r = process_epoll(e, timeout, threshold, &epoll_min_priority);
4809 if (r == -EINTR) {
4810 e->state = SD_EVENT_PENDING;
4811 return 1;
4812 }
4813 if (r < 0)
4814 goto finish;
4815 if (r == 0 && threshold < INT64_MAX)
4816 /* No new epoll event. */
4817 break;
4818
4819 r = process_child(e, threshold, &child_min_priority);
4820 if (r < 0)
4821 goto finish;
4822 if (r == 0)
4823 /* No new child event. */
4824 break;
4825
4826 threshold = MIN(epoll_min_priority, child_min_priority);
4827 if (threshold == INT64_MIN)
4828 break;
4829
4830 timeout = 0;
4831 }
4832
4833 r = process_watchdog(e);
4834 if (r < 0)
4835 goto finish;
4836
4837 r = process_inotify(e);
4838 if (r < 0)
4839 goto finish;
4840
4841 r = process_timer(e, e->timestamp.realtime, &e->realtime);
4842 if (r < 0)
4843 goto finish;
4844
4845 r = process_timer(e, e->timestamp.boottime, &e->boottime);
4846 if (r < 0)
4847 goto finish;
4848
4849 r = process_timer(e, e->timestamp.realtime, &e->realtime_alarm);
4850 if (r < 0)
4851 goto finish;
4852
4853 r = process_timer(e, e->timestamp.boottime, &e->boottime_alarm);
4854 if (r < 0)
4855 goto finish;
4856
4857 r = process_timer(e, e->timestamp.monotonic, &e->monotonic);
4858 if (r < 0)
4859 goto finish;
4860 else if (r == 1) {
4861 /* Ratelimit expiry callback was called. Let's postpone processing pending sources and
4862 * put loop in the initial state in order to evaluate (in the next iteration) also sources
4863 * there were potentially re-enabled by the callback.
4864 *
4865 * Wondering why we treat only this invocation of process_timer() differently? Once event
4866 * source is ratelimited we essentially transform it into CLOCK_MONOTONIC timer hence
4867 * ratelimit expiry callback is never called for any other timer type. */
4868 r = 0;
4869 goto finish;
4870 }
4871
4872 if (event_next_pending(e)) {
4873 e->state = SD_EVENT_PENDING;
4874 return 1;
4875 }
4876
4877 r = 0;
4878
4879 finish:
4880 e->state = SD_EVENT_INITIAL;
4881
4882 return r;
4883 }
4884
4885 _public_ int sd_event_dispatch(sd_event *e) {
4886 sd_event_source *p;
4887 int r;
4888
4889 assert_return(e, -EINVAL);
4890 assert_return(e = event_resolve(e), -ENOPKG);
4891 assert_return(!event_origin_changed(e), -ECHILD);
4892 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
4893 assert_return(e->state == SD_EVENT_PENDING, -EBUSY);
4894
4895 if (e->exit_requested)
4896 return dispatch_exit(e);
4897
4898 p = event_next_pending(e);
4899 if (p) {
4900 PROTECT_EVENT(e);
4901
4902 e->state = SD_EVENT_RUNNING;
4903 r = source_dispatch(p);
4904 e->state = SD_EVENT_INITIAL;
4905 return r;
4906 }
4907
4908 e->state = SD_EVENT_INITIAL;
4909
4910 return 1;
4911 }
4912
4913 static void event_log_delays(sd_event *e) {
4914 char b[ELEMENTSOF(e->delays) * DECIMAL_STR_MAX(unsigned) + 1], *p;
4915 size_t l;
4916
4917 p = b;
4918 l = sizeof(b);
4919 FOREACH_ELEMENT(delay, e->delays) {
4920 l = strpcpyf(&p, l, "%u ", *delay);
4921 *delay = 0;
4922 }
4923 log_debug("Event loop iterations: %s", b);
4924 }
4925
4926 _public_ int sd_event_run(sd_event *e, uint64_t timeout) {
4927 int r;
4928
4929 assert_return(e, -EINVAL);
4930 assert_return(e = event_resolve(e), -ENOPKG);
4931 assert_return(!event_origin_changed(e), -ECHILD);
4932 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
4933 assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
4934
4935 /* When running on a fiber, delegate to the suspending implementation. Note that the
4936 * profile_delays accounting below is intentionally skipped on that path: the suspending variant
4937 * drives the event loop via sd_event_prepare()/sd_event_wait()/sd_event_dispatch() itself, which
4938 * are the same primitives profile_delays tracks when called directly. */
4939 if (sd_fiber_is_running())
4940 return event_run_suspend(e, timeout);
4941
4942 if (e->profile_delays && e->last_run_usec != 0) {
4943 usec_t this_run;
4944 unsigned l;
4945
4946 this_run = now(CLOCK_MONOTONIC);
4947
4948 l = log2u64(this_run - e->last_run_usec);
4949 assert(l < ELEMENTSOF(e->delays));
4950 e->delays[l]++;
4951
4952 if (this_run - e->last_log_usec >= 5*USEC_PER_SEC) {
4953 event_log_delays(e);
4954 e->last_log_usec = this_run;
4955 }
4956 }
4957
4958 /* Make sure that none of the preparation callbacks ends up freeing the event source under our feet */
4959 PROTECT_EVENT(e);
4960
4961 r = sd_event_prepare(e);
4962 if (r == 0)
4963 /* There was nothing? Then wait... */
4964 r = sd_event_wait(e, timeout);
4965
4966 if (e->profile_delays)
4967 e->last_run_usec = now(CLOCK_MONOTONIC);
4968
4969 if (r > 0) {
4970 /* There's something now, then let's dispatch it */
4971 r = sd_event_dispatch(e);
4972 if (r < 0)
4973 return r;
4974
4975 return 1;
4976 }
4977
4978 return r;
4979 }
4980
4981 _public_ int sd_event_loop(sd_event *e) {
4982 int r;
4983
4984 assert_return(e, -EINVAL);
4985 assert_return(e = event_resolve(e), -ENOPKG);
4986 assert_return(!event_origin_changed(e), -ECHILD);
4987 assert_return(e->state == SD_EVENT_INITIAL, -EBUSY);
4988
4989 PROTECT_EVENT(e);
4990
4991 while (e->state != SD_EVENT_FINISHED) {
4992 r = sd_event_run(e, UINT64_MAX);
4993 if (r < 0)
4994 return r;
4995 }
4996
4997 return e->exit_code;
4998 }
4999
5000 _public_ int sd_event_get_fd(sd_event *e) {
5001 assert_return(e, -EINVAL);
5002 assert_return(e = event_resolve(e), -ENOPKG);
5003 assert_return(!event_origin_changed(e), -ECHILD);
5004
5005 return e->epoll_fd;
5006 }
5007
5008 _public_ int sd_event_get_state(sd_event *e) {
5009 assert_return(e, -EINVAL);
5010 assert_return(e = event_resolve(e), -ENOPKG);
5011 assert_return(!event_origin_changed(e), -ECHILD);
5012
5013 return e->state;
5014 }
5015
5016 _public_ int sd_event_get_exit_code(sd_event *e, int *ret) {
5017 assert_return(e, -EINVAL);
5018 assert_return(e = event_resolve(e), -ENOPKG);
5019 assert_return(!event_origin_changed(e), -ECHILD);
5020
5021 if (!e->exit_requested)
5022 return -ENODATA;
5023
5024 if (ret)
5025 *ret = e->exit_code;
5026 return 0;
5027 }
5028
5029 _public_ int sd_event_exit(sd_event *e, int code) {
5030 assert_return(e, -EINVAL);
5031 assert_return(e = event_resolve(e), -ENOPKG);
5032 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
5033 assert_return(!event_origin_changed(e), -ECHILD);
5034
5035 e->exit_requested = true;
5036 e->exit_code = code;
5037
5038 return 0;
5039 }
5040
5041 _public_ int sd_event_now(sd_event *e, clockid_t clock, uint64_t *ret) {
5042 assert_return(e, -EINVAL);
5043 assert_return(e = event_resolve(e), -ENOPKG);
5044 assert_return(ret, -EINVAL);
5045 assert_return(!event_origin_changed(e), -ECHILD);
5046
5047 if (!TRIPLE_TIMESTAMP_HAS_CLOCK(clock))
5048 return -EOPNOTSUPP;
5049
5050 if (!triple_timestamp_is_set(&e->timestamp)) {
5051 /* Implicitly fall back to now() if we never ran before and thus have no cached time. */
5052 *ret = now(clock);
5053 return 1;
5054 }
5055
5056 *ret = triple_timestamp_by_clock(&e->timestamp, clock);
5057 return 0;
5058 }
5059
5060 _public_ int sd_event_default(sd_event **ret) {
5061 sd_event *e = NULL;
5062 int r;
5063
5064 if (!ret)
5065 return !!default_event;
5066
5067 if (default_event) {
5068 *ret = sd_event_ref(default_event);
5069 return 0;
5070 }
5071
5072 r = sd_event_new(&e);
5073 if (r < 0)
5074 return r;
5075
5076 e->default_event_ptr = &default_event;
5077 e->tid = gettid();
5078 default_event = e;
5079
5080 *ret = e;
5081 return 1;
5082 }
5083
5084 _public_ int sd_event_get_tid(sd_event *e, pid_t *ret) {
5085 assert_return(e, -EINVAL);
5086 assert_return(e = event_resolve(e), -ENOPKG);
5087 assert_return(ret, -EINVAL);
5088 assert_return(!event_origin_changed(e), -ECHILD);
5089
5090 if (e->tid == 0)
5091 return -ENXIO;
5092
5093 *ret = e->tid;
5094 return 0;
5095 }
5096
5097 _public_ int sd_event_set_watchdog(sd_event *e, int b) {
5098 int r;
5099
5100 assert_return(e, -EINVAL);
5101 assert_return(e = event_resolve(e), -ENOPKG);
5102 assert_return(!event_origin_changed(e), -ECHILD);
5103
5104 if (e->watchdog == !!b)
5105 return e->watchdog;
5106
5107 if (b) {
5108 r = sd_watchdog_enabled(false, &e->watchdog_period);
5109 if (r <= 0)
5110 return r;
5111
5112 /* Issue first ping immediately */
5113 sd_notify(false, "WATCHDOG=1");
5114 e->watchdog_last = now(CLOCK_MONOTONIC);
5115
5116 e->watchdog_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
5117 if (e->watchdog_fd < 0)
5118 return -errno;
5119
5120 r = arm_watchdog(e);
5121 if (r < 0)
5122 goto fail;
5123
5124 struct epoll_event ev = {
5125 .events = EPOLLIN,
5126 .data.ptr = INT_TO_PTR(SOURCE_WATCHDOG),
5127 };
5128
5129 if (epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, e->watchdog_fd, &ev) < 0) {
5130 r = -errno;
5131 goto fail;
5132 }
5133
5134 } else {
5135 if (e->watchdog_fd >= 0) {
5136 (void) epoll_ctl(e->epoll_fd, EPOLL_CTL_DEL, e->watchdog_fd, NULL);
5137 e->watchdog_fd = safe_close(e->watchdog_fd);
5138 }
5139 }
5140
5141 e->watchdog = b;
5142 return e->watchdog;
5143
5144 fail:
5145 e->watchdog_fd = safe_close(e->watchdog_fd);
5146 return r;
5147 }
5148
5149 _public_ int sd_event_get_watchdog(sd_event *e) {
5150 assert_return(e, -EINVAL);
5151 assert_return(e = event_resolve(e), -ENOPKG);
5152 assert_return(!event_origin_changed(e), -ECHILD);
5153
5154 return e->watchdog;
5155 }
5156
5157 _public_ int sd_event_get_iteration(sd_event *e, uint64_t *ret) {
5158 assert_return(e, -EINVAL);
5159 assert_return(e = event_resolve(e), -ENOPKG);
5160 assert_return(ret, -EINVAL);
5161 assert_return(!event_origin_changed(e), -ECHILD);
5162
5163 *ret = e->iteration;
5164 return 0;
5165 }
5166
5167 _public_ int sd_event_source_set_destroy_callback(sd_event_source *s, sd_event_destroy_t callback) {
5168 assert_return(s, -EINVAL);
5169 assert_return(s->event, -EINVAL);
5170 assert_return(!event_origin_changed(s->event), -ECHILD);
5171
5172 s->destroy_callback = callback;
5173 return 0;
5174 }
5175
5176 _public_ int sd_event_source_get_destroy_callback(sd_event_source *s, sd_event_destroy_t *ret) {
5177 assert_return(s, -EINVAL);
5178 assert_return(!event_origin_changed(s->event), -ECHILD);
5179
5180 if (ret)
5181 *ret = s->destroy_callback;
5182
5183 return !!s->destroy_callback;
5184 }
5185
5186 _public_ int sd_event_source_get_floating(sd_event_source *s) {
5187 assert_return(s, -EINVAL);
5188 assert_return(!event_origin_changed(s->event), -ECHILD);
5189
5190 return s->floating;
5191 }
5192
5193 _public_ int sd_event_source_set_floating(sd_event_source *s, int b) {
5194 assert_return(s, -EINVAL);
5195 assert_return(!event_origin_changed(s->event), -ECHILD);
5196
5197 if (s->floating == !!b)
5198 return 0;
5199
5200 if (!s->event) /* Already disconnected */
5201 return -ESTALE;
5202
5203 s->floating = b;
5204
5205 if (b) {
5206 sd_event_source_ref(s);
5207 sd_event_unref(s->event);
5208 } else {
5209 sd_event_ref(s->event);
5210 sd_event_source_unref(s);
5211 }
5212
5213 return 1;
5214 }
5215
5216 _public_ int sd_event_source_get_exit_on_failure(sd_event_source *s) {
5217 assert_return(s, -EINVAL);
5218 assert_return(s->type != SOURCE_EXIT, -EDOM);
5219 assert_return(!event_origin_changed(s->event), -ECHILD);
5220
5221 return s->exit_on_failure;
5222 }
5223
5224 _public_ int sd_event_source_set_exit_on_failure(sd_event_source *s, int b) {
5225 assert_return(s, -EINVAL);
5226 assert_return(s->type != SOURCE_EXIT, -EDOM);
5227 assert_return(!event_origin_changed(s->event), -ECHILD);
5228
5229 if (s->exit_on_failure == !!b)
5230 return 0;
5231
5232 s->exit_on_failure = b;
5233 return 1;
5234 }
5235
5236 _public_ int sd_event_source_set_ratelimit(sd_event_source *s, uint64_t interval, unsigned burst) {
5237 int r;
5238
5239 assert_return(s, -EINVAL);
5240 assert_return(!event_origin_changed(s->event), -ECHILD);
5241
5242 /* Turning on ratelimiting on event source types that don't support it, is a loggable offense. Doing
5243 * so is a programming error. */
5244 assert_return(EVENT_SOURCE_CAN_RATE_LIMIT(s->type), -EDOM);
5245
5246 /* When ratelimiting is configured we'll always reset the rate limit state first and start fresh,
5247 * non-ratelimited. */
5248 r = event_source_leave_ratelimit(s, /* run_callback= */ false);
5249 if (r < 0)
5250 return r;
5251
5252 s->rate_limit = (RateLimit) { interval, burst };
5253 return 0;
5254 }
5255
5256 _public_ int sd_event_source_set_ratelimit_expire_callback(sd_event_source *s, sd_event_handler_t callback) {
5257 assert_return(s, -EINVAL);
5258 assert_return(!event_origin_changed(s->event), -ECHILD);
5259
5260 s->ratelimit_expire_callback = callback;
5261 return 0;
5262 }
5263
5264 _public_ int sd_event_source_get_ratelimit(sd_event_source *s, uint64_t *ret_interval, unsigned *ret_burst) {
5265 assert_return(s, -EINVAL);
5266 assert_return(!event_origin_changed(s->event), -ECHILD);
5267
5268 /* Querying whether an event source has ratelimiting configured is not a loggable offense, hence
5269 * don't use assert_return(). Unlike turning on ratelimiting it's not really a programming error. */
5270 if (!EVENT_SOURCE_CAN_RATE_LIMIT(s->type))
5271 return -EDOM;
5272
5273 if (!ratelimit_configured(&s->rate_limit))
5274 return -ENOEXEC;
5275
5276 if (ret_interval)
5277 *ret_interval = s->rate_limit.interval;
5278 if (ret_burst)
5279 *ret_burst = s->rate_limit.burst;
5280
5281 return 0;
5282 }
5283
5284 _public_ int sd_event_source_is_ratelimited(sd_event_source *s) {
5285 assert_return(s, -EINVAL);
5286 assert_return(!event_origin_changed(s->event), -ECHILD);
5287
5288 if (!EVENT_SOURCE_CAN_RATE_LIMIT(s->type))
5289 return false;
5290
5291 if (!ratelimit_configured(&s->rate_limit))
5292 return false;
5293
5294 return s->ratelimited;
5295 }
5296
5297 _public_ int sd_event_source_leave_ratelimit(sd_event_source *s) {
5298 int r;
5299
5300 assert_return(s, -EINVAL);
5301
5302 if (!EVENT_SOURCE_CAN_RATE_LIMIT(s->type))
5303 return 0;
5304
5305 if (!ratelimit_configured(&s->rate_limit))
5306 return 0;
5307
5308 if (!s->ratelimited)
5309 return 0;
5310
5311 r = event_source_leave_ratelimit(s, /* run_callback= */ false);
5312 if (r < 0)
5313 return r;
5314
5315 return 1; /* tell caller that we indeed just left the ratelimit state */
5316 }
5317
5318 _public_ int sd_event_set_signal_exit(sd_event *e, int b) {
5319 bool change = false;
5320 int r;
5321
5322 assert_return(e, -EINVAL);
5323 assert_return(e = event_resolve(e), -ENOPKG);
5324 assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
5325 assert_return(!event_origin_changed(e), -ECHILD);
5326
5327 if (b) {
5328 /* We want to maintain pointers to these event sources, so that we can destroy them when told
5329 * so. But we also don't want them to pin the event loop itself. Hence we mark them as
5330 * floating after creation (and undo this before deleting them again). */
5331
5332 if (!e->sigint_event_source) {
5333 r = sd_event_add_signal(e, &e->sigint_event_source, SIGINT | SD_EVENT_SIGNAL_PROCMASK, NULL, NULL);
5334 if (r < 0)
5335 return r;
5336
5337 assert_se(sd_event_source_set_floating(e->sigint_event_source, true) >= 0);
5338 change = true;
5339 }
5340
5341 if (!e->sigterm_event_source) {
5342 r = sd_event_add_signal(e, &e->sigterm_event_source, SIGTERM | SD_EVENT_SIGNAL_PROCMASK, NULL, NULL);
5343 if (r < 0) {
5344 if (change) {
5345 assert_se(sd_event_source_set_floating(e->sigint_event_source, false) >= 0);
5346 e->sigint_event_source = sd_event_source_unref(e->sigint_event_source);
5347 }
5348
5349 return r;
5350 }
5351
5352 assert_se(sd_event_source_set_floating(e->sigterm_event_source, true) >= 0);
5353 change = true;
5354 }
5355
5356 } else {
5357 if (e->sigint_event_source) {
5358 assert_se(sd_event_source_set_floating(e->sigint_event_source, false) >= 0);
5359 e->sigint_event_source = sd_event_source_unref(e->sigint_event_source);
5360 change = true;
5361 }
5362
5363 if (e->sigterm_event_source) {
5364 assert_se(sd_event_source_set_floating(e->sigterm_event_source, false) >= 0);
5365 e->sigterm_event_source = sd_event_source_unref(e->sigterm_event_source);
5366 change = true;
5367 }
5368 }
5369
5370 return change;
5371 }
5372
5373 _public_ int sd_event_set_exit_on_idle(sd_event *e, int b) {
5374 assert_return(e, -EINVAL);
5375 assert_return(e = event_resolve(e), -ENOPKG);
5376 assert_return(!event_origin_changed(e), -ECHILD);
5377
5378 return e->exit_on_idle = b;
5379 }
5380
5381 _public_ int sd_event_get_exit_on_idle(sd_event *e) {
5382 assert_return(e, -EINVAL);
5383 assert_return(e = event_resolve(e), -ENOPKG);
5384 assert_return(!event_origin_changed(e), -ECHILD);
5385
5386 return e->exit_on_idle;
5387 }
5388
5389 static int event_source_set_pressure_type(sd_event_source *s, const char *ty) {
5390 _cleanup_free_ char *b = NULL;
5391 _cleanup_free_ void *w = NULL;
5392
5393 assert_return(s, -EINVAL);
5394 assert_return(EVENT_SOURCE_IS_PRESSURE(s), -EDOM);
5395 assert_return(ty, -EINVAL);
5396 assert_return(!event_origin_changed(s->event), -ECHILD);
5397
5398 if (!STR_IN_SET(ty, "some", "full"))
5399 return -EINVAL;
5400
5401 if (s->pressure.locked) /* Refuse adjusting parameters, if caller told us how to watch for events */
5402 return -EBUSY;
5403
5404 char* space = memchr(s->pressure.write_buffer, ' ', s->pressure.write_buffer_size);
5405 if (!space)
5406 return -EINVAL;
5407
5408 size_t l = space - (char*) s->pressure.write_buffer;
5409 b = memdup_suffix0(s->pressure.write_buffer, l);
5410 if (!b)
5411 return -ENOMEM;
5412 if (!STR_IN_SET(b, "some", "full"))
5413 return -EINVAL;
5414
5415 if (streq(b, ty))
5416 return 0;
5417
5418 size_t nl = strlen(ty) + (s->pressure.write_buffer_size - l);
5419 w = new(char, nl);
5420 if (!w)
5421 return -ENOMEM;
5422
5423 memcpy(stpcpy(w, ty), space, (s->pressure.write_buffer_size - l));
5424
5425 free_and_replace(s->pressure.write_buffer, w);
5426 s->pressure.write_buffer_size = nl;
5427 s->pressure.locked = false;
5428
5429 return 1;
5430 }
5431
5432 _public_ int sd_event_source_set_memory_pressure_type(sd_event_source *s, const char *ty) {
5433 assert_return(s, -EINVAL);
5434 assert_return(s->type == SOURCE_MEMORY_PRESSURE, -EDOM);
5435
5436 return event_source_set_pressure_type(s, ty);
5437 }
5438
5439 _public_ int sd_event_source_set_cpu_pressure_type(sd_event_source *s, const char *ty) {
5440 assert_return(s, -EINVAL);
5441 assert_return(s->type == SOURCE_CPU_PRESSURE, -EDOM);
5442
5443 return event_source_set_pressure_type(s, ty);
5444 }
5445
5446 _public_ int sd_event_source_set_io_pressure_type(sd_event_source *s, const char *ty) {
5447 assert_return(s, -EINVAL);
5448 assert_return(s->type == SOURCE_IO_PRESSURE, -EDOM);
5449
5450 return event_source_set_pressure_type(s, ty);
5451 }
5452
5453 static int event_source_set_pressure_period(sd_event_source *s, uint64_t threshold_usec, uint64_t window_usec) {
5454 _cleanup_free_ char *b = NULL;
5455 _cleanup_free_ void *w = NULL;
5456
5457 assert_return(s, -EINVAL);
5458 assert_return(EVENT_SOURCE_IS_PRESSURE(s), -EDOM);
5459 assert_return(!event_origin_changed(s->event), -ECHILD);
5460
5461 if (threshold_usec <= 0 || threshold_usec >= UINT64_MAX)
5462 return -ERANGE;
5463 if (window_usec <= 0 || window_usec >= UINT64_MAX)
5464 return -ERANGE;
5465 if (threshold_usec > window_usec)
5466 return -EINVAL;
5467
5468 if (s->pressure.locked) /* Refuse adjusting parameters, if caller told us how to watch for events */
5469 return -EBUSY;
5470
5471 char* space = memchr(s->pressure.write_buffer, ' ', s->pressure.write_buffer_size);
5472 if (!space)
5473 return -EINVAL;
5474
5475 size_t l = space - (char*) s->pressure.write_buffer;
5476 b = memdup_suffix0(s->pressure.write_buffer, l);
5477 if (!b)
5478 return -ENOMEM;
5479 if (!STR_IN_SET(b, "some", "full"))
5480 return -EINVAL;
5481
5482 if (asprintf((char**) &w,
5483 "%s " USEC_FMT " " USEC_FMT "",
5484 b,
5485 threshold_usec,
5486 window_usec) < 0)
5487 return -EINVAL;
5488
5489 l = strlen(w) + 1;
5490 if (memcmp_nn(s->pressure.write_buffer, s->pressure.write_buffer_size, w, l) == 0)
5491 return 0;
5492
5493 free_and_replace(s->pressure.write_buffer, w);
5494 s->pressure.write_buffer_size = l;
5495 s->pressure.locked = false;
5496
5497 return 1;
5498 }
5499
5500 _public_ int sd_event_source_set_memory_pressure_period(sd_event_source *s, uint64_t threshold_usec, uint64_t window_usec) {
5501 assert_return(s, -EINVAL);
5502 assert_return(s->type == SOURCE_MEMORY_PRESSURE, -EDOM);
5503
5504 return event_source_set_pressure_period(s, threshold_usec, window_usec);
5505 }
5506
5507 _public_ int sd_event_source_set_cpu_pressure_period(sd_event_source *s, uint64_t threshold_usec, uint64_t window_usec) {
5508 assert_return(s, -EINVAL);
5509 assert_return(s->type == SOURCE_CPU_PRESSURE, -EDOM);
5510
5511 return event_source_set_pressure_period(s, threshold_usec, window_usec);
5512 }
5513
5514 _public_ int sd_event_source_set_io_pressure_period(sd_event_source *s, uint64_t threshold_usec, uint64_t window_usec) {
5515 assert_return(s, -EINVAL);
5516 assert_return(s->type == SOURCE_IO_PRESSURE, -EDOM);
5517
5518 return event_source_set_pressure_period(s, threshold_usec, window_usec);
5519 }