592caf
From 395eb7753a9772f505102fbbe3ba3261b57abbe9 Mon Sep 17 00:00:00 2001
592caf
From: Lennart Poettering <lennart@poettering.net>
592caf
Date: Mon, 23 Nov 2020 18:02:40 +0100
592caf
Subject: [PATCH] sd-event: add ability to ratelimit event sources
592caf
592caf
Let's a concept of "rate limiting" to event sources: if specific event
592caf
sources fire too often in some time interval temporarily take them
592caf
offline, and take them back online once the interval passed.
592caf
592caf
This is a simple scheme of avoiding starvation of event sources if some
592caf
event source fires too often.
592caf
592caf
This introduces the new conceptual states of "offline" and "online" for
592caf
event sources: an event source is "online" only when enabled *and* not
592caf
ratelimited, and offline in all other cases. An event source that is
592caf
online hence has its fds registered in the epoll, its signals in the
592caf
signalfd and so on.
592caf
592caf
(cherry picked from commit b6d5481b3d9f7c9b1198ab54b54326ec73e855bf)
592caf
592caf
Related: #1819868
592caf
---
592caf
 src/basic/ratelimit.h              |   8 +
592caf
 src/libsystemd/libsystemd.sym      |   7 +
592caf
 src/libsystemd/sd-event/sd-event.c | 433 +++++++++++++++++++++++------
592caf
 src/systemd/sd-event.h             |   3 +
592caf
 4 files changed, 369 insertions(+), 82 deletions(-)
592caf
592caf
diff --git a/src/basic/ratelimit.h b/src/basic/ratelimit.h
592caf
index de91def28d..0012b49935 100644
592caf
--- a/src/basic/ratelimit.h
592caf
+++ b/src/basic/ratelimit.h
592caf
@@ -38,3 +38,11 @@ typedef struct RateLimit {
592caf
         } while (false)
592caf
 
592caf
 bool ratelimit_below(RateLimit *r);
592caf
+
592caf
+static inline void ratelimit_reset(RateLimit *rl) {
592caf
+        rl->num = rl->begin = 0;
592caf
+}
592caf
+
592caf
+static inline bool ratelimit_configured(RateLimit *rl) {
592caf
+        return rl->interval > 0 && rl->burst > 0;
592caf
+}
592caf
diff --git a/src/libsystemd/libsystemd.sym b/src/libsystemd/libsystemd.sym
592caf
index 778e88a16c..149d2e7b82 100644
592caf
--- a/src/libsystemd/libsystemd.sym
592caf
+++ b/src/libsystemd/libsystemd.sym
592caf
@@ -572,3 +572,10 @@ global:
592caf
         sd_bus_enqueue_for_read;
592caf
         sd_event_source_disable_unref;
592caf
 } LIBSYSTEMD_238;
592caf
+
592caf
+LIBSYSTEMD_248 {
592caf
+global:
592caf
+        sd_event_source_set_ratelimit;
592caf
+        sd_event_source_get_ratelimit;
592caf
+        sd_event_source_is_ratelimited;
592caf
+} LIBSYSTEMD_239;
592caf
diff --git a/src/libsystemd/sd-event/sd-event.c b/src/libsystemd/sd-event/sd-event.c
592caf
index d18ce28a92..be912d94e3 100644
592caf
--- a/src/libsystemd/sd-event/sd-event.c
592caf
+++ b/src/libsystemd/sd-event/sd-event.c
592caf
@@ -19,6 +19,7 @@
592caf
 #include "missing.h"
592caf
 #include "prioq.h"
592caf
 #include "process-util.h"
592caf
+#include "ratelimit.h"
592caf
 #include "set.h"
592caf
 #include "signal-util.h"
592caf
 #include "string-table.h"
592caf
@@ -46,6 +47,7 @@ typedef enum EventSourceType {
592caf
         _SOURCE_EVENT_SOURCE_TYPE_INVALID = -1
592caf
 } EventSourceType;
592caf
 
592caf
+
592caf
 static const char* const event_source_type_table[_SOURCE_EVENT_SOURCE_TYPE_MAX] = {
592caf
         [SOURCE_IO] = "io",
592caf
         [SOURCE_TIME_REALTIME] = "realtime",
592caf
@@ -76,7 +78,25 @@ typedef enum WakeupType {
592caf
         _WAKEUP_TYPE_INVALID = -1,
592caf
 } WakeupType;
592caf
 
592caf
-#define EVENT_SOURCE_IS_TIME(t) IN_SET((t), SOURCE_TIME_REALTIME, SOURCE_TIME_BOOTTIME, SOURCE_TIME_MONOTONIC, SOURCE_TIME_REALTIME_ALARM, SOURCE_TIME_BOOTTIME_ALARM)
592caf
+#define EVENT_SOURCE_IS_TIME(t)                 \
592caf
+        IN_SET((t),                             \
592caf
+               SOURCE_TIME_REALTIME,            \
592caf
+               SOURCE_TIME_BOOTTIME,            \
592caf
+               SOURCE_TIME_MONOTONIC,           \
592caf
+               SOURCE_TIME_REALTIME_ALARM,      \
592caf
+               SOURCE_TIME_BOOTTIME_ALARM)
592caf
+
592caf
+#define EVENT_SOURCE_CAN_RATE_LIMIT(t)          \
592caf
+        IN_SET((t),                             \
592caf
+               SOURCE_IO,                       \
592caf
+               SOURCE_TIME_REALTIME,            \
592caf
+               SOURCE_TIME_BOOTTIME,            \
592caf
+               SOURCE_TIME_MONOTONIC,           \
592caf
+               SOURCE_TIME_REALTIME_ALARM,      \
592caf
+               SOURCE_TIME_BOOTTIME_ALARM,      \
592caf
+               SOURCE_SIGNAL,                   \
592caf
+               SOURCE_DEFER,                    \
592caf
+               SOURCE_INOTIFY)
592caf
 
592caf
 struct inode_data;
592caf
 
592caf
@@ -96,6 +116,7 @@ struct sd_event_source {
592caf
         bool pending:1;
592caf
         bool dispatching:1;
592caf
         bool floating:1;
592caf
+        bool ratelimited:1;
592caf
 
592caf
         int64_t priority;
592caf
         unsigned pending_index;
592caf
@@ -107,6 +128,10 @@ struct sd_event_source {
592caf
 
592caf
         LIST_FIELDS(sd_event_source, sources);
592caf
 
592caf
+        RateLimit rate_limit;
592caf
+
592caf
+        /* These are primarily fields relevant for time event sources, but since any event source can
592caf
+         * effectively become one when rate-limited, this is part of the common fields. */
592caf
         unsigned earliest_index;
592caf
         unsigned latest_index;
592caf
 
592caf
@@ -266,7 +291,7 @@ struct sd_event {
592caf
         Hashmap *signal_data; /* indexed by priority */
592caf
 
592caf
         Hashmap *child_sources;
592caf
-        unsigned n_enabled_child_sources;
592caf
+        unsigned n_online_child_sources;
592caf
 
592caf
         Set *post_sources;
592caf
 
592caf
@@ -311,12 +336,23 @@ static thread_local sd_event *default_event = NULL;
592caf
 static void source_disconnect(sd_event_source *s);
592caf
 static void event_gc_inode_data(sd_event *e, struct inode_data *d);
592caf
 
592caf
+static bool event_source_is_online(sd_event_source *s) {
592caf
+        assert(s);
592caf
+        return s->enabled != SD_EVENT_OFF && !s->ratelimited;
592caf
+}
592caf
+
592caf
+static bool event_source_is_offline(sd_event_source *s) {
592caf
+        assert(s);
592caf
+        return s->enabled == SD_EVENT_OFF || s->ratelimited;
592caf
+}
592caf
+
592caf
 static sd_event *event_resolve(sd_event *e) {
592caf
         return e == SD_EVENT_DEFAULT ? default_event : e;
592caf
 }
592caf
 
592caf
 static int pending_prioq_compare(const void *a, const void *b) {
592caf
         const sd_event_source *x = a, *y = b;
592caf
+        int r;
592caf
 
592caf
         assert(x->pending);
592caf
         assert(y->pending);
592caf
@@ -327,23 +363,23 @@ static int pending_prioq_compare(const void *a, const void *b) {
592caf
         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
592caf
                 return 1;
592caf
 
592caf
+        /* Non rate-limited ones first. */
592caf
+        r = CMP(!!x->ratelimited, !!y->ratelimited);
592caf
+        if (r != 0)
592caf
+                return r;
592caf
+
592caf
         /* Lower priority values first */
592caf
-        if (x->priority < y->priority)
592caf
-                return -1;
592caf
-        if (x->priority > y->priority)
592caf
-                return 1;
592caf
+        r = CMP(x->priority, y->priority);
592caf
+        if (r != 0)
592caf
+                return r;
592caf
 
592caf
         /* Older entries first */
592caf
-        if (x->pending_iteration < y->pending_iteration)
592caf
-                return -1;
592caf
-        if (x->pending_iteration > y->pending_iteration)
592caf
-                return 1;
592caf
-
592caf
-        return 0;
592caf
+        return CMP(x->pending_iteration, y->pending_iteration);
592caf
 }
592caf
 
592caf
 static int prepare_prioq_compare(const void *a, const void *b) {
592caf
         const sd_event_source *x = a, *y = b;
592caf
+        int r;
592caf
 
592caf
         assert(x->prepare);
592caf
         assert(y->prepare);
592caf
@@ -354,29 +390,46 @@ static int prepare_prioq_compare(const void *a, const void *b) {
592caf
         if (x->enabled == SD_EVENT_OFF && y->enabled != SD_EVENT_OFF)
592caf
                 return 1;
592caf
 
592caf
+        /* Non rate-limited ones first. */
592caf
+        r = CMP(!!x->ratelimited, !!y->ratelimited);
592caf
+        if (r != 0)
592caf
+                return r;
592caf
+
592caf
         /* Move most recently prepared ones last, so that we can stop
592caf
          * preparing as soon as we hit one that has already been
592caf
          * prepared in the current iteration */
592caf
-        if (x->prepare_iteration < y->prepare_iteration)
592caf
-                return -1;
592caf
-        if (x->prepare_iteration > y->prepare_iteration)
592caf
-                return 1;
592caf
+        r = CMP(x->prepare_iteration, y->prepare_iteration);
592caf
+        if (r != 0)
592caf
+                return r;
592caf
 
592caf
         /* Lower priority values first */
592caf
-        if (x->priority < y->priority)
592caf
-                return -1;
592caf
-        if (x->priority > y->priority)
592caf
-                return 1;
592caf
+        return CMP(x->priority, y->priority);
592caf
+}
592caf
 
592caf
-        return 0;
592caf
+static usec_t time_event_source_next(const sd_event_source *s) {
592caf
+        assert(s);
592caf
+
592caf
+        /* We have two kinds of event sources that have elapsation times associated with them: the actual
592caf
+         * time based ones and the ones for which a ratelimit can be in effect (where we want to be notified
592caf
+         * once the ratelimit time window ends). Let's return the next elapsing time depending on what we are
592caf
+         * looking at here. */
592caf
+
592caf
+        if (s->ratelimited) { /* If rate-limited the next elapsation is when the ratelimit time window ends */
592caf
+                assert(s->rate_limit.begin != 0);
592caf
+                assert(s->rate_limit.interval != 0);
592caf
+                return usec_add(s->rate_limit.begin, s->rate_limit.interval);
592caf
+        }
592caf
+
592caf
+        /* Otherwise this must be a time event source, if not ratelimited */
592caf
+        if (EVENT_SOURCE_IS_TIME(s->type))
592caf
+                return s->time.next;
592caf
+
592caf
+        return USEC_INFINITY;
592caf
 }
592caf
 
592caf
 static int earliest_time_prioq_compare(const void *a, const void *b) {
592caf
         const sd_event_source *x = a, *y = b;
592caf
 
592caf
-        assert(EVENT_SOURCE_IS_TIME(x->type));
592caf
-        assert(x->type == y->type);
592caf
-
592caf
         /* Enabled ones first */
592caf
         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
592caf
                 return -1;
592caf
@@ -390,24 +443,30 @@ static int earliest_time_prioq_compare(const void *a, const void *b) {
592caf
                 return 1;
592caf
 
592caf
         /* Order by time */
592caf
-        if (x->time.next < y->time.next)
592caf
-                return -1;
592caf
-        if (x->time.next > y->time.next)
592caf
-                return 1;
592caf
-
592caf
-        return 0;
592caf
+        return CMP(time_event_source_next(x), time_event_source_next(y));
592caf
 }
592caf
 
592caf
 static usec_t time_event_source_latest(const sd_event_source *s) {
592caf
-        return usec_add(s->time.next, s->time.accuracy);
592caf
+        assert(s);
592caf
+
592caf
+        if (s->ratelimited) { /* For ratelimited stuff the earliest and the latest time shall actually be the
592caf
+                               * same, as we should avoid adding additional inaccuracy on an inaccuracy time
592caf
+                               * window */
592caf
+                assert(s->rate_limit.begin != 0);
592caf
+                assert(s->rate_limit.interval != 0);
592caf
+                return usec_add(s->rate_limit.begin, s->rate_limit.interval);
592caf
+        }
592caf
+
592caf
+        /* Must be a time event source, if not ratelimited */
592caf
+        if (EVENT_SOURCE_IS_TIME(s->type))
592caf
+                return usec_add(s->time.next, s->time.accuracy);
592caf
+
592caf
+        return USEC_INFINITY;
592caf
 }
592caf
 
592caf
 static int latest_time_prioq_compare(const void *a, const void *b) {
592caf
         const sd_event_source *x = a, *y = b;
592caf
 
592caf
-        assert(EVENT_SOURCE_IS_TIME(x->type));
592caf
-        assert(x->type == y->type);
592caf
-
592caf
         /* Enabled ones first */
592caf
         if (x->enabled != SD_EVENT_OFF && y->enabled == SD_EVENT_OFF)
592caf
                 return -1;
592caf
@@ -852,12 +911,12 @@ static void event_gc_signal_data(sd_event *e, const int64_t *priority, int sig)
592caf
          * the signalfd for it. */
592caf
 
592caf
         if (sig == SIGCHLD &&
592caf
-            e->n_enabled_child_sources > 0)
592caf
+            e->n_online_child_sources > 0)
592caf
                 return;
592caf
 
592caf
         if (e->signal_sources &&
592caf
             e->signal_sources[sig] &&
592caf
-            e->signal_sources[sig]->enabled != SD_EVENT_OFF)
592caf
+            event_source_is_online(e->signal_sources[sig]))
592caf
                 return;
592caf
 
592caf
         /*
592caf
@@ -904,11 +963,17 @@ static void event_source_time_prioq_reshuffle(sd_event_source *s) {
592caf
         struct clock_data *d;
592caf
 
592caf
         assert(s);
592caf
-        assert(EVENT_SOURCE_IS_TIME(s->type));
592caf
 
592caf
         /* Called whenever the event source's timer ordering properties changed, i.e. time, accuracy,
592caf
          * pending, enable state. Makes sure the two prioq's are ordered properly again. */
592caf
-        assert_se(d = event_get_clock_data(s->event, s->type));
592caf
+
592caf
+        if (s->ratelimited)
592caf
+                d = &s->event->monotonic;
592caf
+        else {
592caf
+                assert(EVENT_SOURCE_IS_TIME(s->type));
592caf
+                assert_se(d = event_get_clock_data(s->event, s->type));
592caf
+        }
592caf
+
592caf
         prioq_reshuffle(d->earliest, s, &s->earliest_index);
592caf
         prioq_reshuffle(d->latest, s, &s->latest_index);
592caf
         d->needs_rearm = true;
592caf
@@ -949,12 +1014,18 @@ static void source_disconnect(sd_event_source *s) {
592caf
         case SOURCE_TIME_BOOTTIME:
592caf
         case SOURCE_TIME_MONOTONIC:
592caf
         case SOURCE_TIME_REALTIME_ALARM:
592caf
-        case SOURCE_TIME_BOOTTIME_ALARM: {
592caf
-                struct clock_data *d;
592caf
-                assert_se(d = event_get_clock_data(s->event, s->type));
592caf
-                event_source_time_prioq_remove(s, d);
592caf
+        case SOURCE_TIME_BOOTTIME_ALARM:
592caf
+                /* Only remove this event source from the time event source here if it is not ratelimited. If
592caf
+                 * it is ratelimited, we'll remove it below, separately. Why? Because the clock used might
592caf
+                 * differ: ratelimiting always uses CLOCK_MONOTONIC, but timer events might use any clock */
592caf
+
592caf
+                if (!s->ratelimited) {
592caf
+                        struct clock_data *d;
592caf
+                        assert_se(d = event_get_clock_data(s->event, s->type));
592caf
+                        event_source_time_prioq_remove(s, d);
592caf
+                }
592caf
+
592caf
                 break;
592caf
-        }
592caf
 
592caf
         case SOURCE_SIGNAL:
592caf
                 if (s->signal.sig > 0) {
592caf
@@ -969,9 +1040,9 @@ static void source_disconnect(sd_event_source *s) {
592caf
 
592caf
         case SOURCE_CHILD:
592caf
                 if (s->child.pid > 0) {
592caf
-                        if (s->enabled != SD_EVENT_OFF) {
592caf
-                                assert(s->event->n_enabled_child_sources > 0);
592caf
-                                s->event->n_enabled_child_sources--;
592caf
+                        if (event_source_is_online(s)) {
592caf
+                                assert(s->event->n_online_child_sources > 0);
592caf
+                                s->event->n_online_child_sources--;
592caf
                         }
592caf
 
592caf
                         (void) hashmap_remove(s->event->child_sources, PID_TO_PTR(s->child.pid));
592caf
@@ -1037,6 +1108,9 @@ static void source_disconnect(sd_event_source *s) {
592caf
         if (s->prepare)
592caf
                 prioq_remove(s->event->prepare, s, &s->prepare_index);
592caf
 
592caf
+        if (s->ratelimited)
592caf
+                event_source_time_prioq_remove(s, &s->event->monotonic);
592caf
+
592caf
         event = s->event;
592caf
 
592caf
         s->type = _SOURCE_EVENT_SOURCE_TYPE_INVALID;
592caf
@@ -1458,11 +1532,11 @@ _public_ int sd_event_add_child(
592caf
                 return r;
592caf
         }
592caf
 
592caf
-        e->n_enabled_child_sources++;
592caf
+        e->n_online_child_sources++;
592caf
 
592caf
         r = event_make_signal_data(e, SIGCHLD, NULL);
592caf
         if (r < 0) {
592caf
-                e->n_enabled_child_sources--;
592caf
+                e->n_online_child_sources--;
592caf
                 source_free(s);
592caf
                 return r;
592caf
         }
592caf
@@ -2079,7 +2153,7 @@ _public_ int sd_event_source_set_io_fd(sd_event_source *s, int fd) {
592caf
         if (s->io.fd == fd)
592caf
                 return 0;
592caf
 
592caf
-        if (s->enabled == SD_EVENT_OFF) {
592caf
+        if (event_source_is_offline(s)) {
592caf
                 s->io.fd = fd;
592caf
                 s->io.registered = false;
592caf
         } else {
592caf
@@ -2146,7 +2220,7 @@ _public_ int sd_event_source_set_io_events(sd_event_source *s, uint32_t events)
592caf
         if (r < 0)
592caf
                 return r;
592caf
 
592caf
-        if (s->enabled != SD_EVENT_OFF) {
592caf
+        if (event_source_is_online(s)) {
592caf
                 r = source_io_register(s, s->enabled, events);
592caf
                 if (r < 0)
592caf
                         return r;
592caf
@@ -2249,7 +2323,7 @@ _public_ int sd_event_source_set_priority(sd_event_source *s, int64_t priority)
592caf
 
592caf
                 event_gc_inode_data(s->event, old_inode_data);
592caf
 
592caf
-        } else if (s->type == SOURCE_SIGNAL && s->enabled != SD_EVENT_OFF) {
592caf
+        } else if (s->type == SOURCE_SIGNAL && event_source_is_online(s)) {
592caf
                 struct signal_data *old, *d;
592caf
 
592caf
                 /* Move us from the signalfd belonging to the old
592caf
@@ -2296,20 +2370,29 @@ _public_ int sd_event_source_get_enabled(sd_event_source *s, int *ret) {
592caf
         return s->enabled != SD_EVENT_OFF;
592caf
 }
592caf
 
592caf
-static int event_source_disable(sd_event_source *s) {
592caf
+static int event_source_offline(
592caf
+                sd_event_source *s,
592caf
+                int enabled,
592caf
+                bool ratelimited) {
592caf
+
592caf
+        bool was_offline;
592caf
         int r;
592caf
 
592caf
         assert(s);
592caf
-        assert(s->enabled != SD_EVENT_OFF);
592caf
+        assert(enabled == SD_EVENT_OFF || ratelimited);
592caf
 
592caf
         /* Unset the pending flag when this event source is disabled */
592caf
-        if (!IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
592caf
+        if (s->enabled != SD_EVENT_OFF &&
592caf
+            enabled == SD_EVENT_OFF &&
592caf
+            !IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
592caf
                 r = source_set_pending(s, false);
592caf
                 if (r < 0)
592caf
                         return r;
592caf
         }
592caf
 
592caf
-        s->enabled = SD_EVENT_OFF;
592caf
+        was_offline = event_source_is_offline(s);
592caf
+        s->enabled = enabled;
592caf
+        s->ratelimited = ratelimited;
592caf
 
592caf
         switch (s->type) {
592caf
 
592caf
@@ -2330,8 +2413,10 @@ static int event_source_disable(sd_event_source *s) {
592caf
                 break;
592caf
 
592caf
         case SOURCE_CHILD:
592caf
-                assert(s->event->n_enabled_child_sources > 0);
592caf
-                s->event->n_enabled_child_sources--;
592caf
+                if (!was_offline) {
592caf
+                        assert(s->event->n_online_child_sources > 0);
592caf
+                        s->event->n_online_child_sources--;
592caf
+                }
592caf
 
592caf
                 event_gc_signal_data(s->event, &s->priority, SIGCHLD);
592caf
                 break;
592caf
@@ -2349,26 +2434,42 @@ static int event_source_disable(sd_event_source *s) {
592caf
                 assert_not_reached("Wut? I shouldn't exist.");
592caf
         }
592caf
 
592caf
-        return 0;
592caf
+        return 1;
592caf
 }
592caf
 
592caf
-static int event_source_enable(sd_event_source *s, int enable) {
592caf
+static int event_source_online(
592caf
+                sd_event_source *s,
592caf
+                int enabled,
592caf
+                bool ratelimited) {
592caf
+
592caf
+        bool was_online;
592caf
         int r;
592caf
 
592caf
         assert(s);
592caf
-        assert(IN_SET(enable, SD_EVENT_ON, SD_EVENT_ONESHOT));
592caf
-        assert(s->enabled == SD_EVENT_OFF);
592caf
+        assert(enabled != SD_EVENT_OFF || !ratelimited);
592caf
 
592caf
         /* Unset the pending flag when this event source is enabled */
592caf
-        if (!IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
592caf
+        if (s->enabled == SD_EVENT_OFF &&
592caf
+            enabled != SD_EVENT_OFF &&
592caf
+            !IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
592caf
                 r = source_set_pending(s, false);
592caf
                 if (r < 0)
592caf
                         return r;
592caf
         }
592caf
 
592caf
+        /* Are we really ready for onlining? */
592caf
+        if (enabled == SD_EVENT_OFF || ratelimited) {
592caf
+                /* Nope, we are not ready for onlining, then just update the precise state and exit */
592caf
+                s->enabled = enabled;
592caf
+                s->ratelimited = ratelimited;
592caf
+                return 0;
592caf
+        }
592caf
+
592caf
+        was_online = event_source_is_online(s);
592caf
+
592caf
         switch (s->type) {
592caf
         case SOURCE_IO:
592caf
-                r = source_io_register(s, enable, s->io.events);
592caf
+                r = source_io_register(s, enabled, s->io.events);
592caf
                 if (r < 0)
592caf
                         return r;
592caf
                 break;
592caf
@@ -2386,13 +2487,13 @@ static int event_source_enable(sd_event_source *s, int enable) {
592caf
                 r = event_make_signal_data(s->event, SIGCHLD, NULL);
592caf
                 if (r < 0) {
592caf
                         s->enabled = SD_EVENT_OFF;
592caf
-                        s->event->n_enabled_child_sources--;
592caf
+                        s->event->n_online_child_sources--;
592caf
                         event_gc_signal_data(s->event, &s->priority, SIGCHLD);
592caf
                         return r;
592caf
                 }
592caf
 
592caf
-                s->event->n_enabled_child_sources++;
592caf
-
592caf
+                if (!was_online)
592caf
+                        s->event->n_online_child_sources++;
592caf
                 break;
592caf
 
592caf
         case SOURCE_TIME_REALTIME:
592caf
@@ -2410,7 +2511,8 @@ static int event_source_enable(sd_event_source *s, int enable) {
592caf
                 assert_not_reached("Wut? I shouldn't exist.");
592caf
         }
592caf
 
592caf
-        s->enabled = enable;
592caf
+        s->enabled = enabled;
592caf
+        s->ratelimited = ratelimited;
592caf
 
592caf
         /* Non-failing operations below */
592caf
         switch (s->type) {
592caf
@@ -2430,7 +2532,7 @@ static int event_source_enable(sd_event_source *s, int enable) {
592caf
                 break;
592caf
         }
592caf
 
592caf
-        return 0;
592caf
+        return 1;
592caf
 }
592caf
 
592caf
 _public_ int sd_event_source_set_enabled(sd_event_source *s, int m) {
592caf
@@ -2448,7 +2550,7 @@ _public_ int sd_event_source_set_enabled(sd_event_source *s, int m) {
592caf
                 return 0;
592caf
 
592caf
         if (m == SD_EVENT_OFF)
592caf
-                r = event_source_disable(s);
592caf
+                r = event_source_offline(s, m, s->ratelimited);
592caf
         else {
592caf
                 if (s->enabled != SD_EVENT_OFF) {
592caf
                         /* Switching from "on" to "oneshot" or back? If that's the case, we can take a shortcut, the
592caf
@@ -2457,7 +2559,7 @@ _public_ int sd_event_source_set_enabled(sd_event_source *s, int m) {
592caf
                         return 0;
592caf
                 }
592caf
 
592caf
-                r = event_source_enable(s, m);
592caf
+                r = event_source_online(s, m, s->ratelimited);
592caf
         }
592caf
         if (r < 0)
592caf
                 return r;
592caf
@@ -2605,6 +2707,96 @@ _public_ void *sd_event_source_set_userdata(sd_event_source *s, void *userdata)
592caf
         return ret;
592caf
 }
592caf
 
592caf
+static int event_source_enter_ratelimited(sd_event_source *s) {
592caf
+        int r;
592caf
+
592caf
+        assert(s);
592caf
+
592caf
+        /* When an event source becomes ratelimited, we place it in the CLOCK_MONOTONIC priority queue, with
592caf
+         * the end of the rate limit time window, much as if it was a timer event source. */
592caf
+
592caf
+        if (s->ratelimited)
592caf
+                return 0; /* Already ratelimited, this is a NOP hence */
592caf
+
592caf
+        /* Make sure we can install a CLOCK_MONOTONIC event further down. */
592caf
+        r = setup_clock_data(s->event, &s->event->monotonic, CLOCK_MONOTONIC);
592caf
+        if (r < 0)
592caf
+                return r;
592caf
+
592caf
+        /* Timer event sources are already using the earliest/latest queues for the timer scheduling. Let's
592caf
+         * first remove them from the prioq appropriate for their own clock, so that we can use the prioq
592caf
+         * fields of the event source then for adding it to the CLOCK_MONOTONIC prioq instead. */
592caf
+        if (EVENT_SOURCE_IS_TIME(s->type))
592caf
+                event_source_time_prioq_remove(s, event_get_clock_data(s->event, s->type));
592caf
+
592caf
+        /* Now, let's add the event source to the monotonic clock instead */
592caf
+        r = event_source_time_prioq_put(s, &s->event->monotonic);
592caf
+        if (r < 0)
592caf
+                goto fail;
592caf
+
592caf
+        /* And let's take the event source officially offline */
592caf
+        r = event_source_offline(s, s->enabled, /* ratelimited= */ true);
592caf
+        if (r < 0) {
592caf
+                event_source_time_prioq_remove(s, &s->event->monotonic);
592caf
+                goto fail;
592caf
+        }
592caf
+
592caf
+        event_source_pp_prioq_reshuffle(s);
592caf
+
592caf
+        log_debug("Event source %p (%s) entered rate limit state.", s, strna(s->description));
592caf
+        return 0;
592caf
+
592caf
+fail:
592caf
+        /* Reinstall time event sources in the priority queue as before. This shouldn't fail, since the queue
592caf
+         * space for it should already be allocated. */
592caf
+        if (EVENT_SOURCE_IS_TIME(s->type))
592caf
+                assert_se(event_source_time_prioq_put(s, event_get_clock_data(s->event, s->type)) >= 0);
592caf
+
592caf
+        return r;
592caf
+}
592caf
+
592caf
+static int event_source_leave_ratelimit(sd_event_source *s) {
592caf
+        int r;
592caf
+
592caf
+        assert(s);
592caf
+
592caf
+        if (!s->ratelimited)
592caf
+                return 0;
592caf
+
592caf
+        /* Let's take the event source out of the monotonic prioq first. */
592caf
+        event_source_time_prioq_remove(s, &s->event->monotonic);
592caf
+
592caf
+        /* Let's then add the event source to its native clock prioq again — if this is a timer event source */
592caf
+        if (EVENT_SOURCE_IS_TIME(s->type)) {
592caf
+                r = event_source_time_prioq_put(s, event_get_clock_data(s->event, s->type));
592caf
+                if (r < 0)
592caf
+                        goto fail;
592caf
+        }
592caf
+
592caf
+        /* Let's try to take it online again.  */
592caf
+        r = event_source_online(s, s->enabled, /* ratelimited= */ false);
592caf
+        if (r < 0) {
592caf
+                /* Do something roughly sensible when this failed: undo the two prioq ops above */
592caf
+                if (EVENT_SOURCE_IS_TIME(s->type))
592caf
+                        event_source_time_prioq_remove(s, event_get_clock_data(s->event, s->type));
592caf
+
592caf
+                goto fail;
592caf
+        }
592caf
+
592caf
+        event_source_pp_prioq_reshuffle(s);
592caf
+        ratelimit_reset(&s->rate_limit);
592caf
+
592caf
+        log_debug("Event source %p (%s) left rate limit state.", s, strna(s->description));
592caf
+        return 0;
592caf
+
592caf
+fail:
592caf
+        /* Do something somewhat reasonable when we cannot move an event sources out of ratelimited mode:
592caf
+         * simply put it back in it, maybe we can then process it more successfully next iteration. */
592caf
+        assert_se(event_source_time_prioq_put(s, &s->event->monotonic) >= 0);
592caf
+
592caf
+        return r;
592caf
+}
592caf
+
592caf
 static usec_t sleep_between(sd_event *e, usec_t a, usec_t b) {
592caf
         usec_t c;
592caf
         assert(e);
592caf
@@ -2703,7 +2895,7 @@ static int event_arm_timer(
592caf
                 d->needs_rearm = false;
592caf
 
592caf
         a = prioq_peek(d->earliest);
592caf
-        if (!a || a->enabled == SD_EVENT_OFF || a->time.next == USEC_INFINITY) {
592caf
+        if (!a || a->enabled == SD_EVENT_OFF || time_event_source_next(a) == USEC_INFINITY) {
592caf
 
592caf
                 if (d->fd < 0)
592caf
                         return 0;
592caf
@@ -2723,7 +2915,7 @@ static int event_arm_timer(
592caf
         b = prioq_peek(d->latest);
592caf
         assert_se(b && b->enabled != SD_EVENT_OFF);
592caf
 
592caf
-        t = sleep_between(e, a->time.next, time_event_source_latest(b));
592caf
+        t = sleep_between(e, time_event_source_next(a), time_event_source_latest(b));
592caf
         if (d->next == t)
592caf
                 return 0;
592caf
 
592caf
@@ -2802,10 +2994,22 @@ static int process_timer(
592caf
 
592caf
         for (;;) {
592caf
                 s = prioq_peek(d->earliest);
592caf
-                if (!s ||
592caf
-                    s->time.next > n ||
592caf
-                    s->enabled == SD_EVENT_OFF ||
592caf
-                    s->pending)
592caf
+                if (!s || time_event_source_next(s) > n)
592caf
+                        break;
592caf
+
592caf
+                if (s->ratelimited) {
592caf
+                        /* This is an event sources whose ratelimit window has ended. Let's turn it on
592caf
+                         * again. */
592caf
+                        assert(s->ratelimited);
592caf
+
592caf
+                        r = event_source_leave_ratelimit(s);
592caf
+                        if (r < 0)
592caf
+                                return r;
592caf
+
592caf
+                        continue;
592caf
+                }
592caf
+
592caf
+                if (s->enabled == SD_EVENT_OFF || s->pending)
592caf
                         break;
592caf
 
592caf
                 r = source_set_pending(s, true);
592caf
@@ -2851,7 +3055,7 @@ static int process_child(sd_event *e) {
592caf
                 if (s->pending)
592caf
                         continue;
592caf
 
592caf
-                if (s->enabled == SD_EVENT_OFF)
592caf
+                if (event_source_is_offline(s))
592caf
                         continue;
592caf
 
592caf
                 zero(s->child.siginfo);
592caf
@@ -3024,7 +3228,7 @@ static int event_inotify_data_process(sd_event *e, struct inotify_data *d) {
592caf
 
592caf
                                 LIST_FOREACH(inotify.by_inode_data, s, inode_data->event_sources) {
592caf
 
592caf
-                                        if (s->enabled == SD_EVENT_OFF)
592caf
+                                        if (event_source_is_offline(s))
592caf
                                                 continue;
592caf
 
592caf
                                         r = source_set_pending(s, true);
592caf
@@ -3060,7 +3264,7 @@ static int event_inotify_data_process(sd_event *e, struct inotify_data *d) {
592caf
                          * sources if IN_IGNORED or IN_UNMOUNT is set. */
592caf
                         LIST_FOREACH(inotify.by_inode_data, s, inode_data->event_sources) {
592caf
 
592caf
-                                if (s->enabled == SD_EVENT_OFF)
592caf
+                                if (event_source_is_offline(s))
592caf
                                         continue;
592caf
 
592caf
                                 if ((d->buffer.ev.mask & (IN_IGNORED|IN_UNMOUNT)) == 0 &&
592caf
@@ -3099,6 +3303,7 @@ static int process_inotify(sd_event *e) {
592caf
 }
592caf
 
592caf
 static int source_dispatch(sd_event_source *s) {
592caf
+        _cleanup_(sd_event_unrefp) sd_event *saved_event = NULL;
592caf
         EventSourceType saved_type;
592caf
         int r = 0;
592caf
 
592caf
@@ -3109,6 +3314,20 @@ static int source_dispatch(sd_event_source *s) {
592caf
          * the event. */
592caf
         saved_type = s->type;
592caf
 
592caf
+        /* Similar, store a reference to the event loop object, so that we can still access it after the
592caf
+         * callback might have invalidated/disconnected the event source. */
592caf
+        saved_event = sd_event_ref(s->event);
592caf
+
592caf
+        /* Check if we hit the ratelimit for this event source, if so, let's disable it. */
592caf
+        assert(!s->ratelimited);
592caf
+        if (!ratelimit_below(&s->rate_limit)) {
592caf
+                r = event_source_enter_ratelimited(s);
592caf
+                if (r < 0)
592caf
+                        return r;
592caf
+
592caf
+                return 1;
592caf
+        }
592caf
+
592caf
         if (!IN_SET(s->type, SOURCE_DEFER, SOURCE_EXIT)) {
592caf
                 r = source_set_pending(s, false);
592caf
                 if (r < 0)
592caf
@@ -3235,7 +3454,7 @@ static int event_prepare(sd_event *e) {
592caf
                 sd_event_source *s;
592caf
 
592caf
                 s = prioq_peek(e->prepare);
592caf
-                if (!s || s->prepare_iteration == e->iteration || s->enabled == SD_EVENT_OFF)
592caf
+                if (!s || s->prepare_iteration == e->iteration || event_source_is_offline(s))
592caf
                         break;
592caf
 
592caf
                 s->prepare_iteration = e->iteration;
592caf
@@ -3269,7 +3488,7 @@ static int dispatch_exit(sd_event *e) {
592caf
         assert(e);
592caf
 
592caf
         p = prioq_peek(e->exit);
592caf
-        if (!p || p->enabled == SD_EVENT_OFF) {
592caf
+        if (!p || event_source_is_offline(p)) {
592caf
                 e->state = SD_EVENT_FINISHED;
592caf
                 return 0;
592caf
         }
592caf
@@ -3291,7 +3510,7 @@ static sd_event_source* event_next_pending(sd_event *e) {
592caf
         if (!p)
592caf
                 return NULL;
592caf
 
592caf
-        if (p->enabled == SD_EVENT_OFF)
592caf
+        if (event_source_is_offline(p))
592caf
                 return NULL;
592caf
 
592caf
         return p;
592caf
@@ -3844,3 +4063,53 @@ _public_ int sd_event_source_get_destroy_callback(sd_event_source *s, sd_event_d
592caf
 
592caf
         return !!s->destroy_callback;
592caf
 }
592caf
+
592caf
+_public_ int sd_event_source_set_ratelimit(sd_event_source *s, uint64_t interval, unsigned burst) {
592caf
+        int r;
592caf
+
592caf
+        assert_return(s, -EINVAL);
592caf
+
592caf
+        /* Turning on ratelimiting on event source types that don't support it, is a loggable offense. Doing
592caf
+         * so is a programming error. */
592caf
+        assert_return(EVENT_SOURCE_CAN_RATE_LIMIT(s->type), -EDOM);
592caf
+
592caf
+        /* When ratelimiting is configured we'll always reset the rate limit state first and start fresh,
592caf
+         * non-ratelimited. */
592caf
+        r = event_source_leave_ratelimit(s);
592caf
+        if (r < 0)
592caf
+                return r;
592caf
+
592caf
+        RATELIMIT_INIT(s->rate_limit, interval, burst);
592caf
+        return 0;
592caf
+}
592caf
+
592caf
+_public_ int sd_event_source_get_ratelimit(sd_event_source *s, uint64_t *ret_interval, unsigned *ret_burst) {
592caf
+        assert_return(s, -EINVAL);
592caf
+
592caf
+        /* Querying whether an event source has ratelimiting configured is not a loggable offsense, hence
592caf
+         * don't use assert_return(). Unlike turning on ratelimiting it's not really a programming error */
592caf
+        if (!EVENT_SOURCE_CAN_RATE_LIMIT(s->type))
592caf
+                return -EDOM;
592caf
+
592caf
+        if (!ratelimit_configured(&s->rate_limit))
592caf
+                return -ENOEXEC;
592caf
+
592caf
+        if (ret_interval)
592caf
+                *ret_interval = s->rate_limit.interval;
592caf
+        if (ret_burst)
592caf
+                *ret_burst = s->rate_limit.burst;
592caf
+
592caf
+        return 0;
592caf
+}
592caf
+
592caf
+_public_ int sd_event_source_is_ratelimited(sd_event_source *s) {
592caf
+        assert_return(s, -EINVAL);
592caf
+
592caf
+        if (!EVENT_SOURCE_CAN_RATE_LIMIT(s->type))
592caf
+                return false;
592caf
+
592caf
+        if (!ratelimit_configured(&s->rate_limit))
592caf
+                return false;
592caf
+
592caf
+        return s->ratelimited;
592caf
+}
592caf
diff --git a/src/systemd/sd-event.h b/src/systemd/sd-event.h
592caf
index 9876be01c6..a17a9b3488 100644
592caf
--- a/src/systemd/sd-event.h
592caf
+++ b/src/systemd/sd-event.h
592caf
@@ -144,6 +144,9 @@ int sd_event_source_get_child_pid(sd_event_source *s, pid_t *pid);
592caf
 int sd_event_source_get_inotify_mask(sd_event_source *s, uint32_t *ret);
592caf
 int sd_event_source_set_destroy_callback(sd_event_source *s, sd_event_destroy_t callback);
592caf
 int sd_event_source_get_destroy_callback(sd_event_source *s, sd_event_destroy_t *ret);
592caf
+int sd_event_source_set_ratelimit(sd_event_source *s, uint64_t interval_usec, unsigned burst);
592caf
+int sd_event_source_get_ratelimit(sd_event_source *s, uint64_t *ret_interval_usec, unsigned *ret_burst);
592caf
+int sd_event_source_is_ratelimited(sd_event_source *s);
592caf
 
592caf
 /* Define helpers so that __attribute__((cleanup(sd_event_unrefp))) and similar may be used. */
592caf
 _SD_DEFINE_POINTER_CLEANUP_FUNC(sd_event, sd_event_unref);