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))
....
# 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
}
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
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.