man mkswap it is recommended to use the
dd command as demonstrated in @vanadium post.
If you don't know the page size that your machine uses,
you may be able to look it up with
(or you may not – the contents of this file depend on architecture and kernel version).
To set up a swap file, it is necessary to create that file before
initializing it with mkswap, e.g. using a command like
# fallocate --length 8GiB swapfile
Note that a swap file must not contain any holes. Using cp(1) to
create the file is not acceptable.
Neither is use of fallocate(1) on file systems that support preallocated
files, such as XFS or ext4, or on copy-on-write filesystems like btrfs.
It is recommended to use dd(1) and /dev/zero in these cases.
Please read notes from swapon(8) before adding a swap file to copy-on-
And here the notes of
You should not use swapon on a file with holes. This can be seen in
the system log as
swapon: swapfile has holes.
The swap file implementation in the kernel expects to be able to write
to the file directly, without the assistance of the filesystem. This
is a problem on preallocated files (e.g. fallocate(1)) on filesys‐
tems like XFS or ext4, and on copy-on-write filesystems like btrfs.
It is recommended to use dd(1) and /dev/zero to avoid holes on XFS
swapon may not work correctly when using a swap file with some
versions of btrfs. This is due to btrfs being a copy-on-write
filesystem: the file location may not be static and corruption can
Btrfs actively disallows the use of swap files on its filesystems
by refusing to map the file.
One possible workaround is to map the swap file to a loopback device.
This will allow the filesystem to determine the mapping properly but
may come with a performance impact.
Swap over NFS may not work.