From: Karel Zak Date: Wed, 29 Jan 2025 11:05:10 +0000 (+0100) Subject: mkswap: improve --file option for use on btrfs X-Git-Tag: v2.42-start~65^2~3 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=ec3ecd0141c62a93a8ff221746251e96bdbe2975;p=thirdparty%2Futil-linux.git mkswap: improve --file option for use on btrfs We will now try to set the "nocow" attribute, but will ignore it if it is not supported. Suggested-by: Zbigniew Jędrzejewski-Szmek Signed-off-by: Karel Zak --- diff --git a/disk-utils/mkswap.8.adoc b/disk-utils/mkswap.8.adoc index 2aba655de..70d0fb315 100644 --- a/disk-utils/mkswap.8.adoc +++ b/disk-utils/mkswap.8.adoc @@ -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)) .... diff --git a/disk-utils/mkswap.c b/disk-utils/mkswap.c index b1f3a3285..08db89b2c 100644 --- a/disk-utils/mkswap.c +++ b/disk-utils/mkswap.c @@ -33,8 +33,10 @@ # include # include "selinux-utils.h" #endif -#ifdef HAVE_LINUX_FIEMAP_H +#ifdef HAVE_LINUX_FS_H # include +#endif +#ifdef HAVE_LINUX_FIEMAP_H # include #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 diff --git a/sys-utils/swapon.8.adoc b/sys-utils/swapon.8.adoc index 4335d7f86..a25309d18 100644 --- a/sys-utils/swapon.8.adoc +++ b/sys-utils/swapon.8.adoc @@ -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.