]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - src/core/swap.c
core: add a concept of "dynamic" user ids, that are allocated as long as a service...
[thirdparty/systemd.git] / src / core / swap.c
index 346a5fd7121af758c973fd06e3b71fbbb8594f58..66a318d01f388987006ea39bc4137497eef68c53 100644 (file)
@@ -1,5 +1,3 @@
-/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
-
 /***
   This file is part of systemd.
 
 ***/
 
 #include <errno.h>
-#include <limits.h>
-#include <unistd.h>
-#include <fcntl.h>
 #include <sys/epoll.h>
 #include <sys/stat.h>
-#include <sys/swap.h>
-#include <libudev.h>
+#include <unistd.h>
 
-#include "unit.h"
-#include "swap.h"
-#include "load-fragment.h"
-#include "load-dropin.h"
-#include "unit-name.h"
+#include "libudev.h"
+
+#include "alloc-util.h"
 #include "dbus-swap.h"
-#include "special.h"
-#include "bus-errors.h"
+#include "escape.h"
 #include "exit-status.h"
-#include "def.h"
+#include "fd-util.h"
+#include "formats-util.h"
+#include "fstab-util.h"
+#include "parse-util.h"
 #include "path-util.h"
-#include "virt.h"
+#include "process-util.h"
+#include "special.h"
+#include "string-table.h"
+#include "string-util.h"
+#include "swap.h"
 #include "udev-util.h"
+#include "unit-name.h"
+#include "unit.h"
+#include "virt.h"
 
 static const UnitActiveState state_translation_table[_SWAP_STATE_MAX] = {
         [SWAP_DEAD] = UNIT_INACTIVE,
@@ -64,8 +65,7 @@ static void swap_unset_proc_swaps(Swap *s) {
         if (!s->from_proc_swaps)
                 return;
 
-        free(s->parameters_proc_swaps.what);
-        s->parameters_proc_swaps.what = NULL;
+        s->parameters_proc_swaps.what = mfree(s->parameters_proc_swaps.what);
 
         s->from_proc_swaps = false;
 }
@@ -92,8 +92,7 @@ static int swap_set_devnode(Swap *s, const char *devnode) {
                 else
                         hashmap_remove(swaps, s->devnode);
 
-                free(s->devnode);
-                s->devnode = NULL;
+                s->devnode = mfree(s->devnode);
         }
 
         if (devnode) {
@@ -146,48 +145,49 @@ static void swap_done(Unit *u) {
         swap_unset_proc_swaps(s);
         swap_set_devnode(s, NULL);
 
-        free(s->what);
-        s->what = NULL;
-
-        free(s->parameters_fragment.what);
-        s->parameters_fragment.what = NULL;
-
-        free(s->parameters_fragment.options);
-        s->parameters_fragment.options = NULL;
+        s->what = mfree(s->what);
+        s->parameters_fragment.what = mfree(s->parameters_fragment.what);
+        s->parameters_fragment.options = mfree(s->parameters_fragment.options);
 
         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
         exec_command_done_array(s->exec_command, _SWAP_EXEC_COMMAND_MAX);
         s->control_command = NULL;
 
+        dynamic_creds_unref(&s->dynamic_creds);
+
         swap_unwatch_control_pid(s);
 
         s->timer_event_source = sd_event_source_unref(s->timer_event_source);
 }
 
-static int swap_arm_timer(Swap *s) {
+static int swap_arm_timer(Swap *s, usec_t usec) {
         int r;
 
         assert(s);
 
-        if (s->timeout_usec <= 0) {
-                s->timer_event_source = sd_event_source_unref(s->timer_event_source);
-                return 0;
-        }
-
         if (s->timer_event_source) {
-                r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + s->timeout_usec);
+                r = sd_event_source_set_time(s->timer_event_source, usec);
                 if (r < 0)
                         return r;
 
                 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
         }
 
-        return sd_event_add_time(
+        if (usec == USEC_INFINITY)
+                return 0;
+
+        r = sd_event_add_time(
                         UNIT(s)->manager->event,
                         &s->timer_event_source,
                         CLOCK_MONOTONIC,
-                        now(CLOCK_MONOTONIC) + s->timeout_usec, 0,
+                        usec, 0,
                         swap_dispatch_timer, s);
+        if (r < 0)
+                return r;
+
+        (void) sd_event_source_set_description(s->timer_event_source, "swap-timer");
+
+        return 0;
 }
 
 static int swap_add_device_links(Swap *s) {
@@ -200,7 +200,7 @@ static int swap_add_device_links(Swap *s) {
                 return 0;
 
         if (is_device_path(s->what))
-                return unit_add_node_link(UNIT(s), s->what, UNIT(s)->manager->running_as == SYSTEMD_SYSTEM);
+                return unit_add_node_link(UNIT(s), s->what, MANAGER_IS_SYSTEM(UNIT(s)->manager), UNIT_BINDS_TO);
         else
                 /* File based swap devices need to be ordered after
                  * systemd-remount-fs.service, since they might need a
@@ -209,36 +209,46 @@ static int swap_add_device_links(Swap *s) {
 }
 
 static int swap_add_default_dependencies(Swap *s) {
+        int r;
+
         assert(s);
 
-        if (UNIT(s)->manager->running_as != SYSTEMD_SYSTEM)
+        if (!UNIT(s)->default_dependencies)
+                return 0;
+
+        if (!MANAGER_IS_SYSTEM(UNIT(s)->manager))
                 return 0;
 
-        if (detect_container(NULL) > 0)
+        if (detect_container() > 0)
                 return 0;
 
+        /* swap units generated for the swap dev links are missing the
+         * ordering dep against the swap target. */
+        r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SWAP_TARGET, NULL, true);
+        if (r < 0)
+                return r;
+
         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_UMOUNT_TARGET, NULL, true);
 }
 
 static int swap_verify(Swap *s) {
-        bool b;
         _cleanup_free_ char *e = NULL;
+        int r;
 
         if (UNIT(s)->load_state != UNIT_LOADED)
                 return 0;
 
-        e = unit_name_from_path(s->what, ".swap");
-        if (!e)
-                return log_oom();
+        r = unit_name_from_path(s->what, ".swap", &e);
+        if (r < 0)
+                return log_unit_error_errno(UNIT(s), r, "Failed to generate unit name from path: %m");
 
-        b = unit_has_name(UNIT(s), e);
-        if (!b) {
-                log_unit_error(UNIT(s)->id, "%s: Value of \"What\" and unit name do not match, not loading.", UNIT(s)->id);
+        if (!unit_has_name(UNIT(s), e)) {
+                log_unit_error(UNIT(s), "Value of What= and unit name do not match, not loading.");
                 return -EINVAL;
         }
 
         if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
-                log_unit_error(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.", UNIT(s)->id);
+                log_unit_error(UNIT(s), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing to load.");
                 return -EINVAL;
         }
 
@@ -288,8 +298,11 @@ static int swap_load(Unit *u) {
                                 s->what = strdup(s->parameters_fragment.what);
                         else if (s->parameters_proc_swaps.what)
                                 s->what = strdup(s->parameters_proc_swaps.what);
-                        else
-                                s->what = unit_name_to_path(u->id);
+                        else {
+                                r = unit_name_to_path(u->id, &s->what);
+                                if (r < 0)
+                                        return r;
+                        }
 
                         if (!s->what)
                                 return -ENOMEM;
@@ -323,21 +336,19 @@ static int swap_load(Unit *u) {
                 if (r < 0)
                         return r;
 
-                r = unit_add_default_slice(u, &s->cgroup_context);
+                r = unit_set_default_slice(u);
                 if (r < 0)
                         return r;
 
-                if (UNIT(s)->default_dependencies) {
-                        r = swap_add_default_dependencies(s);
-                        if (r < 0)
-                                return r;
-                }
+                r = swap_add_default_dependencies(s);
+                if (r < 0)
+                        return r;
         }
 
         return swap_verify(s);
 }
 
-static int swap_add_one(
+static int swap_setup_unit(
                 Manager *m,
                 const char *what,
                 const char *what_proc_swaps,
@@ -354,16 +365,18 @@ static int swap_add_one(
         assert(what);
         assert(what_proc_swaps);
 
-        e = unit_name_from_path(what, ".swap");
-        if (!e)
-                return log_oom();
+        r = unit_name_from_path(what, ".swap", &e);
+        if (r < 0)
+                return log_unit_error_errno(u, r, "Failed to generate unit name from path: %m");
 
         u = manager_get_unit(m, e);
 
         if (u &&
             SWAP(u)->from_proc_swaps &&
-            !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps))
+            !path_equal(SWAP(u)->parameters_proc_swaps.what, what_proc_swaps)) {
+                log_error("Swap %s appeared twice with different device paths %s and %s", e, SWAP(u)->parameters_proc_swaps.what, what_proc_swaps);
                 return -EEXIST;
+        }
 
         if (!u) {
                 delete = true;
@@ -378,7 +391,7 @@ static int swap_add_one(
 
                 SWAP(u)->what = strdup(what);
                 if (!SWAP(u)->what) {
-                        r = log_oom();
+                        r = -ENOMEM;
                         goto fail;
                 }
 
@@ -406,11 +419,10 @@ static int swap_add_one(
         p->priority = priority;
 
         unit_add_to_dbus_queue(u);
-
         return 0;
 
 fail:
-        log_unit_warning_errno(e, r, "Failed to load swap unit: %m");
+        log_unit_warning_errno(u, r, "Failed to load swap unit: %m");
 
         if (delete && u)
                 unit_free(u);
@@ -418,7 +430,7 @@ fail:
         return r;
 }
 
-static int swap_process_new_swap(Manager *m, const char *device, int prio, bool set_flags) {
+static int swap_process_new(Manager *m, const char *device, int prio, bool set_flags) {
         _cleanup_udev_device_unref_ struct udev_device *d = NULL;
         struct udev_list_entry *item = NULL, *first = NULL;
         const char *dn;
@@ -427,7 +439,7 @@ static int swap_process_new_swap(Manager *m, const char *device, int prio, bool
 
         assert(m);
 
-        r = swap_add_one(m, device, device, prio, set_flags);
+        r = swap_setup_unit(m, device, device, prio, set_flags);
         if (r < 0)
                 return r;
 
@@ -443,7 +455,7 @@ static int swap_process_new_swap(Manager *m, const char *device, int prio, bool
         /* Add the main device node */
         dn = udev_device_get_devnode(d);
         if (dn && !streq(dn, device))
-                swap_add_one(m, dn, device, prio, set_flags);
+                swap_setup_unit(m, dn, device, prio, set_flags);
 
         /* Add additional units for all symlinks */
         first = udev_device_get_devlinks_list_entry(d);
@@ -464,7 +476,7 @@ static int swap_process_new_swap(Manager *m, const char *device, int prio, bool
                             st.st_rdev != udev_device_get_devnum(d))
                                 continue;
 
-                swap_add_one(m, p, device, prio, set_flags);
+                swap_setup_unit(m, p, device, prio, set_flags);
         }
 
         return r;
@@ -472,6 +484,7 @@ static int swap_process_new_swap(Manager *m, const char *device, int prio, bool
 
 static void swap_set_state(Swap *s, SwapState state) {
         SwapState old_state;
+        Swap *other;
 
         assert(s);
 
@@ -492,13 +505,18 @@ static void swap_set_state(Swap *s, SwapState state) {
         }
 
         if (state != old_state)
-                log_unit_debug(UNIT(s)->id,
-                               "%s changed %s -> %s",
-                               UNIT(s)->id,
-                               swap_state_to_string(old_state),
-                               swap_state_to_string(state));
+                log_unit_debug(UNIT(s), "Changed %s -> %s", swap_state_to_string(old_state), swap_state_to_string(state));
 
         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
+
+        /* If there other units for the same device node have a job
+           queued it might be worth checking again if it is runnable
+           now. This is necessary, since swap_start() refuses
+           operation with EAGAIN if there's already another job for
+           the same device node queued. */
+        LIST_FOREACH_OTHERS(same_devnode, other, s)
+                if (UNIT(other)->job)
+                        job_add_to_run_queue(UNIT(other)->job);
 }
 
 static int swap_coldplug(Unit *u) {
@@ -517,26 +535,29 @@ static int swap_coldplug(Unit *u) {
         if (new_state == s->state)
                 return 0;
 
-        if (new_state == SWAP_ACTIVATING ||
-            new_state == SWAP_ACTIVATING_SIGTERM ||
-            new_state == SWAP_ACTIVATING_SIGKILL ||
-            new_state == SWAP_ACTIVATING_DONE ||
-            new_state == SWAP_DEACTIVATING ||
-            new_state == SWAP_DEACTIVATING_SIGTERM ||
-            new_state == SWAP_DEACTIVATING_SIGKILL) {
-
-                if (s->control_pid <= 0)
-                        return -EBADMSG;
+        if (s->control_pid > 0 &&
+            pid_is_unwaited(s->control_pid) &&
+            IN_SET(new_state,
+                   SWAP_ACTIVATING,
+                   SWAP_ACTIVATING_SIGTERM,
+                   SWAP_ACTIVATING_SIGKILL,
+                   SWAP_ACTIVATING_DONE,
+                   SWAP_DEACTIVATING,
+                   SWAP_DEACTIVATING_SIGTERM,
+                   SWAP_DEACTIVATING_SIGKILL)) {
 
                 r = unit_watch_pid(UNIT(s), s->control_pid);
                 if (r < 0)
                         return r;
 
-                r = swap_arm_timer(s);
+                r = swap_arm_timer(s, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec));
                 if (r < 0)
                         return r;
         }
 
+        if (!IN_SET(new_state, SWAP_DEAD, SWAP_FAILED))
+                (void) unit_setup_dynamic_creds(u);
+
         swap_set_state(s, new_state);
         return 0;
 }
@@ -593,19 +614,30 @@ static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
                 .apply_permissions = true,
                 .apply_chroot      = true,
                 .apply_tty_stdin   = true,
+                .stdin_fd          = -1,
+                .stdout_fd         = -1,
+                .stderr_fd         = -1,
         };
 
         assert(s);
         assert(c);
         assert(_pid);
 
-        unit_realize_cgroup(UNIT(s));
+        (void) unit_realize_cgroup(UNIT(s));
+        if (s->reset_cpu_usage) {
+                (void) unit_reset_cpu_usage(UNIT(s));
+                s->reset_cpu_usage = false;
+        }
 
         r = unit_setup_exec_runtime(UNIT(s));
         if (r < 0)
                 goto fail;
 
-        r = swap_arm_timer(s);
+        r = unit_setup_dynamic_creds(UNIT(s));
+        if (r < 0)
+                return r;
+
+        r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
         if (r < 0)
                 goto fail;
 
@@ -615,12 +647,13 @@ static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
         exec_params.cgroup_path = UNIT(s)->cgroup_path;
         exec_params.cgroup_delegate = s->cgroup_context.delegate;
         exec_params.runtime_prefix = manager_get_runtime_prefix(UNIT(s)->manager);
-        exec_params.unit_id = UNIT(s)->id;
 
-        r = exec_spawn(c,
+        r = exec_spawn(UNIT(s),
+                       c,
                        &s->exec_context,
                        &exec_params,
                        s->exec_runtime,
+                       &s->dynamic_creds,
                        &pid);
         if (r < 0)
                 goto fail;
@@ -636,7 +669,6 @@ static int swap_spawn(Swap *s, ExecCommand *c, pid_t *_pid) {
 
 fail:
         s->timer_event_source = sd_event_source_unref(s->timer_event_source);
-
         return r;
 }
 
@@ -646,12 +678,14 @@ static void swap_enter_dead(Swap *s, SwapResult f) {
         if (f != SWAP_SUCCESS)
                 s->result = f;
 
+        swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD);
+
         exec_runtime_destroy(s->exec_runtime);
         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
 
         exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
 
-        swap_set_state(s, s->result != SWAP_SUCCESS ? SWAP_FAILED : SWAP_DEAD);
+        dynamic_creds_destroy(&s->dynamic_creds);
 }
 
 static void swap_enter_active(Swap *s, SwapResult f) {
@@ -683,7 +717,7 @@ static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) {
                 goto fail;
 
         if (r > 0) {
-                r = swap_arm_timer(s);
+                r = swap_arm_timer(s, usec_add(now(CLOCK_MONOTONIC), s->timeout_usec));
                 if (r < 0)
                         goto fail;
 
@@ -698,80 +732,13 @@ static void swap_enter_signal(Swap *s, SwapState state, SwapResult f) {
         return;
 
 fail:
-        log_unit_warning(UNIT(s)->id,
-                         "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
-
+        log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
         swap_enter_dead(s, SWAP_FAILURE_RESOURCES);
 }
 
-static int mount_find_pri(const char *options, int *ret) {
-        const char *opt;
-        char *end;
-        unsigned long r;
-
-        assert(ret);
-
-        if (!options)
-                return 0;
-
-        opt = mount_test_option(options, "pri");
-        if (!opt)
-                return 0;
-
-        opt += strlen("pri");
-        if (*opt != '=')
-                return -EINVAL;
-
-        errno = 0;
-        r = strtoul(opt + 1, &end, 10);
-        if (errno > 0)
-                return -errno;
-
-        if (end == opt + 1 || (*end != ',' && *end != 0))
-                return -EINVAL;
-
-        *ret = (int) r;
-        return 1;
-}
-
-static int mount_find_discard(const char *options, char **ret) {
-        const char *opt;
-        char *ans;
-        size_t len;
-
-        assert(ret);
-
-        if (!options)
-                return 0;
-
-        opt = mount_test_option(options, "discard");
-        if (!opt)
-                return 0;
-
-        opt += strlen("discard");
-        if (*opt == ',' || *opt == '\0')
-                ans = strdup("all");
-        else {
-                if (*opt != '=')
-                        return -EINVAL;
-
-                len = strcspn(opt + 1, ",");
-                if (len == 0)
-                        return -EINVAL;
-
-                ans = strndup(opt + 1, len);
-        }
-
-        if (!ans)
-                return -ENOMEM;
-
-        *ret = ans;
-        return 1;
-}
-
 static void swap_enter_activating(Swap *s) {
-        _cleanup_free_ char *discard = NULL;
-        int r, priority = -1;
+        _cleanup_free_ char *opts = NULL;
+        int r;
 
         assert(s);
 
@@ -779,35 +746,31 @@ static void swap_enter_activating(Swap *s) {
         s->control_command = s->exec_command + SWAP_EXEC_ACTIVATE;
 
         if (s->from_fragment) {
-                mount_find_discard(s->parameters_fragment.options, &discard);
+                int priority = -1;
+
+                r = fstab_find_pri(s->parameters_fragment.options, &priority);
+                if (r < 0)
+                        log_warning_errno(r, "Failed to parse swap priority \"%s\", ignoring: %m", s->parameters_fragment.options);
+                else if (r == 1 && s->parameters_fragment.priority >= 0)
+                        log_warning("Duplicate swap priority configuration by Priority and Options fields.");
 
-                priority = s->parameters_fragment.priority;
-                if (priority < 0)
-                        mount_find_pri(s->parameters_fragment.options, &priority);
+                if (r <= 0 && s->parameters_fragment.priority >= 0) {
+                        if (s->parameters_fragment.options)
+                                r = asprintf(&opts, "%s,pri=%i", s->parameters_fragment.options, s->parameters_fragment.priority);
+                        else
+                                r = asprintf(&opts, "pri=%i", s->parameters_fragment.priority);
+                        if (r < 0)
+                                goto fail;
+                }
         }
 
         r = exec_command_set(s->control_command, "/sbin/swapon", NULL);
         if (r < 0)
                 goto fail;
 
-        if (priority >= 0) {
-                char p[DECIMAL_STR_MAX(int)];
-
-                sprintf(p, "%i", priority);
-                r = exec_command_append(s->control_command, "-p", p, NULL);
-                if (r < 0)
-                        goto fail;
-        }
-
-        if (discard && !streq(discard, "none")) {
-                const char *discard_arg;
-
-                if (streq(discard, "all"))
-                        discard_arg = "--discard";
-                else
-                        discard_arg = strappenda("--discard=", discard);
-
-                r = exec_command_append(s->control_command, discard_arg, NULL);
+        if (s->parameters_fragment.options || opts) {
+                r = exec_command_append(s->control_command, "-o",
+                                opts ? : s->parameters_fragment.options, NULL);
                 if (r < 0)
                         goto fail;
         }
@@ -827,9 +790,7 @@ static void swap_enter_activating(Swap *s) {
         return;
 
 fail:
-        log_unit_warning(UNIT(s)->id,
-                         "%s failed to run 'swapon' task: %s",
-                         UNIT(s)->id, strerror(-r));
+        log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapon' task: %m");
         swap_enter_dead(s, SWAP_FAILURE_RESOURCES);
 }
 
@@ -859,14 +820,13 @@ static void swap_enter_deactivating(Swap *s) {
         return;
 
 fail:
-        log_unit_warning(UNIT(s)->id,
-                         "%s failed to run 'swapoff' task: %s",
-                         UNIT(s)->id, strerror(-r));
+        log_unit_warning_errno(UNIT(s), r, "Failed to run 'swapoff' task: %m");
         swap_enter_active(s, SWAP_FAILURE_RESOURCES);
 }
 
 static int swap_start(Unit *u) {
-        Swap *s = SWAP(u);
+        Swap *s = SWAP(u), *other;
+        int r;
 
         assert(s);
 
@@ -885,12 +845,27 @@ static int swap_start(Unit *u) {
 
         assert(s->state == SWAP_DEAD || s->state == SWAP_FAILED);
 
-        if (detect_container(NULL) > 0)
+        if (detect_container() > 0)
                 return -EPERM;
 
+        /* If there's a job for another swap unit for the same node
+         * running, then let's not dispatch this one for now, and wait
+         * until that other job has finished. */
+        LIST_FOREACH_OTHERS(same_devnode, other, s)
+                if (UNIT(other)->job && UNIT(other)->job->state == JOB_RUNNING)
+                        return -EAGAIN;
+
+        r = unit_start_limit_test(u);
+        if (r < 0) {
+                swap_enter_dead(s, SWAP_FAILURE_START_LIMIT_HIT);
+                return r;
+        }
+
         s->result = SWAP_SUCCESS;
+        s->reset_cpu_usage = true;
+
         swap_enter_activating(s);
-        return 0;
+        return 1;
 }
 
 static int swap_stop(Unit *u) {
@@ -909,11 +884,11 @@ static int swap_stop(Unit *u) {
                s->state == SWAP_ACTIVATING_DONE ||
                s->state == SWAP_ACTIVE);
 
-        if (detect_container(NULL) > 0)
+        if (detect_container() > 0)
                 return -EPERM;
 
         swap_enter_deactivating(s);
-        return 0;
+        return 1;
 }
 
 static int swap_serialize(Unit *u, FILE *f, FDSet *fds) {
@@ -946,7 +921,7 @@ static int swap_deserialize_item(Unit *u, const char *key, const char *value, FD
 
                 state = swap_state_from_string(value);
                 if (state < 0)
-                        log_unit_debug(u->id, "Failed to parse state value %s", value);
+                        log_unit_debug(u, "Failed to parse state value: %s", value);
                 else
                         s->deserialized_state = state;
         } else if (streq(key, "result")) {
@@ -954,14 +929,14 @@ static int swap_deserialize_item(Unit *u, const char *key, const char *value, FD
 
                 f = swap_result_from_string(value);
                 if (f < 0)
-                        log_unit_debug(u->id, "Failed to parse result value %s", value);
+                        log_unit_debug(u, "Failed to parse result value: %s", value);
                 else if (f != SWAP_SUCCESS)
                         s->result = f;
         } else if (streq(key, "control-pid")) {
                 pid_t pid;
 
                 if (parse_pid(value, &pid) < 0)
-                        log_unit_debug(u->id, "Failed to parse control-pid value %s", value);
+                        log_unit_debug(u, "Failed to parse control-pid value: %s", value);
                 else
                         s->control_pid = pid;
 
@@ -970,13 +945,13 @@ static int swap_deserialize_item(Unit *u, const char *key, const char *value, FD
 
                 id = swap_exec_command_from_string(value);
                 if (id < 0)
-                        log_unit_debug(u->id, "Failed to parse exec-command value %s", value);
+                        log_unit_debug(u, "Failed to parse exec-command value: %s", value);
                 else {
                         s->control_command_id = id;
                         s->control_command = s->exec_command + id;
                 }
         } else
-                log_unit_debug(u->id, "Unknown serialization key '%s'", key);
+                log_unit_debug(u, "Unknown serialization key: %s", key);
 
         return 0;
 }
@@ -1034,10 +1009,8 @@ static void swap_sigchld_event(Unit *u, pid_t pid, int code, int status) {
                 s->control_command_id = _SWAP_EXEC_COMMAND_INVALID;
         }
 
-        log_unit_full(u->id,
-                      f == SWAP_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
-                      "%s swap process exited, code=%s status=%i",
-                      u->id, sigchld_code_to_string(code), status);
+        log_unit_full(u, f == SWAP_SUCCESS ? LOG_DEBUG : LOG_NOTICE, 0,
+                      "Swap process exited, code=%s status=%i", sigchld_code_to_string(code), status);
 
         switch (s->state) {
 
@@ -1077,38 +1050,38 @@ static int swap_dispatch_timer(sd_event_source *source, usec_t usec, void *userd
 
         case SWAP_ACTIVATING:
         case SWAP_ACTIVATING_DONE:
-                log_unit_warning(UNIT(s)->id, "%s activation timed out. Stopping.", UNIT(s)->id);
+                log_unit_warning(UNIT(s), "Activation timed out. Stopping.");
                 swap_enter_signal(s, SWAP_ACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
                 break;
 
         case SWAP_DEACTIVATING:
-                log_unit_warning(UNIT(s)->id, "%s deactivation timed out. Stopping.", UNIT(s)->id);
+                log_unit_warning(UNIT(s), "Deactivation timed out. Stopping.");
                 swap_enter_signal(s, SWAP_DEACTIVATING_SIGTERM, SWAP_FAILURE_TIMEOUT);
                 break;
 
         case SWAP_ACTIVATING_SIGTERM:
                 if (s->kill_context.send_sigkill) {
-                        log_unit_warning(UNIT(s)->id, "%s activation timed out. Killing.", UNIT(s)->id);
+                        log_unit_warning(UNIT(s), "Activation timed out. Killing.");
                         swap_enter_signal(s, SWAP_ACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT);
                 } else {
-                        log_unit_warning(UNIT(s)->id, "%s activation timed out. Skipping SIGKILL. Ignoring.", UNIT(s)->id);
+                        log_unit_warning(UNIT(s), "Activation timed out. Skipping SIGKILL. Ignoring.");
                         swap_enter_dead(s, SWAP_FAILURE_TIMEOUT);
                 }
                 break;
 
         case SWAP_DEACTIVATING_SIGTERM:
                 if (s->kill_context.send_sigkill) {
-                        log_unit_warning(UNIT(s)->id, "%s deactivation timed out. Killing.", UNIT(s)->id);
+                        log_unit_warning(UNIT(s), "Deactivation timed out. Killing.");
                         swap_enter_signal(s, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILURE_TIMEOUT);
                 } else {
-                        log_unit_warning(UNIT(s)->id, "%s deactivation timed out. Skipping SIGKILL. Ignoring.", UNIT(s)->id);
+                        log_unit_warning(UNIT(s), "Deactivation timed out. Skipping SIGKILL. Ignoring.");
                         swap_enter_dead(s, SWAP_FAILURE_TIMEOUT);
                 }
                 break;
 
         case SWAP_ACTIVATING_SIGKILL:
         case SWAP_DEACTIVATING_SIGKILL:
-                log_unit_warning(UNIT(s)->id, "%s swap process still around after SIGKILL. Ignoring.", UNIT(s)->id);
+                log_unit_warning(UNIT(s), "Swap process still around after SIGKILL. Ignoring.");
                 swap_enter_dead(s, SWAP_FAILURE_TIMEOUT);
                 break;
 
@@ -1144,15 +1117,16 @@ static int swap_load_proc_swaps(Manager *m, bool set_flags) {
                         if (k == EOF)
                                 break;
 
-                        log_warning("Failed to parse /proc/swaps:%u", i);
+                        log_warning("Failed to parse /proc/swaps:%u.", i);
                         continue;
                 }
 
-                d = cunescape(dev);
-                if (!d)
-                        return -ENOMEM;
+                if (cunescape(dev, UNESCAPE_RELAX, &d) < 0)
+                        return log_oom();
+
+                device_found_node(m, d, true, DEVICE_FOUND_SWAP, set_flags);
 
-                k = swap_process_new_swap(m, d, prio, set_flags);
+                k = swap_process_new(m, d, prio, set_flags);
                 if (k < 0)
                         r = k;
         }
@@ -1204,6 +1178,9 @@ static int swap_dispatch_io(sd_event_source *source, int fd, uint32_t revents, v
                                 break;
                         }
 
+                        if (swap->what)
+                                device_found_node(m, swap->what, false, DEVICE_FOUND_SWAP, true);
+
                 } else if (swap->just_activated) {
 
                         /* New swap entry */
@@ -1248,15 +1225,11 @@ static Unit *swap_following(Unit *u) {
         if (s->from_fragment)
                 return NULL;
 
-        LIST_FOREACH_AFTER(same_devnode, other, s)
+        LIST_FOREACH_OTHERS(same_devnode, other, s)
                 if (other->from_fragment)
                         return UNIT(other);
 
-        LIST_FOREACH_BEFORE(same_devnode, other, s)
-                if (other->from_fragment)
-                        return UNIT(other);
-
-        /* Otherwise make everybody follow the unit that's named after
+        /* Otherwise, make everybody follow the unit that's named after
          * the swap device in the kernel */
 
         if (streq_ptr(s->what, s->devnode))
@@ -1294,13 +1267,7 @@ static int swap_following_set(Unit *u, Set **_set) {
         if (!set)
                 return -ENOMEM;
 
-        LIST_FOREACH_AFTER(same_devnode, other, s) {
-                r = set_put(set, other);
-                if (r < 0)
-                        goto fail;
-        }
-
-        LIST_FOREACH_BEFORE(same_devnode, other, s) {
+        LIST_FOREACH_OTHERS(same_devnode, other, s) {
                 r = set_put(set, other);
                 if (r < 0)
                         goto fail;
@@ -1319,49 +1286,56 @@ static void swap_shutdown(Manager *m) {
 
         m->swap_event_source = sd_event_source_unref(m->swap_event_source);
 
-        if (m->proc_swaps) {
-                fclose(m->proc_swaps);
-                m->proc_swaps = NULL;
-        }
+        m->proc_swaps = safe_fclose(m->proc_swaps);
 
-        hashmap_free(m->swaps_by_devnode);
-        m->swaps_by_devnode = NULL;
+        m->swaps_by_devnode = hashmap_free(m->swaps_by_devnode);
 }
 
-static int swap_enumerate(Manager *m) {
+static void swap_enumerate(Manager *m) {
         int r;
 
         assert(m);
 
         if (!m->proc_swaps) {
                 m->proc_swaps = fopen("/proc/swaps", "re");
-                if (!m->proc_swaps)
-                        return errno == ENOENT ? 0 : -errno;
+                if (!m->proc_swaps) {
+                        if (errno == ENOENT)
+                                log_debug("Not swap enabled, skipping enumeration");
+                        else
+                                log_error_errno(errno, "Failed to open /proc/swaps: %m");
+
+                        return;
+                }
 
                 r = sd_event_add_io(m->event, &m->swap_event_source, fileno(m->proc_swaps), EPOLLPRI, swap_dispatch_io, m);
-                if (r < 0)
+                if (r < 0) {
+                        log_error_errno(r, "Failed to watch /proc/swaps: %m");
                         goto fail;
+                }
 
                 /* Dispatch this before we dispatch SIGCHLD, so that
                  * we always get the events from /proc/swaps before
                  * the SIGCHLD of /sbin/swapon. */
                 r = sd_event_source_set_priority(m->swap_event_source, -10);
-                if (r < 0)
+                if (r < 0) {
+                        log_error_errno(r, "Failed to change /proc/swaps priority: %m");
                         goto fail;
+                }
+
+                (void) sd_event_source_set_description(m->swap_event_source, "swap-proc");
         }
 
         r = swap_load_proc_swaps(m, false);
         if (r < 0)
                 goto fail;
 
-        return 0;
+        return;
 
 fail:
         swap_shutdown(m);
-        return r;
 }
 
-int swap_process_new_device(Manager *m, struct udev_device *dev) {
+int swap_process_device_new(Manager *m, struct udev_device *dev) {
         struct udev_list_entry *item = NULL, *first = NULL;
         _cleanup_free_ char *e = NULL;
         const char *dn;
@@ -1375,9 +1349,9 @@ int swap_process_new_device(Manager *m, struct udev_device *dev) {
         if (!dn)
                 return 0;
 
-        e = unit_name_from_path(dn, ".swap");
-        if (!e)
-                return -ENOMEM;
+        r = unit_name_from_path(dn, ".swap", &e);
+        if (r < 0)
+                return r;
 
         s = hashmap_get(m->units, e);
         if (s)
@@ -1386,15 +1360,14 @@ int swap_process_new_device(Manager *m, struct udev_device *dev) {
         first = udev_device_get_devlinks_list_entry(dev);
         udev_list_entry_foreach(item, first) {
                 _cleanup_free_ char *n = NULL;
+                int q;
 
-                n = unit_name_from_path(udev_list_entry_get_name(item), ".swap");
-                if (!n)
-                        return -ENOMEM;
+                q = unit_name_from_path(udev_list_entry_get_name(item), ".swap", &n);
+                if (q < 0)
+                        return q;
 
                 s = hashmap_get(m->units, n);
                 if (s) {
-                        int q;
-
                         q = swap_set_devnode(s, dn);
                         if (q < 0)
                                 r = q;
@@ -1404,7 +1377,7 @@ int swap_process_new_device(Manager *m, struct udev_device *dev) {
         return r;
 }
 
-int swap_process_removed_device(Manager *m, struct udev_device *dev) {
+int swap_process_device_remove(Manager *m, struct udev_device *dev) {
         const char *dn;
         int r = 0;
         Swap *s;
@@ -1439,34 +1412,46 @@ static int swap_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
         return unit_kill_common(u, who, signo, -1, SWAP(u)->control_pid, error);
 }
 
-static int swap_get_timeout(Unit *u, uint64_t *timeout) {
+static int swap_get_timeout(Unit *u, usec_t *timeout) {
         Swap *s = SWAP(u);
+        usec_t t;
         int r;
 
         if (!s->timer_event_source)
                 return 0;
 
-        r = sd_event_source_get_time(s->timer_event_source, timeout);
+        r = sd_event_source_get_time(s->timer_event_source, &t);
         if (r < 0)
                 return r;
+        if (t == USEC_INFINITY)
+                return 0;
 
+        *timeout = t;
         return 1;
 }
 
-static const char* const swap_state_table[_SWAP_STATE_MAX] = {
-        [SWAP_DEAD] = "dead",
-        [SWAP_ACTIVATING] = "activating",
-        [SWAP_ACTIVATING_DONE] = "activating-done",
-        [SWAP_ACTIVE] = "active",
-        [SWAP_DEACTIVATING] = "deactivating",
-        [SWAP_ACTIVATING_SIGTERM] = "activating-sigterm",
-        [SWAP_ACTIVATING_SIGKILL] = "activating-sigkill",
-        [SWAP_DEACTIVATING_SIGTERM] = "deactivating-sigterm",
-        [SWAP_DEACTIVATING_SIGKILL] = "deactivating-sigkill",
-        [SWAP_FAILED] = "failed"
-};
+static bool swap_supported(void) {
+        static int supported = -1;
+
+        /* If swap support is not available in the kernel, or we are
+         * running in a container we don't support swap units, and any
+         * attempts to starting one should fail immediately. */
 
-DEFINE_STRING_TABLE_LOOKUP(swap_state, SwapState);
+        if (supported < 0)
+                supported =
+                        access("/proc/swaps", F_OK) >= 0 &&
+                        detect_container() <= 0;
+
+        return supported;
+}
+
+static int swap_control_pid(Unit *u) {
+        Swap *s = SWAP(u);
+
+        assert(s);
+
+        return s->control_pid;
+}
 
 static const char* const swap_exec_command_table[_SWAP_EXEC_COMMAND_MAX] = {
         [SWAP_EXEC_ACTIVATE] = "ExecActivate",
@@ -1481,7 +1466,8 @@ static const char* const swap_result_table[_SWAP_RESULT_MAX] = {
         [SWAP_FAILURE_TIMEOUT] = "timeout",
         [SWAP_FAILURE_EXIT_CODE] = "exit-code",
         [SWAP_FAILURE_SIGNAL] = "signal",
-        [SWAP_FAILURE_CORE_DUMP] = "core-dump"
+        [SWAP_FAILURE_CORE_DUMP] = "core-dump",
+        [SWAP_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
 };
 
 DEFINE_STRING_TABLE_LOOKUP(swap_result, SwapResult);
@@ -1492,6 +1478,7 @@ const UnitVTable swap_vtable = {
         .cgroup_context_offset = offsetof(Swap, cgroup_context),
         .kill_context_offset = offsetof(Swap, kill_context),
         .exec_runtime_offset = offsetof(Swap, exec_runtime),
+        .dynamic_creds_offset = offsetof(Swap, dynamic_creds),
 
         .sections =
                 "Unit\0"
@@ -1499,9 +1486,6 @@ const UnitVTable swap_vtable = {
                 "Install\0",
         .private_section = "Swap",
 
-        .no_alias = true,
-        .no_instances = true,
-
         .init = swap_init,
         .load = swap_load,
         .done = swap_done,
@@ -1529,7 +1513,8 @@ const UnitVTable swap_vtable = {
 
         .reset_failed = swap_reset_failed,
 
-        .bus_interface = "org.freedesktop.systemd1.Swap",
+        .control_pid = swap_control_pid,
+
         .bus_vtable = bus_swap_vtable,
         .bus_set_property = bus_swap_set_property,
         .bus_commit_properties = bus_swap_commit_properties,
@@ -1539,6 +1524,7 @@ const UnitVTable swap_vtable = {
 
         .enumerate = swap_enumerate,
         .shutdown = swap_shutdown,
+        .supported = swap_supported,
 
         .status_message_formats = {
                 .starting_stopping = {
@@ -1548,7 +1534,6 @@ const UnitVTable swap_vtable = {
                 .finished_start_job = {
                         [JOB_DONE]       = "Activated swap %s.",
                         [JOB_FAILED]     = "Failed to activate swap %s.",
-                        [JOB_DEPENDENCY] = "Dependency failed for %s.",
                         [JOB_TIMEOUT]    = "Timed out activating swap %s.",
                 },
                 .finished_stop_job = {