about summary refs log tree commit diff
path: root/pkgs/by-name/sy
diff options
context:
space:
mode:
authorAnderson Torres <torres.anderson.85@protonmail.com>2023-11-24 16:39:57 -0300
committerAnderson Torres <torres.anderson.85@protonmail.com>2023-11-25 20:11:32 -0300
commit33d2a40d6751477472a2eeb0531ef7ddbf1cc695 (patch)
treed5530e5dc60d139fa102c6e5fa45639bb800901d /pkgs/by-name/sy
parent7c588d141dafe72381bb1bef5c67353349bb1fde (diff)
systemd: migrate to by-name
Diffstat (limited to 'pkgs/by-name/sy')
-rw-r--r--pkgs/by-name/sy/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch29
-rw-r--r--pkgs/by-name/sy/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch45
-rw-r--r--pkgs/by-name/sy/systemd/0003-Fix-NixOS-containers.patch31
-rw-r--r--pkgs/by-name/sy/systemd/0004-Add-some-NixOS-specific-unit-directories.patch127
-rw-r--r--pkgs/by-name/sy/systemd/0005-Get-rid-of-a-useless-message-in-user-sessions.patch28
-rw-r--r--pkgs/by-name/sy/systemd/0006-hostnamed-localed-timedated-disable-methods-that-cha.patch105
-rw-r--r--pkgs/by-name/sy/systemd/0007-Fix-hwdb-paths.patch24
-rw-r--r--pkgs/by-name/sy/systemd/0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch138
-rw-r--r--pkgs/by-name/sy/systemd/0009-localectl-use-etc-X11-xkb-for-list-x11.patch24
-rw-r--r--pkgs/by-name/sy/systemd/0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch23
-rw-r--r--pkgs/by-name/sy/systemd/0011-add-rootprefix-to-lookup-dir-paths.patch35
-rw-r--r--pkgs/by-name/sy/systemd/0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch23
-rw-r--r--pkgs/by-name/sy/systemd/0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch22
-rw-r--r--pkgs/by-name/sy/systemd/0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch30
-rw-r--r--pkgs/by-name/sy/systemd/0015-pkg-config-derive-prefix-from-prefix.patch30
-rw-r--r--pkgs/by-name/sy/systemd/0016-inherit-systemd-environment-when-calling-generators.patch39
-rw-r--r--pkgs/by-name/sy/systemd/0017-core-don-t-taint-on-unmerged-usr.patch33
-rw-r--r--pkgs/by-name/sy/systemd/0018-tpm2_context_init-fix-driver-name-checking.patch41
-rw-r--r--pkgs/by-name/sy/systemd/0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch45
-rw-r--r--pkgs/by-name/sy/systemd/package.nix831
20 files changed, 1703 insertions, 0 deletions
diff --git a/pkgs/by-name/sy/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch b/pkgs/by-name/sy/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch
new file mode 100644
index 0000000000000..104a9dad959a9
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch
@@ -0,0 +1,29 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Eelco Dolstra <eelco.dolstra@logicblox.com>
+Date: Tue, 8 Jan 2013 15:46:30 +0100
+Subject: [PATCH] Start device units for uninitialised encrypted devices
+
+This is necessary because the NixOS service that initialises the
+filesystem depends on the appearance of the device unit.  Also, this
+makes more sense to me: the device is ready; it's the filesystem
+that's not, but taking care of that is the responsibility of the mount
+unit.  (However, this ignores the fsck unit, so it's not perfect...)
+---
+ rules.d/99-systemd.rules.in | 4 ----
+ 1 file changed, 4 deletions(-)
+
+diff --git a/rules.d/99-systemd.rules.in b/rules.d/99-systemd.rules.in
+index c0defc31de..8f80235731 100644
+--- a/rules.d/99-systemd.rules.in
++++ b/rules.d/99-systemd.rules.in
+@@ -20,10 +20,6 @@ SUBSYSTEM=="block", TAG+="systemd"
+ SUBSYSTEM=="block", ENV{DM_SUSPENDED}=="1", IMPORT{db}="SYSTEMD_READY", GOTO="systemd_end"
+ SUBSYSTEM=="block", ACTION=="add", ENV{DM_UDEV_DISABLE_OTHER_RULES_FLAG}=="1", ENV{SYSTEMD_READY}="0"
+ 
+-# Ignore encrypted devices with no identified superblock on it, since
+-# we are probably still calling mke2fs or mkswap on it.
+-SUBSYSTEM=="block", ENV{DM_UUID}=="CRYPT-*", ENV{ID_PART_TABLE_TYPE}=="", ENV{ID_FS_USAGE}=="", ENV{SYSTEMD_READY}="0"
+-
+ # Explicitly set SYSTEMD_READY=1 for DM devices that don't have it set yet, so that we always have something to import above
+ SUBSYSTEM=="block", ENV{DM_UUID}=="?*", ENV{SYSTEMD_READY}=="", ENV{SYSTEMD_READY}="1"
+ 
diff --git a/pkgs/by-name/sy/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch b/pkgs/by-name/sy/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch
new file mode 100644
index 0000000000000..dda8524c498da
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch
@@ -0,0 +1,45 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Raito Bezarius <masterancpp@gmail.com>
+Date: Mon, 19 Jun 2023 02:11:35 +0200
+Subject: [PATCH] Don't try to unmount /nix or /nix/store
+
+They'll still be remounted read-only.
+
+https://github.com/NixOS/nixos/issues/126
+
+Original-Author: Eelco Dolstra <eelco.dolstra@logicblox.com>
+---
+ src/shared/fstab-util.c | 2 ++
+ src/shutdown/umount.c   | 6 ++++--
+ 2 files changed, 6 insertions(+), 2 deletions(-)
+
+diff --git a/src/shared/fstab-util.c b/src/shared/fstab-util.c
+index 4ffec25c75..b99031c54e 100644
+--- a/src/shared/fstab-util.c
++++ b/src/shared/fstab-util.c
+@@ -43,6 +43,8 @@ bool fstab_is_extrinsic(const char *mount, const char *opts) {
+         /* Don't bother with the OS data itself */
+         if (PATH_IN_SET(mount,
+                         "/",
++                        "/nix",
++                        "/nix/store",
+                         "/usr",
+                         "/etc"))
+                 return true;
+diff --git a/src/shutdown/umount.c b/src/shutdown/umount.c
+index 1586c2e214..fcae95f824 100644
+--- a/src/shutdown/umount.c
++++ b/src/shutdown/umount.c
+@@ -170,8 +170,10 @@ int mount_points_list_get(const char *mountinfo, MountPoint **head) {
+ static bool nonunmountable_path(const char *path) {
+         assert(path);
+ 
+-        return PATH_IN_SET(path, "/", "/usr") ||
+-                path_startswith(path, "/run/initramfs");
++        return PATH_IN_SET(path, "/", "/usr")
++                || path_equal(path, "/nix")
++                || path_equal(path, "/nix/store")
++                || path_startswith(path, "/run/initramfs");
+ }
+ 
+ static void log_umount_blockers(const char *mnt) {
diff --git a/pkgs/by-name/sy/systemd/0003-Fix-NixOS-containers.patch b/pkgs/by-name/sy/systemd/0003-Fix-NixOS-containers.patch
new file mode 100644
index 0000000000000..2d86d1e6957a1
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0003-Fix-NixOS-containers.patch
@@ -0,0 +1,31 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Eelco Dolstra <eelco.dolstra@logicblox.com>
+Date: Wed, 16 Apr 2014 10:59:28 +0200
+Subject: [PATCH] Fix NixOS containers
+
+In NixOS containers, the init script is bind-mounted into the
+container, so checking early whether it exists will fail.
+---
+ src/nspawn/nspawn.c | 2 ++
+ 1 file changed, 2 insertions(+)
+
+diff --git a/src/nspawn/nspawn.c b/src/nspawn/nspawn.c
+index e170958fc5..898a674631 100644
+--- a/src/nspawn/nspawn.c
++++ b/src/nspawn/nspawn.c
+@@ -5648,6 +5648,7 @@ static int run(int argc, char *argv[]) {
+                                 goto finish;
+                         }
+                 } else {
++#if 0
+                         _cleanup_free_ char *p = NULL;
+ 
+                         if (arg_pivot_root_new)
+@@ -5662,6 +5663,7 @@ static int run(int argc, char *argv[]) {
+                                                     "Directory %s doesn't look like it has an OS tree (/usr/ directory is missing). Refusing.", arg_directory);
+                                 goto finish;
+                         }
++#endif
+                 }
+ 
+         } else {
diff --git a/pkgs/by-name/sy/systemd/0004-Add-some-NixOS-specific-unit-directories.patch b/pkgs/by-name/sy/systemd/0004-Add-some-NixOS-specific-unit-directories.patch
new file mode 100644
index 0000000000000..c905a4d812af2
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0004-Add-some-NixOS-specific-unit-directories.patch
@@ -0,0 +1,127 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Raito Bezarius <masterancpp@gmail.com>
+Date: Mon, 19 Jun 2023 02:13:42 +0200
+Subject: [PATCH] Add some NixOS-specific unit directories
+
+Look in `/nix/var/nix/profiles/default/lib/systemd/{system,user}` for
+units provided by packages installed into the default profile via
+`nix-env -iA nixos.$package`.
+
+Also, remove /usr and /lib as these don't exist on NixOS.
+
+Original-Author: Eelco Dolstra <eelco.dolstra@logicblox.com>
+---
+ src/basic/path-lookup.c | 17 ++---------------
+ src/core/systemd.pc.in  |  8 ++++----
+ 2 files changed, 6 insertions(+), 19 deletions(-)
+
+diff --git a/src/basic/path-lookup.c b/src/basic/path-lookup.c
+index 7d158a8295..f9bd62b631 100644
+--- a/src/basic/path-lookup.c
++++ b/src/basic/path-lookup.c
+@@ -92,11 +92,7 @@ int xdg_user_data_dir(char **ret, const char *suffix) {
+ }
+ 
+ static const char* const user_data_unit_paths[] = {
+-        "/usr/local/lib/systemd/user",
+-        "/usr/local/share/systemd/user",
+         USER_DATA_UNIT_DIR,
+-        "/usr/lib/systemd/user",
+-        "/usr/share/systemd/user",
+         NULL
+ };
+ 
+@@ -617,15 +613,13 @@ int lookup_paths_init(
+                                         persistent_config,
+                                         SYSTEM_CONFIG_UNIT_DIR,
+                                         "/etc/systemd/system",
++                                        "/nix/var/nix/profiles/default/lib/systemd/system",
+                                         STRV_IFNOTNULL(persistent_attached),
+                                         runtime_config,
+                                         "/run/systemd/system",
+                                         STRV_IFNOTNULL(runtime_attached),
+                                         STRV_IFNOTNULL(generator),
+-                                        "/usr/local/lib/systemd/system",
+                                         SYSTEM_DATA_UNIT_DIR,
+-                                        "/usr/lib/systemd/system",
+-                                        STRV_IFNOTNULL(flags & LOOKUP_PATHS_SPLIT_USR ? "/lib/systemd/system" : NULL),
+                                         STRV_IFNOTNULL(generator_late));
+                         break;
+ 
+@@ -641,14 +635,11 @@ int lookup_paths_init(
+                                         persistent_config,
+                                         USER_CONFIG_UNIT_DIR,
+                                         "/etc/systemd/user",
++                                        "/nix/var/nix/profiles/default/lib/systemd/user",
+                                         runtime_config,
+                                         "/run/systemd/user",
+                                         STRV_IFNOTNULL(generator),
+-                                        "/usr/local/share/systemd/user",
+-                                        "/usr/share/systemd/user",
+-                                        "/usr/local/lib/systemd/user",
+                                         USER_DATA_UNIT_DIR,
+-                                        "/usr/lib/systemd/user",
+                                         STRV_IFNOTNULL(generator_late));
+                         break;
+ 
+@@ -808,7 +799,6 @@ char **generator_binary_paths(RuntimeScope scope) {
+                 case RUNTIME_SCOPE_SYSTEM:
+                         add = strv_new("/run/systemd/system-generators",
+                                        "/etc/systemd/system-generators",
+-                                       "/usr/local/lib/systemd/system-generators",
+                                        SYSTEM_GENERATOR_DIR);
+                         break;
+ 
+@@ -816,7 +806,6 @@ char **generator_binary_paths(RuntimeScope scope) {
+                 case RUNTIME_SCOPE_USER:
+                         add = strv_new("/run/systemd/user-generators",
+                                        "/etc/systemd/user-generators",
+-                                       "/usr/local/lib/systemd/user-generators",
+                                        USER_GENERATOR_DIR);
+                         break;
+ 
+@@ -855,14 +844,12 @@ char **env_generator_binary_paths(RuntimeScope runtime_scope) {
+                 case RUNTIME_SCOPE_SYSTEM:
+                         add = strv_new("/run/systemd/system-environment-generators",
+                                         "/etc/systemd/system-environment-generators",
+-                                        "/usr/local/lib/systemd/system-environment-generators",
+                                         SYSTEM_ENV_GENERATOR_DIR);
+                         break;
+ 
+                 case RUNTIME_SCOPE_USER:
+                         add = strv_new("/run/systemd/user-environment-generators",
+                                        "/etc/systemd/user-environment-generators",
+-                                       "/usr/local/lib/systemd/user-environment-generators",
+                                        USER_ENV_GENERATOR_DIR);
+                         break;
+ 
+diff --git a/src/core/systemd.pc.in b/src/core/systemd.pc.in
+index 693433b34b..5932a21b5b 100644
+--- a/src/core/systemd.pc.in
++++ b/src/core/systemd.pc.in
+@@ -38,10 +38,10 @@ systemdsystemconfdir=${systemd_system_conf_dir}
+ systemd_user_conf_dir=${sysconfdir}/systemd/user
+ systemduserconfdir=${systemd_user_conf_dir}
+ 
+-systemd_system_unit_path=${systemd_system_conf_dir}:/etc/systemd/system:/run/systemd/system:/usr/local/lib/systemd/system:${systemd_system_unit_dir}:/usr/lib/systemd/system:/lib/systemd/system
++systemd_system_unit_path=${systemd_system_conf_dir}:/etc/systemd/system:/nix/var/nix/profiles/default/lib/systemd/system:/run/systemd/system:${systemdsystemunitdir}
+ systemdsystemunitpath=${systemd_system_unit_path}
+ 
+-systemd_user_unit_path=${systemd_user_conf_dir}:/etc/systemd/user:/run/systemd/user:/usr/local/lib/systemd/user:/usr/local/share/systemd/user:${systemd_user_unit_dir}:/usr/lib/systemd/user:/usr/share/systemd/user
++systemd_user_unit_path=${systemd_user_conf_dir}:/etc/systemd/user:/nix/var/nix/profiles/default/lib/systemd/user:/run/systemd/user:${systemduserunitdir}
+ systemduserunitpath=${systemd_user_unit_path}
+ 
+ systemd_system_generator_dir=${root_prefix}/lib/systemd/system-generators
+@@ -50,10 +50,10 @@ systemdsystemgeneratordir=${systemd_system_generator_dir}
+ systemd_user_generator_dir=${prefix}/lib/systemd/user-generators
+ systemdusergeneratordir=${systemd_user_generator_dir}
+ 
+-systemd_system_generator_path=/run/systemd/system-generators:/etc/systemd/system-generators:/usr/local/lib/systemd/system-generators:${systemd_system_generator_dir}
++systemd_system_generator_path=/run/systemd/system-generators:/etc/systemd/system-generators:${systemd_system_generator_dir}
+ systemdsystemgeneratorpath=${systemd_system_generator_path}
+ 
+-systemd_user_generator_path=/run/systemd/user-generators:/etc/systemd/user-generators:/usr/local/lib/systemd/user-generators:${systemd_user_generator_dir}
++systemd_user_generator_path=/run/systemd/user-generators:/etc/systemd/user-generators:${systemd_user_generator_dir}
+ systemdusergeneratorpath=${systemd_user_generator_path}
+ 
+ systemd_sleep_dir=${root_prefix}/lib/systemd/system-sleep
diff --git a/pkgs/by-name/sy/systemd/0005-Get-rid-of-a-useless-message-in-user-sessions.patch b/pkgs/by-name/sy/systemd/0005-Get-rid-of-a-useless-message-in-user-sessions.patch
new file mode 100644
index 0000000000000..0a80d5ac4e83e
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0005-Get-rid-of-a-useless-message-in-user-sessions.patch
@@ -0,0 +1,28 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Eelco Dolstra <eelco.dolstra@logicblox.com>
+Date: Mon, 11 May 2015 15:39:38 +0200
+Subject: [PATCH] Get rid of a useless message in user sessions
+
+Namely lots of variants of
+
+  Unit nix-var-nix-db.mount is bound to inactive unit dev-disk-by\x2dlabel-nixos.device. Stopping, too.
+
+in containers.
+---
+ src/core/manager.c | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+diff --git a/src/core/manager.c b/src/core/manager.c
+index 22ec6e79b1..771e8e7f16 100644
+--- a/src/core/manager.c
++++ b/src/core/manager.c
+@@ -1559,7 +1559,8 @@ static unsigned manager_dispatch_stop_when_bound_queue(Manager *m) {
+                 if (!unit_is_bound_by_inactive(u, &culprit))
+                         continue;
+ 
+-                log_unit_debug(u, "Unit is stopped because bound to inactive unit %s.", culprit->id);
++                if (u->type != UNIT_MOUNT || detect_container() <= 0)
++                        log_unit_debug(u, "Unit is stopped because bound to inactive unit %s.", culprit->id);
+ 
+                 /* If stopping a unit fails continuously we might enter a stop loop here, hence stop acting on the
+                  * service being unnecessary after a while. */
diff --git a/pkgs/by-name/sy/systemd/0006-hostnamed-localed-timedated-disable-methods-that-cha.patch b/pkgs/by-name/sy/systemd/0006-hostnamed-localed-timedated-disable-methods-that-cha.patch
new file mode 100644
index 0000000000000..abc6c24dbf511
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0006-hostnamed-localed-timedated-disable-methods-that-cha.patch
@@ -0,0 +1,105 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Gabriel Ebner <gebner@gebner.org>
+Date: Sun, 6 Dec 2015 14:26:36 +0100
+Subject: [PATCH] hostnamed, localed, timedated: disable methods that change
+ system settings.
+
+---
+ src/hostname/hostnamed.c |  6 ++++++
+ src/locale/localed.c     |  9 +++++++++
+ src/timedate/timedated.c | 10 ++++++++++
+ 3 files changed, 25 insertions(+)
+
+diff --git a/src/hostname/hostnamed.c b/src/hostname/hostnamed.c
+index 9ef45f8e75..99b1ec2e36 100644
+--- a/src/hostname/hostnamed.c
++++ b/src/hostname/hostnamed.c
+@@ -1053,6 +1053,9 @@ static int method_set_static_hostname(sd_bus_message *m, void *userdata, sd_bus_
+         if (r < 0)
+                 return r;
+ 
++        return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++            "Changing system settings via systemd is not supported on NixOS.");
++
+         name = empty_to_null(name);
+ 
+         context_read_etc_hostname(c);
+@@ -1116,6 +1119,9 @@ static int set_machine_info(Context *c, sd_bus_message *m, int prop, sd_bus_mess
+         if (r < 0)
+                 return r;
+ 
++        return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++            "Changing system settings via systemd is not supported on NixOS.");
++
+         name = empty_to_null(name);
+ 
+         context_read_machine_info(c);
+diff --git a/src/locale/localed.c b/src/locale/localed.c
+index f544a73580..ce00c262cc 100644
+--- a/src/locale/localed.c
++++ b/src/locale/localed.c
+@@ -229,6 +229,9 @@ static int method_set_locale(sd_bus_message *m, void *userdata, sd_bus_error *er
+ 
+         use_localegen = locale_gen_check_available();
+ 
++        return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++            "Changing system settings via systemd is not supported on NixOS.");
++
+         /* If single locale without variable name is provided, then we assume it is LANG=. */
+         if (strv_length(l) == 1 && !strchr(l[0], '=')) {
+                 if (!locale_is_valid(l[0]))
+@@ -347,6 +350,9 @@ static int method_set_vc_keyboard(sd_bus_message *m, void *userdata, sd_bus_erro
+         if (r < 0)
+                 return bus_log_parse_error(r);
+ 
++        return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++            "Changing system settings via systemd is not supported on NixOS.");
++
+         vc_context_empty_to_null(&in);
+ 
+         r = vc_context_verify_and_warn(&in, LOG_ERR, error);
+@@ -465,6 +471,9 @@ static int method_set_x11_keyboard(sd_bus_message *m, void *userdata, sd_bus_err
+         if (r < 0)
+                 return bus_log_parse_error(r);
+ 
++        return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++            "Changing system settings via systemd is not supported on NixOS.");
++
+         x11_context_empty_to_null(&in);
+ 
+         r = x11_context_verify_and_warn(&in, LOG_ERR, error);
+diff --git a/src/timedate/timedated.c b/src/timedate/timedated.c
+index ad1d492d6b..331af34505 100644
+--- a/src/timedate/timedated.c
++++ b/src/timedate/timedated.c
+@@ -665,6 +665,10 @@ static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *
+         if (r < 0)
+                 return r;
+ 
++        if (getenv("NIXOS_STATIC_TIMEZONE"))
++                return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++                    "Changing timezone via systemd is not supported when it is set in NixOS configuration.");
++
+         if (!timezone_is_valid(z, LOG_DEBUG))
+                 return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Invalid or not installed time zone '%s'", z);
+ 
+@@ -743,6 +747,9 @@ static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error
+         if (r < 0)
+                 return r;
+ 
++        return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++            "Changing system settings via systemd is not supported on NixOS.");
++
+         if (lrtc == c->local_rtc && !fix_system)
+                 return sd_bus_reply_method_return(m, NULL);
+ 
+@@ -923,6 +930,9 @@ static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error
+         if (r < 0)
+                 return r;
+ 
++        return sd_bus_error_setf(error, SD_BUS_ERROR_NOT_SUPPORTED,
++            "Changing system settings via systemd is not supported on NixOS.");
++
+         r = context_update_ntp_status(c, bus, m);
+         if (r < 0)
+                 return r;
diff --git a/pkgs/by-name/sy/systemd/0007-Fix-hwdb-paths.patch b/pkgs/by-name/sy/systemd/0007-Fix-hwdb-paths.patch
new file mode 100644
index 0000000000000..7777ba7e42593
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0007-Fix-hwdb-paths.patch
@@ -0,0 +1,24 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Nikolay Amiantov <ab@fmap.me>
+Date: Thu, 7 Jul 2016 02:47:13 +0300
+Subject: [PATCH] Fix hwdb paths
+
+Patch by vcunat.
+---
+ src/libsystemd/sd-hwdb/hwdb-internal.h | 6 +-----
+ 1 file changed, 1 insertion(+), 5 deletions(-)
+
+diff --git a/src/libsystemd/sd-hwdb/hwdb-internal.h b/src/libsystemd/sd-hwdb/hwdb-internal.h
+index 5302679a62..39e59a527f 100644
+--- a/src/libsystemd/sd-hwdb/hwdb-internal.h
++++ b/src/libsystemd/sd-hwdb/hwdb-internal.h
+@@ -83,8 +83,4 @@ struct trie_value_entry2_f {
+ } _packed_;
+ 
+ #define hwdb_bin_paths                          \
+-        "/etc/systemd/hwdb/hwdb.bin\0"          \
+-        "/etc/udev/hwdb.bin\0"                  \
+-        "/usr/lib/systemd/hwdb/hwdb.bin\0"      \
+-        _CONF_PATHS_SPLIT_USR_NULSTR("systemd/hwdb/hwdb.bin") \
+-        UDEVLIBEXECDIR "/hwdb.bin\0"
++        "/etc/udev/hwdb.bin\0"
diff --git a/pkgs/by-name/sy/systemd/0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch b/pkgs/by-name/sy/systemd/0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
new file mode 100644
index 0000000000000..3150d97be2e1a
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
@@ -0,0 +1,138 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Nikolay Amiantov <ab@fmap.me>
+Date: Tue, 11 Oct 2016 13:12:08 +0300
+Subject: [PATCH] Change /usr/share/zoneinfo to /etc/zoneinfo
+
+NixOS uses this path.
+---
+ man/localtime.xml         | 4 ++--
+ src/basic/time-util.c     | 8 ++++----
+ src/firstboot/firstboot.c | 2 +-
+ src/nspawn/nspawn.c       | 4 ++--
+ src/timedate/timedated.c  | 8 ++++----
+ 5 files changed, 13 insertions(+), 13 deletions(-)
+
+diff --git a/man/localtime.xml b/man/localtime.xml
+index e486474c44..5f373d0723 100644
+--- a/man/localtime.xml
++++ b/man/localtime.xml
+@@ -20,7 +20,7 @@
+   </refnamediv>
+ 
+   <refsynopsisdiv>
+-    <para><filename>/etc/localtime</filename> -&gt; <filename>../usr/share/zoneinfo/…</filename></para>
++    <para><filename>/etc/localtime</filename> -&gt; <filename>zoneinfo/…</filename></para>
+   </refsynopsisdiv>
+ 
+   <refsect1>
+@@ -30,7 +30,7 @@
+     system-wide timezone of the local system that is used by
+     applications for presentation to the user. It should be an
+     absolute or relative symbolic link pointing to
+-    <filename>/usr/share/zoneinfo/</filename>, followed by a timezone
++    <filename>/etc/zoneinfo/</filename>, followed by a timezone
+     identifier such as <literal>Europe/Berlin</literal> or
+     <literal>Etc/UTC</literal>. The resulting link should lead to the
+     corresponding binary
+diff --git a/src/basic/time-util.c b/src/basic/time-util.c
+index 1db630003a..31744c3e68 100644
+--- a/src/basic/time-util.c
++++ b/src/basic/time-util.c
+@@ -1350,7 +1350,7 @@ static int get_timezones_from_zone1970_tab(char ***ret) {
+ 
+         assert(ret);
+ 
+-        f = fopen("/usr/share/zoneinfo/zone1970.tab", "re");
++        f = fopen("/etc/zoneinfo/zone1970.tab", "re");
+         if (!f)
+                 return -errno;
+ 
+@@ -1391,7 +1391,7 @@ static int get_timezones_from_tzdata_zi(char ***ret) {
+ 
+         assert(ret);
+ 
+-        f = fopen("/usr/share/zoneinfo/tzdata.zi", "re");
++        f = fopen("/etc/zoneinfo/tzdata.zi", "re");
+         if (!f)
+                 return -errno;
+ 
+@@ -1503,7 +1503,7 @@ int verify_timezone(const char *name, int log_level) {
+         if (p - name >= PATH_MAX)
+                 return -ENAMETOOLONG;
+ 
+-        t = strjoina("/usr/share/zoneinfo/", name);
++        t = strjoina("/etc/zoneinfo/", name);
+ 
+         fd = open(t, O_RDONLY|O_CLOEXEC);
+         if (fd < 0)
+@@ -1563,7 +1563,7 @@ int get_timezone(char **ret) {
+         if (r < 0)
+                 return r; /* returns EINVAL if not a symlink */
+ 
+-        e = PATH_STARTSWITH_SET(t, "/usr/share/zoneinfo/", "../usr/share/zoneinfo/");
++        e = PATH_STARTSWITH_SET(t, "/etc/zoneinfo/", "../etc/zoneinfo/");
+         if (!e)
+                 return -EINVAL;
+ 
+diff --git a/src/firstboot/firstboot.c b/src/firstboot/firstboot.c
+index 1956ab3b13..9ef356f8af 100644
+--- a/src/firstboot/firstboot.c
++++ b/src/firstboot/firstboot.c
+@@ -630,7 +630,7 @@ static int process_timezone(int rfd) {
+         if (isempty(arg_timezone))
+                 return 0;
+ 
+-        e = strjoina("../usr/share/zoneinfo/", arg_timezone);
++        e = strjoina("zoneinfo/", arg_timezone);
+ 
+         r = symlinkat_atomic_full(e, pfd, f, /* make_relative= */ false);
+         if (r < 0)
+diff --git a/src/nspawn/nspawn.c b/src/nspawn/nspawn.c
+index 898a674631..c41a416e04 100644
+--- a/src/nspawn/nspawn.c
++++ b/src/nspawn/nspawn.c
+@@ -1924,8 +1924,8 @@ int userns_mkdir(const char *root, const char *path, mode_t mode, uid_t uid, gid
+ static const char *timezone_from_path(const char *path) {
+         return PATH_STARTSWITH_SET(
+                         path,
+-                        "../usr/share/zoneinfo/",
+-                        "/usr/share/zoneinfo/");
++                        "../etc/zoneinfo/",
++                        "/etc/zoneinfo/");
+ }
+ 
+ static bool etc_writable(void) {
+diff --git a/src/timedate/timedated.c b/src/timedate/timedated.c
+index 331af34505..722c4b5b4f 100644
+--- a/src/timedate/timedated.c
++++ b/src/timedate/timedated.c
+@@ -282,7 +282,7 @@ static int context_read_data(Context *c) {
+ 
+         r = get_timezone(&t);
+         if (r == -EINVAL)
+-                log_warning_errno(r, "/etc/localtime should be a symbolic link to a time zone data file in /usr/share/zoneinfo/.");
++                log_warning_errno(r, "/etc/localtime should be a symbolic link to a time zone data file in /etc/zoneinfo/.");
+         else if (r < 0)
+                 log_warning_errno(r, "Failed to get target of /etc/localtime: %m");
+ 
+@@ -306,7 +306,7 @@ static int context_write_data_timezone(Context *c) {
+ 
+         if (isempty(c->zone) || streq(c->zone, "UTC")) {
+ 
+-                if (access("/usr/share/zoneinfo/UTC", F_OK) < 0) {
++                if (access("/etc/zoneinfo/UTC", F_OK) < 0) {
+ 
+                         if (unlink("/etc/localtime") < 0 && errno != ENOENT)
+                                 return -errno;
+@@ -314,9 +314,9 @@ static int context_write_data_timezone(Context *c) {
+                         return 0;
+                 }
+ 
+-                source = "../usr/share/zoneinfo/UTC";
++                source = "../etc/zoneinfo/UTC";
+         } else {
+-                p = path_join("../usr/share/zoneinfo", c->zone);
++                p = path_join("../etc/zoneinfo", c->zone);
+                 if (!p)
+                         return -ENOMEM;
+ 
diff --git a/pkgs/by-name/sy/systemd/0009-localectl-use-etc-X11-xkb-for-list-x11.patch b/pkgs/by-name/sy/systemd/0009-localectl-use-etc-X11-xkb-for-list-x11.patch
new file mode 100644
index 0000000000000..c0f6afd7fc7ba
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0009-localectl-use-etc-X11-xkb-for-list-x11.patch
@@ -0,0 +1,24 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Imuli <i@imu.li>
+Date: Wed, 19 Oct 2016 08:46:47 -0400
+Subject: [PATCH] localectl: use /etc/X11/xkb for list-x11-*
+
+NixOS has an option to link the xkb data files to /etc/X11, but not to
+/usr/share/X11.
+---
+ src/locale/localectl.c | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/locale/localectl.c b/src/locale/localectl.c
+index d8db9d9d22..4601bb5431 100644
+--- a/src/locale/localectl.c
++++ b/src/locale/localectl.c
+@@ -297,7 +297,7 @@ static int list_x11_keymaps(int argc, char **argv, void *userdata) {
+         } state = NONE, look_for;
+         int r;
+ 
+-        f = fopen("/usr/share/X11/xkb/rules/base.lst", "re");
++        f = fopen("/etc/X11/xkb/rules/base.lst", "re");
+         if (!f)
+                 return log_error_errno(errno, "Failed to open keyboard mapping list. %m");
+ 
diff --git a/pkgs/by-name/sy/systemd/0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch b/pkgs/by-name/sy/systemd/0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
new file mode 100644
index 0000000000000..b8f97308acfb7
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
@@ -0,0 +1,23 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Franz Pletz <fpletz@fnordicwalking.de>
+Date: Sun, 11 Feb 2018 04:37:44 +0100
+Subject: [PATCH] build: don't create statedir and don't touch prefixdir
+
+---
+ meson.build | 3 ---
+ 1 file changed, 3 deletions(-)
+
+diff --git a/meson.build b/meson.build
+index 395eca1943..082cd748bb 100644
+--- a/meson.build
++++ b/meson.build
+@@ -4707,9 +4707,6 @@ install_data('LICENSE.GPL2',
+ install_subdir('LICENSES',
+                install_dir : docdir)
+ 
+-meson.add_install_script('sh', '-c', mkdir_p.format(systemdstatedir))
+-meson.add_install_script('sh', '-c', 'touch $DESTDIR@0@'.format(prefixdir))
+-
+ ############################################################
+ 
+ # Ensure that changes to the docs/ directory do not break the
diff --git a/pkgs/by-name/sy/systemd/0011-add-rootprefix-to-lookup-dir-paths.patch b/pkgs/by-name/sy/systemd/0011-add-rootprefix-to-lookup-dir-paths.patch
new file mode 100644
index 0000000000000..fa201126ae277
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0011-add-rootprefix-to-lookup-dir-paths.patch
@@ -0,0 +1,35 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Andreas Rammhold <andreas@rammhold.de>
+Date: Thu, 9 May 2019 11:15:22 +0200
+Subject: [PATCH] add rootprefix to lookup dir paths
+
+systemd does not longer use the UDEVLIBEXEC directory as root for
+discovery default udev rules. By adding `$out/lib` to the lookup paths
+we should again be able to discover the udev rules amongst other default
+files that I might have missed.
+---
+ src/basic/constants.h | 6 ++++--
+ 1 file changed, 4 insertions(+), 2 deletions(-)
+
+diff --git a/src/basic/constants.h b/src/basic/constants.h
+index 3f96786da9..6e8fb40c08 100644
+--- a/src/basic/constants.h
++++ b/src/basic/constants.h
+@@ -74,13 +74,15 @@
+         "/run/" n "\0"                          \
+         "/usr/local/lib/" n "\0"                \
+         "/usr/lib/" n "\0"                      \
+-        _CONF_PATHS_SPLIT_USR_NULSTR(n)
++        _CONF_PATHS_SPLIT_USR_NULSTR(n)         \
++        ROOTPREFIX "/lib/" n "\0"
+ 
+ #define CONF_PATHS_USR(n)                       \
+         "/etc/" n,                              \
+         "/run/" n,                              \
+         "/usr/local/lib/" n,                    \
+-        "/usr/lib/" n
++        "/usr/lib/" n,                          \
++        ROOTPREFIX "/lib/" n
+ 
+ #define CONF_PATHS(n)                           \
+         CONF_PATHS_USR(n)                       \
diff --git a/pkgs/by-name/sy/systemd/0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch b/pkgs/by-name/sy/systemd/0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
new file mode 100644
index 0000000000000..fde1e2b276c51
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
@@ -0,0 +1,23 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Nikolay Amiantov <ab@fmap.me>
+Date: Thu, 25 Jul 2019 20:45:55 +0300
+Subject: [PATCH] systemd-shutdown: execute scripts in
+ /etc/systemd/system-shutdown
+
+This is needed for NixOS to use such scripts as systemd directory is immutable.
+---
+ src/shutdown/shutdown.c | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/src/shutdown/shutdown.c b/src/shutdown/shutdown.c
+index 8395bb429d..14fbc85bb4 100644
+--- a/src/shutdown/shutdown.c
++++ b/src/shutdown/shutdown.c
+@@ -334,6 +334,7 @@ static void init_watchdog(void) {
+ int main(int argc, char *argv[]) {
+         static const char* const dirs[] = {
+                 SYSTEM_SHUTDOWN_PATH,
++                "/etc/systemd/system-shutdown",
+                 NULL
+         };
+         _cleanup_free_ char *cgroup = NULL;
diff --git a/pkgs/by-name/sy/systemd/0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch b/pkgs/by-name/sy/systemd/0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
new file mode 100644
index 0000000000000..d91150cfc4901
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
@@ -0,0 +1,22 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Nikolay Amiantov <ab@fmap.me>
+Date: Thu, 25 Jul 2019 20:46:58 +0300
+Subject: [PATCH] systemd-sleep: execute scripts in /etc/systemd/system-sleep
+
+This is needed for NixOS to use such scripts as systemd directory is immutable.
+---
+ src/sleep/sleep.c | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/src/sleep/sleep.c b/src/sleep/sleep.c
+index de1f6c7ec1..d0cdebd80a 100644
+--- a/src/sleep/sleep.c
++++ b/src/sleep/sleep.c
+@@ -224,6 +224,7 @@ static int execute(
+         };
+         static const char* const dirs[] = {
+                 SYSTEM_SLEEP_PATH,
++                "/etc/systemd/system-sleep",
+                 NULL
+         };
+ 
diff --git a/pkgs/by-name/sy/systemd/0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch b/pkgs/by-name/sy/systemd/0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
new file mode 100644
index 0000000000000..13dec1070ffc0
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
@@ -0,0 +1,30 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Florian Klink <flokli@flokli.de>
+Date: Sun, 8 Mar 2020 01:05:54 +0100
+Subject: [PATCH] path-util.h: add placeholder for DEFAULT_PATH_NORMAL
+
+This will be the $PATH used to lookup ExecStart= etc. options, which
+systemd itself uses extensively.
+---
+ src/basic/path-util.h | 6 +++---
+ 1 file changed, 3 insertions(+), 3 deletions(-)
+
+diff --git a/src/basic/path-util.h b/src/basic/path-util.h
+index 97175bee11..3839704901 100644
+--- a/src/basic/path-util.h
++++ b/src/basic/path-util.h
+@@ -25,11 +25,11 @@
+ #  define PATH_SBIN_BIN_NULSTR(x) PATH_NORMAL_SBIN_BIN_NULSTR(x)
+ #endif
+ 
+-#define DEFAULT_PATH_NORMAL PATH_SBIN_BIN("/usr/local/") ":" PATH_SBIN_BIN("/usr/")
+-#define DEFAULT_PATH_NORMAL_NULSTR PATH_SBIN_BIN_NULSTR("/usr/local/") PATH_SBIN_BIN_NULSTR("/usr/")
++#define DEFAULT_PATH_NORMAL "@defaultPathNormal@"
++#define DEFAULT_PATH_NORMAL_NULSTR "@defaultPathNormal@\0"
+ #define DEFAULT_PATH_SPLIT_USR DEFAULT_PATH_NORMAL ":" PATH_SBIN_BIN("/")
+ #define DEFAULT_PATH_SPLIT_USR_NULSTR DEFAULT_PATH_NORMAL_NULSTR PATH_SBIN_BIN_NULSTR("/")
+-#define DEFAULT_PATH_COMPAT PATH_SPLIT_SBIN_BIN("/usr/local/") ":" PATH_SPLIT_SBIN_BIN("/usr/") ":" PATH_SPLIT_SBIN_BIN("/")
++#define DEFAULT_PATH_COMPAT DEFAULT_PATH_NORMAL
+ 
+ #if HAVE_SPLIT_USR
+ #  define DEFAULT_PATH DEFAULT_PATH_SPLIT_USR
diff --git a/pkgs/by-name/sy/systemd/0015-pkg-config-derive-prefix-from-prefix.patch b/pkgs/by-name/sy/systemd/0015-pkg-config-derive-prefix-from-prefix.patch
new file mode 100644
index 0000000000000..3fbfd7f10ab49
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0015-pkg-config-derive-prefix-from-prefix.patch
@@ -0,0 +1,30 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?J=C3=B6rg=20Thalheim?= <joerg@thalheim.io>
+Date: Sun, 6 Dec 2020 08:34:19 +0100
+Subject: [PATCH] pkg-config: derive prefix from --prefix
+
+Point prefix to the one configured, instead of `/usr` `systemd` has limited
+support for making the pkgconfig prefix overridable, and interpolates those
+values later down.
+
+So we only need to patch this one value to get the correct paths.
+See systemd/systemd@bc4e6e27922a2873985ab9367d79fb099f70b505 for details.
+
+Co-Authored-By: Florian Klink <flokli@flokli.de>
+---
+ src/core/systemd.pc.in | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/core/systemd.pc.in b/src/core/systemd.pc.in
+index 5932a21b5b..20bf8e316d 100644
+--- a/src/core/systemd.pc.in
++++ b/src/core/systemd.pc.in
+@@ -11,7 +11,7 @@
+ # considered deprecated (though there is no plan to remove them). New names
+ # shall have underscores.
+ 
+-prefix=/usr
++prefix={{PREFIX}}
+ root_prefix={{ROOTPREFIX_NOSLASH}}
+ rootprefix=${root_prefix}
+ sysconf_dir={{SYSCONF_DIR}}
diff --git a/pkgs/by-name/sy/systemd/0016-inherit-systemd-environment-when-calling-generators.patch b/pkgs/by-name/sy/systemd/0016-inherit-systemd-environment-when-calling-generators.patch
new file mode 100644
index 0000000000000..d6640c87454a8
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0016-inherit-systemd-environment-when-calling-generators.patch
@@ -0,0 +1,39 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Yuriy Taraday <yorik.sar@gmail.com>
+Date: Fri, 17 Jun 2022 12:45:10 +0000
+Subject: [PATCH] inherit systemd environment when calling generators.
+
+Systemd generators need access to the environment configured in
+stage-2-init.sh since it schedules fsck and mkfs executions based on
+being able to find an appropriate binary for the target filesystem.
+
+With this commit I am altering the systemd behaviour since upstream
+tries to gather environments with that they call
+"environment-generators" and then seems to pass that on to all the other
+executables that are being called from managers.
+---
+ src/core/manager.c | 8 ++++++++
+ 1 file changed, 8 insertions(+)
+
+diff --git a/src/core/manager.c b/src/core/manager.c
+index 771e8e7f16..acf3ead8d7 100644
+--- a/src/core/manager.c
++++ b/src/core/manager.c
+@@ -3899,9 +3899,17 @@ static int build_generator_environment(Manager *m, char ***ret) {
+          * adjust generated units to that. Let's pass down some bits of information that are easy for us to
+          * determine (but a bit harder for generator scripts to determine), as environment variables. */
+ 
++        // On NixOS we must propagate PATH to generators so they are
++        // able to find binaries such as `fsck.${fstype}` and
++        // `mkfs.${fstype}`. That is why we ignore transient_environment that
++        // overrides the PATH variable. This propagates systemd's
++        // environment (e.g. PATH) that was setup
++        // before calling systemd from stage-2-init.sh.
++#if 0
+         nl = strv_copy(m->transient_environment);
+         if (!nl)
+                 return -ENOMEM;
++#endif
+ 
+         r = strv_env_assign(&nl, "SYSTEMD_SCOPE", runtime_scope_to_string(m->runtime_scope));
+         if (r < 0)
diff --git a/pkgs/by-name/sy/systemd/0017-core-don-t-taint-on-unmerged-usr.patch b/pkgs/by-name/sy/systemd/0017-core-don-t-taint-on-unmerged-usr.patch
new file mode 100644
index 0000000000000..73b237a29602b
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0017-core-don-t-taint-on-unmerged-usr.patch
@@ -0,0 +1,33 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: oxalica <oxalicc@pm.me>
+Date: Tue, 4 Oct 2022 09:18:07 +0800
+Subject: [PATCH] core: don't taint on unmerged /usr
+
+NixOS has very different approach towards /bin and /sbin - they don't
+really exist (except for /bin/sh and /usr/bin/env, because these are used
+heavily in shebangs around the world). The concept of merged or unmerged
+usr doesn't really apply here at all, it's neither of the two.
+Users don't execute things from /bin or /sbin, there's nothing else in
+there. In all cases, systemd doesn't look things up from /usr/bin or /bin,
+so showing the taint isn't really helpful.
+
+See also: https://github.com/systemd/systemd/issues/24191
+---
+ src/core/manager.c | 4 ----
+ 1 file changed, 4 deletions(-)
+
+diff --git a/src/core/manager.c b/src/core/manager.c
+index acf3ead8d7..bdbab16829 100644
+--- a/src/core/manager.c
++++ b/src/core/manager.c
+@@ -4754,10 +4754,6 @@ char* manager_taint_string(const Manager *m) {
+         if (m->taint_usr)
+                 stage[n++] = "split-usr";
+ 
+-        _cleanup_free_ char *usrbin = NULL;
+-        if (readlink_malloc("/bin", &usrbin) < 0 || !PATH_IN_SET(usrbin, "usr/bin", "/usr/bin"))
+-                stage[n++] = "unmerged-usr";
+-
+         if (access("/proc/cgroups", F_OK) < 0)
+                 stage[n++] = "cgroups-missing";
+ 
diff --git a/pkgs/by-name/sy/systemd/0018-tpm2_context_init-fix-driver-name-checking.patch b/pkgs/by-name/sy/systemd/0018-tpm2_context_init-fix-driver-name-checking.patch
new file mode 100644
index 0000000000000..6de01a0ae8020
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0018-tpm2_context_init-fix-driver-name-checking.patch
@@ -0,0 +1,41 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Nick Cao <nickcao@nichi.co>
+Date: Sun, 15 Jan 2023 20:15:55 +0800
+Subject: [PATCH] tpm2_context_init: fix driver name checking
+
+https://github.com/systemd/systemd/commit/542dbc623e introduced
+additional checks for tpm2 driver names, namely ensuring the driver
+name, when concated with "libtss2-tcti-" and ".so.0", generates a valid
+filename (with no '/' inside).
+
+For example, if the driver is name "device", the line
+  fn = strjoina("libtss2-tcti-", driver, ".so.0")
+would yield "libtss2-tcti-device.so.0", passing the check. And the
+filename is then passed to dlopen for loading the driver.
+
+Our current approach for systemd to correctly locate these dynamically
+loaded libraries is to patch the filenames to include their absolute
+path. Thus the line mentioned above is patched into
+  fn = strjoina("/nix/store/xxxxxxx-tpm2-tss-3.2.0/lib/libtss2-tcti-", driver, ".so.0")
+yielding "/nix/store/xxxxxxx-tpm2-tss-3.2.0/lib/libtss2-tcti-device.so.0",
+tripping the check.
+
+This patch relaxes the check to also accept absolute paths, by replacing
+filename_is_valid with path_is_valid.
+---
+ src/shared/tpm2-util.c | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/src/shared/tpm2-util.c b/src/shared/tpm2-util.c
+index ae8a8bc073..c284b244f8 100644
+--- a/src/shared/tpm2-util.c
++++ b/src/shared/tpm2-util.c
+@@ -582,7 +582,7 @@ int tpm2_context_new(const char *device, Tpm2Context **ret_context) {
+                 fn = strjoina("libtss2-tcti-", driver, ".so.0");
+ 
+                 /* Better safe than sorry, let's refuse strings that cannot possibly be valid driver early, before going to disk. */
+-                if (!filename_is_valid(fn))
++                if (!path_is_valid(fn))
+                         return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "TPM2 driver name '%s' not valid, refusing.", driver);
+ 
+                 context->tcti_dl = dlopen(fn, RTLD_NOW);
diff --git a/pkgs/by-name/sy/systemd/0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch b/pkgs/by-name/sy/systemd/0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch
new file mode 100644
index 0000000000000..dd9af6738c4e5
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch
@@ -0,0 +1,45 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Maximilian Bosch <maximilian@mbosch.me>
+Date: Fri, 1 Sep 2023 09:57:02 +0200
+Subject: [PATCH] systemctl-edit: suggest `systemdctl edit --runtime` on system
+ scope
+
+This is a NixOS-specific change. When trying to modify a unit with
+`systemctl edit` on NixOS, it'll fail with "Read-only file system":
+
+    $ systemctl edit libvirtd
+    Failed to open "/etc/systemd/system/libvirtd.service.d/.#override.conffa9825a0c9a249eb": Read-only file system
+
+This is because `/etc/systemd/system` is a symlink into the store. In
+fact, I'd consider this a feature rather than a bug since this ensures I
+don't introduce state imperatively.
+
+However, people wrongly assume that it's not possible to edit units
+ad-hoc and re-deploy their system for quick&dirty debugging where this
+would be absolutely fine (and doable with `--runtime` which adds a
+transient and non-persistent unit override in `/run`).
+
+To make sure that people learn about it quicker, this patch
+throws an error which suggests using `--runtime` when running
+`systemctl edit` on the system scope.
+
+For the user scope this isn't needed because user-level unit overrides
+are written into `$XDG_CONFIG_HOME/systemd/user`.
+---
+ src/systemctl/systemctl-edit.c | 3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/src/systemctl/systemctl-edit.c b/src/systemctl/systemctl-edit.c
+index e3f25d52d5..81c9c6f6b7 100644
+--- a/src/systemctl/systemctl-edit.c
++++ b/src/systemctl/systemctl-edit.c
+@@ -323,6 +323,9 @@ int verb_edit(int argc, char *argv[], void *userdata) {
+         sd_bus *bus;
+         int r;
+ 
++        if (!arg_runtime && arg_runtime_scope == RUNTIME_SCOPE_SYSTEM)
++                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "The unit-directory '/etc/systemd/system' is read-only on NixOS, so it's not possible to edit system-units directly. Use 'systemctl edit --runtime' instead.");
++
+         if (!on_tty())
+                 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Cannot edit units if not on a tty.");
+ 
diff --git a/pkgs/by-name/sy/systemd/package.nix b/pkgs/by-name/sy/systemd/package.nix
new file mode 100644
index 0000000000000..87e7396c496cb
--- /dev/null
+++ b/pkgs/by-name/sy/systemd/package.nix
@@ -0,0 +1,831 @@
+# NOTE: Make sure to (re-)format this file on changes with `nixpkgs-fmt`!
+
+{ stdenv
+, lib
+, nixosTests
+, pkgsCross
+, fetchFromGitHub
+, fetchpatch
+, fetchzip
+, buildPackages
+, makeBinaryWrapper
+, ninja
+, meson
+, m4
+, pkg-config
+, coreutils
+, gperf
+, getent
+, glibcLocales
+
+  # glib is only used during tests (test-bus-gvariant, test-bus-marshal)
+, glib
+, substituteAll
+, gettext
+, python3Packages
+
+  # Mandatory dependencies
+, libcap
+, util-linux
+, kbd
+, kmod
+, libxcrypt
+
+  # Optional dependencies
+, pam
+, cryptsetup
+, audit
+, acl
+, lz4
+, libgcrypt
+, libgpg-error
+, libidn2
+, curl
+, gnutar
+, gnupg
+, zlib
+, xz
+, zstd
+, tpm2-tss
+, libuuid
+, libapparmor
+, intltool
+, bzip2
+, pcre2
+, e2fsprogs
+, elfutils
+, linuxHeaders ? stdenv.cc.libc.linuxHeaders
+, iptables
+, withSelinux ? false
+, libselinux
+, withLibseccomp ? lib.meta.availableOn stdenv.hostPlatform libseccomp
+, libseccomp
+, withKexectools ? lib.meta.availableOn stdenv.hostPlatform kexec-tools
+, kexec-tools
+, bashInteractive
+, bash
+, libmicrohttpd
+, libfido2
+, p11-kit
+
+  # the (optional) BPF feature requires bpftool, libbpf, clang and llvm-strip to be available during build time.
+  # Only libbpf should be a runtime dependency.
+  # Note: llvmPackages is explicitly taken from buildPackages instead of relying
+  # on splicing. Splicing will evaluate the adjacent (pkgsHostTarget) llvmPackages
+  # which is sometimes problematic: llvmPackages.clang looks at targetPackages.stdenv.cc
+  # which, in the unfortunate case of pkgsCross.ghcjs, `throw`s. If we explicitly
+  # take buildPackages.llvmPackages, this is no problem because
+  # `buildPackages.targetPackages.stdenv.cc == stdenv.cc` relative to us. Working
+  # around this is important, because systemd is in the dependency closure of
+  # GHC via emscripten and jdk.
+, bpftools
+, libbpf
+
+  # Needed to produce a ukify that works for cross compiling UKIs.
+, targetPackages
+
+, withAcl ? true
+, withAnalyze ? true
+, withApparmor ? true
+, withAudit ? true
+, withBootloader ? withEfi && !stdenv.hostPlatform.isMusl # compiles systemd-boot, assumes EFI is available.
+, withCompression ? true  # adds bzip2, lz4, xz and zstd
+, withCoredump ? true
+, withCryptsetup ? true
+, withRepart ? true
+, withDocumentation ? true
+, withEfi ? stdenv.hostPlatform.isEfi
+, withFido2 ? true
+, withFirstboot ? false # conflicts with the NixOS /etc management
+, withHomed ? !stdenv.hostPlatform.isMusl
+, withHostnamed ? true
+, withHwdb ? true
+, withImportd ? !stdenv.hostPlatform.isMusl
+, withKmod ? true
+, withLibBPF ? lib.versionAtLeast buildPackages.llvmPackages.clang.version "10.0"
+    && (stdenv.hostPlatform.isAarch -> lib.versionAtLeast stdenv.hostPlatform.parsed.cpu.version "6") # assumes hard floats
+    && !stdenv.hostPlatform.isMips64   # see https://github.com/NixOS/nixpkgs/pull/194149#issuecomment-1266642211
+    # buildPackages.targetPackages.llvmPackages is the same as llvmPackages,
+    # but we do it this way to avoid taking llvmPackages as an input, and
+    # risking making it too easy to ignore the above comment about llvmPackages.
+    && lib.meta.availableOn stdenv.hostPlatform buildPackages.targetPackages.llvmPackages.compiler-rt
+, withLibidn2 ? true
+, withLocaled ? true
+, withLogind ? true
+, withMachined ? true
+, withNetworkd ? true
+, withNss ? !stdenv.hostPlatform.isMusl
+, withOomd ? true
+, withPam ? true
+, withPasswordQuality ? false
+, withPCRE2 ? true
+, withPolkit ? true
+, withPortabled ? !stdenv.hostPlatform.isMusl
+, withRemote ? !stdenv.hostPlatform.isMusl
+, withResolved ? true
+, withShellCompletions ? true
+, withSysusers ? true
+, withSysupdate ? true
+, withTimedated ? true
+, withTimesyncd ? true
+, withTpm2Tss ? true
+, withUkify ? false  # adds python to closure which is too much by default
+, withUserDb ? true
+, withUtmp ? !stdenv.hostPlatform.isMusl
+  # tests assume too much system access for them to be feasible for us right now
+, withTests ? false
+  # build only libudev and libsystemd
+, buildLibsOnly ? false
+
+  # name argument
+, pname ? "systemd"
+
+, libxslt
+, docbook_xsl
+, docbook_xml_dtd_42
+, docbook_xml_dtd_45
+}:
+
+assert withBootloader -> withEfi;
+assert withCoredump -> withCompression;
+assert withHomed -> withCryptsetup;
+assert withHomed -> withPam;
+assert withImportd -> withCompression;
+assert withRepart -> withCryptsetup;
+assert withUkify -> withEfi;
+# passwdqc is not in nixpkgs yet. Feel free to please submit a PR.
+assert !withPasswordQuality;
+
+let
+  wantCurl = withRemote || withImportd;
+  wantGcrypt = withResolved || withImportd;
+  version = "254.3";
+
+  # Bump this variable on every (major) version change. See below (in the meson
+  # options list) for why.
+  # Use the script below to do this:
+  #  $ curl -s https://api.github.com/repos/systemd/systemd/releases/latest | \
+  #     jq '.created_at|strptime("%Y-%m-%dT%H:%M:%SZ")|mktime'
+  releaseTimestamp = "1690536449";
+in
+stdenv.mkDerivation (finalAttrs: {
+  inherit pname version;
+
+  # We use systemd/systemd-stable for src, and ship NixOS-specific patches
+  # inside nixpkgs directly This has proven to be less error-prone than the
+  # previous systemd fork.
+  src = fetchFromGitHub {
+    owner = "systemd";
+    repo = "systemd-stable";
+    rev = "v${version}";
+    hash = "sha256-ObnsAiKwhwEb4ti611eS/wGpg3Sss/pUy/gANPAbXbs=";
+  };
+
+  # On major changes, or when otherwise required, you *must* reformat the
+  # patches, `git am path/to/00*.patch` them into a systemd worktree, rebase to
+  # the more recent systemd version, and export the patches again via
+  # `git -c format.signoff=false format-patch v${version} --no-numbered --zero-commit --no-signature`.
+  # Use `find . -name "*.patch" | sort` to get an up-to-date listing of all patches
+  patches = [
+    ./0001-Start-device-units-for-uninitialised-encrypted-devic.patch
+    ./0002-Don-t-try-to-unmount-nix-or-nix-store.patch
+    ./0003-Fix-NixOS-containers.patch
+    ./0004-Add-some-NixOS-specific-unit-directories.patch
+    ./0005-Get-rid-of-a-useless-message-in-user-sessions.patch
+    ./0006-hostnamed-localed-timedated-disable-methods-that-cha.patch
+    ./0007-Fix-hwdb-paths.patch
+    ./0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
+    ./0009-localectl-use-etc-X11-xkb-for-list-x11.patch
+    ./0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
+    ./0011-add-rootprefix-to-lookup-dir-paths.patch
+    ./0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
+    ./0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
+    ./0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
+    ./0015-pkg-config-derive-prefix-from-prefix.patch
+    ./0016-inherit-systemd-environment-when-calling-generators.patch
+    ./0017-core-don-t-taint-on-unmerged-usr.patch
+    ./0018-tpm2_context_init-fix-driver-name-checking.patch
+    ./0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch
+
+    # Fix for `RuntimeError: ELF .dynamic section is missing.`
+    # https://github.com/systemd/systemd/issues/29381
+    # https://github.com/systemd/systemd/pull/29392
+    (fetchpatch {
+      url = "https://github.com/systemd/systemd/commit/cecbb162a3134b43d2ca160e13198c73ff34c3ef.patch";
+      hash = "sha256-hWpUosTDA18mYm5nIb9KnjwOlnzbEHgzha/WpyHoC54=";
+    })
+  ] ++ lib.optional stdenv.hostPlatform.isMusl (
+    let
+      oe-core = fetchzip {
+        url = "https://git.openembedded.org/openembedded-core/snapshot/openembedded-core-eb8a86fee9eeae787cc0a58ef2ed087fd48d93eb.tar.gz";
+        sha256 = "tE2KpXLvOknIpEZFdOnNxvBmDvZrra3kvQp9tKxa51c=";
+      };
+      musl-patches = oe-core + "/meta/recipes-core/systemd/systemd";
+    in
+    [
+      (musl-patches + "/0001-Adjust-for-musl-headers.patch")
+      (musl-patches + "/0005-pass-correct-parameters-to-getdents64.patch")
+      (musl-patches + "/0006-test-bus-error-strerror-is-assumed-to-be-GNU-specifi.patch")
+      (musl-patches + "/0009-missing_type.h-add-comparison_fn_t.patch")
+      (musl-patches + "/0010-add-fallback-parse_printf_format-implementation.patch")
+      (musl-patches + "/0011-src-basic-missing.h-check-for-missing-strndupa.patch")
+      (musl-patches + "/0012-don-t-fail-if-GLOB_BRACE-and-GLOB_ALTDIRFUNC-is-not-.patch")
+      (musl-patches + "/0013-add-missing-FTW_-macros-for-musl.patch")
+      (musl-patches + "/0014-Use-uintmax_t-for-handling-rlim_t.patch")
+      (musl-patches + "/0016-don-t-pass-AT_SYMLINK_NOFOLLOW-flag-to-faccessat.patch")
+      (musl-patches + "/0017-Define-glibc-compatible-basename-for-non-glibc-syste.patch")
+      (musl-patches + "/0018-Do-not-disable-buffering-when-writing-to-oom_score_a.patch")
+      (musl-patches + "/0019-distinguish-XSI-compliant-strerror_r-from-GNU-specif.patch")
+      (musl-patches + "/0020-avoid-redefinition-of-prctl_mm_map-structure.patch")
+      (musl-patches + "/0021-do-not-disable-buffer-in-writing-files.patch")
+      (musl-patches + "/0022-Handle-__cpu_mask-usage.patch")
+      (musl-patches + "/0023-Handle-missing-gshadow.patch")
+      (musl-patches + "/0024-missing_syscall.h-Define-MIPS-ABI-defines-for-musl.patch")
+      (musl-patches + "/0028-sd-event-Make-malloc_trim-conditional-on-glibc.patch")
+      (musl-patches + "/0029-shared-Do-not-use-malloc_info-on-musl.patch")
+    ]
+  );
+
+  postPatch = ''
+    substituteInPlace src/basic/path-util.h --replace "@defaultPathNormal@" "${placeholder "out"}/bin/"
+  '' + lib.optionalString withLibBPF ''
+    substituteInPlace meson.build \
+      --replace "find_program('clang'" "find_program('${stdenv.cc.targetPrefix}clang'"
+  '' + lib.optionalString withUkify ''
+    substituteInPlace src/ukify/ukify.py \
+      --replace \
+      "'readelf'" \
+      "'${targetPackages.stdenv.cc.bintools.targetPrefix}readelf'"
+  '' + (
+    let
+      # The following patches references to dynamic libraries to ensure that
+      # all the features that are implemented via dlopen(3) are available (or
+      # explicitly deactivated) by pointing dlopen to the absolute store path
+      # instead of relying on the linkers runtime lookup code.
+      #
+      # All of the shared library references have to be handled. When new ones
+      # are introduced by upstream (or one of our patches) they must be
+      # explicitly declared, otherwise the build will fail.
+      #
+      # As of systemd version 247 we've seen a few errors like `libpcre2.… not
+      # found` when using e.g. --grep with journalctl. Those errors should
+      # become less unexpected now.
+      #
+      # There are generally two classes of dlopen(3) calls. Those that we want to
+      # support and those that should be deactivated / unsupported. This change
+      # enforces that we handle all dlopen calls explicitly. Meaning: There is
+      # not a single dlopen call in the source code tree that we did not
+      # explicitly handle.
+      #
+      # In order to do this we introduced a list of attributes that maps from
+      # shared object name to the package that contains them. The package can be
+      # null meaning the reference should be nuked and the shared object will
+      # never be loadable during runtime (because it points at an invalid store
+      # path location).
+      #
+      # To get a list of dynamically loaded libraries issue something like
+      # `grep -ri '"lib[a-zA-Z0-9-]*\.so[\.0-9a-zA-z]*"'' $src` and update the below list.
+      dlopenLibs =
+        let
+          opt = condition: pkg: if condition then pkg else null;
+        in
+        [
+          # bpf compilation support. We use libbpf 1 now.
+          { name = "libbpf.so.1"; pkg = opt withLibBPF libbpf; }
+          { name = "libbpf.so.0"; pkg = null; }
+
+          # We did never provide support for libxkbcommon & qrencode
+          { name = "libxkbcommon.so.0"; pkg = null; }
+          { name = "libqrencode.so.4"; pkg = null; }
+          { name = "libqrencode.so.3"; pkg = null; }
+
+          # We did not provide libpwquality before so it is safe to disable it for
+          # now.
+          { name = "libpwquality.so.1"; pkg = null; }
+
+          # Only include cryptsetup if it is enabled. We might not be able to
+          # provide it during "bootstrap" in e.g. the minimal systemd build as
+          # cryptsetup has udev (aka systemd) in it's dependencies.
+          { name = "libcryptsetup.so.12"; pkg = opt withCryptsetup cryptsetup; }
+
+          # We are using libidn2 so we only provide that and ignore the others.
+          # Systemd does this decision during configure time and uses ifdef's to
+          # enable specific branches. We can safely ignore (nuke) the libidn "v1"
+          # libraries.
+          { name = "libidn2.so.0"; pkg = opt withLibidn2 libidn2; }
+          { name = "libidn.so.12"; pkg = null; }
+          { name = "libidn.so.11"; pkg = null; }
+
+          # journalctl --grep requires libpcre so let's provide it
+          { name = "libpcre2-8.so.0"; pkg = pcre2; }
+
+          # Support for TPM2 in systemd-cryptsetup, systemd-repart and systemd-cryptenroll
+          { name = "libtss2-esys.so.0"; pkg = opt withTpm2Tss tpm2-tss; }
+          { name = "libtss2-rc.so.0"; pkg = opt withTpm2Tss tpm2-tss; }
+          { name = "libtss2-mu.so.0"; pkg = opt withTpm2Tss tpm2-tss; }
+          { name = "libtss2-tcti-"; pkg = opt withTpm2Tss tpm2-tss; }
+          { name = "libfido2.so.1"; pkg = opt withFido2 libfido2; }
+
+          # inspect-elf support
+          { name = "libelf.so.1"; pkg = opt withCoredump elfutils; }
+          { name = "libdw.so.1"; pkg = opt withCoredump elfutils; }
+
+          # Support for PKCS#11 in systemd-cryptsetup, systemd-cryptenroll and systemd-homed
+          { name = "libp11-kit.so.0"; pkg = opt (withHomed || withCryptsetup) p11-kit; }
+
+          # Password quality support
+          { name = "libpasswdqc.so.1"; pkg = opt withPasswordQuality null; }
+        ];
+
+      patchDlOpen = dl:
+        let
+          library = "${lib.makeLibraryPath [ dl.pkg ]}/${dl.name}";
+        in
+        if dl.pkg == null then ''
+          # remove the dependency on the library by replacing it with an invalid path
+          for file in $(grep -lr '"${dl.name}"' src); do
+            echo "patching dlopen(\"${dl.name}\", …) in $file to an invalid store path ("${builtins.storeDir}/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-not-implemented/${dl.name}")…"
+            substituteInPlace "$file" --replace '"${dl.name}"' '"${builtins.storeDir}/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-not-implemented/${dl.name}"'
+          done
+        '' else ''
+          # ensure that the library we provide actually exists
+          if ! [ -e ${library} ]; then
+            # exceptional case, details:
+            # https://github.com/systemd/systemd-stable/blob/v249-stable/src/shared/tpm2-util.c#L157
+            if ! [[ "${library}" =~ .*libtss2-tcti-$ ]]; then
+              echo 'The shared library `${library}` does not exist but was given as substitute for `${dl.name}`'
+              exit 1
+            fi
+          fi
+          # make the path to the dependency explicit
+          for file in $(grep -lr '"${dl.name}"' src); do
+            echo "patching dlopen(\"${dl.name}\", …) in $file to ${library}…"
+            substituteInPlace "$file" --replace '"${dl.name}"' '"${library}"'
+          done
+
+        '';
+    in
+    # patch all the dlopen calls to contain absolute paths to the libraries
+    lib.concatMapStringsSep "\n" patchDlOpen dlopenLibs
+  )
+  # finally ensure that there are no left-over dlopen calls (or rather strings pointing to shared libraries) that we didn't handle
+  + ''
+    if grep -qr '"lib[a-zA-Z0-9-]*\.so[\.0-9a-zA-z]*"' src; then
+      echo "Found unhandled dynamic library calls: "
+      grep -r '"lib[a-zA-Z0-9-]*\.so[\.0-9a-zA-z]*"' src
+      exit 1
+    fi
+  ''
+  # Finally, patch shebangs in scripts used at build time. This must not patch
+  # scripts that will end up in the output, to avoid build platform references
+  # when cross-compiling.
+  + ''
+    shopt -s extglob
+    patchShebangs tools test src/!(rpm|kernel-install|ukify) src/kernel-install/test-kernel-install.sh
+  '';
+
+  outputs = [ "out" "dev" ] ++ (lib.optional (!buildLibsOnly) "man");
+
+  nativeBuildInputs =
+    [
+      pkg-config
+      makeBinaryWrapper
+      gperf
+      ninja
+      meson
+      glibcLocales
+      getent
+      m4
+
+      intltool
+      gettext
+
+      libxslt
+      docbook_xsl
+      docbook_xml_dtd_42
+      docbook_xml_dtd_45
+      bash
+      (buildPackages.python3Packages.python.withPackages (ps: with ps; [ lxml jinja2 ] ++ lib.optional withEfi ps.pyelftools))
+    ]
+    ++ lib.optionals withLibBPF [
+      bpftools
+      buildPackages.llvmPackages.clang
+      buildPackages.llvmPackages.libllvm
+    ]
+  ;
+
+  buildInputs =
+    [
+      libxcrypt
+      libcap
+      libuuid
+      linuxHeaders
+      bashInteractive # for patch shebangs
+    ]
+
+    ++ lib.optionals wantGcrypt [ libgcrypt libgpg-error ]
+    ++ lib.optional withTests glib
+    ++ lib.optional withAcl acl
+    ++ lib.optional withApparmor libapparmor
+    ++ lib.optional withAudit audit
+    ++ lib.optional wantCurl (lib.getDev curl)
+    ++ lib.optionals withCompression [ bzip2 lz4 xz zstd ]
+    ++ lib.optional withCoredump elfutils
+    ++ lib.optional withCryptsetup (lib.getDev cryptsetup.dev)
+    ++ lib.optional withKexectools kexec-tools
+    ++ lib.optional withKmod kmod
+    ++ lib.optional withLibidn2 libidn2
+    ++ lib.optional withLibseccomp libseccomp
+    ++ lib.optional withNetworkd iptables
+    ++ lib.optional withPam pam
+    ++ lib.optional withPCRE2 pcre2
+    ++ lib.optional withSelinux libselinux
+    ++ lib.optional withRemote libmicrohttpd
+    ++ lib.optionals (withHomed || withCryptsetup) [ p11-kit ]
+    ++ lib.optionals (withHomed || withCryptsetup) [ libfido2 ]
+    ++ lib.optionals withLibBPF [ libbpf ]
+    ++ lib.optional withTpm2Tss tpm2-tss
+    ++ lib.optional withUkify (python3Packages.python.withPackages (ps: with ps; [ pefile ]))
+  ;
+
+  mesonBuildType = "release";
+
+  mesonFlags = [
+    (lib.mesonOption "version-tag" version)
+    # We bump this variable on every (major) version change to ensure that we
+    # have known-good value for a timestamp that is in the (not so distant)
+    # past.
+    # This serves as a lower bound for valid system timestamps during
+    # startup. Systemd will reset the system timestamp if this date is +- 15
+    # years from the system time.
+    #
+    # See the systemd v250 release notes for further details:
+    # https://github.com/systemd/systemd/blob/60e930fc3e6eb8a36fbc184773119eb8d2f30364/NEWS#L258-L266
+    (lib.mesonOption "time-epoch" releaseTimestamp)
+
+    (lib.mesonOption "mode" "release")
+    (lib.mesonOption "dbuspolicydir" "${placeholder "out"}/share/dbus-1/system.d")
+    (lib.mesonOption "dbussessionservicedir" "${placeholder "out"}/share/dbus-1/services")
+    (lib.mesonOption "dbussystemservicedir" "${placeholder "out"}/share/dbus-1/system-services")
+
+    (lib.mesonBool "pam" withPam)
+    (lib.mesonOption "pamconfdir" "${placeholder "out"}/etc/pam.d")
+    (lib.mesonOption "rootprefix" "${placeholder "out"}")
+    (lib.mesonOption "pkgconfiglibdir" "${placeholder "dev"}/lib/pkgconfig")
+    (lib.mesonOption "pkgconfigdatadir" "${placeholder "dev"}/share/pkgconfig")
+    (lib.mesonOption "loadkeys-path" "${kbd}/bin/loadkeys")
+    (lib.mesonOption "setfont-path" "${kbd}/bin/setfont")
+    (lib.mesonOption "tty-gid" "3") # tty in NixOS has gid 3
+    (lib.mesonOption "debug-shell" "${bashInteractive}/bin/bash")
+    (lib.mesonBool "glib" withTests)
+    # while we do not run tests we should also not build them. Removes about 600 targets
+    (lib.mesonBool "tests" false)
+    (lib.mesonBool "acl" withAcl)
+    (lib.mesonBool "analyze" withAnalyze)
+    (lib.mesonBool "audit" withAudit)
+    (lib.mesonBool "gcrypt" wantGcrypt)
+    (lib.mesonBool "importd" withImportd)
+    (lib.mesonBool "lz4" withCompression)
+    (lib.mesonBool "homed" withHomed)
+    (lib.mesonBool "logind" withLogind)
+    (lib.mesonBool "localed" withLocaled)
+    (lib.mesonBool "hostnamed" withHostnamed)
+    (lib.mesonBool "machined" withMachined)
+    (lib.mesonBool "networkd" withNetworkd)
+    (lib.mesonBool "oomd" withOomd)
+    (lib.mesonBool "polkit" withPolkit)
+    (lib.mesonBool "libcryptsetup" withCryptsetup)
+    (lib.mesonBool "portabled" withPortabled)
+    (lib.mesonBool "hwdb" withHwdb)
+    (lib.mesonBool "remote" withRemote)
+    (lib.mesonBool "timedated" withTimedated)
+    (lib.mesonBool "timesyncd" withTimesyncd)
+    (lib.mesonBool "userdb" withUserDb)
+    (lib.mesonBool "coredump" withCoredump)
+    (lib.mesonBool "firstboot" false)
+    (lib.mesonBool "resolve" withResolved)
+    (lib.mesonBool "split-usr" false)
+    (lib.mesonBool "libcurl" wantCurl)
+    (lib.mesonBool "libidn" false)
+    (lib.mesonBool "libidn2" withLibidn2)
+    (lib.mesonBool "firstboot" withFirstboot)
+    (lib.mesonBool "sysusers" withSysusers)
+    (lib.mesonBool "repart" withRepart)
+    (lib.mesonBool "sysupdate" withSysupdate)
+    (lib.mesonBool "quotacheck" false)
+    (lib.mesonBool "ldconfig" false)
+    (lib.mesonBool "smack" true)
+    (lib.mesonBool "b_pie" true)
+    (lib.mesonBool "install-sysconfdir" false)
+    (lib.mesonOption "sbat-distro" "nixos")
+    (lib.mesonOption "sbat-distro-summary" "NixOS")
+    (lib.mesonOption "sbat-distro-url" "https://nixos.org/")
+    (lib.mesonOption "sbat-distro-pkgname" "${pname}")
+    (lib.mesonOption "sbat-distro-version" "${version}")
+    /*
+      As of now, systemd doesn't allow runtime configuration of these values. So
+      the settings in /etc/login.defs have no effect on it. Many people think this
+      should be supported however, see
+      - https://github.com/systemd/systemd/issues/3855
+      - https://github.com/systemd/systemd/issues/4850
+      - https://github.com/systemd/systemd/issues/9769
+      - https://github.com/systemd/systemd/issues/9843
+      - https://github.com/systemd/systemd/issues/10184
+    */
+    (lib.mesonOption "system-uid-max" "999")
+    (lib.mesonOption "system-gid-max" "999")
+
+    (lib.mesonOption "sysvinit-path" "")
+    (lib.mesonOption "sysvrcnd-path" "")
+
+    (lib.mesonOption "sulogin-path" "${util-linux.login}/bin/sulogin")
+    (lib.mesonOption "nologin-path" "${util-linux.login}/bin/nologin")
+    (lib.mesonOption "mount-path" "${lib.getOutput "mount" util-linux}/bin/mount")
+    (lib.mesonOption "umount-path" "${lib.getOutput "mount" util-linux}/bin/umount")
+    (lib.mesonBool "create-log-dirs" false)
+
+    # Use cgroupsv2. This is already the upstream default, but better be explicit.
+    (lib.mesonOption "default-hierarchy" "unified")
+    # Upstream defaulted to disable manpages since they optimize for the much
+    # more frequent development builds
+    (lib.mesonBool "man" true)
+
+    (lib.mesonBool "efi" withEfi)
+    (lib.mesonBool "bootloader" withBootloader)
+
+    (lib.mesonBool "ukify" withUkify)
+  ] ++ lib.optionals (withShellCompletions == false) [
+    (lib.mesonOption "bashcompletiondir" "no")
+    (lib.mesonOption "zshcompletiondir" "no")
+
+    (lib.mesonBool "nss-myhostname" withNss)
+    (lib.mesonBool "nss-mymachines" withNss)
+    (lib.mesonBool "nss-resolve" withNss)
+    (lib.mesonBool "nss-systemd" withNss)
+    (lib.mesonBool "bpf-framework" withLibBPF)
+    (lib.mesonBool "tpm2" withTpm2Tss)
+    (lib.mesonBool "utmp" withUtmp)
+    (lib.mesonBool "gshadow" (!stdenv.hostPlatform.isMusl))
+    (lib.mesonBool "idn" (!stdenv.hostPlatform.isMusl))
+  ] ++ lib.optionals withKmod [
+    (lib.mesonBool "kmod" true)
+    (lib.mesonOption "kmod-path" "${kmod}/bin/kmod")
+  ];
+
+  preConfigure =
+    let
+      # A list of all the runtime binaries that the systemd executables, tests
+      # and libraries are referencing in their source code, scripts and unit
+      # files.
+      # As soon as a dependency isn't required anymore we should remove it from
+      # the list. The `where` attribute for each of the replacement patterns
+      # must be exhaustive. If another (unhandled) case is found in the source
+      # code the build fails with an error message.
+      binaryReplacements = [
+        {
+          search = "/usr/bin/getent";
+          replacement = "${getent}/bin/getent";
+          where = [ "src/nspawn/nspawn-setuid.c" ];
+        }
+        {
+          search = "/sbin/mkswap";
+          replacement = "${lib.getBin util-linux}/sbin/mkswap";
+          where = [ "man/systemd-makefs@.service.xml" ];
+        }
+        {
+          search = "/sbin/swapon";
+          replacement = "${lib.getOutput "swap" util-linux}/sbin/swapon";
+          where = [
+            "src/core/swap.c"
+            "src/basic/unit-def.h"
+          ];
+        }
+        {
+          search = "/sbin/swapoff";
+          replacement = "${lib.getOutput "swap" util-linux}/sbin/swapoff";
+          where = [ "src/core/swap.c" ];
+        }
+        {
+          search = "/bin/echo";
+          replacement = "${coreutils}/bin/echo";
+          where = [
+            "man/systemd-analyze.xml"
+            "man/systemd.service.xml"
+            "man/systemd-run.xml"
+            "src/analyze/test-verify.c"
+            "src/test/test-env-file.c"
+            "src/test/test-fileio.c"
+            "src/test/test-load-fragment.c"
+          ];
+        }
+        {
+          search = "/bin/cat";
+          replacement = "${coreutils}/bin/cat";
+          where = [
+            "test/test-execute/exec-noexecpaths-simple.service"
+            "src/journal/cat.c"
+          ];
+        }
+        {
+          search = "/usr/lib/systemd/systemd-fsck";
+          replacement = "$out/lib/systemd/systemd-fsck";
+          where = [ "man/systemd-fsck@.service.xml" ];
+        }
+      ] ++ lib.optionals withImportd [
+        {
+          search = "\"gpg\"";
+          replacement = "\\\"${gnupg}/bin/gpg\\\"";
+          where = [ "src/import/pull-common.c" ];
+        }
+        {
+          search = "\"tar\"";
+          replacement = "\\\"${gnutar}/bin/tar\\\"";
+          where = [
+            "src/import/export-tar.c"
+            "src/import/import-common.c"
+            "src/import/import-tar.c"
+          ];
+          ignore = [
+            # occurrences here refer to the tar sub command
+            "src/sysupdate/sysupdate-resource.c"
+            "src/sysupdate/sysupdate-transfer.c"
+            "src/import/pull.c"
+            "src/import/export.c"
+            "src/import/import.c"
+            "src/import/importd.c"
+            # runs `tar` but also also creates a temporary directory with the string
+            "src/import/pull-tar.c"
+          ];
+        }
+      ] ++ lib.optionals withKmod [
+        { search = "/sbin/modprobe"; replacement = "${lib.getBin kmod}/sbin/modprobe"; where = [ "units/modprobe@.service" ]; }
+      ];
+
+      # { replacement, search, where } -> List[str]
+      mkSubstitute = { replacement, search, where, ignore ? [ ] }:
+        map (path: "substituteInPlace ${path} --replace '${search}' \"${replacement}\"") where;
+      mkEnsureSubstituted = { replacement, search, where, ignore ? [ ] }:
+        let
+          ignore' = lib.concatStringsSep "|" (ignore ++ [ "^test" "NEWS" ]);
+        in
+        ''
+          set +e
+          search=$(grep '${search}' -r | grep -v "${replacement}" | grep -Ev "${ignore'}")
+          set -e
+          if [[ -n "$search" ]]; then
+            echo "Not all references to '${search}' have been replaced. Found the following matches:"
+            echo "$search"
+            exit 1
+          fi
+        '';
+    in
+    ''
+      mesonFlagsArray+=(-Dntp-servers="0.nixos.pool.ntp.org 1.nixos.pool.ntp.org 2.nixos.pool.ntp.org 3.nixos.pool.ntp.org")
+      export LC_ALL="en_US.UTF-8";
+
+      ${lib.concatStringsSep "\n" (lib.flatten (map mkSubstitute binaryReplacements))}
+      ${lib.concatMapStringsSep "\n" mkEnsureSubstituted binaryReplacements}
+
+      substituteInPlace src/libsystemd/sd-journal/catalog.c \
+        --replace /usr/lib/systemd/catalog/ $out/lib/systemd/catalog/
+
+      substituteInPlace src/import/pull-tar.c \
+        --replace 'wait_for_terminate_and_check("tar"' 'wait_for_terminate_and_check("${gnutar}/bin/tar"'
+    '';
+
+  # These defines are overridden by CFLAGS and would trigger annoying
+  # warning messages
+  postConfigure = ''
+    substituteInPlace config.h \
+      --replace "POLKIT_AGENT_BINARY_PATH" "_POLKIT_AGENT_BINARY_PATH" \
+      --replace "SYSTEMD_BINARY_PATH" "_SYSTEMD_BINARY_PATH" \
+      --replace "SYSTEMD_CGROUP_AGENTS_PATH" "_SYSTEMD_CGROUP_AGENT_PATH"
+  '';
+
+  env.NIX_CFLAGS_COMPILE = toString ([
+    # Can't say ${polkit.bin}/bin/pkttyagent here because that would lead to a
+    # cyclic dependency.
+    "-UPOLKIT_AGENT_BINARY_PATH"
+    "-DPOLKIT_AGENT_BINARY_PATH=\"/run/current-system/sw/bin/pkttyagent\""
+
+    # Set the release_agent on /sys/fs/cgroup/systemd to the currently running
+    # systemd (/run/current-system/systemd) so that we don't use an
+    # obsolete/garbage-collected release agent.
+    "-USYSTEMD_CGROUP_AGENTS_PATH"
+    "-DSYSTEMD_CGROUP_AGENTS_PATH=\"/run/current-system/systemd/lib/systemd/systemd-cgroups-agent\""
+
+    "-USYSTEMD_BINARY_PATH"
+    "-DSYSTEMD_BINARY_PATH=\"/run/current-system/systemd/lib/systemd/systemd\""
+
+  ] ++ lib.optionals stdenv.hostPlatform.isMusl [
+    "-D__UAPI_DEF_ETHHDR=0"
+  ]);
+
+  doCheck = false; # fails a bunch of tests
+
+  # trigger the test -n "$DESTDIR" || mutate in upstreams build system
+  preInstall = ''
+    export DESTDIR=/
+  '';
+
+  mesonInstallTags = lib.optionals buildLibsOnly [ "devel" "libudev" "libsystemd" ];
+
+  postInstall = lib.optionalString (!buildLibsOnly) ''
+    mkdir -p $out/example/systemd
+    mv $out/lib/{binfmt.d,sysctl.d,tmpfiles.d} $out/example
+    mv $out/lib/systemd/{system,user} $out/example/systemd
+
+    rm -rf $out/etc/systemd/system
+
+    # Fix reference to /bin/false in the D-Bus services.
+    for i in $out/share/dbus-1/system-services/*.service; do
+      substituteInPlace $i --replace /bin/false ${coreutils}/bin/false
+    done
+
+    rm -rf $out/etc/rpm
+
+    # "kernel-install" shouldn't be used on NixOS.
+    find $out -name "*kernel-install*" -exec rm {} \;
+  '' + lib.optionalString (!withDocumentation) ''
+    rm -rf $out/share/doc
+  '' + lib.optionalString (withKmod && !buildLibsOnly) ''
+    mv $out/lib/modules-load.d $out/example
+  '' + lib.optionalString withSysusers ''
+    mv $out/lib/sysusers.d $out/example
+  '';
+
+  # Avoid *.EFI binary stripping. At least on aarch64-linux strip removes too
+  # much from PE32+ files:
+  #   https://github.com/NixOS/nixpkgs/issues/169693
+  # The hack is to move EFI file out of lib/ before doStrip run and return it
+  # after doStrip run.
+  preFixup = lib.optionalString withBootloader ''
+    mv $out/lib/systemd/boot/efi $out/dont-strip-me
+  '';
+
+  # Wrap in the correct path for LUKS2 tokens.
+  postFixup = lib.optionalString withCryptsetup ''
+    for f in lib/systemd/systemd-cryptsetup bin/systemd-cryptenroll; do
+      # This needs to be in LD_LIBRARY_PATH because rpath on a binary is not
+      # propagated to libraries using dlopen, in this case `libcryptsetup.so`
+      wrapProgram $out/$f --prefix LD_LIBRARY_PATH : ${placeholder "out"}/lib/cryptsetup
+    done
+  '' + lib.optionalString withBootloader ''
+    mv $out/dont-strip-me $out/lib/systemd/boot/efi
+  '' + lib.optionalString withUkify ''
+    # To cross compile a derivation that builds a UKI with ukify, we need to
+    # wrap ukify with the correct binutils. When wrapping, no splicing happens
+    # so we have to explicitly pull binutils from targetPackages.
+    wrapProgram $out/lib/systemd/ukify --prefix PATH : ${lib.makeBinPath [ targetPackages.stdenv.cc.bintools ] }:${placeholder "out"}/lib/systemd
+  '';
+
+  disallowedReferences = lib.optionals (stdenv.buildPlatform != stdenv.hostPlatform)
+    # 'or p' is for manually specified buildPackages as they dont have __spliced
+    (builtins.map (p: p.__spliced.buildHost or p) finalAttrs.nativeBuildInputs);
+
+  passthru = {
+    # The interface version prevents NixOS from switching to an incompatible
+    # systemd at runtime.
+    # (Switching across reboots is fine, of course.)
+    # It should be increased whenever systemd changes in a
+    # backwards-incompatible way.
+    # If the interface version of two systemd builds is the same, then we can
+    # switch between them at runtime; otherwise we can't and we need to reboot.
+    interfaceVersion = 2;
+
+    inherit withCryptsetup withHostnamed withImportd withKmod withLocaled withMachined withPortabled withTimedated withUtmp util-linux kmod kbd;
+
+    tests = {
+      inherit (nixosTests) switchTest;
+      cross = pkgsCross.${if stdenv.buildPlatform.isAarch64 then "gnu64" else "aarch64-multiplatform"}.systemd;
+    };
+  };
+
+  meta = with lib; {
+    homepage = "https://www.freedesktop.org/wiki/Software/systemd/";
+    description = "A system and service manager for Linux";
+    longDescription = ''
+      systemd is a suite of basic building blocks for a Linux system. It
+      provides a system and service manager that runs as PID 1 and starts the
+      rest of the system. systemd provides aggressive parallelization
+      capabilities, uses socket and D-Bus activation for starting services,
+      offers on-demand starting of daemons, keeps track of processes using Linux
+      control groups, maintains mount and automount points, and implements an
+      elaborate transactional dependency-based service control logic. systemd
+      supports SysV and LSB init scripts and works as a replacement for
+      sysvinit. Other parts include a logging daemon, utilities to control basic
+      system configuration like the hostname, date, locale, maintain a list of
+      logged-in users and running containers and virtual machines, system
+      accounts, runtime directories and settings, and daemons to manage simple
+      network configuration, network time synchronization, log forwarding, and
+      name resolution.
+    '';
+    license = licenses.lgpl21Plus;
+    platforms = platforms.linux;
+    badPlatforms = [ lib.systems.inspect.platformPatterns.isStatic ];
+    # https://github.com/systemd/systemd/issues/20600#issuecomment-912338965
+    broken = stdenv.hostPlatform.isStatic;
+    priority = 10;
+    maintainers = with maintainers; [ flokli kloenk ];
+  };
+})