diff --git a/lib/eval-config.nix b/lib/eval-config.nix
index ffc0db1c7ea6..c2bbf036af04 100644
--- a/lib/eval-config.nix
+++ b/lib/eval-config.nix
@@ -31,6 +31,7 @@ rec {
     inherit pkgs modules baseModules;
     modulesPath = ../modules;
     pkgs_i686 = import <nixpkgs> { system = "i686-linux"; };
+    utils = import ./utils.nix pkgs;
   };
 
   # Import Nixpkgs, allowing the NixOS option nixpkgs.config to
diff --git a/lib/utils.nix b/lib/utils.nix
new file mode 100644
index 000000000000..b75e063eaa92
--- /dev/null
+++ b/lib/utils.nix
@@ -0,0 +1,10 @@
+pkgs: with pkgs.lib;
+
+rec {
+
+  # Escape a path according to the systemd rules, e.g. /dev/xyzzy
+  # becomes dev-xyzzy.  FIXME: slow.
+  escapeSystemdPath = s:
+   replaceChars ["/" "-"] ["-" "\\x2d"] (substring 1 (stringLength s) s);
+
+}
diff --git a/modules/config/swap.nix b/modules/config/swap.nix
index 776574bc0168..84185ff3bbd5 100644
--- a/modules/config/swap.nix
+++ b/modules/config/swap.nix
@@ -1,6 +1,7 @@
-{ config, pkgs, ... }:
+{ config, pkgs, utils, ... }:
 
 with pkgs.lib;
+with utils;
 
 {
 
@@ -84,13 +85,13 @@ with pkgs.lib;
     boot.systemd.services =
       let
 
-        escapePath = s: # FIXME: slow
-          replaceChars ["/" "-"] ["-" "\\x2d"] (substring 1 (stringLength s) s);
-
-        createSwapDevice = sw: assert sw.device != ""; nameValuePair "mkswap-${escapePath sw.device}"
+        createSwapDevice = sw:
+          assert sw.device != "";
+          let device' = escapeSystemdPath sw.device; in
+          nameValuePair "mkswap-${escapeSystemdPath sw.device}"
           { description = "Initialisation of Swapfile ${sw.device}";
-            wantedBy = [ "${escapePath sw.device}.swap" ];
-            before = [ "${escapePath sw.device}.swap" ];
+            wantedBy = [ "${device'}.swap" ];
+            before = [ "${device'}.swap" ];
             path = [ pkgs.utillinux ];
             script =
               ''