chiark / gitweb /
Major cleanup of all leftovers after rebasing on master.
[elogind.git] / src / login / logind.c
index 89e4eee..0b7d965 100644 (file)
 ***/
 
 #include <errno.h>
-#include <pwd.h>
 #include <libudev.h>
 #include <fcntl.h>
 #include <string.h>
 #include <unistd.h>
-#include <sys/epoll.h>
-#include <sys/ioctl.h>
-#include <linux/vt.h>
-#include <sys/timerfd.h>
 
-#include <systemd/sd-daemon.h>
-
-#include "logind.h"
-#include "dbus-common.h"
-#include "dbus-loop.h"
+#include "sd-daemon.h"
 #include "strv.h"
 #include "conf-parser.h"
-#include "mkdir.h"
+#include "bus-util.h"
+#include "bus-error.h"
+#include "udev-util.h"
+#include "formats-util.h"
+#include "signal-util.h"
+#include "label.h"
+#include "logind.h"
+#include "cgroup.h"
+#include "mount-setup.h"
+#include "virt.h"
+
+static void manager_free(Manager *m);
 
-Manager *manager_new(void) {
+static Manager *manager_new(void) {
         Manager *m;
+        int r;
 
         m = new0(Manager, 1);
         if (!m)
                 return NULL;
 
+        m->pin_cgroupfs_fd = -1;
+
         m->console_active_fd = -1;
-        m->bus_fd = -1;
-        m->udev_seat_fd = -1;
-        m->udev_vcsa_fd = -1;
-        m->udev_button_fd = -1;
-        m->epoll_fd = -1;
+
+/// elogind does not support autospawning of vts
+#if 0
         m->reserve_vt_fd = -1;
 
         m->n_autovts = 6;
         m->reserve_vt = 6;
+#endif // 0
+        m->remove_ipc = true;
         m->inhibit_delay_max = 5 * USEC_PER_SEC;
         m->handle_power_key = HANDLE_POWEROFF;
         m->handle_suspend_key = HANDLE_SUSPEND;
         m->handle_hibernate_key = HANDLE_HIBERNATE;
         m->handle_lid_switch = HANDLE_SUSPEND;
+        m->handle_lid_switch_docked = HANDLE_IGNORE;
         m->lid_switch_ignore_inhibited = true;
+        m->holdoff_timeout_usec = 30 * USEC_PER_SEC;
 
-        m->idle_action_fd = -1;
         m->idle_action_usec = 30 * USEC_PER_MINUTE;
         m->idle_action = HANDLE_IGNORE;
         m->idle_action_not_before_usec = now(CLOCK_MONOTONIC);
 
-        m->devices = hashmap_new(string_hash_func, string_compare_func);
-        m->seats = hashmap_new(string_hash_func, string_compare_func);
-        m->sessions = hashmap_new(string_hash_func, string_compare_func);
-        m->users = hashmap_new(trivial_hash_func, trivial_compare_func);
-        m->inhibitors = hashmap_new(string_hash_func, string_compare_func);
-        m->buttons = hashmap_new(string_hash_func, string_compare_func);
-        m->busnames = hashmap_new(string_hash_func, string_compare_func);
+        m->runtime_dir_size = PAGE_ALIGN((size_t) (physical_memory() / 10)); /* 10% */
 
-        m->user_units = hashmap_new(string_hash_func, string_compare_func);
-        m->session_units = hashmap_new(string_hash_func, string_compare_func);
+        m->devices = hashmap_new(&string_hash_ops);
+        m->seats = hashmap_new(&string_hash_ops);
+        m->sessions = hashmap_new(&string_hash_ops);
+        m->users = hashmap_new(NULL);
+        m->inhibitors = hashmap_new(&string_hash_ops);
+        m->buttons = hashmap_new(&string_hash_ops);
 
-        m->session_fds = hashmap_new(trivial_hash_func, trivial_compare_func);
-        m->inhibitor_fds = hashmap_new(trivial_hash_func, trivial_compare_func);
-        m->button_fds = hashmap_new(trivial_hash_func, trivial_compare_func);
+        m->user_units = hashmap_new(&string_hash_ops);
+        m->session_units = hashmap_new(&string_hash_ops);
 
-        if (!m->devices || !m->seats || !m->sessions || !m->users || !m->inhibitors || !m->buttons || !m->busnames ||
-            !m->user_units || !m->session_units ||
-            !m->session_fds || !m->inhibitor_fds || !m->button_fds) {
-                manager_free(m);
-                return NULL;
-        }
+        m->running_as = MANAGER_SYSTEM;
+        m->test_run   = false;
+
+        if (!m->devices || !m->seats || !m->sessions || !m->users || !m->inhibitors || !m->buttons || !m->user_units || !m->session_units)
+                goto fail;
 
         m->kill_exclude_users = strv_new("root", NULL);
-        if (!m->kill_exclude_users) {
-                manager_free(m);
-                return NULL;
+        if (!m->kill_exclude_users)
+                goto fail;
+
+        /* If elogind should be its own controller, mount its cgroup */
+        if (streq(ELOGIND_CGROUP_CONTROLLER, "name=elogind")) {
+                r = mount_setup(true);
+                if (r < 0)
+                        goto fail;
         }
 
+        /* Make cgroups */
+        r = manager_setup_cgroup(m);
+        if (r < 0)
+                goto fail;
+
+        m->suspend_mode = NULL;
+        m->suspend_state = strv_new("mem", "standby", "freeze", NULL);
+        if (!m->suspend_state)
+                goto fail;
+        m->hibernate_mode = strv_new("platform", "shutdown", NULL);
+        if (!m->hibernate_mode)
+                goto fail;
+        m->hibernate_state = strv_new("disk", NULL);
+        if (!m->hibernate_state)
+                goto fail;
+        m->hybrid_sleep_mode = strv_new("suspend", "platform", "shutdown", NULL);
+        if (!m->hybrid_sleep_mode)
+                goto fail;
+        m->hybrid_sleep_state = strv_new("disk", NULL);
+        if (!m->hybrid_sleep_state)
+                goto fail;
+
         m->udev = udev_new();
-        if (!m->udev) {
-                manager_free(m);
-                return NULL;
-        }
+        if (!m->udev)
+                goto fail;
+
+        r = sd_event_default(&m->event);
+        if (r < 0)
+                goto fail;
+
+        sd_event_set_watchdog(m->event, true);
 
         return m;
+
+fail:
+        manager_free(m);
+        return NULL;
 }
 
-void manager_free(Manager *m) {
+static void manager_free(Manager *m) {
         Session *session;
         User *u;
         Device *d;
         Seat *s;
         Inhibitor *i;
         Button *b;
-        char *n;
 
         assert(m);
 
@@ -134,364 +170,79 @@ void manager_free(Manager *m) {
         while ((b = hashmap_first(m->buttons)))
                 button_free(b);
 
-        while ((n = hashmap_first(m->busnames)))
-                free(hashmap_remove(m->busnames, n));
-
         hashmap_free(m->devices);
         hashmap_free(m->seats);
         hashmap_free(m->sessions);
         hashmap_free(m->users);
         hashmap_free(m->inhibitors);
         hashmap_free(m->buttons);
-        hashmap_free(m->busnames);
 
         hashmap_free(m->user_units);
         hashmap_free(m->session_units);
 
-        hashmap_free(m->session_fds);
-        hashmap_free(m->inhibitor_fds);
-        hashmap_free(m->button_fds);
+        sd_event_source_unref(m->idle_action_event_source);
+        sd_event_source_unref(m->inhibit_timeout_source);
+        sd_event_source_unref(m->scheduled_shutdown_timeout_source);
+        sd_event_source_unref(m->nologin_timeout_source);
+        sd_event_source_unref(m->wall_message_timeout_source);
+
+        sd_event_source_unref(m->console_active_event_source);
+        sd_event_source_unref(m->udev_seat_event_source);
+        sd_event_source_unref(m->udev_device_event_source);
+        sd_event_source_unref(m->udev_vcsa_event_source);
+        sd_event_source_unref(m->udev_button_event_source);
+        sd_event_source_unref(m->lid_switch_ignore_event_source);
 
-        if (m->console_active_fd >= 0)
-                close_nointr_nofail(m->console_active_fd);
+        safe_close(m->console_active_fd);
 
-        if (m->udev_seat_monitor)
                 udev_monitor_unref(m->udev_seat_monitor);
-        if (m->udev_device_monitor)
                 udev_monitor_unref(m->udev_device_monitor);
-        if (m->udev_vcsa_monitor)
                 udev_monitor_unref(m->udev_vcsa_monitor);
-        if (m->udev_button_monitor)
                 udev_monitor_unref(m->udev_button_monitor);
 
-        if (m->udev)
                 udev_unref(m->udev);
 
-        if (m->bus) {
-                dbus_connection_flush(m->bus);
-                dbus_connection_close(m->bus);
-                dbus_connection_unref(m->bus);
-        }
+        if (m->unlink_nologin)
+                (void) unlink("/run/nologin");
+
+        bus_verify_polkit_async_registry_free(m->polkit_registry);
 
-        if (m->bus_fd >= 0)
-                close_nointr_nofail(m->bus_fd);
+        sd_bus_unref(m->bus);
+        sd_event_unref(m->event);
 
-        if (m->epoll_fd >= 0)
-                close_nointr_nofail(m->epoll_fd);
+/// elogind does not support autospawning of vts
+#if 0
+        safe_close(m->reserve_vt_fd);
+#endif // 0
 
-        if (m->reserve_vt_fd >= 0)
-                close_nointr_nofail(m->reserve_vt_fd);
+        /* Avoid the creation of new processes forked by the
+         * kernel; at this point, we will not listen to the
+         * signals anyway */
+        if (detect_container(NULL) <= 0)
+                (void) cg_uninstall_release_agent(ELOGIND_CGROUP_CONTROLLER);
 
-        if (m->idle_action_fd >= 0)
-                close_nointr_nofail(m->idle_action_fd);
+        manager_shutdown_cgroup(m, true);
 
         strv_free(m->kill_only_users);
         strv_free(m->kill_exclude_users);
 
-        free(m->action_job);
-        free(m);
-}
-
-int manager_add_device(Manager *m, const char *sysfs, bool master, Device **_device) {
-        Device *d;
-
-        assert(m);
-        assert(sysfs);
-
-        d = hashmap_get(m->devices, sysfs);
-        if (d) {
-                if (_device)
-                        *_device = d;
-
-                /* we support adding master-flags, but not removing them */
-                d->master = d->master || master;
-
-                return 0;
-        }
-
-        d = device_new(m, sysfs, master);
-        if (!d)
-                return -ENOMEM;
-
-        if (_device)
-                *_device = d;
-
-        return 0;
-}
-
-int manager_add_seat(Manager *m, const char *id, Seat **_seat) {
-        Seat *s;
-
-        assert(m);
-        assert(id);
-
-        s = hashmap_get(m->seats, id);
-        if (s) {
-                if (_seat)
-                        *_seat = s;
-
-                return 0;
-        }
-
-        s = seat_new(m, id);
-        if (!s)
-                return -ENOMEM;
-
-        if (_seat)
-                *_seat = s;
-
-        return 0;
-}
-
-int manager_add_session(Manager *m, const char *id, Session **_session) {
-        Session *s;
-
-        assert(m);
-        assert(id);
-
-        s = hashmap_get(m->sessions, id);
-        if (s) {
-                if (_session)
-                        *_session = s;
-
-                return 0;
-        }
-
-        s = session_new(m, id);
-        if (!s)
-                return -ENOMEM;
-
-        if (_session)
-                *_session = s;
-
-        return 0;
-}
-
-int manager_add_user(Manager *m, uid_t uid, gid_t gid, const char *name, User **_user) {
-        User *u;
-
-        assert(m);
-        assert(name);
-
-        u = hashmap_get(m->users, ULONG_TO_PTR((unsigned long) uid));
-        if (u) {
-                if (_user)
-                        *_user = u;
-
-                return 0;
-        }
-
-        u = user_new(m, uid, gid, name);
-        if (!u)
-                return -ENOMEM;
-
-        if (_user)
-                *_user = u;
-
-        return 0;
-}
-
-int manager_add_user_by_name(Manager *m, const char *name, User **_user) {
-        uid_t uid;
-        gid_t gid;
-        int r;
-
-        assert(m);
-        assert(name);
-
-        r = get_user_creds(&name, &uid, &gid, NULL, NULL);
-        if (r < 0)
-                return r;
-
-        return manager_add_user(m, uid, gid, name, _user);
-}
-
-int manager_add_user_by_uid(Manager *m, uid_t uid, User **_user) {
-        struct passwd *p;
-
-        assert(m);
-
-        errno = 0;
-        p = getpwuid(uid);
-        if (!p)
-                return errno ? -errno : -ENOENT;
-
-        return manager_add_user(m, uid, p->pw_gid, p->pw_name, _user);
-}
-
-int manager_add_inhibitor(Manager *m, const char* id, Inhibitor **_inhibitor) {
-        Inhibitor *i;
-
-        assert(m);
-        assert(id);
-
-        i = hashmap_get(m->inhibitors, id);
-        if (i) {
-                if (_inhibitor)
-                        *_inhibitor = i;
-
-                return 0;
-        }
-
-        i = inhibitor_new(m, id);
-        if (!i)
-                return -ENOMEM;
-
-        if (_inhibitor)
-                *_inhibitor = i;
-
-        return 0;
-}
-
-int manager_add_button(Manager *m, const char *name, Button **_button) {
-        Button *b;
-
-        assert(m);
-        assert(name);
-
-        b = hashmap_get(m->buttons, name);
-        if (b) {
-                if (_button)
-                        *_button = b;
-
-                return 0;
-        }
-
-        b = button_new(m, name);
-        if (!b)
-                return -ENOMEM;
-
-        if (_button)
-                *_button = b;
-
-        return 0;
-}
-
-int manager_watch_busname(Manager *m, const char *name) {
-        char *n;
-        int r;
-
-        assert(m);
-        assert(name);
-
-        if (hashmap_get(m->busnames, name))
-                return 0;
+        free(m->scheduled_shutdown_type);
+        free(m->scheduled_shutdown_tty);
+        free(m->wall_message);
 
-        n = strdup(name);
-        if (!n)
-                return -ENOMEM;
-
-        r = hashmap_put(m->busnames, n, n);
-        if (r < 0) {
-                free(n);
-                return r;
-        }
-
-        return 0;
-}
-
-void manager_drop_busname(Manager *m, const char *name) {
-        char *key;
-
-        assert(m);
-        assert(name);
-
-        key = hashmap_remove(m->busnames, name);
-        if (key)
-                free(key);
-}
-
-int manager_process_seat_device(Manager *m, struct udev_device *d) {
-        Device *device;
-        int r;
-
-        assert(m);
-
-        if (streq_ptr(udev_device_get_action(d), "remove")) {
-
-                device = hashmap_get(m->devices, udev_device_get_syspath(d));
-                if (!device)
-                        return 0;
-
-                seat_add_to_gc_queue(device->seat);
-                device_free(device);
-
-        } else {
-                const char *sn;
-                Seat *seat = NULL;
-                bool master;
-
-                sn = udev_device_get_property_value(d, "ID_SEAT");
-                if (isempty(sn))
-                        sn = "seat0";
-
-                if (!seat_name_is_valid(sn)) {
-                        log_warning("Device with invalid seat name %s found, ignoring.", sn);
-                        return 0;
-                }
-
-                /* ignore non-master devices for unknown seats */
-                master = udev_device_has_tag(d, "master-of-seat");
-                if (!master && !(seat = hashmap_get(m->seats, sn)))
-                        return 0;
-
-                r = manager_add_device(m, udev_device_get_syspath(d), master, &device);
-                if (r < 0)
-                        return r;
-
-                if (!seat) {
-                        r = manager_add_seat(m, sn, &seat);
-                        if (r < 0) {
-                                if (!device->seat)
-                                        device_free(device);
-
-                                return r;
-                        }
-                }
-
-                device_attach(device, seat);
-                seat_start(seat);
-        }
+        strv_free(m->suspend_mode);
+        strv_free(m->suspend_state);
+        strv_free(m->hibernate_mode);
+        strv_free(m->hibernate_state);
+        strv_free(m->hybrid_sleep_mode);
+        strv_free(m->hybrid_sleep_state);
 
-        return 0;
-}
-
-int manager_process_button_device(Manager *m, struct udev_device *d) {
-        Button *b;
-
-        int r;
-
-        assert(m);
-
-        if (streq_ptr(udev_device_get_action(d), "remove")) {
-
-                b = hashmap_get(m->buttons, udev_device_get_sysname(d));
-                if (!b)
-                        return 0;
-
-                button_free(b);
-
-        } else {
-                const char *sn;
-
-                r = manager_add_button(m, udev_device_get_sysname(d), &b);
-                if (r < 0)
-                        return r;
-
-                sn = udev_device_get_property_value(d, "ID_SEAT");
-                if (isempty(sn))
-                        sn = "seat0";
-
-                button_set_seat(b, sn);
-                button_open(b);
-        }
-
-        return 0;
+        free(m);
 }
 
-int manager_enumerate_devices(Manager *m) {
+static int manager_enumerate_devices(Manager *m) {
         struct udev_list_entry *item = NULL, *first = NULL;
-        struct udev_enumerate *e;
+        _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
         int r;
 
         assert(m);
@@ -500,47 +251,41 @@ int manager_enumerate_devices(Manager *m) {
          * necessary */
 
         e = udev_enumerate_new(m->udev);
-        if (!e) {
-                r = -ENOMEM;
-                goto finish;
-        }
+        if (!e)
+                return -ENOMEM;
 
         r = udev_enumerate_add_match_tag(e, "master-of-seat");
         if (r < 0)
-                goto finish;
+                return r;
+
+        r = udev_enumerate_add_match_is_initialized(e);
+        if (r < 0)
+                return r;
 
         r = udev_enumerate_scan_devices(e);
         if (r < 0)
-                goto finish;
+                return r;
 
         first = udev_enumerate_get_list_entry(e);
         udev_list_entry_foreach(item, first) {
-                struct udev_device *d;
+                _cleanup_udev_device_unref_ struct udev_device *d = NULL;
                 int k;
 
                 d = udev_device_new_from_syspath(m->udev, udev_list_entry_get_name(item));
-                if (!d) {
-                        r = -ENOMEM;
-                        goto finish;
-                }
+                if (!d)
+                        return -ENOMEM;
 
                 k = manager_process_seat_device(m, d);
-                udev_device_unref(d);
-
                 if (k < 0)
                         r = k;
         }
 
-finish:
-        if (e)
-                udev_enumerate_unref(e);
-
         return r;
 }
 
-int manager_enumerate_buttons(Manager *m) {
+static int manager_enumerate_buttons(Manager *m) {
+        _cleanup_udev_enumerate_unref_ struct udev_enumerate *e = NULL;
         struct udev_list_entry *item = NULL, *first = NULL;
-        struct udev_enumerate *e;
         int r;
 
         assert(m);
@@ -550,53 +295,48 @@ int manager_enumerate_buttons(Manager *m) {
         if (m->handle_power_key == HANDLE_IGNORE &&
             m->handle_suspend_key == HANDLE_IGNORE &&
             m->handle_hibernate_key == HANDLE_IGNORE &&
-            m->handle_lid_switch == HANDLE_IGNORE)
+            m->handle_lid_switch == HANDLE_IGNORE &&
+            m->handle_lid_switch_docked == HANDLE_IGNORE)
                 return 0;
 
         e = udev_enumerate_new(m->udev);
-        if (!e) {
-                r = -ENOMEM;
-                goto finish;
-        }
+        if (!e)
+                return -ENOMEM;
 
         r = udev_enumerate_add_match_subsystem(e, "input");
         if (r < 0)
-                goto finish;
+                return r;
 
         r = udev_enumerate_add_match_tag(e, "power-switch");
         if (r < 0)
-                goto finish;
+                return r;
+
+        r = udev_enumerate_add_match_is_initialized(e);
+        if (r < 0)
+                return r;
 
         r = udev_enumerate_scan_devices(e);
         if (r < 0)
-                goto finish;
+                return r;
 
         first = udev_enumerate_get_list_entry(e);
         udev_list_entry_foreach(item, first) {
-                struct udev_device *d;
+                _cleanup_udev_device_unref_ struct udev_device *d = NULL;
                 int k;
 
                 d = udev_device_new_from_syspath(m->udev, udev_list_entry_get_name(item));
-                if (!d) {
-                        r = -ENOMEM;
-                        goto finish;
-                }
+                if (!d)
+                        return -ENOMEM;
 
                 k = manager_process_button_device(m, d);
-                udev_device_unref(d);
-
                 if (k < 0)
                         r = k;
         }
 
-finish:
-        if (e)
-                udev_enumerate_unref(e);
-
         return r;
 }
 
-int manager_enumerate_seats(Manager *m) {
+static int manager_enumerate_seats(Manager *m) {
         _cleanup_closedir_ DIR *d = NULL;
         struct dirent *de;
         int r = 0;
@@ -612,7 +352,7 @@ int manager_enumerate_seats(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/seats: %m");
+                log_error_errno(errno, "Failed to open /run/systemd/seats: %m");
                 return -errno;
         }
 
@@ -649,7 +389,7 @@ static int manager_enumerate_linger_users(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /var/lib/systemd/linger/: %m");
+                log_error_errno(errno, "Failed to open /var/lib/systemd/linger/: %m");
                 return -errno;
         }
 
@@ -661,7 +401,7 @@ static int manager_enumerate_linger_users(Manager *m) {
 
                 k = manager_add_user_by_name(m, de->d_name, NULL);
                 if (k < 0) {
-                        log_notice("Couldn't add lingering user %s: %s", de->d_name, strerror(-k));
+                        log_notice_errno(k, "Couldn't add lingering user %s: %m", de->d_name);
                         r = k;
                 }
         }
@@ -669,7 +409,7 @@ static int manager_enumerate_linger_users(Manager *m) {
         return r;
 }
 
-int manager_enumerate_users(Manager *m) {
+static int manager_enumerate_users(Manager *m) {
         _cleanup_closedir_ DIR *d = NULL;
         struct dirent *de;
         int r, k;
@@ -685,7 +425,7 @@ int manager_enumerate_users(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/users: %m");
+                log_error_errno(errno, "Failed to open /run/systemd/users: %m");
                 return -errno;
         }
 
@@ -697,7 +437,7 @@ int manager_enumerate_users(Manager *m) {
 
                 k = manager_add_user_by_name(m, de->d_name, &u);
                 if (k < 0) {
-                        log_error("Failed to add user by file name %s: %s", de->d_name, strerror(-k));
+                        log_error_errno(k, "Failed to add user by file name %s: %m", de->d_name);
 
                         r = k;
                         continue;
@@ -713,7 +453,7 @@ int manager_enumerate_users(Manager *m) {
         return r;
 }
 
-int manager_enumerate_sessions(Manager *m) {
+static int manager_enumerate_sessions(Manager *m) {
         _cleanup_closedir_ DIR *d = NULL;
         struct dirent *de;
         int r = 0;
@@ -726,7 +466,7 @@ int manager_enumerate_sessions(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/sessions: %m");
+                log_error_errno(errno, "Failed to open /run/systemd/sessions: %m");
                 return -errno;
         }
 
@@ -745,7 +485,7 @@ int manager_enumerate_sessions(Manager *m) {
 
                 k = manager_add_session(m, de->d_name, &s);
                 if (k < 0) {
-                        log_error("Failed to add session by file name %s: %s", de->d_name, strerror(-k));
+                        log_error_errno(k, "Failed to add session by file name %s: %m", de->d_name);
 
                         r = k;
                         continue;
@@ -761,7 +501,7 @@ int manager_enumerate_sessions(Manager *m) {
         return r;
 }
 
-int manager_enumerate_inhibitors(Manager *m) {
+static int manager_enumerate_inhibitors(Manager *m) {
         _cleanup_closedir_ DIR *d = NULL;
         struct dirent *de;
         int r = 0;
@@ -773,7 +513,7 @@ int manager_enumerate_inhibitors(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /run/systemd/inhibit: %m");
+                log_error_errno(errno, "Failed to open /run/systemd/inhibit: %m");
                 return -errno;
         }
 
@@ -786,7 +526,7 @@ int manager_enumerate_inhibitors(Manager *m) {
 
                 k = manager_add_inhibitor(m, de->d_name, &i);
                 if (k < 0) {
-                        log_notice("Couldn't add inhibitor %s: %s", de->d_name, strerror(-k));
+                        log_notice_errno(k, "Couldn't add inhibitor %s: %m", de->d_name);
                         r = k;
                         continue;
                 }
@@ -799,9 +539,9 @@ int manager_enumerate_inhibitors(Manager *m) {
         return r;
 }
 
-int manager_dispatch_seat_udev(Manager *m) {
-        struct udev_device *d;
-        int r;
+static int manager_dispatch_seat_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+        _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+        Manager *m = userdata;
 
         assert(m);
 
@@ -809,15 +549,13 @@ int manager_dispatch_seat_udev(Manager *m) {
         if (!d)
                 return -ENOMEM;
 
-        r = manager_process_seat_device(m, d);
-        udev_device_unref(d);
-
-        return r;
+        manager_process_seat_device(m, d);
+        return 0;
 }
 
-static int manager_dispatch_device_udev(Manager *m) {
-        struct udev_device *d;
-        int r;
+static int manager_dispatch_device_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+        _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+        Manager *m = userdata;
 
         assert(m);
 
@@ -825,15 +563,15 @@ static int manager_dispatch_device_udev(Manager *m) {
         if (!d)
                 return -ENOMEM;
 
-        r = manager_process_seat_device(m, d);
-        udev_device_unref(d);
-
-        return r;
+        manager_process_seat_device(m, d);
+        return 0;
 }
 
-int manager_dispatch_vcsa_udev(Manager *m) {
-        struct udev_device *d;
-        int r = 0;
+/// UNNEEDED by elogind
+#if 0
+static int manager_dispatch_vcsa_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+        _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+        Manager *m = userdata;
         const char *name;
 
         assert(m);
@@ -848,16 +586,15 @@ int manager_dispatch_vcsa_udev(Manager *m) {
          * VTs, to make sure our auto VTs never go away. */
 
         if (name && startswith(name, "vcsa") && streq_ptr(udev_device_get_action(d), "remove"))
-                r = seat_preallocate_vts(m->vtconsole);
-
-        udev_device_unref(d);
+                seat_preallocate_vts(m->seat0);
 
-        return r;
+        return 0;
 }
+#endif // 0
 
-int manager_dispatch_button_udev(Manager *m) {
-        struct udev_device *d;
-        int r;
+static int manager_dispatch_button_udev(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+        _cleanup_udev_device_unref_ struct udev_device *d = NULL;
+        Manager *m = userdata;
 
         assert(m);
 
@@ -865,95 +602,23 @@ int manager_dispatch_button_udev(Manager *m) {
         if (!d)
                 return -ENOMEM;
 
-        r = manager_process_button_device(m, d);
-        udev_device_unref(d);
-
-        return r;
-}
-
-int manager_dispatch_console(Manager *m) {
-        assert(m);
-
-        if (m->vtconsole)
-                seat_read_active_vt(m->vtconsole);
-
+        manager_process_button_device(m, d);
         return 0;
 }
 
-static int vt_is_busy(int vtnr) {
-        struct vt_stat vt_stat;
-        int r = 0, fd;
-
-        assert(vtnr >= 1);
-
-        /* We explicitly open /dev/tty1 here instead of /dev/tty0. If
-         * we'd open the latter we'd open the foreground tty which
-         * hence would be unconditionally busy. By opening /dev/tty1
-         * we avoid this. Since tty1 is special and needs to be an
-         * explicitly loaded getty or DM this is safe. */
-
-        fd = open_terminal("/dev/tty1", O_RDWR|O_NOCTTY|O_CLOEXEC);
-        if (fd < 0)
-                return -errno;
-
-        if (ioctl(fd, VT_GETSTATE, &vt_stat) < 0)
-                r = -errno;
-        else
-                r = !!(vt_stat.v_state & (1 << vtnr));
-
-        close_nointr_nofail(fd);
-
-        return r;
-}
-
-int manager_spawn_autovt(Manager *m, int vtnr) {
-        int r;
-        char *name = NULL;
-        const char *mode = "fail";
+static int manager_dispatch_console(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
+        Manager *m = userdata;
 
         assert(m);
-        assert(vtnr >= 1);
-
-        if ((unsigned) vtnr > m->n_autovts &&
-            (unsigned) vtnr != m->reserve_vt)
-                return 0;
-
-        if ((unsigned) vtnr != m->reserve_vt) {
-                /* If this is the reserved TTY, we'll start the getty
-                 * on it in any case, but otherwise only if it is not
-                 * busy. */
-
-                r = vt_is_busy(vtnr);
-                if (r < 0)
-                        return r;
-                else if (r > 0)
-                        return -EBUSY;
-        }
+        assert(m->seat0);
+        assert(m->console_active_fd == fd);
 
-        if (asprintf(&name, "autovt@tty%i.service", vtnr) < 0) {
-                log_error("Could not allocate service name.");
-                r = -ENOMEM;
-                goto finish;
-        }
-
-        r = bus_method_call_with_reply (
-                        m->bus,
-                        "org.freedesktop.systemd1",
-                        "/org/freedesktop/systemd1",
-                        "org.freedesktop.systemd1.Manager",
-                        "StartUnit",
-                        NULL,
-                        NULL,
-                        DBUS_TYPE_STRING, &name,
-                        DBUS_TYPE_STRING, &mode,
-                        DBUS_TYPE_INVALID);
-
-finish:
-        free(name);
-
-        return r;
+        seat_read_active_vt(m->seat0);
+        return 0;
 }
 
+/// UNNEEDED by elogind
+#if 0
 static int manager_reserve_vt(Manager *m) {
         _cleanup_free_ char *p = NULL;
 
@@ -970,227 +635,200 @@ static int manager_reserve_vt(Manager *m) {
 
                 /* Don't complain on VT-less systems */
                 if (errno != ENOENT)
-                        log_warning("Failed to pin reserved VT: %m");
+                        log_warning_errno(errno, "Failed to pin reserved VT: %m");
                 return -errno;
         }
 
         return 0;
 }
+#endif // 0
 
-int manager_get_session_by_pid(Manager *m, pid_t pid, Session **session) {
-        _cleanup_free_ char *unit = NULL;
+static int signal_agent_released(sd_bus_message *message, void *userdata, sd_bus_error *error) {
+        Manager *m = userdata;
         Session *s;
+        const char *cgroup;
         int r;
 
+        assert(message);
         assert(m);
-        assert(pid >= 1);
-        assert(session);
 
-        r = cg_pid_get_unit(pid, &unit);
-        if (r < 0)
-                return r;
-
-        s = hashmap_get(m->session_units, unit);
-        if (!s)
+        r = sd_bus_message_read(message, "s", &cgroup);
+        if (r < 0) {
+                bus_log_parse_error(r);
                 return 0;
+        }
 
-        *session = s;
-        return 1;
-}
-
-int manager_get_user_by_pid(Manager *m, pid_t pid, User **user) {
-        _cleanup_free_ char *unit = NULL;
-        User *u;
-        int r;
-
-        assert(m);
-        assert(pid >= 1);
-        assert(user);
+        s = hashmap_get(m->sessions, cgroup);
 
-        r = cg_pid_get_slice(pid, &unit);
-        if (r < 0)
-                return r;
-
-        u = hashmap_get(m->user_units, unit);
-        if (!u)
+        if (!s) {
+                log_warning("Session not found: %s", cgroup);
                 return 0;
-
-        *user = u;
-        return 1;
-}
-
-static void manager_dispatch_other(Manager *m, int fd) {
-        Session *s;
-        Inhibitor *i;
-        Button *b;
-
-        assert_se(m);
-        assert_se(fd >= 0);
-
-        s = hashmap_get(m->session_fds, INT_TO_PTR(fd + 1));
-        if (s) {
-                assert(s->fifo_fd == fd);
-                session_remove_fifo(s);
-                session_stop(s);
-                return;
-        }
-
-        i = hashmap_get(m->inhibitor_fds, INT_TO_PTR(fd + 1));
-        if (i) {
-                assert(i->fifo_fd == fd);
-                inhibitor_stop(i);
-                inhibitor_free(i);
-                return;
         }
 
-        b = hashmap_get(m->button_fds, INT_TO_PTR(fd + 1));
-        if (b) {
-                assert(b->fd == fd);
-                button_process(b);
-                return;
-        }
+        session_finalize(s);
+        session_free(s);
 
-        assert_not_reached("Got event for unknown fd");
+        return 0;
 }
 
 static int manager_connect_bus(Manager *m) {
-        DBusError error;
+        _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
         int r;
-        struct epoll_event ev = {
-                .events = EPOLLIN,
-                .data.u32 = FD_BUS,
-        };
 
         assert(m);
         assert(!m->bus);
-        assert(m->bus_fd < 0);
 
-        dbus_error_init(&error);
+        r = sd_bus_default_system(&m->bus);
+        if (r < 0)
+                return log_error_errno(r, "Failed to connect to system bus: %m");
 
-        m->bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
-        if (!m->bus) {
-                log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
-                r = -ECONNREFUSED;
-                goto fail;
-        }
+        r = sd_bus_add_object_vtable(m->bus, NULL, "/org/freedesktop/login1", "org.freedesktop.login1.Manager", manager_vtable, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add manager object vtable: %m");
 
-        if (!dbus_connection_register_object_path(m->bus, "/org/freedesktop/login1", &bus_manager_vtable, m) ||
-            !dbus_connection_register_fallback(m->bus, "/org/freedesktop/login1/seat", &bus_seat_vtable, m) ||
-            !dbus_connection_register_fallback(m->bus, "/org/freedesktop/login1/session", &bus_session_vtable, m) ||
-            !dbus_connection_register_fallback(m->bus, "/org/freedesktop/login1/user", &bus_user_vtable, m) ||
-            !dbus_connection_add_filter(m->bus, bus_message_filter, m, NULL)) {
-                r = log_oom();
-                goto fail;
-        }
+        /* elogind relies on signals from its release agent */
+        r = sd_bus_add_match(m->bus, NULL,
+                             "type='signal',"
+                             "interface='org.freedesktop.elogind.Agent',"
+                             "member='Released',"
+                             "path='/org/freedesktop/elogind/agent'",
+                             signal_agent_released, m);
 
-        dbus_bus_add_match(m->bus,
-                           "type='signal',"
-                           "sender='"DBUS_SERVICE_DBUS"',"
-                           "interface='"DBUS_INTERFACE_DBUS"',"
-                           "member='NameOwnerChanged',"
-                           "path='"DBUS_PATH_DBUS"'",
-                           &error);
-        if (dbus_error_is_set(&error)) {
-                log_error("Failed to add match for NameOwnerChanged: %s", bus_error_message(&error));
-                dbus_error_free(&error);
-        }
+        r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/seat", "org.freedesktop.login1.Seat", seat_vtable, seat_object_find, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add seat object vtable: %m");
 
-        dbus_bus_add_match(m->bus,
-                           "type='signal',"
-                           "sender='org.freedesktop.systemd1',"
-                           "interface='org.freedesktop.systemd1.Manager',"
-                           "member='JobRemoved',"
-                           "path='/org/freedesktop/systemd1'",
-                           &error);
-        if (dbus_error_is_set(&error)) {
-                log_error("Failed to add match for JobRemoved: %s", bus_error_message(&error));
-                dbus_error_free(&error);
-        }
+        r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/seat", seat_node_enumerator, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add seat enumerator: %m");
 
-        dbus_bus_add_match(m->bus,
-                           "type='signal',"
-                           "sender='org.freedesktop.systemd1',"
-                           "interface='org.freedesktop.systemd1.Manager',"
-                           "member='UnitRemoved',"
-                           "path='/org/freedesktop/systemd1'",
-                           &error);
-        if (dbus_error_is_set(&error)) {
-                log_error("Failed to add match for UnitRemoved: %s", bus_error_message(&error));
-                dbus_error_free(&error);
-        }
+        r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/session", "org.freedesktop.login1.Session", session_vtable, session_object_find, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add session object vtable: %m");
 
-        dbus_bus_add_match(m->bus,
-                           "type='signal',"
-                           "sender='org.freedesktop.systemd1',"
-                           "interface='org.freedesktop.DBus.Properties',"
-                           "member='PropertiesChanged'",
-                           &error);
-        if (dbus_error_is_set(&error)) {
-                log_error("Failed to add match for PropertiesChanged: %s", bus_error_message(&error));
-                dbus_error_free(&error);
-        }
+        r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/session", session_node_enumerator, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add session enumerator: %m");
 
-        dbus_bus_add_match(m->bus,
-                           "type='signal',"
-                           "sender='org.freedesktop.systemd1',"
-                           "interface='org.freedesktop.systemd1.Manager',"
-                           "member='Reloading',"
-                           "path='/org/freedesktop/systemd1'",
-                           &error);
-        if (dbus_error_is_set(&error)) {
-                log_error("Failed to add match for Reloading: %s", bus_error_message(&error));
-                dbus_error_free(&error);
-        }
+        r = sd_bus_add_fallback_vtable(m->bus, NULL, "/org/freedesktop/login1/user", "org.freedesktop.login1.User", user_vtable, user_object_find, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add user object vtable: %m");
+
+        r = sd_bus_add_node_enumerator(m->bus, NULL, "/org/freedesktop/login1/user", user_node_enumerator, m);
+        if (r < 0)
+                return log_error_errno(r, "Failed to add user enumerator: %m");
+
+/// elogind does not support systemd as PID 1
+#if 0
+        r = sd_bus_add_match(m->bus,
+                             NULL,
+                             "type='signal',"
+                             "sender='org.freedesktop.systemd1',"
+                             "interface='org.freedesktop.systemd1.Manager',"
+                             "member='JobRemoved',"
+                             "path='/org/freedesktop/systemd1'",
+                             match_job_removed, m);
+        if (r < 0)
+                log_warning_errno(r, "Failed to add match for JobRemoved: %m");
+
+        r = sd_bus_add_match(m->bus,
+                             NULL,
+                             "type='signal',"
+                             "sender='org.freedesktop.systemd1',"
+                             "interface='org.freedesktop.systemd1.Manager',"
+                             "member='UnitRemoved',"
+                             "path='/org/freedesktop/systemd1'",
+                             match_unit_removed, m);
+        if (r < 0)
+                log_warning_errno(r, "Failed to add match for UnitRemoved: %m");
+
+        r = sd_bus_add_match(m->bus,
+                             NULL,
+                             "type='signal',"
+                             "sender='org.freedesktop.systemd1',"
+                             "interface='org.freedesktop.DBus.Properties',"
+                             "member='PropertiesChanged'",
+                             match_properties_changed, m);
+        if (r < 0)
+                log_warning_errno(r, "Failed to add match for PropertiesChanged: %m");
+
+        r = sd_bus_add_match(m->bus,
+                             NULL,
+                             "type='signal',"
+                             "sender='org.freedesktop.systemd1',"
+                             "interface='org.freedesktop.systemd1.Manager',"
+                             "member='Reloading',"
+                             "path='/org/freedesktop/systemd1'",
+                             match_reloading, m);
+        if (r < 0)
+                log_warning_errno(r, "Failed to add match for Reloading: %m");
 
-        r = bus_method_call_with_reply(
+        r = sd_bus_call_method(
                         m->bus,
                         "org.freedesktop.systemd1",
                         "/org/freedesktop/systemd1",
                         "org.freedesktop.systemd1.Manager",
                         "Subscribe",
-                        NULL,
                         &error,
-                        DBUS_TYPE_INVALID);
-        if (r < 0) {
-                log_error("Failed to enable subscription: %s", bus_error(&error, r));
-                dbus_error_free(&error);
-        }
+                        NULL, NULL);
+        if (r < 0)
+                log_notice("Failed to enable subscription: %s", bus_error_message(&error, r));
+#endif // 0
 
-        r = dbus_bus_request_name(m->bus, "org.freedesktop.login1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
-        if (dbus_error_is_set(&error)) {
-                log_error("Failed to register name on bus: %s", bus_error_message(&error));
-                r = -EIO;
-                goto fail;
-        }
+        r = sd_bus_request_name(m->bus, "org.freedesktop.login1", 0);
+        if (r < 0)
+                return log_error_errno(r, "Failed to register name: %m");
 
-        if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)  {
-                log_error("Failed to acquire name.");
-                r = -EEXIST;
-                goto fail;
-        }
+        r = sd_bus_attach_event(m->bus, m->event, 0);
+        if (r < 0)
+                return log_error_errno(r, "Failed to attach bus to event loop: %m");
 
-        m->bus_fd = bus_loop_open(m->bus);
-        if (m->bus_fd < 0) {
-                r = m->bus_fd;
-                goto fail;
+        return 0;
+}
+
+static int manager_vt_switch(sd_event_source *src, const struct signalfd_siginfo *si, void *data) {
+        Manager *m = data;
+        Session *active, *iter;
+
+        /*
+         * We got a VT-switch signal and we have to acknowledge it immediately.
+         * Preferably, we'd just use m->seat0->active->vtfd, but unfortunately,
+         * old user-space might run multiple sessions on a single VT, *sigh*.
+         * Therefore, we have to iterate all sessions and find one with a vtfd
+         * on the requested VT.
+         * As only VTs with active controllers have VT_PROCESS set, our current
+         * notion of the active VT might be wrong (for instance if the switch
+         * happens while we setup VT_PROCESS). Therefore, read the current VT
+         * first and then use s->active->vtnr as reference. Note that this is
+         * not racy, as no further VT-switch can happen as long as we're in
+         * synchronous VT_PROCESS mode.
+         */
+
+        assert(m->seat0);
+        seat_read_active_vt(m->seat0);
+
+        active = m->seat0->active;
+        if (!active || active->vtnr < 1) {
+                log_warning("Received VT_PROCESS signal without a registered session on that VT.");
+                return 0;
         }
 
-        if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->bus_fd, &ev) < 0)
-                goto fail;
+        if (active->vtfd >= 0) {
+                session_leave_vt(active);
+        } else {
+                LIST_FOREACH(sessions_by_seat, iter, m->seat0->sessions) {
+                        if (iter->vtnr == active->vtnr && iter->vtfd >= 0) {
+                                session_leave_vt(iter);
+                                break;
+                        }
+                }
+        }
 
         return 0;
-
-fail:
-        dbus_error_free(&error);
-
-        return r;
 }
 
 static int manager_connect_console(Manager *m) {
-        struct epoll_event ev = {
-                .events = 0,
-                .data.u32 = FD_CONSOLE,
-        };
+        int r;
 
         assert(m);
         assert(m->console_active_fd < 0);
@@ -1198,10 +836,8 @@ static int manager_connect_console(Manager *m) {
         /* On certain architectures (S390 and Xen, and containers),
            /dev/tty0 does not exist, so don't fail if we can't open
            it. */
-        if (access("/dev/tty0", F_OK) < 0) {
-                m->console_active_fd = -1;
+        if (access("/dev/tty0", F_OK) < 0)
                 return 0;
-        }
 
         m->console_active_fd = open("/sys/class/tty/tty0/active", O_RDONLY|O_NOCTTY|O_CLOEXEC);
         if (m->console_active_fd < 0) {
@@ -1211,22 +847,40 @@ static int manager_connect_console(Manager *m) {
                 if (errno == ENOENT)
                         return 0;
 
-                log_error("Failed to open /sys/class/tty/tty0/active: %m");
+                log_error_errno(errno, "Failed to open /sys/class/tty/tty0/active: %m");
                 return -errno;
         }
 
-        if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->console_active_fd, &ev) < 0)
-                return -errno;
+        r = sd_event_add_io(m->event, &m->console_active_event_source, m->console_active_fd, 0, manager_dispatch_console, m);
+        if (r < 0) {
+                log_error("Failed to watch foreground console");
+                return r;
+        }
+
+        /*
+         * SIGRTMIN is used as global VT-release signal, SIGRTMIN + 1 is used
+         * as VT-acquire signal. We ignore any acquire-events (yes, we still
+         * have to provide a valid signal-number for it!) and acknowledge all
+         * release events immediately.
+         */
+
+        if (SIGRTMIN + 1 > SIGRTMAX) {
+                log_error("Not enough real-time signals available: %u-%u", SIGRTMIN, SIGRTMAX);
+                return -EINVAL;
+        }
+
+        assert_se(ignore_signals(SIGRTMIN + 1, -1) >= 0);
+        assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGRTMIN, -1) >= 0);
+
+        r = sd_event_add_signal(m->event, NULL, SIGRTMIN, manager_vt_switch, m);
+        if (r < 0)
+                return r;
 
         return 0;
 }
 
 static int manager_connect_udev(Manager *m) {
         int r;
-        struct epoll_event ev = {
-                .events = EPOLLIN,
-                .data.u32 = FD_SEAT_UDEV,
-        };
 
         assert(m);
         assert(!m->udev_seat_monitor);
@@ -1246,10 +900,9 @@ static int manager_connect_udev(Manager *m) {
         if (r < 0)
                 return r;
 
-        m->udev_seat_fd = udev_monitor_get_fd(m->udev_seat_monitor);
-
-        if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_seat_fd, &ev) < 0)
-                return -errno;
+        r = sd_event_add_io(m->event, &m->udev_seat_event_source, udev_monitor_get_fd(m->udev_seat_monitor), EPOLLIN, manager_dispatch_seat_udev, m);
+        if (r < 0)
+                return r;
 
         m->udev_device_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
         if (!m->udev_device_monitor)
@@ -1271,18 +924,16 @@ static int manager_connect_udev(Manager *m) {
         if (r < 0)
                 return r;
 
-        m->udev_device_fd = udev_monitor_get_fd(m->udev_device_monitor);
-        zero(ev);
-        ev.events = EPOLLIN;
-        ev.data.u32 = FD_DEVICE_UDEV;
-        if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_device_fd, &ev) < 0)
-                return -errno;
+        r = sd_event_add_io(m->event, &m->udev_device_event_source, udev_monitor_get_fd(m->udev_device_monitor), EPOLLIN, manager_dispatch_device_udev, m);
+        if (r < 0)
+                return r;
 
         /* Don't watch keys if nobody cares */
         if (m->handle_power_key != HANDLE_IGNORE ||
             m->handle_suspend_key != HANDLE_IGNORE ||
             m->handle_hibernate_key != HANDLE_IGNORE ||
-            m->handle_lid_switch != HANDLE_IGNORE) {
+            m->handle_lid_switch != HANDLE_IGNORE ||
+            m->handle_lid_switch_docked != HANDLE_IGNORE) {
 
                 m->udev_button_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
                 if (!m->udev_button_monitor)
@@ -1300,16 +951,14 @@ static int manager_connect_udev(Manager *m) {
                 if (r < 0)
                         return r;
 
-                m->udev_button_fd = udev_monitor_get_fd(m->udev_button_monitor);
-
-                zero(ev);
-                ev.events = EPOLLIN;
-                ev.data.u32 = FD_BUTTON_UDEV;
-                if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_button_fd, &ev) < 0)
-                        return -errno;
+                r = sd_event_add_io(m->event, &m->udev_button_event_source, udev_monitor_get_fd(m->udev_button_monitor), EPOLLIN, manager_dispatch_button_udev, m);
+                if (r < 0)
+                        return r;
         }
 
         /* Don't bother watching VCSA devices, if nobody cares */
+/// elogind does not support autospawning of vts
+#if 0
         if (m->n_autovts > 0 && m->console_active_fd >= 0) {
 
                 m->udev_vcsa_monitor = udev_monitor_new_from_netlink(m->udev, "udev");
@@ -1324,19 +973,16 @@ static int manager_connect_udev(Manager *m) {
                 if (r < 0)
                         return r;
 
-                m->udev_vcsa_fd = udev_monitor_get_fd(m->udev_vcsa_monitor);
-
-                zero(ev);
-                ev.events = EPOLLIN;
-                ev.data.u32 = FD_VCSA_UDEV;
-                if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->udev_vcsa_fd, &ev) < 0)
-                        return -errno;
+                r = sd_event_add_io(m->event, &m->udev_vcsa_event_source, udev_monitor_get_fd(m->udev_vcsa_monitor), EPOLLIN, manager_dispatch_vcsa_udev, m);
+                if (r < 0)
+                        return r;
         }
+#endif // 0
 
         return 0;
 }
 
-void manager_gc(Manager *m, bool drop_not_started) {
+static void manager_gc(Manager *m, bool drop_not_started) {
         Seat *seat;
         Session *session;
         User *user;
@@ -1344,113 +990,67 @@ void manager_gc(Manager *m, bool drop_not_started) {
         assert(m);
 
         while ((seat = m->seat_gc_queue)) {
-                LIST_REMOVE(Seat, gc_queue, m->seat_gc_queue, seat);
+                LIST_REMOVE(gc_queue, m->seat_gc_queue, seat);
                 seat->in_gc_queue = false;
 
-                if (seat_check_gc(seat, drop_not_started) == 0) {
-                        seat_stop(seat);
+                if (!seat_check_gc(seat, drop_not_started)) {
+                        seat_stop(seat, false);
                         seat_free(seat);
                 }
         }
 
         while ((session = m->session_gc_queue)) {
-                LIST_REMOVE(Session, gc_queue, m->session_gc_queue, session);
+                LIST_REMOVE(gc_queue, m->session_gc_queue, session);
                 session->in_gc_queue = false;
 
-                if (session_check_gc(session, drop_not_started) == 0) {
-                        session_stop(session);
+                /* First, if we are not closing yet, initiate stopping */
+                if (!session_check_gc(session, drop_not_started) &&
+                    session_get_state(session) != SESSION_CLOSING)
+                        session_stop(session, false);
+
+                /* Normally, this should make the session referenced
+                 * again, if it doesn't then let's get rid of it
+                 * immediately */
+                if (!session_check_gc(session, drop_not_started)) {
                         session_finalize(session);
                         session_free(session);
                 }
         }
 
         while ((user = m->user_gc_queue)) {
-                LIST_REMOVE(User, gc_queue, m->user_gc_queue, user);
+                LIST_REMOVE(gc_queue, m->user_gc_queue, user);
                 user->in_gc_queue = false;
 
-                if (user_check_gc(user, drop_not_started) == 0) {
-                        user_stop(user);
+                /* First step: queue stop jobs */
+                if (!user_check_gc(user, drop_not_started))
+                        user_stop(user, false);
+
+                /* Second step: finalize user */
+                if (!user_check_gc(user, drop_not_started)) {
                         user_finalize(user);
                         user_free(user);
                 }
         }
 }
 
-int manager_get_idle_hint(Manager *m, dual_timestamp *t) {
-        Session *s;
-        bool idle_hint;
-        dual_timestamp ts = { 0, 0 };
-        Iterator i;
-
-        assert(m);
-
-        idle_hint = !manager_is_inhibited(m, INHIBIT_IDLE, INHIBIT_BLOCK, t, false, false, 0);
-
-        HASHMAP_FOREACH(s, m->sessions, i) {
-                dual_timestamp k;
-                int ih;
-
-                ih = session_get_idle_hint(s, &k);
-                if (ih < 0)
-                        return ih;
-
-                if (!ih) {
-                        if (!idle_hint) {
-                                if (k.monotonic < ts.monotonic)
-                                        ts = k;
-                        } else {
-                                idle_hint = false;
-                                ts = k;
-                        }
-                } else if (idle_hint) {
-
-                        if (k.monotonic > ts.monotonic)
-                                ts = k;
-                }
-        }
-
-        if (t)
-                *t = ts;
-
-        return idle_hint;
-}
-
-bool manager_shall_kill(Manager *m, const char *user) {
-        assert(m);
-        assert(user);
-
-        if (!m->kill_user_processes)
-                return false;
-
-        if (strv_contains(m->kill_exclude_users, user))
-                return false;
-
-        if (strv_isempty(m->kill_only_users))
-                return true;
-
-        return strv_contains(m->kill_only_users, user);
-}
-
-int manager_dispatch_idle_action(Manager *m) {
+static int manager_dispatch_idle_action(sd_event_source *s, uint64_t t, void *userdata) {
+        Manager *m = userdata;
         struct dual_timestamp since;
-        struct itimerspec its = {};
+        usec_t n, elapse;
         int r;
-        usec_t n;
 
         assert(m);
 
         if (m->idle_action == HANDLE_IGNORE ||
-            m->idle_action_usec <= 0) {
-                r = 0;
-                goto finish;
-        }
+            m->idle_action_usec <= 0)
+                return 0;
 
         n = now(CLOCK_MONOTONIC);
 
         r = manager_get_idle_hint(m, &since);
         if (r <= 0)
                 /* Not idle. Let's check if after a timeout it might be idle then. */
-                timespec_store(&its.it_value, n + m->idle_action_usec);
+                elapse = n + m->idle_action_usec;
         else {
                 /* Idle! Let's see if it's time to do something, or if
                  * we shall sleep for longer. */
@@ -1463,59 +1063,46 @@ int manager_dispatch_idle_action(Manager *m) {
                         m->idle_action_not_before_usec = n;
                 }
 
-                timespec_store(&its.it_value, MAX(since.monotonic, m->idle_action_not_before_usec) + m->idle_action_usec);
+                elapse = MAX(since.monotonic, m->idle_action_not_before_usec) + m->idle_action_usec;
         }
 
-        if (m->idle_action_fd < 0) {
-                struct epoll_event ev = {
-                        .events = EPOLLIN,
-                        .data.u32 = FD_IDLE_ACTION,
-                };
-
-                m->idle_action_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC);
-                if (m->idle_action_fd < 0) {
-                        log_error("Failed to create idle action timer: %m");
-                        r = -errno;
-                        goto finish;
-                }
+        if (!m->idle_action_event_source) {
 
-                if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, m->idle_action_fd, &ev) < 0) {
-                        log_error("Failed to add idle action timer to epoll: %m");
-                        r = -errno;
-                        goto finish;
-                }
-        }
-
-        if (timerfd_settime(m->idle_action_fd, TFD_TIMER_ABSTIME, &its, NULL) < 0) {
-                log_error("Failed to reset timerfd: %m");
-                r = -errno;
-                goto finish;
-        }
+                r = sd_event_add_time(
+                                m->event,
+                                &m->idle_action_event_source,
+                                CLOCK_MONOTONIC,
+                                elapse, USEC_PER_SEC*30,
+                                manager_dispatch_idle_action, m);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to add idle event source: %m");
 
-        return 0;
+                r = sd_event_source_set_priority(m->idle_action_event_source, SD_EVENT_PRIORITY_IDLE+10);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to set idle event source priority: %m");
+        } else {
+                r = sd_event_source_set_time(m->idle_action_event_source, elapse);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to set idle event timer: %m");
 
-finish:
-        if (m->idle_action_fd >= 0) {
-                close_nointr_nofail(m->idle_action_fd);
-                m->idle_action_fd = -1;
+                r = sd_event_source_set_enabled(m->idle_action_event_source, SD_EVENT_ONESHOT);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to enable idle event timer: %m");
         }
 
-        return r;
+        return 0;
 }
-int manager_startup(Manager *m) {
+
+static int manager_startup(Manager *m) {
         int r;
         Seat *seat;
         Session *session;
         User *user;
+        Button *button;
         Inhibitor *inhibitor;
         Iterator i;
 
         assert(m);
-        assert(m->epoll_fd <= 0);
-
-        m->epoll_fd = epoll_create1(EPOLL_CLOEXEC);
-        if (m->epoll_fd < 0)
-                return -errno;
 
         /* Connect to console */
         r = manager_connect_console(m);
@@ -1525,7 +1112,7 @@ int manager_startup(Manager *m) {
         /* Connect to udev */
         r = manager_connect_udev(m);
         if (r < 0)
-                return r;
+                return log_error_errno(r, "Failed to create udev watchers: %m");
 
         /* Connect to the bus */
         r = manager_connect_bus(m);
@@ -1533,40 +1120,47 @@ int manager_startup(Manager *m) {
                 return r;
 
         /* Instantiate magic seat 0 */
-        r = manager_add_seat(m, "seat0", &m->vtconsole);
+        r = manager_add_seat(m, "seat0", &m->seat0);
         if (r < 0)
-                return r;
+                return log_error_errno(r, "Failed to add seat0: %m");
+
+        r = manager_set_lid_switch_ignore(m, 0 + m->holdoff_timeout_usec);
+        if (r < 0)
+                log_warning_errno(r, "Failed to set up lid switch ignore event source: %m");
 
         /* Deserialize state */
         r = manager_enumerate_devices(m);
         if (r < 0)
-                log_warning("Device enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Device enumeration failed: %m");
 
         r = manager_enumerate_seats(m);
         if (r < 0)
-                log_warning("Seat enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Seat enumeration failed: %m");
 
         r = manager_enumerate_users(m);
         if (r < 0)
-                log_warning("User enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "User enumeration failed: %m");
 
         r = manager_enumerate_sessions(m);
         if (r < 0)
-                log_warning("Session enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Session enumeration failed: %m");
 
         r = manager_enumerate_inhibitors(m);
         if (r < 0)
-                log_warning("Inhibitor enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Inhibitor enumeration failed: %m");
 
         r = manager_enumerate_buttons(m);
         if (r < 0)
-                log_warning("Button enumeration failed: %s", strerror(-r));
+                log_warning_errno(r, "Button enumeration failed: %m");
 
         /* Remove stale objects before we start them */
         manager_gc(m, false);
 
         /* Reserve the special reserved VT */
+/// elogind does not support autospawning of vts
+#if 0
         manager_reserve_vt(m);
+#endif // 0
 
         /* And start everything */
         HASHMAP_FOREACH(seat, m->seats, i)
@@ -1581,145 +1175,80 @@ int manager_startup(Manager *m) {
         HASHMAP_FOREACH(inhibitor, m->inhibitors, i)
                 inhibitor_start(inhibitor);
 
-        manager_dispatch_idle_action(m);
+        HASHMAP_FOREACH(button, m->buttons, i)
+                button_check_switches(button);
+
+        manager_dispatch_idle_action(NULL, 0, m);
 
         return 0;
 }
 
-static int manager_recheck_buttons(Manager *m) {
-        Iterator i;
-        Button *b;
-        int r = 0;
-
-        assert(m);
-
-        HASHMAP_FOREACH(b, m->buttons, i) {
-                int q;
-
-                q = button_recheck(b);
-                if (q > 0)
-                        return 1;
-                if (q < 0)
-                        r = q;
-        }
-
-        return r;
-}
+static int manager_run(Manager *m) {
+        int r;
 
-int manager_run(Manager *m) {
         assert(m);
 
         for (;;) {
-                struct epoll_event event;
-                int n;
-                int msec = -1;
-
-                manager_gc(m, true);
-
-                if (manager_dispatch_delayed(m) > 0)
-                        continue;
-
-                if (manager_recheck_buttons(m) > 0)
-                        continue;
-
-                if (dbus_connection_dispatch(m->bus) != DBUS_DISPATCH_COMPLETE)
-                        continue;
+                r = sd_event_get_state(m->event);
+                if (r < 0)
+                        return r;
+                if (r == SD_EVENT_FINISHED)
+                        return 0;
 
                 manager_gc(m, true);
 
-                if (m->action_what != 0 && !m->action_job) {
-                        usec_t x, y;
-
-                        x = now(CLOCK_MONOTONIC);
-                        y = m->action_timestamp + m->inhibit_delay_max;
-
-                        msec = x >= y ? 0 : (int) ((y - x) / USEC_PER_MSEC);
-                }
-
-                n = epoll_wait(m->epoll_fd, &event, 1, msec);
-                if (n < 0) {
-                        if (errno == EINTR || errno == EAGAIN)
-                                continue;
-
-                        log_error("epoll() failed: %m");
-                        return -errno;
-                }
-
-                if (n == 0)
+                r = manager_dispatch_delayed(m, false);
+                if (r < 0)
+                        return r;
+                if (r > 0)
                         continue;
 
-                switch (event.data.u32) {
-
-                case FD_SEAT_UDEV:
-                        manager_dispatch_seat_udev(m);
-                        break;
-
-                case FD_DEVICE_UDEV:
-                        manager_dispatch_device_udev(m);
-                        break;
-
-                case FD_VCSA_UDEV:
-                        manager_dispatch_vcsa_udev(m);
-                        break;
-
-                case FD_BUTTON_UDEV:
-                        manager_dispatch_button_udev(m);
-                        break;
-
-                case FD_CONSOLE:
-                        manager_dispatch_console(m);
-                        break;
-
-                case FD_IDLE_ACTION:
-                        manager_dispatch_idle_action(m);
-                        break;
-
-                case FD_BUS:
-                        bus_loop_dispatch(m->bus_fd);
-                        break;
-
-                default:
-                        if (event.data.u32 >= FD_OTHER_BASE)
-                                manager_dispatch_other(m, event.data.u32 - FD_OTHER_BASE);
-                }
+                r = sd_event_run(m->event, (uint64_t) -1);
+                if (r < 0)
+                        return r;
         }
-
-        return 0;
 }
 
 static int manager_parse_config_file(Manager *m) {
-        static const char fn[] = "/etc/systemd/logind.conf";
-        _cleanup_fclose_ FILE *f = NULL;
-        int r;
+        const char *unit = NULL, *logind_conf, *sections;
+        FILE *file = NULL;
+        bool relaxed = false, allow_include = false, warn = true;
 
         assert(m);
 
-        f = fopen(fn, "re");
-        if (!f) {
-                if (errno == ENOENT)
-                        return 0;
-
-                log_warning("Failed to open configuration file %s: %m", fn);
-                return -errno;
-        }
-
-        r = config_parse(NULL, fn, f, "Login\0", config_item_perf_lookup,
-                         (void*) logind_gperf_lookup, false, false, m);
-        if (r < 0)
-                log_warning("Failed to parse configuration file: %s", strerror(-r));
-
-        return r;
+/// elogind parses its own config file
+#if 0
+        return config_parse_many("/etc/systemd/logind.conf",
+                                 CONF_DIRS_NULSTR("systemd/logind.conf"),
+                                 "Login\0",
+                                 config_item_perf_lookup, logind_gperf_lookup,
+                                 false, m);
+#endif // 0
+
+        logind_conf = getenv("ELOGIND_CONF_FILE");
+        if (!logind_conf)
+                logind_conf = PKGSYSCONFDIR "/logind.conf";
+        sections = "Login\0Sleep\0";
+
+        return config_parse(unit, logind_conf, file, sections,
+                            config_item_perf_lookup, logind_gperf_lookup,
+                            relaxed, allow_include, warn, m);
 }
 
 int main(int argc, char *argv[]) {
         Manager *m = NULL;
         int r;
 
+        elogind_set_program_name(argv[0]);
         log_set_target(LOG_TARGET_AUTO);
         log_set_facility(LOG_AUTH);
         log_parse_environment();
         log_open();
 
+#ifdef ENABLE_DEBUG_ELOGIND
+        log_set_max_level(LOG_DEBUG);
+#endif // ENABLE_DEBUG_ELOGIND
+
         umask(0022);
 
         if (argc != 1) {
@@ -1733,9 +1262,21 @@ int main(int argc, char *argv[]) {
          * existence of /run/systemd/seats/ to determine whether
          * logind is available, so please always make sure this check
          * stays in. */
-        mkdir_label("/run/systemd/seats", 0755);
-        mkdir_label("/run/systemd/users", 0755);
-        mkdir_label("/run/systemd/sessions", 0755);
+        r = mkdir_label("/run/systemd", 0755);
+        if ( (r < 0) && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd : %m");
+        r = mkdir_label("/run/systemd/seats", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/seats : %m");
+        r = mkdir_label("/run/systemd/users", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/users : %m");
+        r = mkdir_label("/run/systemd/sessions", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/sessions : %m");
+        r = mkdir_label("/run/systemd/machines", 0755);
+        if ( r < 0 && (-EEXIST != r) )
+                return log_error_errno(r, "Failed to create /run/systemd/machines : %m");
 
         m = manager_new();
         if (!m) {
@@ -1747,11 +1288,11 @@ int main(int argc, char *argv[]) {
 
         r = manager_startup(m);
         if (r < 0) {
-                log_error("Failed to fully start up daemon: %s", strerror(-r));
+                log_error_errno(r, "Failed to fully start up daemon: %m");
                 goto finish;
         }
 
-        log_debug("systemd-logind running as pid %lu", (unsigned long) getpid());
+        log_debug("logind running as pid "PID_FMT, getpid());
 
         sd_notify(false,
                   "READY=1\n"
@@ -1759,13 +1300,13 @@ int main(int argc, char *argv[]) {
 
         r = manager_run(m);
 
-        log_debug("systemd-logind stopped as pid %lu", (unsigned long) getpid());
+        log_debug("logind stopped as pid "PID_FMT, getpid());
 
 finish:
         sd_notify(false,
+                  "STOPPING=1\n"
                   "STATUS=Shutting down...");
 
-        if (m)
                 manager_free(m);
 
         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;