1

When is executed the sudo fallocate -l 2G /swapfile command, then 2 GB is created, but with that kind of content or data? Can be it customized? If yes How?. I did do some research but there are no details about this. I want to know if is good use fallocate for swap file purpose.

For example sudo dd if=/dev/zero of=/swapfile bs=1024 count=N creates the data filled with Zeros, not sure if swap file asks for mandatorily the data with zeros - in the swap file tutorials did not mention of this.

Manuel Jordan
  • 1,414
  • 9
  • 33
  • 1
    For filesystems which support the fallocate system call, preallocation is done quickly by allocating blocks and marking them as uninitialized, requiring no IO to the data blocks. This is much faster than creating a file by filling it with zeroes. See https://man7.org/linux/man-pages/man1/fallocate.1.html and https://man7.org/linux/man-pages/man2/fallocate.2.html – GMaster Mar 31 '22 at 00:51

2 Answers2

5

Swap files do not need to full of zeros. The kernel keeps track of what blocks are being used.

However, man mkswap may warn you against using fallocate:

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 filesystems 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-write filesystems.

(Not all versions of the manpage include that)

Further swapon says:

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 filesystems like XFS or ext4, and on copy-on-write filesystems like btrfs.

Another version of the manpage says

Preallocated files created by fallocate(1) may be interpreted as files with holes too depending of the filesystem. Preallocated swap files are supported on XFS since Linux 4.18.

So the question as to whether you can use fallocate to create swapfiles very much depends on your kernel and your file system.

In comparison, a simple dd will work.

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164
Stephen Harris
  • 42,369
  • 5
  • 94
  • 123
1

See Stephen Harris’ answer for details of the suitability of fallocate for swap file creation.

As far as the data “created” by fallocate, the technical answer depends on the file system being used, but the result is always that when fallocate extends the length of a file, the newly-allocated portion of the file will produce zeroes when read (even though it might not contain zeroes on disk). This is described in the documentation of the related system call:

Any subregion within the range specified by offset and len that did not contain data before the call will be initialized to zero.

Stephen Kitt
  • 411,918
  • 54
  • 1,065
  • 1,164