Atomic pwritev2 on Linux
This topic is deeper than I originally thought.
Atomic write is supported by filesystems like btrfs, and codified in syscall at Linux 6.11.
Untorn Direct I/O
This is how you detect the feature:
Save this as atomic-write.c
.
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
int main() {
struct statx stat_buf;
statx(AT_FDCWD, "atomic-write.c", 0, STATX_BASIC_STATS | STATX_WRITE_ATOMIC, &stat_buf);
printf("Atomic direct I/O write Min: %d\n", stat_buf.stx_atomic_write_unit_min);
printf("Atomic direct I/O write Max: %d\n", stat_buf.stx_atomic_write_unit_max);
printf("Support atomic write: %d\n", !!(stat_buf.stx_attributes | STATX_ATTR_WRITE_ATOMIC));
}
To write, use pwritev2
with the RWF_ATOMIC
flag.
Untorn buffered writes on btrfs
Dispite people saying on Reddit that write
calls aro atomic on btrfs, I can’t find any sentence on official Linux kernel or btrfs websites guaranteeing that a pwritev
call may fully commit or not commit.
The closest is from https://btrfs.readthedocs.io/en/latest/Kernel-by-version.html:
Although it is not implemented yet, the new data=ordered code would allow atomic writes of almost any size to a single file to be exported to userland.
- Write to Hardware blocks is atomic. (Confirmed)
- Will 1
pwritev
call span 2 or more hardware transactions?
[untorn buffered write] has been discussed on the Linux mailing list, but the feature is not available yet.
Even Powersafe Overwrite is still an assumption today, I guess this is also an assumption on btrfs.
Atomic file update / transaction
See https://codeberg.org/iacore/atomic-write
References
statx(2)
pwritev2(2)