Skip to contentSkip to conversation

exfat: add EXFAT_IOC_COMBINE to append a file's clusters to another

PATCH Superseded Shaopei Zhu 1 participant 1 message Nov 22

Subsystems (4)

v2 of 14 Superseded Latest is v14 →

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 exfat: add EXFAT_IOC_COMBINE to append a file's clusters to another

Cameras and dashcams recording to exFAT SD cards often write the video stream and auxiliary data (e.g. IMU samples) to separate files and merge them when recording stops. Doing that with read()/write() or copy_file_range() copies all the data of the source, which takes time proportional to its size on such media, wears the flash and needs free space for a second copy.

Filesystems supporting reflink can already avoid the copy by cloning the source to the end of the destination with FICLONERANGE and then unlinking it. exFAT cannot share clusters between files, so it needs an operation that moves them instead. Its semantics follow from the exFAT on-disk format (cluster granularity, a single valid_size per file), so it is added as an exfat ioctl rather than a VFS interface; fallocate() does not fit either, as it only takes a single file.

Add an ioctl that moves the cluster chain of a source file to the end of a destination file and then unlinks the source, so that only metadata changes: the FAT, the stream extension entry of the destination and the entry set of the source:

	struct exfat_combine_args args = { .src_fd = src_fd };
	ioctl(dst_fd, EXFAT_IOC_COMBINE, &args);

The source is unlinked as unlink(2) does it: start_removing_dentry() revalidates the dentry of the open file and locks its parent, and security_path_unlink() and vfs_unlink() check permissions and security modules, break leases and delegations, and handle mount points; vfs_unlink() calls exfat_unlink(), which deletes the entry set. Since the in-memory inode no longer owns the clusters, evicting it frees nothing. The checks that can be made without unlinking are made before anything is changed, and an already unlinked source is accepted.

As with EXT4_IOC_MOVE_EXT and F2FS_IOC_MOVE_RANGE, the source must be open for reading and writing, the destination for writing, and both must be regular files on the same mount.

exFAT has a single size and valid_size per file, so clusters can only be appended at a cluster boundary of a fully initialized file. The destination is therefore first zero-filled up to the end of its last cluster with exfat_extend_valid_size(), leaving a zero-filled gap between the original and the appended data when its size is not cluster aligned. This is documented in the uapi header, and keeps stale on-disk data out of the file.

exFAT has no journal, so the data and the FAT, then the destination entry, then the deletion of the source entry set are written and flushed to the device in that order, as recommended by section 8.1 of the exFAT specification; the allocation bitmap is not touched. A crash at any point leaves all data reachable from at least one entry. In the worst case both entries share the appended clusters; fsck.exfat keeps them in the file it checks first and truncates the other one, so either the combine has completed or the source still holds its data. If the call fails before the clusters are moved, the zero padding is removed again. s_lock is only held while updating the FAT and the entries, not while waiting for the device, so that writers to other files on the volume are not stalled.

No file data is copied, so the cost depends on the number of clusters (when a FAT chain has to be built for a contiguous file) rather than on the amount of data.

The ioctl number is taken from the 'r' range next to the FAT ioctls. A user space tool for exfatprogs (exfatcombine) and a test for fstests (exfat/002) are posted separately.

This patch was written with the help of an AI coding assistant (Claude Code, Opus 5.5); I have reviewed and tested the result.

---

Notes:
Changes in v2, following the Sashiko review of v1 [1]:

- Unlink the source with security_path_unlink() and vfs_unlink() instead of open coding it, so that security modules, leases and delegations, swap files and mount points are handled as for unlink(2). exfat_unlink() is no longer split, so namei.c and exfat_fs.h are not touched anymore.
- Retry looking up the parent of the source only after a rename, and fail instead of looping when the parent was removed. A rename no longer skips the permission check before the combine.
- Refuse a source that is a mount point in any namespace before changing anything.
- Write back all of the destination before its new valid_size is written, not only from the padding on.
- On failure, restore the size, valid_size and zeroed_size of the destination, also when the padding itself failed part way or the destination was already cluster aligned.
- Check IS_SWAPFILE() under the inode locks.
- Return -EIO instead of WARN_ON_ONCE() when an earlier failed truncate left an inode inconsistent, and also check that an empty destination has no first cluster.
- Not changed: a store through a shared mapping of the destination into the padding, between exfat_extend_valid_size() and taking the invalidate lock, is kept as file data like any concurrent write; it cannot expose stale data, and if the call fails the padding is truncated as by a concurrent ftruncate(). A test storing through a mapping during 2000 combines found only zeroes or the stored bytes in the padding.
- Changelog: copying the source takes time proportional to its size; it does not rewrite the whole payload as v1 said.

Testing (linux-next 20261118 + this patch, arm64, PROVE_LOCKING, DEBUG_ATOMIC_SLEEP, DEBUG_LIST; no lockdep or other warnings):

- Functional tests on 512 B, 4 KiB and 128 KiB clusters: aligned and unaligned destination, empty destination/source, contiguous and fragmented chains, NO_FAT_CHAIN -> FAT chain conversion, destination extended by ftruncate()/fallocate(), already unlinked source, invalid arguments. Every file is compared byte by byte, again after a remount, followed by fsck.exfat; the source is gone after every successful call and left alone after every failed one.
- Unlinking the source: fails with EACCES and changes nothing in a directory the caller may not write to, or under a Landlock ruleset that does not allow removing files; succeeds otherwise. A source that is a mount point fails with EBUSY, a swap file as source or destination is refused, and a source whose parent directory was removed fails with ENOENT; nothing is changed in any of these cases.
- Files around 4 GiB on 4 KiB clusters (dst 4G-1, 4G, 4G+1, src 4G+7, 2G+1 + 2G+1), fully verified after remount, fsck.exfat clean.
- 300 MiB + 5 MiB on 128 KiB clusters: md5 matches dst + zero gap + src.
- Time until durable, 300 MiB destination, 128 KiB clusters: the ioctl takes 12-15 ms for sources of 5 MiB to 1 GiB; appending them with copy_file_range() and fsync() takes 25 ms to 0.9 s on the test disk, and 135 ms to 46 s with the disk limited to 90/30 MiB/s read/write by cgroup io.max, as for an SD card.
- Concurrency: 300 combines with a concurrent O_APPEND writer on the source and buffered, O_DIRECT and mmap readers on the destination; no record lost or duplicated. Stores through a shared mapping into the padding during 2000 combines: see above.
- Power cut: 30 runs with fsync'ed records (22 inside the ioctl, 12 left both entries sharing clusters), and 30 runs without any fsync and with dirty destination data at every combine; after fsck.exfat -y, everything synced or combined before the cut was present, with no stale data, and fsck was clean afterwards.
- Impact on other writers: a thread appending 128 KiB chunks to another file on the volume while combines run back to back (about 820 in 10 s) keeps ~94% of its throughput, p99 write latency 0.075 ms (0.053 ms without combines).
- Error paths with fail_make_request: failures while padding (also with a destination extended by truncate, aligned or not) leave the size, the data and the never written range, which reads as zeroes, unchanged, and the source in place; a failure at the FAT flush leaves the destination usable; after a truncate that failed with I/O errors, the call returns EIO without any warning.
- KASAN with SLUB_DEBUG_ON: all of the above tests and fstests -g quick reported nothing.
- fstests -g quick: the same 14 failures with and without the patch (generic/029 030 131 260 288 436 490 554 569 571 634 740 786 787), 109 passed including the new exfat/002.
- Builds without warnings with W=1 for arm64 (gcc, clang), arm and i386, built-in and as a module; no new sparse warnings.

The test programs are available on request.

[1] https://sashiko.dev/#/patchset/20261121174315.500249-1-shaopei_1012%40163.com

v1: https://lore.kernel.org/all/[email protected]/

 .../userspace-api/ioctl/ioctl-number.rst      |   1 +
 fs/exfat/file.c                               | 484 ++++++++++++++++++
 include/uapi/linux/exfat.h                    |  45 ++
 3 files changed, 530 insertions(+)
Documentation/userspace-api/ioctl/ioctl-number.rst +1 -0
index dbe4620..e9b4c13 100644
@@ -292,6 +292,7 @@ Code  Seq#    Include File                                             Comments
 'q'   80-FF  linux/telephony.h                                         Internet PhoneJACK, Internet LineJACK
              linux/ixjuser.h                                           <http://web.archive.org/web/%2A/http://www.quicknet.net>
 'r'   00-1F  linux/msdos_fs.h and fs/fat/dir.c
+'r'   20-2F  linux/exfat.h
 's'   all    linux/cdk.h
 't'   00-7F  linux/ppp-ioctl.h
 't'   80-8F  linux/isdn_ppp.h
fs/exfat/file.c +484 -0

504 lines not on this page · raw message

include/uapi/linux/exfat.h +45 -0

55 lines not on this page · raw message

Signature · 1 line
2.50.1 (Apple Git-155)