Is it safe to use
fallocate --dig-holes on a file while it is being modified/written? For example on a QCOW2 image opened by a KVM guest?
I'd generally say no. If the file is an image mounted to a VM, you can try TRIM (e.g., fstrim -a) instead. Strictly speaking, this is not an equivalent (TRIM can also free space of some deleted file that is not zeroed), but this might be what you want.
It might be safe in some specific cases, but I wouldn't rely on it. For example, when some data are sequentially streamed to a file without any preallocation, it sounds potentially safe. But since this is not implied by documentation and it would rely only on implementation, I strongly don't recommend it.
What can go wrong? Imagine the app/VM is going to overwrite some zeroed block and you concurrently run fallocate -d. The race can look like:
- Fallocate sees a block of zeroes, so it decides to dig a hole there.
- Another application/VM writes to the zeroed block some data.
- Fallocate digs a hole in the block.
It might sound like there is a small timeframe between 1 and 3. Maybe it is true, but fallocate might want to free multiple subsequent blocks at once. (Not sure, I haven't checked the implementation, but even if the opposite is true, you cannot rely on it in the future.) This can increase the delay between 1 and 3, making the race condition much more likely.