summary refs log tree commit diff
path: root/pkgs/os-specific/linux/systemd
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs/os-specific/linux/systemd')
-rw-r--r--pkgs/os-specific/linux/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch19
-rw-r--r--pkgs/os-specific/linux/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch39
-rw-r--r--pkgs/os-specific/linux/systemd/0003-Fix-NixOS-containers.patch17
-rw-r--r--pkgs/os-specific/linux/systemd/0004-Add-some-NixOS-specific-unit-directories.patch (renamed from pkgs/os-specific/linux/systemd/0005-Add-some-NixOS-specific-unit-directories.patch)63
-rw-r--r--pkgs/os-specific/linux/systemd/0004-Look-for-fsck-in-the-right-place.patch25
-rw-r--r--pkgs/os-specific/linux/systemd/0005-Get-rid-of-a-useless-message-in-user-sessions.patch28
-rw-r--r--pkgs/os-specific/linux/systemd/0006-Get-rid-of-a-useless-message-in-user-sessions.patch31
-rw-r--r--pkgs/os-specific/linux/systemd/0006-hostnamed-localed-timedated-disable-methods-that-cha.patch (renamed from pkgs/os-specific/linux/systemd/0007-hostnamed-localed-timedated-disable-methods-that-cha.patch)49
-rw-r--r--pkgs/os-specific/linux/systemd/0007-Fix-hwdb-paths.patch24
-rw-r--r--pkgs/os-specific/linux/systemd/0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch (renamed from pkgs/os-specific/linux/systemd/0009-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch)62
-rw-r--r--pkgs/os-specific/linux/systemd/0008-Fix-hwdb-paths.patch32
-rw-r--r--pkgs/os-specific/linux/systemd/0009-localectl-use-etc-X11-xkb-for-list-x11.patch (renamed from pkgs/os-specific/linux/systemd/0010-localectl-use-etc-X11-xkb-for-list-x11.patch)11
-rw-r--r--pkgs/os-specific/linux/systemd/0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch (renamed from pkgs/os-specific/linux/systemd/0011-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch)17
-rw-r--r--pkgs/os-specific/linux/systemd/0011-add-rootprefix-to-lookup-dir-paths.patch (renamed from pkgs/os-specific/linux/systemd/0013-add-rootprefix-to-lookup-dir-paths.patch)19
-rw-r--r--pkgs/os-specific/linux/systemd/0012-inherit-systemd-environment-when-calling-generators.patch42
-rw-r--r--pkgs/os-specific/linux/systemd/0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch23
-rw-r--r--pkgs/os-specific/linux/systemd/0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch (renamed from pkgs/os-specific/linux/systemd/0015-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch)12
-rw-r--r--pkgs/os-specific/linux/systemd/0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch (renamed from pkgs/os-specific/linux/systemd/0017-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch)11
-rw-r--r--pkgs/os-specific/linux/systemd/0014-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch27
-rw-r--r--pkgs/os-specific/linux/systemd/0015-pkg-config-derive-prefix-from-prefix.patch (renamed from pkgs/os-specific/linux/systemd/0019-pkg-config-derive-prefix-from-prefix.patch)15
-rw-r--r--pkgs/os-specific/linux/systemd/0016-inherit-systemd-environment-when-calling-generators.patch39
-rw-r--r--pkgs/os-specific/linux/systemd/0016-kmod-static-nodes.service-Update-ConditionFileNotEmp.patch27
-rw-r--r--pkgs/os-specific/linux/systemd/0017-core-don-t-taint-on-unmerged-usr.patch33
-rw-r--r--pkgs/os-specific/linux/systemd/0018-logind-seat-debus-show-CanMultiSession-again.patch26
-rw-r--r--pkgs/os-specific/linux/systemd/0018-tpm2_context_init-fix-driver-name-checking.patch41
-rw-r--r--pkgs/os-specific/linux/systemd/0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch45
-rw-r--r--pkgs/os-specific/linux/systemd/default.nix694
27 files changed, 870 insertions, 601 deletions
diff --git a/pkgs/os-specific/linux/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch b/pkgs/os-specific/linux/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch
index ac2d0018160..104a9dad959 100644
--- a/pkgs/os-specific/linux/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch
+++ b/pkgs/os-specific/linux/systemd/0001-Start-device-units-for-uninitialised-encrypted-devic.patch
@@ -1,7 +1,7 @@
-From 2f4a5e9c9ef1cd57662e8bd4c24e1029a00d55b5 Mon Sep 17 00:00:00 2001
+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 01/19] Start device units for uninitialised encrypted devices
+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
@@ -13,20 +13,17 @@ unit.  (However, this ignores the fsck unit, so it's not perfect...)
  1 file changed, 4 deletions(-)
 
 diff --git a/rules.d/99-systemd.rules.in b/rules.d/99-systemd.rules.in
-index 7c22eefdb7..e3a55e00b5 100644
+index c0defc31de..8f80235731 100644
 --- a/rules.d/99-systemd.rules.in
 +++ b/rules.d/99-systemd.rules.in
-@@ -17,10 +17,6 @@ SUBSYSTEM=="ubi", TAG+="systemd"
- SUBSYSTEM=="block", TAG+="systemd"
+@@ -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"
 -
- # add symlink to GPT root disk
- SUBSYSTEM=="block", ENV{ID_PART_GPT_AUTO_ROOT}=="1", ENV{ID_FS_TYPE}!="crypto_LUKS", SYMLINK+="gpt-auto-root"
- SUBSYSTEM=="block", ENV{ID_PART_GPT_AUTO_ROOT}=="1", ENV{ID_FS_TYPE}=="crypto_LUKS", SYMLINK+="gpt-auto-root-luks"
--- 
-2.30.1
-
+ # 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/os-specific/linux/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch b/pkgs/os-specific/linux/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch
index f54430f764e..dda8524c498 100644
--- a/pkgs/os-specific/linux/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch
+++ b/pkgs/os-specific/linux/systemd/0002-Don-t-try-to-unmount-nix-or-nix-store.patch
@@ -1,21 +1,23 @@
-From 4e96b2e074c4a4f4ce900409872ce2f86704ee5b Mon Sep 17 00:00:00 2001
-From: Eelco Dolstra <eelco.dolstra@logicblox.com>
-Date: Fri, 12 Apr 2013 13:16:57 +0200
-Subject: [PATCH 02/19] Don't try to unmount /nix or /nix/store
+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   | 2 ++
- 2 files changed, 4 insertions(+)
+ 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 292b97cd69..791b8e6b7e 100644
+index 4ffec25c75..b99031c54e 100644
 --- a/src/shared/fstab-util.c
 +++ b/src/shared/fstab-util.c
-@@ -40,6 +40,8 @@ bool fstab_is_extrinsic(const char *mount, const char *opts) {
+@@ -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,
                          "/",
@@ -25,18 +27,19 @@ index 292b97cd69..791b8e6b7e 100644
                          "/etc"))
                  return true;
 diff --git a/src/shutdown/umount.c b/src/shutdown/umount.c
-index 3a72a13e1a..541320dc9d 100644
+index 1586c2e214..fcae95f824 100644
 --- a/src/shutdown/umount.c
 +++ b/src/shutdown/umount.c
-@@ -500,6 +500,8 @@ static int delete_md(MountPoint *m) {
- 
+@@ -170,8 +170,10 @@ int mount_points_list_get(const char *mountinfo, MountPoint **head) {
  static bool nonunmountable_path(const char *path) {
-         return path_equal(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")
- #if ! HAVE_SPLIT_USR
-                 || path_equal(path, "/usr")
- #endif
--- 
-2.30.1
-
++                || path_startswith(path, "/run/initramfs");
+ }
+ 
+ static void log_umount_blockers(const char *mnt) {
diff --git a/pkgs/os-specific/linux/systemd/0003-Fix-NixOS-containers.patch b/pkgs/os-specific/linux/systemd/0003-Fix-NixOS-containers.patch
index 37caffb97d7..2d86d1e6957 100644
--- a/pkgs/os-specific/linux/systemd/0003-Fix-NixOS-containers.patch
+++ b/pkgs/os-specific/linux/systemd/0003-Fix-NixOS-containers.patch
@@ -1,7 +1,7 @@
-From 3d1b2e56a6ed6cc86a64f6f89765a2900e576402 Mon Sep 17 00:00:00 2001
+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 03/19] Fix NixOS containers
+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.
@@ -10,25 +10,22 @@ container, so checking early whether it exists will fail.
  1 file changed, 2 insertions(+)
 
 diff --git a/src/nspawn/nspawn.c b/src/nspawn/nspawn.c
-index 7515380fcd..14f8a82eb8 100644
+index e170958fc5..898a674631 100644
 --- a/src/nspawn/nspawn.c
 +++ b/src/nspawn/nspawn.c
-@@ -5323,6 +5323,7 @@ static int run(int argc, char *argv[]) {
+@@ -5648,6 +5648,7 @@ static int run(int argc, char *argv[]) {
                                  goto finish;
                          }
                  } else {
 +#if 0
-                         const char *p, *q;
+                         _cleanup_free_ char *p = NULL;
  
                          if (arg_pivot_root_new)
-@@ -5337,6 +5338,7 @@ static int run(int argc, char *argv[]) {
-                                 r = -EINVAL;
+@@ -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 {
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0005-Add-some-NixOS-specific-unit-directories.patch b/pkgs/os-specific/linux/systemd/0004-Add-some-NixOS-specific-unit-directories.patch
index 0acccacd613..c905a4d812a 100644
--- a/pkgs/os-specific/linux/systemd/0005-Add-some-NixOS-specific-unit-directories.patch
+++ b/pkgs/os-specific/linux/systemd/0004-Add-some-NixOS-specific-unit-directories.patch
@@ -1,23 +1,25 @@
-From 8b7f881cf22e98e907506f4c403b9e304e332bf9 Mon Sep 17 00:00:00 2001
-From: Eelco Dolstra <eelco.dolstra@logicblox.com>
-Date: Fri, 19 Dec 2014 14:46:17 +0100
-Subject: [PATCH 05/19] Add some NixOS-specific unit directories
+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  |  5 +++--
- 2 files changed, 5 insertions(+), 17 deletions(-)
+ 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 96b82170d0..bf66bd6b77 100644
+index 7d158a8295..f9bd62b631 100644
 --- a/src/basic/path-lookup.c
 +++ b/src/basic/path-lookup.c
-@@ -94,11 +94,7 @@ int xdg_user_data_dir(char **ret, const char *suffix) {
+@@ -92,11 +92,7 @@ int xdg_user_data_dir(char **ret, const char *suffix) {
  }
  
  static const char* const user_data_unit_paths[] = {
@@ -29,7 +31,7 @@ index 96b82170d0..bf66bd6b77 100644
          NULL
  };
  
-@@ -616,15 +612,13 @@ int lookup_paths_init(
+@@ -617,15 +613,13 @@ int lookup_paths_init(
                                          persistent_config,
                                          SYSTEM_CONFIG_UNIT_DIR,
                                          "/etc/systemd/system",
@@ -40,13 +42,13 @@ index 96b82170d0..bf66bd6b77 100644
                                          STRV_IFNOTNULL(runtime_attached),
                                          STRV_IFNOTNULL(generator),
 -                                        "/usr/local/lib/systemd/system",
-                                         SYSTEM_DATA_UNIT_PATH,
+                                         SYSTEM_DATA_UNIT_DIR,
 -                                        "/usr/lib/systemd/system",
 -                                        STRV_IFNOTNULL(flags & LOOKUP_PATHS_SPLIT_USR ? "/lib/systemd/system" : NULL),
                                          STRV_IFNOTNULL(generator_late));
                          break;
  
-@@ -640,14 +634,11 @@ int lookup_paths_init(
+@@ -641,14 +635,11 @@ int lookup_paths_init(
                                          persistent_config,
                                          USER_CONFIG_UNIT_DIR,
                                          "/etc/systemd/user",
@@ -62,40 +64,42 @@ index 96b82170d0..bf66bd6b77 100644
                                          STRV_IFNOTNULL(generator_late));
                          break;
  
-@@ -797,7 +788,6 @@ char **generator_binary_paths(UnitFileScope scope) {
-                 case UNIT_FILE_SYSTEM:
+@@ -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;
  
-@@ -805,7 +795,6 @@ char **generator_binary_paths(UnitFileScope scope) {
-                 case UNIT_FILE_USER:
+@@ -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;
  
-@@ -844,12 +833,10 @@ char **env_generator_binary_paths(bool is_system) {
-                 if (is_system)
+@@ -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);
-                 else
+                         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;
  
-                 if (!add)
 diff --git a/src/core/systemd.pc.in b/src/core/systemd.pc.in
-index b5cc8f94a5..a701cd05f8 100644
+index 693433b34b..5932a21b5b 100644
 --- a/src/core/systemd.pc.in
 +++ b/src/core/systemd.pc.in
-@@ -38,10 +38,11 @@ systemdsystemconfdir=${systemd_system_conf_dir}
+@@ -38,10 +38,10 @@ systemdsystemconfdir=${systemd_system_conf_dir}
  systemd_user_conf_dir=${sysconfdir}/systemd/user
  systemduserconfdir=${systemd_user_conf_dir}
  
@@ -105,10 +109,19 @@ index b5cc8f94a5..a701cd05f8 100644
  
 -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
--- 
-2.30.1
-
+@@ -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/os-specific/linux/systemd/0004-Look-for-fsck-in-the-right-place.patch b/pkgs/os-specific/linux/systemd/0004-Look-for-fsck-in-the-right-place.patch
deleted file mode 100644
index 2f14a9d6a7e..00000000000
--- a/pkgs/os-specific/linux/systemd/0004-Look-for-fsck-in-the-right-place.patch
+++ /dev/null
@@ -1,25 +0,0 @@
-From 3a721cf70e952e933ef5374006bbb11a3a0ad36a Mon Sep 17 00:00:00 2001
-From: Eelco Dolstra <eelco.dolstra@logicblox.com>
-Date: Thu, 1 May 2014 14:10:10 +0200
-Subject: [PATCH 04/19] Look for fsck in the right place
-
----
- src/fsck/fsck.c | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/src/fsck/fsck.c b/src/fsck/fsck.c
-index 510689f3b7..25cab5acae 100644
---- a/src/fsck/fsck.c
-+++ b/src/fsck/fsck.c
-@@ -368,7 +368,7 @@ static int run(int argc, char *argv[]) {
-                 } else
-                         dash_c[0] = 0;
- 
--                cmdline[i++] = "/sbin/fsck";
-+                cmdline[i++] = "/run/current-system/sw/bin/fsck";
-                 cmdline[i++] =  arg_repair;
-                 cmdline[i++] = "-T";
- 
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0005-Get-rid-of-a-useless-message-in-user-sessions.patch b/pkgs/os-specific/linux/systemd/0005-Get-rid-of-a-useless-message-in-user-sessions.patch
new file mode 100644
index 00000000000..0a80d5ac4e8
--- /dev/null
+++ b/pkgs/os-specific/linux/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/os-specific/linux/systemd/0006-Get-rid-of-a-useless-message-in-user-sessions.patch b/pkgs/os-specific/linux/systemd/0006-Get-rid-of-a-useless-message-in-user-sessions.patch
deleted file mode 100644
index bda27ac1762..00000000000
--- a/pkgs/os-specific/linux/systemd/0006-Get-rid-of-a-useless-message-in-user-sessions.patch
+++ /dev/null
@@ -1,31 +0,0 @@
-From 7a6529ee27028860b93bc539e8bbf3f2374d712f 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 06/19] 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/unit.c | 3 ++-
- 1 file changed, 2 insertions(+), 1 deletion(-)
-
-diff --git a/src/core/unit.c b/src/core/unit.c
-index 45a417a090..8af3cb08d6 100644
---- a/src/core/unit.c
-+++ b/src/core/unit.c
-@@ -2163,7 +2163,8 @@ static void unit_check_binds_to(Unit *u) {
-         }
- 
-         assert(other);
--        log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
-+        if (u->type != UNIT_MOUNT || detect_container() <= 0)
-+                log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
- 
-         /* A unit we need to run is gone. Sniff. Let's stop this. */
-         r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, NULL, &error, NULL);
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0007-hostnamed-localed-timedated-disable-methods-that-cha.patch b/pkgs/os-specific/linux/systemd/0006-hostnamed-localed-timedated-disable-methods-that-cha.patch
index d51e1c0f566..abc6c24dbf5 100644
--- a/pkgs/os-specific/linux/systemd/0007-hostnamed-localed-timedated-disable-methods-that-cha.patch
+++ b/pkgs/os-specific/linux/systemd/0006-hostnamed-localed-timedated-disable-methods-that-cha.patch
@@ -1,8 +1,8 @@
-From 5580303956ca7d8eb431d23c2af0030c9cc0e6e9 Mon Sep 17 00:00:00 2001
+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 07/19] hostnamed, localed, timedated: disable methods that
- change system settings.
+Subject: [PATCH] hostnamed, localed, timedated: disable methods that change
+ system settings.
 
 ---
  src/hostname/hostnamed.c |  6 ++++++
@@ -11,10 +11,10 @@ Subject: [PATCH 07/19] hostnamed, localed, timedated: disable methods that
  3 files changed, 25 insertions(+)
 
 diff --git a/src/hostname/hostnamed.c b/src/hostname/hostnamed.c
-index a1794bdab1..77134731e1 100644
+index 9ef45f8e75..99b1ec2e36 100644
 --- a/src/hostname/hostnamed.c
 +++ b/src/hostname/hostnamed.c
-@@ -643,6 +643,9 @@ static int method_set_static_hostname(sd_bus_message *m, void *userdata, sd_bus_
+@@ -1053,6 +1053,9 @@ static int method_set_static_hostname(sd_bus_message *m, void *userdata, sd_bus_
          if (r < 0)
                  return r;
  
@@ -24,7 +24,7 @@ index a1794bdab1..77134731e1 100644
          name = empty_to_null(name);
  
          context_read_etc_hostname(c);
-@@ -702,6 +705,9 @@ static int set_machine_info(Context *c, sd_bus_message *m, int prop, sd_bus_mess
+@@ -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;
  
@@ -35,12 +35,12 @@ index a1794bdab1..77134731e1 100644
  
          context_read_machine_info(c);
 diff --git a/src/locale/localed.c b/src/locale/localed.c
-index 736dacdee9..53e0ee935e 100644
+index f544a73580..ce00c262cc 100644
 --- a/src/locale/localed.c
 +++ b/src/locale/localed.c
-@@ -317,6 +317,9 @@ static int method_set_locale(sd_bus_message *m, void *userdata, sd_bus_error *er
-         if (r < 0)
-                 return r;
+@@ -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.");
@@ -48,31 +48,31 @@ index 736dacdee9..53e0ee935e 100644
          /* 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]))
-@@ -432,6 +435,9 @@ static int method_set_vc_keyboard(sd_bus_message *m, void *userdata, sd_bus_erro
+@@ -347,6 +350,9 @@ static int method_set_vc_keyboard(sd_bus_message *m, void *userdata, sd_bus_erro
          if (r < 0)
-                 return r;
+                 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.");
 +
-         keymap = empty_to_null(keymap);
-         keymap_toggle = empty_to_null(keymap_toggle);
+         vc_context_empty_to_null(&in);
  
-@@ -606,6 +612,9 @@ static int method_set_x11_keyboard(sd_bus_message *m, void *userdata, sd_bus_err
+         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 r;
+                 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.");
 +
-         layout = empty_to_null(layout);
-         model = empty_to_null(model);
-         variant = empty_to_null(variant);
+         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 76fe04900d..e87c4c8919 100644
+index ad1d492d6b..331af34505 100644
 --- a/src/timedate/timedated.c
 +++ b/src/timedate/timedated.c
-@@ -646,6 +646,10 @@ static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *
+@@ -665,6 +665,10 @@ static int method_set_timezone(sd_bus_message *m, void *userdata, sd_bus_error *
          if (r < 0)
                  return r;
  
@@ -83,7 +83,7 @@ index 76fe04900d..e87c4c8919 100644
          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);
  
-@@ -725,6 +729,9 @@ static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error
+@@ -743,6 +747,9 @@ static int method_set_local_rtc(sd_bus_message *m, void *userdata, sd_bus_error
          if (r < 0)
                  return r;
  
@@ -93,7 +93,7 @@ index 76fe04900d..e87c4c8919 100644
          if (lrtc == c->local_rtc && !fix_system)
                  return sd_bus_reply_method_return(m, NULL);
  
-@@ -907,6 +914,9 @@ static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error
+@@ -923,6 +930,9 @@ static int method_set_ntp(sd_bus_message *m, void *userdata, sd_bus_error *error
          if (r < 0)
                  return r;
  
@@ -103,6 +103,3 @@ index 76fe04900d..e87c4c8919 100644
          r = context_update_ntp_status(c, bus, m);
          if (r < 0)
                  return r;
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0007-Fix-hwdb-paths.patch b/pkgs/os-specific/linux/systemd/0007-Fix-hwdb-paths.patch
new file mode 100644
index 00000000000..7777ba7e425
--- /dev/null
+++ b/pkgs/os-specific/linux/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/os-specific/linux/systemd/0009-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch b/pkgs/os-specific/linux/systemd/0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
index a1e8ec963c7..3150d97be2e 100644
--- a/pkgs/os-specific/linux/systemd/0009-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
+++ b/pkgs/os-specific/linux/systemd/0008-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
@@ -1,16 +1,16 @@
-From 367d0dad3d1853048569e315931cb8a27e16a098 Mon Sep 17 00:00:00 2001
+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 09/19] Change /usr/share/zoneinfo to /etc/zoneinfo
+Subject: [PATCH] Change /usr/share/zoneinfo to /etc/zoneinfo
 
 NixOS uses this path.
 ---
  man/localtime.xml         | 4 ++--
- src/basic/time-util.c     | 6 +++---
+ src/basic/time-util.c     | 8 ++++----
  src/firstboot/firstboot.c | 2 +-
  src/nspawn/nspawn.c       | 4 ++--
  src/timedate/timedated.c  | 8 ++++----
- 5 files changed, 12 insertions(+), 12 deletions(-)
+ 5 files changed, 13 insertions(+), 13 deletions(-)
 
 diff --git a/man/localtime.xml b/man/localtime.xml
 index e486474c44..5f373d0723 100644
@@ -35,28 +35,37 @@ index e486474c44..5f373d0723 100644
      <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 5318d6378d..04069dc27b 100644
+index 1db630003a..31744c3e68 100644
 --- a/src/basic/time-util.c
 +++ b/src/basic/time-util.c
-@@ -1277,7 +1277,7 @@ int get_timezones(char ***ret) {
-         n_allocated = 2;
-         n_zones = 1;
+@@ -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) {
-                 for (;;) {
-                         _cleanup_free_ char *line = NULL;
-@@ -1372,7 +1372,7 @@ bool timezone_is_valid(const char *name, int log_level) {
+         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 false;
+                 return -ENAMETOOLONG;
  
 -        t = strjoina("/usr/share/zoneinfo/", name);
 +        t = strjoina("/etc/zoneinfo/", name);
  
          fd = open(t, O_RDONLY|O_CLOEXEC);
-         if (fd < 0) {
-@@ -1470,7 +1470,7 @@ int get_timezone(char **ret) {
+         if (fd < 0)
+@@ -1563,7 +1563,7 @@ int get_timezone(char **ret) {
          if (r < 0)
                  return r; /* returns EINVAL if not a symlink */
  
@@ -66,23 +75,23 @@ index 5318d6378d..04069dc27b 100644
                  return -EINVAL;
  
 diff --git a/src/firstboot/firstboot.c b/src/firstboot/firstboot.c
-index 742b43f9fc..f2cb121816 100644
+index 1956ab3b13..9ef356f8af 100644
 --- a/src/firstboot/firstboot.c
 +++ b/src/firstboot/firstboot.c
-@@ -459,7 +459,7 @@ static int process_timezone(void) {
+@@ -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);
  
-         (void) mkdir_parents(etc_localtime, 0755);
-         if (symlink(e, etc_localtime) < 0)
+         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 14f8a82eb8..8632dadec6 100644
+index 898a674631..c41a416e04 100644
 --- a/src/nspawn/nspawn.c
 +++ b/src/nspawn/nspawn.c
-@@ -1810,8 +1810,8 @@ static int userns_mkdir(const char *root, const char *path, mode_t mode, uid_t u
+@@ -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,
@@ -94,10 +103,10 @@ index 14f8a82eb8..8632dadec6 100644
  
  static bool etc_writable(void) {
 diff --git a/src/timedate/timedated.c b/src/timedate/timedated.c
-index e87c4c8919..964a40ba81 100644
+index 331af34505..722c4b5b4f 100644
 --- a/src/timedate/timedated.c
 +++ b/src/timedate/timedated.c
-@@ -269,7 +269,7 @@ static int context_read_data(Context *c) {
+@@ -282,7 +282,7 @@ static int context_read_data(Context *c) {
  
          r = get_timezone(&t);
          if (r == -EINVAL)
@@ -106,7 +115,7 @@ index e87c4c8919..964a40ba81 100644
          else if (r < 0)
                  log_warning_errno(r, "Failed to get target of /etc/localtime: %m");
  
-@@ -293,7 +293,7 @@ static int context_write_data_timezone(Context *c) {
+@@ -306,7 +306,7 @@ static int context_write_data_timezone(Context *c) {
  
          if (isempty(c->zone) || streq(c->zone, "UTC")) {
  
@@ -115,7 +124,7 @@ index e87c4c8919..964a40ba81 100644
  
                          if (unlink("/etc/localtime") < 0 && errno != ENOENT)
                                  return -errno;
-@@ -301,9 +301,9 @@ static int context_write_data_timezone(Context *c) {
+@@ -314,9 +314,9 @@ static int context_write_data_timezone(Context *c) {
                          return 0;
                  }
  
@@ -127,6 +136,3 @@ index e87c4c8919..964a40ba81 100644
                  if (!p)
                          return -ENOMEM;
  
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0008-Fix-hwdb-paths.patch b/pkgs/os-specific/linux/systemd/0008-Fix-hwdb-paths.patch
deleted file mode 100644
index 2b1c02b233c..00000000000
--- a/pkgs/os-specific/linux/systemd/0008-Fix-hwdb-paths.patch
+++ /dev/null
@@ -1,32 +0,0 @@
-From 874698425f6d68fc0d662cb17c7c29e0af3e8c25 Mon Sep 17 00:00:00 2001
-From: Nikolay Amiantov <ab@fmap.me>
-Date: Thu, 7 Jul 2016 02:47:13 +0300
-Subject: [PATCH 08/19] Fix hwdb paths
-
-Patch by vcunat.
----
- src/libsystemd/sd-hwdb/sd-hwdb.c | 7 +------
- 1 file changed, 1 insertion(+), 6 deletions(-)
-
-diff --git a/src/libsystemd/sd-hwdb/sd-hwdb.c b/src/libsystemd/sd-hwdb/sd-hwdb.c
-index cb3c77ce96..7b8c80071f 100644
---- a/src/libsystemd/sd-hwdb/sd-hwdb.c
-+++ b/src/libsystemd/sd-hwdb/sd-hwdb.c
-@@ -297,13 +297,8 @@ static int trie_search_f(sd_hwdb *hwdb, const char *search) {
- }
- 
- static const char hwdb_bin_paths[] =
--        "/etc/systemd/hwdb/hwdb.bin\0"
-         "/etc/udev/hwdb.bin\0"
--        "/usr/lib/systemd/hwdb/hwdb.bin\0"
--#if HAVE_SPLIT_USR
--        "/lib/systemd/hwdb/hwdb.bin\0"
--#endif
--        UDEVLIBEXECDIR "/hwdb.bin\0";
-+        ;
- 
- _public_ int sd_hwdb_new(sd_hwdb **ret) {
-         _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL;
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0010-localectl-use-etc-X11-xkb-for-list-x11.patch b/pkgs/os-specific/linux/systemd/0009-localectl-use-etc-X11-xkb-for-list-x11.patch
index 334156495fc..c0f6afd7fc7 100644
--- a/pkgs/os-specific/linux/systemd/0010-localectl-use-etc-X11-xkb-for-list-x11.patch
+++ b/pkgs/os-specific/linux/systemd/0009-localectl-use-etc-X11-xkb-for-list-x11.patch
@@ -1,7 +1,7 @@
-From bf285fe7e12bd22f95c14bcefbb5008888c32bfa Mon Sep 17 00:00:00 2001
+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 10/19] localectl: use /etc/X11/xkb for list-x11-*
+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.
@@ -10,10 +10,10 @@ NixOS has an option to link the xkb data files to /etc/X11, but not to
  1 file changed, 1 insertion(+), 1 deletion(-)
 
 diff --git a/src/locale/localectl.c b/src/locale/localectl.c
-index 7d2e887660..91c5139eed 100644
+index d8db9d9d22..4601bb5431 100644
 --- a/src/locale/localectl.c
 +++ b/src/locale/localectl.c
-@@ -277,7 +277,7 @@ static int list_x11_keymaps(int argc, char **argv, void *userdata) {
+@@ -297,7 +297,7 @@ static int list_x11_keymaps(int argc, char **argv, void *userdata) {
          } state = NONE, look_for;
          int r;
  
@@ -22,6 +22,3 @@ index 7d2e887660..91c5139eed 100644
          if (!f)
                  return log_error_errno(errno, "Failed to open keyboard mapping list. %m");
  
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0011-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch b/pkgs/os-specific/linux/systemd/0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
index 902018ee4b9..b8f97308acf 100644
--- a/pkgs/os-specific/linux/systemd/0011-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
+++ b/pkgs/os-specific/linux/systemd/0010-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
@@ -1,26 +1,23 @@
-From 293b19c5fdbda1b4ee579a7e8ba12f024a6f34c9 Mon Sep 17 00:00:00 2001
+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 11/19] build: don't create statedir and don't touch prefixdir
+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 580964c3fa..f99d4f3ab5 100644
+index 395eca1943..082cd748bb 100644
 --- a/meson.build
 +++ b/meson.build
-@@ -3518,9 +3518,6 @@ install_data('LICENSE.GPL2',
-              'src/libsystemd/sd-bus/GVARIANT-SERIALIZATION',
-              install_dir : docdir)
+@@ -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))
 -
  ############################################################
  
- check_help = find_program('tools/check-help.sh')
--- 
-2.30.1
-
+ # Ensure that changes to the docs/ directory do not break the
diff --git a/pkgs/os-specific/linux/systemd/0013-add-rootprefix-to-lookup-dir-paths.patch b/pkgs/os-specific/linux/systemd/0011-add-rootprefix-to-lookup-dir-paths.patch
index b9bab2d387e..fa201126ae2 100644
--- a/pkgs/os-specific/linux/systemd/0013-add-rootprefix-to-lookup-dir-paths.patch
+++ b/pkgs/os-specific/linux/systemd/0011-add-rootprefix-to-lookup-dir-paths.patch
@@ -1,21 +1,21 @@
-From 561dc3b864d96753b5dc448e6e1a80460d5f0bc4 Mon Sep 17 00:00:00 2001
+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 13/19] add rootprefix to lookup dir paths
+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/def.h | 6 ++++--
+ src/basic/constants.h | 6 ++++--
  1 file changed, 4 insertions(+), 2 deletions(-)
 
-diff --git a/src/basic/def.h b/src/basic/def.h
-index 2e60abb4f1..732ec51d36 100644
---- a/src/basic/def.h
-+++ b/src/basic/def.h
-@@ -39,13 +39,15 @@
+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"                      \
@@ -33,6 +33,3 @@ index 2e60abb4f1..732ec51d36 100644
  
  #define CONF_PATHS(n)                           \
          CONF_PATHS_USR(n)                       \
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0012-inherit-systemd-environment-when-calling-generators.patch b/pkgs/os-specific/linux/systemd/0012-inherit-systemd-environment-when-calling-generators.patch
deleted file mode 100644
index 05fce10e856..00000000000
--- a/pkgs/os-specific/linux/systemd/0012-inherit-systemd-environment-when-calling-generators.patch
+++ /dev/null
@@ -1,42 +0,0 @@
-From 63777e7f690b67952bf4571f8e09e5d8e769d3c0 Mon Sep 17 00:00:00 2001
-From: Andreas Rammhold <andreas@rammhold.de>
-Date: Fri, 2 Nov 2018 21:15:42 +0100
-Subject: [PATCH 12/19] 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 | 11 ++++++++---
- 1 file changed, 8 insertions(+), 3 deletions(-)
-
-diff --git a/src/core/manager.c b/src/core/manager.c
-index 6858950107..07a599ede7 100644
---- a/src/core/manager.c
-+++ b/src/core/manager.c
-@@ -4142,9 +4142,14 @@ static int manager_run_generators(Manager *m) {
-         argv[4] = NULL;
- 
-         RUN_WITH_UMASK(0022)
--                (void) execute_directories((const char* const*) paths, DEFAULT_TIMEOUT_USEC, NULL, NULL,
--                                           (char**) argv, m->transient_environment, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
--
-+                (void) execute_directories((const char* const*) paths, DEFAULT_TIMEOUT_USEC,
-+                                    // 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 the last argument of the
-+                                    // function (envp) is set to NULL. This propagates systemd's
-+                                    // environment (e.g. PATH) that was setup
-+                                    // before calling systemd from stage-2-init.sh.
-+                                    NULL, NULL, (char**) argv, /* NixOS: use inherited env */ NULL, EXEC_DIR_PARALLEL | EXEC_DIR_IGNORE_ERRORS);
-         r = 0;
- 
- finish:
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch b/pkgs/os-specific/linux/systemd/0012-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
new file mode 100644
index 00000000000..fde1e2b276c
--- /dev/null
+++ b/pkgs/os-specific/linux/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/os-specific/linux/systemd/0015-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch b/pkgs/os-specific/linux/systemd/0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
index 3059216f7c5..d91150cfc49 100644
--- a/pkgs/os-specific/linux/systemd/0015-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
+++ b/pkgs/os-specific/linux/systemd/0013-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
@@ -1,8 +1,7 @@
-From 577b11afe38fc185d785ca8f125f518a4eb21a00 Mon Sep 17 00:00:00 2001
+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 15/19] systemd-sleep: execute scripts in
- /etc/systemd/system-sleep
+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.
 ---
@@ -10,10 +9,10 @@ This is needed for NixOS to use such scripts as systemd directory is immutable.
  1 file changed, 1 insertion(+)
 
 diff --git a/src/sleep/sleep.c b/src/sleep/sleep.c
-index 39ab554290..880ac7ccb0 100644
+index de1f6c7ec1..d0cdebd80a 100644
 --- a/src/sleep/sleep.c
 +++ b/src/sleep/sleep.c
-@@ -178,6 +178,7 @@ static int execute(char **modes, char **states) {
+@@ -224,6 +224,7 @@ static int execute(
          };
          static const char* const dirs[] = {
                  SYSTEM_SLEEP_PATH,
@@ -21,6 +20,3 @@ index 39ab554290..880ac7ccb0 100644
                  NULL
          };
  
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0017-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch b/pkgs/os-specific/linux/systemd/0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
index 585a0aa112e..13dec1070ff 100644
--- a/pkgs/os-specific/linux/systemd/0017-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
+++ b/pkgs/os-specific/linux/systemd/0014-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
@@ -1,7 +1,7 @@
-From c639f311bd27c2bff62a22c34bc92613aaf77587 Mon Sep 17 00:00:00 2001
+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 17/19] path-util.h: add placeholder for DEFAULT_PATH_NORMAL
+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.
@@ -10,10 +10,10 @@ systemd itself uses extensively.
  1 file changed, 3 insertions(+), 3 deletions(-)
 
 diff --git a/src/basic/path-util.h b/src/basic/path-util.h
-index d613709f0b..5cced4c115 100644
+index 97175bee11..3839704901 100644
 --- a/src/basic/path-util.h
 +++ b/src/basic/path-util.h
-@@ -24,11 +24,11 @@
+@@ -25,11 +25,11 @@
  #  define PATH_SBIN_BIN_NULSTR(x) PATH_NORMAL_SBIN_BIN_NULSTR(x)
  #endif
  
@@ -28,6 +28,3 @@ index d613709f0b..5cced4c115 100644
  
  #if HAVE_SPLIT_USR
  #  define DEFAULT_PATH DEFAULT_PATH_SPLIT_USR
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0014-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch b/pkgs/os-specific/linux/systemd/0014-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
deleted file mode 100644
index c737b61e749..00000000000
--- a/pkgs/os-specific/linux/systemd/0014-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
+++ /dev/null
@@ -1,27 +0,0 @@
-From 8f619304804b02f4e9d7a340ca90359f96adc6e8 Mon Sep 17 00:00:00 2001
-From: Nikolay Amiantov <ab@fmap.me>
-Date: Thu, 25 Jul 2019 20:45:55 +0300
-Subject: [PATCH 14/19] 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 | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/src/shutdown/shutdown.c b/src/shutdown/shutdown.c
-index 0d07865542..26d974ef73 100644
---- a/src/shutdown/shutdown.c
-+++ b/src/shutdown/shutdown.c
-@@ -312,7 +312,7 @@ int main(int argc, char *argv[]) {
-         _cleanup_free_ char *cgroup = NULL;
-         char *arguments[3], *watchdog_device;
-         int cmd, r, umount_log_level = LOG_INFO;
--        static const char* const dirs[] = {SYSTEM_SHUTDOWN_PATH, NULL};
-+        static const char* const dirs[] = {SYSTEM_SHUTDOWN_PATH, "/etc/systemd/system-shutdown", NULL};
- 
-         /* The log target defaults to console, but the original systemd process will pass its log target in through a
-          * command line argument, which will override this default. Also, ensure we'll never log to the journal or
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0019-pkg-config-derive-prefix-from-prefix.patch b/pkgs/os-specific/linux/systemd/0015-pkg-config-derive-prefix-from-prefix.patch
index 2d93cdef9a3..3fbfd7f10ab 100644
--- a/pkgs/os-specific/linux/systemd/0019-pkg-config-derive-prefix-from-prefix.patch
+++ b/pkgs/os-specific/linux/systemd/0015-pkg-config-derive-prefix-from-prefix.patch
@@ -1,7 +1,7 @@
-From 5439a516995f9fd57fc91c2cdd016bb18f31aadf Mon Sep 17 00:00:00 2001
+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 19/19] pkg-config: derive prefix from --prefix
+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
@@ -16,7 +16,7 @@ Co-Authored-By: Florian Klink <flokli@flokli.de>
  1 file changed, 1 insertion(+), 1 deletion(-)
 
 diff --git a/src/core/systemd.pc.in b/src/core/systemd.pc.in
-index a701cd05f8..85d6911bdf 100644
+index 5932a21b5b..20bf8e316d 100644
 --- a/src/core/systemd.pc.in
 +++ b/src/core/systemd.pc.in
 @@ -11,7 +11,7 @@
@@ -24,10 +24,7 @@ index a701cd05f8..85d6911bdf 100644
  # shall have underscores.
  
 -prefix=/usr
-+prefix=@prefix@
- root_prefix=@rootprefix_noslash@
++prefix={{PREFIX}}
+ root_prefix={{ROOTPREFIX_NOSLASH}}
  rootprefix=${root_prefix}
- sysconf_dir=@sysconfdir@
--- 
-2.30.1
-
+ sysconf_dir={{SYSCONF_DIR}}
diff --git a/pkgs/os-specific/linux/systemd/0016-inherit-systemd-environment-when-calling-generators.patch b/pkgs/os-specific/linux/systemd/0016-inherit-systemd-environment-when-calling-generators.patch
new file mode 100644
index 00000000000..d6640c87454
--- /dev/null
+++ b/pkgs/os-specific/linux/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/os-specific/linux/systemd/0016-kmod-static-nodes.service-Update-ConditionFileNotEmp.patch b/pkgs/os-specific/linux/systemd/0016-kmod-static-nodes.service-Update-ConditionFileNotEmp.patch
deleted file mode 100644
index ad19d910e1e..00000000000
--- a/pkgs/os-specific/linux/systemd/0016-kmod-static-nodes.service-Update-ConditionFileNotEmp.patch
+++ /dev/null
@@ -1,27 +0,0 @@
-From ba19f629c1806ca2d2ab58154e45bce4ae4a3f0c Mon Sep 17 00:00:00 2001
-From: Florian Klink <flokli@flokli.de>
-Date: Sat, 7 Mar 2020 22:40:27 +0100
-Subject: [PATCH 16/19] kmod-static-nodes.service: Update ConditionFileNotEmpty
-
-On NixOS, kernel modules of the currently booted systems are located at
-/run/booted-system/kernel-modules/lib/modules/%v/, not /lib/modules/%v/.
----
- units/kmod-static-nodes.service.in | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/units/kmod-static-nodes.service.in b/units/kmod-static-nodes.service.in
-index f4170d6a99..9a6a591bea 100644
---- a/units/kmod-static-nodes.service.in
-+++ b/units/kmod-static-nodes.service.in
-@@ -12,7 +12,7 @@ Description=Create list of static device nodes for the current kernel
- DefaultDependencies=no
- Before=sysinit.target systemd-tmpfiles-setup-dev.service
- ConditionCapability=CAP_SYS_MODULE
--ConditionFileNotEmpty=/lib/modules/%v/modules.devname
-+ConditionFileNotEmpty=/run/booted-system/kernel-modules/lib/modules/%v/modules.devname
- 
- [Service]
- Type=oneshot
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0017-core-don-t-taint-on-unmerged-usr.patch b/pkgs/os-specific/linux/systemd/0017-core-don-t-taint-on-unmerged-usr.patch
new file mode 100644
index 00000000000..73b237a2960
--- /dev/null
+++ b/pkgs/os-specific/linux/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/os-specific/linux/systemd/0018-logind-seat-debus-show-CanMultiSession-again.patch b/pkgs/os-specific/linux/systemd/0018-logind-seat-debus-show-CanMultiSession-again.patch
deleted file mode 100644
index f634e74e663..00000000000
--- a/pkgs/os-specific/linux/systemd/0018-logind-seat-debus-show-CanMultiSession-again.patch
+++ /dev/null
@@ -1,26 +0,0 @@
-From ebb37f81c28aaa80acd9187a7d77dcb3cb3828db Mon Sep 17 00:00:00 2001
-From: Thomas Tuegel <ttuegel@mailbox.org>
-Date: Mon, 26 Oct 2020 21:21:38 +0100
-Subject: [PATCH 18/19] logind-seat-debus: show CanMultiSession again
-
-Fixes the "switch user" function in Plasma < 5.20.
----
- src/login/logind-seat-dbus.c | 2 +-
- 1 file changed, 1 insertion(+), 1 deletion(-)
-
-diff --git a/src/login/logind-seat-dbus.c b/src/login/logind-seat-dbus.c
-index a60ed2d3c2..69b6271075 100644
---- a/src/login/logind-seat-dbus.c
-+++ b/src/login/logind-seat-dbus.c
-@@ -450,7 +450,7 @@ static const sd_bus_vtable seat_vtable[] = {
- 
-         SD_BUS_PROPERTY("Id", "s", NULL, offsetof(Seat, id), SD_BUS_VTABLE_PROPERTY_CONST),
-         SD_BUS_PROPERTY("ActiveSession", "(so)", property_get_active_session, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
--        SD_BUS_PROPERTY("CanMultiSession", "b", property_get_const_true, 0, SD_BUS_VTABLE_PROPERTY_CONST|SD_BUS_VTABLE_HIDDEN),
-+        SD_BUS_PROPERTY("CanMultiSession", "b", property_get_const_true, 0, SD_BUS_VTABLE_PROPERTY_CONST),
-         SD_BUS_PROPERTY("CanTTY", "b", property_get_can_tty, 0, SD_BUS_VTABLE_PROPERTY_CONST),
-         SD_BUS_PROPERTY("CanGraphical", "b", property_get_can_graphical, 0, SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE),
-         SD_BUS_PROPERTY("Sessions", "a(so)", property_get_sessions, 0, 0),
--- 
-2.30.1
-
diff --git a/pkgs/os-specific/linux/systemd/0018-tpm2_context_init-fix-driver-name-checking.patch b/pkgs/os-specific/linux/systemd/0018-tpm2_context_init-fix-driver-name-checking.patch
new file mode 100644
index 00000000000..6de01a0ae80
--- /dev/null
+++ b/pkgs/os-specific/linux/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/os-specific/linux/systemd/0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch b/pkgs/os-specific/linux/systemd/0019-systemctl-edit-suggest-systemdctl-edit-runtime-on-sy.patch
new file mode 100644
index 00000000000..dd9af6738c4
--- /dev/null
+++ b/pkgs/os-specific/linux/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/os-specific/linux/systemd/default.nix b/pkgs/os-specific/linux/systemd/default.nix
index a33bb3c1a1d..0311d46d1fc 100644
--- a/pkgs/os-specific/linux/systemd/default.nix
+++ b/pkgs/os-specific/linux/systemd/default.nix
@@ -2,9 +2,13 @@
 
 { stdenv
 , lib
+, nixosTests
+, pkgsCross
 , fetchFromGitHub
 , fetchpatch
+, fetchzip
 , buildPackages
+, makeBinaryWrapper
 , ninja
 , meson
 , m4
@@ -12,8 +16,9 @@
 , coreutils
 , gperf
 , getent
-, patchelf
 , glibcLocales
+
+  # glib is only used during tests (test-bus-gvariant, test-bus-marshal)
 , glib
 , substituteAll
 , gettext
@@ -24,99 +29,146 @@
 , util-linux
 , kbd
 , kmod
+, libxcrypt
 
   # Optional dependencies
 , pam
 , cryptsetup
-, lvm2
 , audit
 , acl
 , lz4
 , libgcrypt
-, libgpgerror
+, libgpg-error
 , libidn2
 , curl
 , gnutar
 , gnupg
 , zlib
 , xz
+, zstd
+, tpm2-tss
 , libuuid
 , libapparmor
 , intltool
 , bzip2
 , pcre2
 , e2fsprogs
+, elfutils
 , linuxHeaders ? stdenv.cc.libc.linuxHeaders
-, gnu-efi
 , iptables
 , withSelinux ? false
 , libselinux
 , withLibseccomp ? lib.meta.availableOn stdenv.hostPlatform libseccomp
 , libseccomp
-, withKexectools ? lib.meta.availableOn stdenv.hostPlatform kexectools
-, kexectools
+, 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
-, withCompression ? true  # adds bzip2, lz4 and xz
+, 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
-, withHomed ? false
+, withFido2 ? true
+, withFirstboot ? false # conflicts with the NixOS /etc management
+, withHomed ? !stdenv.hostPlatform.isMusl
 , withHostnamed ? true
 , withHwdb ? true
-, withImportd ? 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 ? true
-, withOomd ? false
+, withNss ? !stdenv.hostPlatform.isMusl
+, withOomd ? true
+, withPam ? true
+, withPasswordQuality ? false
 , withPCRE2 ? true
 , withPolkit ? true
-, withPortabled ? false
-, withRemote ? 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
-, libfido2
-, p11-kit
+, 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 withResolved -> (libgcrypt != null && libgpgerror != null);
-assert withImportd ->
-(curl.dev != null && zlib != null && xz != null && libgcrypt != null
-  && gnutar != null && gnupg != null && withCompression);
-
-assert withEfi -> (gnu-efi != null);
-assert withRemote -> lib.getDev curl != null;
+assert withImportd -> withCompression;
 assert withCoredump -> withCompression;
-
 assert withHomed -> withCryptsetup;
+assert withHomed -> withPam;
+assert withUkify -> withEfi;
+assert withRepart -> withCryptsetup;
+assert withBootloader -> withEfi;
+# passwdqc is not packaged in nixpkgs yet, if you want to fix this, please submit a PR.
+assert !withPasswordQuality;
 
-assert withCryptsetup ->
-(cryptsetup != null);
 let
   wantCurl = withRemote || withImportd;
-
-  version = "247.6";
+  wantGcrypt = withResolved || withImportd;
+  version = "254.3";
+
+  # Bump this variable on every (major) version change. See below (in the meson options list) for why.
+  # command:
+  #  $ 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 {
-  inherit version pname;
+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.
@@ -124,67 +176,94 @@ stdenv.mkDerivation {
     owner = "systemd";
     repo = "systemd-stable";
     rev = "v${version}";
-    sha256 = "sha256-7XYEq3Qw25suwjbtPzx9lVPHUu9ZY/1bADXl2wQbkJc=";
+    hash = "sha256-ObnsAiKwhwEb4ti611eS/wGpg3Sss/pUy/gANPAbXbs=";
   };
 
-  # If these need to be regenerated, `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}`.
+  # 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-Look-for-fsck-in-the-right-place.patch
-    ./0005-Add-some-NixOS-specific-unit-directories.patch
-    ./0006-Get-rid-of-a-useless-message-in-user-sessions.patch
-    ./0007-hostnamed-localed-timedated-disable-methods-that-cha.patch
-    ./0008-Fix-hwdb-paths.patch
-    ./0009-Change-usr-share-zoneinfo-to-etc-zoneinfo.patch
-    ./0010-localectl-use-etc-X11-xkb-for-list-x11.patch
-    ./0011-build-don-t-create-statedir-and-don-t-touch-prefixdi.patch
-    ./0012-inherit-systemd-environment-when-calling-generators.patch
-    ./0013-add-rootprefix-to-lookup-dir-paths.patch
-    ./0014-systemd-shutdown-execute-scripts-in-etc-systemd-syst.patch
-    ./0015-systemd-sleep-execute-scripts-in-etc-systemd-system-.patch
-    ./0016-kmod-static-nodes.service-Update-ConditionFileNotEmp.patch
-    ./0017-path-util.h-add-placeholder-for-DEFAULT_PATH_NORMAL.patch
-    ./0018-logind-seat-debus-show-CanMultiSession-again.patch
-    ./0019-pkg-config-derive-prefix-from-prefix.patch
-
-    # Fix -Werror=format.
-    (fetchpatch {
-      url = "https://github.com/systemd/systemd/commit/ab1aa6368a883bce88e3162fee2bea14aacedf23.patch";
-      sha256 = "1b280l5jrjsg8qhsang199mpqjhkpix4c8bm3blknjnq9iv43add";
-    })
-
-    # Fix CVE-2021-33910, disclosed 2021-07-20
+    ./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 {
-      name = "CVE-2021-33910.patch";
-      url = "https://github.com/systemd/systemd/commit/441e0115646d54f080e5c3bb0ba477c892861ab9.patch";
-      sha256 = "1g1lk95igaadg67kah9bpi4zsc01rg398sd1247ghjsvl5hxn4v4";
+      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/"
-    substituteInPlace src/boot/efi/meson.build \
-      --replace \
-      "find_program('ld'" \
-      "find_program('${stdenv.cc.bintools.targetPrefix}ld'" \
+  '' + 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 \
-      "find_program('objcopy'" \
-      "find_program('${stdenv.cc.bintools.targetPrefix}objcopy'"
+      "'readelf'" \
+      "'${targetPackages.stdenv.cc.bintools.targetPrefix}readelf'"
   '' + (
     let
-      # The folllowing dlopen patches 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.
+      # 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 dlopen calls 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.
+      # 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
@@ -203,32 +282,58 @@ stdenv.mkDerivation {
       # path location).
       #
       # To get a list of dynamically loaded libraries issue something like
-      # `grep -ri 'dlopen("lib' $src` and update the below list.
-      dlopenLibs = [
-        # We did never provide support for libxkbcommon & qrencode
-        { name = "libxkbcommon.so.0"; pkg = null; }
-        { name = "libqrencode.so.4"; 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 = if withCryptsetup then cryptsetup else null; }
-
-        # 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 = libidn2; }
-        { name = "libidn.so.12"; pkg = null; }
-        { name = "libidn.so.11"; pkg = null; }
-
-        # journalctl --grep requires libpcre so lets provide it
-        { name = "libpcre2-8.so.0"; pkg = pcre2; }
-      ];
+      # `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
@@ -236,46 +341,57 @@ stdenv.mkDerivation {
         in
         if dl.pkg == null then ''
           # remove the dependency on the library by replacing it with an invalid path
-          for file in $(grep -lr 'dlopen("${dl.name}"' src); do
-            echo "patching dlopen(\"${dl.name}\", …) in $file to an invalid store path ("/nix/store/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-not-implemented/${dl.name}")…"
-            substituteInPlace "$file" --replace 'dlopen("${dl.name}"' 'dlopen("/nix/store/eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-not-implemented/${dl.name}"'
+          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
-            echo 'The shared library `${library}` does not exist but was given as subtitute for `${dl.name}`'
-            exit 1
+            # 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 'dlopen("${dl.name}"' src); do
+          for file in $(grep -lr '"${dl.name}"' src); do
             echo "patching dlopen(\"${dl.name}\", …) in $file to ${library}…"
-            substituteInPlace "$file" --replace 'dlopen("${dl.name}"' 'dlopen("${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 that we didn't handle
+  # 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 'dlopen("[^/]' src; then
-      echo "Found unhandled dlopen calls: "
-      grep -r 'dlopen("[^/]' src
+    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" "man" "dev" ];
+  outputs = [ "out" "dev" ] ++ (lib.optional (!buildLibsOnly) "man");
 
   nativeBuildInputs =
     [
       pkg-config
+      makeBinaryWrapper
       gperf
       ninja
       meson
-      coreutils # meson calls date, stat etc.
       glibcLocales
-      patchelf
       getent
       m4
 
@@ -286,44 +402,67 @@ stdenv.mkDerivation {
       docbook_xsl
       docbook_xml_dtd_42
       docbook_xml_dtd_45
-      (buildPackages.python3Packages.python.withPackages (ps: with ps; [ python3Packages.lxml ]))
-    ];
+      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 =
     [
-      acl
-      audit
-      glib
-      kmod
+      libxcrypt
       libcap
-      libgcrypt
-      libidn2
       libuuid
       linuxHeaders
-      pam
+      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 ]
+    ++ lib.optionals withCompression [ bzip2 lz4 xz zstd ]
+    ++ lib.optional withCoredump elfutils
     ++ lib.optional withCryptsetup (lib.getDev cryptsetup.dev)
-    ++ lib.optional withEfi gnu-efi
-    ++ lib.optional withKexectools kexectools
+    ++ 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 withResolved libgpgerror
     ++ lib.optional withSelinux libselinux
     ++ lib.optional withRemote libmicrohttpd
-    ++ lib.optionals withHomed [ p11-kit libfido2 ]
+    ++ 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 ]))
   ;
 
-  #dontAddPrefix = true;
+  mesonBuildType = "release";
 
   mesonFlags = [
+    "-Dversion-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
+    "-Dtime-epoch=${releaseTimestamp}"
+
+    "-Dmode=release"
     "-Ddbuspolicydir=${placeholder "out"}/share/dbus-1/system.d"
     "-Ddbussessionservicedir=${placeholder "out"}/share/dbus-1/services"
     "-Ddbussystemservicedir=${placeholder "out"}/share/dbus-1/system-services"
+    "-Dpam=${lib.boolToString withPam}"
     "-Dpamconfdir=${placeholder "out"}/etc/pam.d"
     "-Drootprefix=${placeholder "out"}"
     "-Dpkgconfiglibdir=${placeholder "dev"}/lib/pkgconfig"
@@ -332,11 +471,13 @@ stdenv.mkDerivation {
     "-Dsetfont-path=${kbd}/bin/setfont"
     "-Dtty-gid=3" # tty in NixOS has gid 3
     "-Ddebug-shell=${bashInteractive}/bin/bash"
-    "-Dglib=${lib.boolToString (glib != null)}"
+    "-Dglib=${lib.boolToString withTests}"
     # while we do not run tests we should also not build them. Removes about 600 targets
     "-Dtests=false"
+    "-Dacl=${lib.boolToString withAcl}"
     "-Danalyze=${lib.boolToString withAnalyze}"
-    "-Dgcrypt=${lib.boolToString (libgcrypt != null)}"
+    "-Daudit=${lib.boolToString withAudit}"
+    "-Dgcrypt=${lib.boolToString wantGcrypt}"
     "-Dimportd=${lib.boolToString withImportd}"
     "-Dlz4=${lib.boolToString withCompression}"
     "-Dhomed=${lib.boolToString withHomed}"
@@ -347,11 +488,10 @@ stdenv.mkDerivation {
     "-Dnetworkd=${lib.boolToString withNetworkd}"
     "-Doomd=${lib.boolToString withOomd}"
     "-Dpolkit=${lib.boolToString withPolkit}"
-    "-Dcryptsetup=${lib.boolToString withCryptsetup}"
+    "-Dlibcryptsetup=${lib.boolToString withCryptsetup}"
     "-Dportabled=${lib.boolToString withPortabled}"
     "-Dhwdb=${lib.boolToString withHwdb}"
     "-Dremote=${lib.boolToString withRemote}"
-    "-Dsysusers=false"
     "-Dtimedated=${lib.boolToString withTimedated}"
     "-Dtimesyncd=${lib.boolToString withTimesyncd}"
     "-Duserdb=${lib.boolToString withUserDb}"
@@ -361,34 +501,41 @@ stdenv.mkDerivation {
     "-Dsplit-usr=false"
     "-Dlibcurl=${lib.boolToString wantCurl}"
     "-Dlibidn=false"
-    "-Dlibidn2=true"
+    "-Dlibidn2=${lib.boolToString withLibidn2}"
+    "-Dfirstboot=${lib.boolToString withFirstboot}"
+    "-Dsysusers=${lib.boolToString withSysusers}"
+    "-Drepart=${lib.boolToString withRepart}"
+    "-Dsysupdate=${lib.boolToString withSysupdate}"
     "-Dquotacheck=false"
     "-Dldconfig=false"
     "-Dsmack=true"
     "-Db_pie=true"
     "-Dinstall-sysconfdir=false"
+    "-Dsbat-distro=nixos"
+    "-Dsbat-distro-summary=NixOS"
+    "-Dsbat-distro-url=https://nixos.org/"
+    "-Dsbat-distro-pkgname=${pname}"
+    "-Dsbat-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
+      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
     */
     "-Dsystem-uid-max=999"
     "-Dsystem-gid-max=999"
-    # "-Dtime-epoch=1"
 
     "-Dsysvinit-path="
     "-Dsysvrcnd-path="
 
-    "-Dkill-path=${coreutils}/bin/kill"
-    "-Dkmod-path=${kmod}/bin/kmod"
-    "-Dsulogin-path=${util-linux}/bin/sulogin"
-    "-Dmount-path=${util-linux}/bin/mount"
-    "-Dumount-path=${util-linux}/bin/umount"
+    "-Dsulogin-path=${util-linux.login}/bin/sulogin"
+    "-Dnologin-path=${util-linux.login}/bin/nologin"
+    "-Dmount-path=${lib.getOutput "mount" util-linux}/bin/mount"
+    "-Dumount-path=${lib.getOutput "mount" util-linux}/bin/umount"
     "-Dcreate-log-dirs=false"
 
     # Use cgroupsv2. This is already the upstream default, but better be explicit.
@@ -398,11 +545,9 @@ stdenv.mkDerivation {
     "-Dman=true"
 
     "-Defi=${lib.boolToString withEfi}"
-    "-Dgnu-efi=${lib.boolToString withEfi}"
-  ] ++ lib.optionals withEfi [
-    "-Defi-libdir=${toString gnu-efi}/lib"
-    "-Defi-includedir=${toString gnu-efi}/include/efi"
-    "-Defi-ldsdir=${toString gnu-efi}/lib"
+    "-Dbootloader=${lib.boolToString withBootloader}"
+
+    "-Dukify=${lib.boolToString withUkify}"
   ] ++ lib.optionals (withShellCompletions == false) [
     "-Dbashcompletiondir=no"
     "-Dzshcompletiondir=no"
@@ -411,57 +556,121 @@ stdenv.mkDerivation {
     "-Dnss-mymachines=false"
     "-Dnss-resolve=false"
     "-Dnss-systemd=false"
+  ] ++ lib.optionals withLibBPF [
+    "-Dbpf-framework=true"
+  ] ++ lib.optionals withTpm2Tss [
+    "-Dtpm2=true"
+  ] ++ lib.optionals (!withUtmp) [
+    "-Dutmp=false"
+  ] ++ lib.optionals stdenv.hostPlatform.isMusl [
+    "-Dgshadow=false"
+    "-Didn=false"
+  ] ++ lib.optionals withKmod [
+    "-Dkmod=true"
+    "-Dkmod-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" ]; }
+      ];
 
-  preConfigure = ''
-    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";
-    # FIXME: patch this in systemd properly (and send upstream).
-    # already fixed in f00929ad622c978f8ad83590a15a765b4beecac9: (u)mount
-    for i in \
-      src/core/mount.c \
-      src/core/swap.c \
-      src/cryptsetup/cryptsetup-generator.c \
-      src/journal/cat.c \
-      src/nspawn/nspawn.c \
-      src/remount-fs/remount-fs.c \
-      src/shared/generator.c \
-      src/shutdown/shutdown.c \
-      units/emergency.service.in \
-      units/modprobe@.service \
-      units/rescue.service.in \
-      units/systemd-logind.service.in \
-      units/systemd-nspawn@.service.in; \
-    do
-      test -e $i
-      substituteInPlace $i \
-        --replace /usr/bin/getent ${getent}/bin/getent \
-        --replace /sbin/mkswap ${lib.getBin util-linux}/sbin/mkswap \
-        --replace /sbin/swapon ${lib.getBin util-linux}/sbin/swapon \
-        --replace /sbin/swapoff ${lib.getBin util-linux}/sbin/swapoff \
-        --replace /bin/echo ${coreutils}/bin/echo \
-        --replace /bin/cat ${coreutils}/bin/cat \
-        --replace /sbin/sulogin ${lib.getBin util-linux}/sbin/sulogin \
-        --replace /sbin/modprobe ${lib.getBin kmod}/sbin/modprobe \
-        --replace /usr/lib/systemd/systemd-fsck $out/lib/systemd/systemd-fsck \
-        --replace /bin/plymouth /run/current-system/sw/bin/plymouth # To avoid dependency
-    done
+      # { 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";
 
-    for dir in tools src/resolve test src/test src/shared; do
-      patchShebangs $dir
-    done
+      ${lib.concatStringsSep "\n" (lib.flatten (map mkSubstitute binaryReplacements))}
+      ${lib.concatMapStringsSep "\n" mkEnsureSubstituted binaryReplacements}
 
-    # absolute paths to gpg & tar
-    substituteInPlace src/import/pull-common.c \
-      --replace '"gpg"' '"${gnupg}/bin/gpg"'
-    for file in src/import/{{export,import,pull}-tar,import-common}.c; do
-      substituteInPlace $file \
-        --replace '"tar"' '"${gnutar}/bin/tar"'
-    done
+      substituteInPlace src/libsystemd/sd-journal/catalog.c \
+        --replace /usr/lib/systemd/catalog/ $out/lib/systemd/catalog/
 
-    substituteInPlace src/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
@@ -469,10 +678,10 @@ stdenv.mkDerivation {
     substituteInPlace config.h \
       --replace "POLKIT_AGENT_BINARY_PATH" "_POLKIT_AGENT_BINARY_PATH" \
       --replace "SYSTEMD_BINARY_PATH" "_SYSTEMD_BINARY_PATH" \
-      --replace "SYSTEMD_CGROUP_AGENT_PATH" "_SYSTEMD_CGROUP_AGENT_PATH"
+      --replace "SYSTEMD_CGROUP_AGENTS_PATH" "_SYSTEMD_CGROUP_AGENT_PATH"
   '';
 
-  NIX_CFLAGS_COMPILE = toString [
+  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"
@@ -481,12 +690,15 @@ stdenv.mkDerivation {
     # 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_AGENT_PATH"
-    "-DSYSTEMD_CGROUP_AGENT_PATH=\"/run/current-system/systemd/lib/systemd/systemd-cgroups-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
 
@@ -495,15 +707,11 @@ stdenv.mkDerivation {
     export DESTDIR=/
   '';
 
-  postInstall = ''
-    # sysinit.target: Don't depend on
-    # systemd-tmpfiles-setup.service. This interferes with NixOps's
-    # send-keys feature (since sshd.service depends indirectly on
-    # sysinit.target).
-    mv $out/lib/systemd/system/sysinit.target.wants/systemd-tmpfiles-setup-dev.service $out/lib/systemd/system/multi-user.target.wants/
+  mesonInstallTags = lib.optionals buildLibsOnly [ "devel" "libudev" "libsystemd" ];
 
+  postInstall = lib.optionalString (!buildLibsOnly) ''
     mkdir -p $out/example/systemd
-    mv $out/lib/{modules-load.d,binfmt.d,sysctl.d,tmpfiles.d} $out/example
+    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
@@ -519,22 +727,66 @@ stdenv.mkDerivation {
     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
   '';
 
-  # 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.
-  passthru.interfaceVersion = 2;
+  # 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";
     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; [ andir eelco flokli kloenk ];
+    maintainers = with maintainers; [ flokli kloenk ];
   };
-}
+})