]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
mkswap: improve --file option for use on btrfs
authorKarel Zak <kzak@redhat.com>
Wed, 29 Jan 2025 11:05:10 +0000 (12:05 +0100)
committerKarel Zak <kzak@redhat.com>
Wed, 29 Jan 2025 12:45:28 +0000 (13:45 +0100)
We will now try to set the "nocow" attribute, but will ignore it if it
is not supported.

Suggested-by: Zbigniew Jędrzejewski-Szmek <zbyszek@in.waw.pl>
Signed-off-by: Karel Zak <kzak@redhat.com>
disk-utils/mkswap.8.adoc
disk-utils/mkswap.c
sys-utils/swapon.8.adoc

index 2aba655de4e0aca09d622dd4882af3171e3cb614..70d0fb315b661e9821d87aa23c2b790661f218e0 100644 (file)
@@ -114,6 +114,8 @@ If you don't know the page size that your machine uses, you can look it up with
 
 Aside from *mkswap --file*, it is also possible to create the swapfile manually before initializing it with *mkswap*, e.g. using a command like
 
+Since version 2.41, *mkswap --file* sets the nocow attribute for newly created files to support swapfiles on Btrfs.
+
 ....
 # dd if=/dev/zero of=swapfile bs=1MiB count=$((8*1024))
 ....
index b1f3a328569d119f25b7bf137190120785a93830..08db89b2c38e42c3f991158766380a3c0aae5b4c 100644 (file)
 # include <selinux/context.h>
 # include "selinux-utils.h"
 #endif
-#ifdef HAVE_LINUX_FIEMAP_H
+#ifdef HAVE_LINUX_FS_H
 # include <linux/fs.h>
+#endif
+#ifdef HAVE_LINUX_FIEMAP_H
 # include <linux/fiemap.h>
 #endif
 
@@ -405,7 +407,21 @@ static void open_device(struct mkswap_control *ctl)
        }
        if (ctl->fd < 0)
                err(EXIT_FAILURE, _("cannot open %s"), ctl->devname);
+
        if (ctl->file && ctl->filesz) {
+               int attr = 0;
+
+               /* Let's attempt to set the "nocow" attribute for Btrfs, etc.
+                * Ignore if unsupported. */
+#if defined(FS_IOC_GETFLAGS) && defined(FS_NOCOW_FL)
+               if (ioctl(ctl->fd, FS_IOC_GETFLAGS, &attr) == 0) {
+                       attr |= FS_NOCOW_FL;
+                       if (ioctl(ctl->fd, FS_IOC_SETFLAGS, &attr) < 0 &&
+                           (errno != EOPNOTSUPP && errno != ENOSYS && errno != EINVAL))
+                               warn(_("failed to set 'nocow' attribute"));
+               }
+#endif
+
                if (ftruncate(ctl->fd, ctl->filesz) < 0)
                        err(EXIT_FAILURE, _("couldn't allocate swap file %s"), ctl->devname);
 #ifdef HAVE_POSIX_FALLOCATE
index 4335d7f86e0ce5ef79a55b0c5ccc0462e484be14..a25309d181bde686a281533966a1d7d6fdaf5aed 100644 (file)
@@ -152,6 +152,8 @@ The most portable solution to create a swap file is to use *dd*(1) and _/dev/zer
 
 Swap files on Btrfs are supported since Linux 5.0 on files with *nocow* attribute. See the *btrfs*(5) manual page for more details.
 
+Since version 2.41, the command *mkswap --file* can create a new swap file with the *nocow* attribute.
+
 === NFS
 
 Swap over *NFS* may not work.