* [PATCH v14] exfat: add EXFAT_IOC_COMBINE to append a file's clusters to another
@ 2026-12-01 20:38 Shaopei Zhu
0 siblings, 0 replies; only message in thread
From: Shaopei Zhu @ 2026-12-01 20:38 UTC (permalink / raw)
To: Namjae Jeon, Sungjong Seo
Cc: Yuezhang Mo, exfat, linux-fsdevel, linux-api, linux-doc,
linux-kernel, Matthew Wilcox, Andy Lutomirski, David Timber
Cameras recording to exFAT SD cards often write auxiliary data, such as
GPS, motion or per-frame exposure data, to separate files next to the
video stream, and merge them into the video file when recording stops,
so that playback, editing and post-processing work on a single file.
That data grows with the length of the recording, to hundreds of MiB.
Merging it with read()/write() or copy_file_range() copies all of that
data, which takes time proportional to its size on such media, wears
the flash and needs free space for a second copy. On a battery-powered
device with a removable card, a copy that takes tens of seconds is also
a long window in which the card can be pulled or the power lost,
leaving a partially merged file.
Filesystems supporting reflink can already avoid the copy by cloning
the source to the end of the destination with FICLONERANGE. 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 leaves the source as an empty file, so that
no file data is copied: only the FAT and the stream extension entries
of both files change:
struct exfat_combine_args args = { .src_fd = src_fd };
ioctl(dst_fd, EXFAT_IOC_COMBINE, &args);
As with the other interfaces that move or share data between files,
removing the source is left to the caller, which unlinks it afterwards
if it is not needed. An already unlinked source is accepted. An
unlinked destination is refused with -ENOENT, as its entry is no longer
written and the data of the source would be lost with it.
The source must be open for reading and writing, as it is emptied and
its data becomes readable through the destination, and the destination
for writing; both must be regular files on the same mount. Files whose
allocation, chain layout or valid_size are inconsistent, as after a
failed truncate or on a corrupt volume, or that are found to share
clusters, are refused with -EIO before anything is changed.
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 therefore has to end at a cluster boundary and to be written
up to its size; otherwise the call fails with -EINVAL. Padding the
destination is left to user space, which knows what its file format
allows there, e.g. an MP4 'free' box, rather than having the kernel
insert zeroes into the middle of the file. The cluster size is reported
in st_blksize. This is documented in the uapi header.
exFAT has no journal, so the data and the FAT, then the destination
entry, then the source entry as an empty file 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. A crash
between the first two writes leaves the chain of the destination linked
to the clusters of the source while its size does not cover them, which
fsck.exfat cuts off again. In both cases neither file may be truncated
or removed before fsck.exfat has run, as freeing the clusters of one
would free clusters the other still uses; the volume is marked dirty
before the FAT is changed. On a volume that was not cleanly unmounted,
the call fails with -EUCLEAN until fsck.exfat has run, so that it never
works on clusters that two files may already share or that may already
be linked.
A step is only taken once the previous one has reached the medium. If
the FAT cannot be flushed, the link is undone and the call fails with
nothing changed. If the device fails a write after that, of an entry or
of the cache flush that follows it, the call stops there: the source is
not emptied unless the destination entry is known to be on the medium.
The two files may then share clusters on disk, so the volume is kept
dirty across unmount and a filesystem error is raised, which makes the
volume read-only with the default errors=remount-ro, until fsck.exfat
has run. Once the volume is in an emergency state, nothing more is
written, which leaves what a crash at that point would. Write back
errors are checked through the errseq of the mappings, as their error
flags may be taken by a concurrent fsync(). 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. Measured on a disk throttled to SD card speeds
(30 MiB/s write), appending to a 300 MiB file with 128 KiB clusters,
until the result is on disk:
source EXFAT_IOC_COMBINE copy_file_range() + fsync()
50 MiB 9.9 ms 2.2 s
500 MiB 10.1 ms 22.3 s
1 GiB 10.3 ms 45.6 s
The files of this test were contiguous. Building the FAT chain of a
contiguous file, when it is needed, takes about 100 ms per GiB with
4 KiB clusters, and 32 times less with 128 KiB clusters.
The ioctl uses the magic number 0xEF, which fs/ntfs already uses for
00-0F, with the range 10-1F for exfat. 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.
Signed-off-by: Shaopei Zhu <shaopei_1012@163.com>
---
Notes:
Changes in v14:
- Namjae: when the cache flush after writing the destination entry
fails, return the error without updating the source entry.
- Andy: a destination that does not end at a cluster boundary, or is
not written up to its size, is refused with -EINVAL instead of being
zero-filled by the kernel. The padding and the code undoing it are
gone; user space pads the file with what its format allows.
- David, Namjae: use the ioctl magic number 0xEF instead of 'r'. I took
10-1F, as 00-0F belongs to fs/ntfs; please tell me if you prefer
another range.
- Sashiko on v13 [1]: after a failed write of the destination entry,
write the old entry back at once instead of leaving it to writeback.
- Every write or flush failure after the FAT or an entry was changed is
handled in one place: stop, keep the volume dirty across unmount and
raise a filesystem error. That now covers the final flush of the
source entry as well.
- A chain of the destination that does not end with its size is refused
as a bogus chain; so far it was accepted if it ran into the source.
- Cleanups: helpers for setting a chain and for writing an entry, the
two chain checks merged, the duplicate checks in __exfat_combine()
dropped, inode_dio_wait() before the consistency checks, and the last
flush only flushes the device cache.
Not changed: a source opened with O_APPEND is still accepted.
Testing (next-20261118 + this patch, arm64):
- Functional tests on 512 B, 4 KiB and 128 KiB clusters, checked again
after a remount, including the refused destinations (unaligned,
extended by truncate or fallocate), which are combined after the
test pads them; unlinked source; no permission to remove the source,
source that is a mount point.
- fstests exfat/001 and exfat/002 (002 updated for the new rule).
- Power cuts: 30 runs with fsync (18 inside the ioctl, 9 with shared
clusters repaired by fsck.exfat) and 20 without; nothing synced lost.
- With a test-only knob that fails a write the way
end_buffer_write_sync() does, or a flush: failures of the destination
entry, of writing it back, of the flush after it, of the source
entry, of the final flush and of the flush when undoing the link all
leave the files with the expected contents and the volume read-only
and dirty, and fsck.exfat repairs it; a failed flush of the FAT with
a working undo leaves the volume clean and writable, and a retry
succeeds.
- Builds without warnings with W=1 for arm64 (gcc, clang), arm and
i386, built-in and as a module; no new sparse warnings.
- The measurements in the commit message were redone with this version.
- Not rerun: the long-running tests reported for v2.
This applies to linux-next (next-20261118). It uses
exfat_emergency_state(), which comes with "exfat: don't set SB_RDONLY
after filesystem errors" in the vfs tree (vfs-7.5.super.ro), so it does
not build on mainline or on the exfat dev branch until that is merged
there.
[1] https://sashiko.dev/#/patchset/20261128135710.961256-1-shaopei_1012%40163.com
v13: https://lore.kernel.org/all/20261128135710.961256-1-shaopei_1012@163.com/
v12: https://lore.kernel.org/all/20261127183351.952174-1-shaopei_1012@163.com/
v11: https://lore.kernel.org/all/20261126234846.940461-1-shaopei_1012@163.com/
v8: https://lore.kernel.org/all/20261126125216.927053-1-shaopei_1012@163.com/
v7: https://lore.kernel.org/all/20261124230746.850528-1-shaopei_1012@163.com/
.../userspace-api/ioctl/ioctl-number.rst | 1 +
fs/exfat/file.c | 537 ++++++++++++++++++
include/uapi/linux/exfat.h | 50 ++
3 files changed, 588 insertions(+)
diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
index dbe462040..7ee1c512d 100644
--- a/Documentation/userspace-api/ioctl/ioctl-number.rst
+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
@@ -403,6 +403,7 @@ Code Seq# Include File Comments
0xEC 00-01 linux/platform_data/cros_ec_chardev.h ChromeOS EC driver
0xEE 00-09 uapi/linux/pfrut.h Platform Firmware Runtime Update and Telemetry
0xEF 00-0F uapi/linux/ntfs.h NTFS
+0xEF 10-1F uapi/linux/exfat.h exFAT
0xF3 00-3F drivers/usb/misc/sisusbvga/sisusb.h sisfb (in development)
<mailto:thomas@winischhofer.net>
0xF6 all LTTng Linux Trace Toolkit Next Generation
diff --git a/fs/exfat/file.c b/fs/exfat/file.c
index 7ca26e3f1..129025305 100644
--- a/fs/exfat/file.c
+++ b/fs/exfat/file.c
@@ -13,6 +13,7 @@
#include <linux/writeback.h>
#include <linux/filelock.h>
#include <linux/falloc.h>
+#include <linux/file.h>
#include <linux/fileattr.h>
#include <linux/iomap.h>
#include <linux/pagemap.h>
@@ -710,6 +711,540 @@ static int exfat_ioctl_set_volume_label(struct super_block *sb,
return exfat_write_volume_label(sb, &uniname);
}
+/*
+ * Write back all dirty metadata buffers and flush the device cache. The
+ * error flags of the block device mapping go to whoever checks them
+ * first, an fsync() of any file on the volume included, so also check
+ * its errseq sampled in @since. Advance @since, also when the writeback
+ * returned the error itself, so that the error is marked seen and fails
+ * one call only.
+ */
+static int exfat_combine_flush(struct super_block *sb, errseq_t *since)
+{
+ int err = sync_blockdev(sb->s_bdev);
+ int ret = errseq_check_and_advance(&sb->s_bdev->bd_mapping->wb_err,
+ since);
+
+ if (!err)
+ err = ret;
+ return err ? err : blkdev_issue_flush(sb->s_bdev);
+}
+
+/*
+ * Write the entry of @inode now. A failure is returned to the caller, so
+ * mark it seen in the errseq of the block device mapping, which no flush
+ * may check afterwards, so that it does not fail later calls. The error
+ * flags of that mapping are left alone: they are shared by every file on
+ * the volume.
+ */
+static int exfat_combine_write_entry(struct inode *inode, errseq_t *since)
+{
+ struct block_device *bdev = inode->i_sb->s_bdev;
+ int err = __exfat_write_inode(inode, 1);
+
+ if (err)
+ errseq_check_and_advance(&bdev->bd_mapping->wb_err, since);
+ return err;
+}
+
+/* Set the cluster chain and the sizes of @inode in memory. */
+static void exfat_combine_set_chain(struct inode *inode, unsigned int start,
+ unsigned char flags, unsigned int clus,
+ loff_t size, loff_t valid_size)
+{
+ struct exfat_inode_info *ei = EXFAT_I(inode);
+
+ ei->start_clu = start;
+ ei->flags = flags;
+ inode->i_blocks = exfat_cluster_to_sectors(EXFAT_SB(inode->i_sb), clus);
+ i_size_write(inode, size);
+ exfat_set_valid_size(ei, valid_size);
+ exfat_set_zeroed_size(ei, valid_size);
+ exfat_cache_inval_inode(inode);
+ ei->hint_bmap.off = EXFAT_EOF_CLUSTER;
+ ei->hint_bmap.clu = EXFAT_EOF_CLUSTER;
+}
+
+/*
+ * A write failed after the FAT or an entry was changed. On disk, two
+ * files may now reference the same clusters, and freeing one of them
+ * would free clusters of the other. Keep the volume dirty, also across
+ * unmount, so that fsck.exfat runs, and stop writing to the volume if the
+ * mount options say so.
+ */
+static void exfat_combine_inconsistent(struct super_block *sb)
+{
+ struct exfat_sb_info *sbi = EXFAT_SB(sb);
+
+ mutex_lock(&sbi->s_lock);
+ sbi->vol_flags_persistent |= VOLUME_DIRTY;
+ exfat_fs_error(sb, "combine failed, clusters may be referenced by two files");
+ mutex_unlock(&sbi->s_lock);
+}
+
+/*
+ * Find the last cluster of @dst, walking only the clusters it owns, and
+ * refuse files that share clusters, which only a corrupt volume has:
+ * linking @src would create a loop in the FAT. Two files owning more
+ * clusters than are in use share some of them, and the result would fail
+ * the check of exfat_find() too. Otherwise look for the clusters of @src
+ * known without walking its chain (all of them if it is contiguous). A
+ * chain that does not end with the size of @dst is refused as well. The
+ * chain of @dst cannot change until the combine, as it is fully allocated
+ * and the caller holds its inode lock.
+ */
+static int exfat_combine_find_last(struct inode *dst, struct inode *src,
+ unsigned int *last)
+{
+ struct super_block *sb = dst->i_sb;
+ struct exfat_sb_info *sbi = EXFAT_SB(sb);
+ struct exfat_inode_info *dst_ei = EXFAT_I(dst);
+ struct exfat_inode_info *src_ei = EXFAT_I(src);
+ unsigned int dst_clus, src_clus, src_end, clu, next, n;
+ struct buffer_head *bh = NULL;
+ bool last_one, at_eof;
+ int err = 0;
+
+ dst_clus = exfat_bytes_to_cluster_round_up(sbi, i_size_read(dst));
+ src_clus = exfat_bytes_to_cluster_round_up(sbi, i_size_read(src));
+ src_end = src_ei->start_clu +
+ (src_ei->flags == ALLOC_NO_FAT_CHAIN ? src_clus : 1);
+ clu = dst_ei->start_clu;
+ *last = EXFAT_EOF_CLUSTER;
+
+ mutex_lock(&sbi->s_lock);
+ if ((u64)dst_clus + src_clus > sbi->used_clusters) {
+ err = -EIO;
+ } else if (dst_clus && dst_ei->flags == ALLOC_NO_FAT_CHAIN) {
+ if (clu < src_end && src_ei->start_clu < clu + dst_clus)
+ err = -EIO;
+ else
+ *last = clu + dst_clus - 1;
+ } else if (dst_clus) {
+ for (n = 1; ; n++) {
+ if (clu >= src_ei->start_clu && clu < src_end) {
+ err = -EIO;
+ break;
+ }
+ err = exfat_ent_get(sb, clu, &next, &bh);
+ if (err)
+ break;
+ /* the chain has to end with the last cluster, not before */
+ last_one = n == dst_clus;
+ at_eof = next == EXFAT_EOF_CLUSTER;
+ if (last_one != at_eof) {
+ exfat_fs_error(sb,
+ "bogus cluster chain (start 0x%08x, %u clusters)",
+ dst_ei->start_clu, dst_clus);
+ err = -EIO;
+ break;
+ }
+ if (last_one) {
+ *last = clu;
+ break;
+ }
+ clu = next;
+ }
+ brelse(bh);
+ }
+ mutex_unlock(&sbi->s_lock);
+ return err;
+}
+
+/*
+ * Move the cluster chain of @src to the end of @dst, leaving @src empty.
+ *
+ * Only the FAT and the two stream extension entries are updated, no file
+ * data is copied. @dst must end at a cluster boundary and be initialized
+ * up to its size, so that no stale data ends up in the middle of the file.
+ * The caller must have found its last cluster @last_clu with
+ * exfat_combine_find_last() and must hold the inode and invalidate locks
+ * of both files.
+ *
+ * exFAT has no journal, so the updates are ordered on disk such that a
+ * crash at any point leaves all data reachable:
+ *
+ * 1. the data of both files and the FAT, so that the new chain of @dst
+ * is complete before any entry refers to it; until step 2, the chain
+ * of @dst runs into the clusters of @src beyond its size, which
+ * fsck.exfat cuts off again;
+ * 2. the entry of @dst, after which both entries reference the clusters
+ * of @src; fsck.exfat keeps them in whichever file it checks first and
+ * truncates the other one;
+ * 3. the entry of @src as an empty file.
+ *
+ * This follows the write ordering recommended by section 8.1 of the
+ * exFAT specification: the FAT before the entry that refers to it. No
+ * cluster is allocated or freed, so the allocation bitmap is not
+ * touched. A step is only taken once the previous one has reached the
+ * medium; if that cannot be told, the call stops there, see
+ * exfat_combine_inconsistent().
+ *
+ * s_lock is only held while updating the FAT and the entries, not while
+ * waiting for the device, so that other files on the volume are not
+ * stalled. Until step 2, the in-memory state of @dst is left alone, so
+ * that writeback cannot publish its new chain flags early, and the
+ * in-memory state of @src is only changed once @dst is on disk.
+ */
+static int __exfat_combine(struct inode *dst, struct inode *src,
+ unsigned int last_clu, errseq_t *meta_since)
+{
+ struct super_block *sb = dst->i_sb;
+ struct exfat_sb_info *sbi = EXFAT_SB(sb);
+ struct exfat_inode_info *dst_ei = EXFAT_I(dst);
+ struct exfat_inode_info *src_ei = EXFAT_I(src);
+ loff_t dst_size = i_size_read(dst);
+ loff_t src_size = i_size_read(src);
+ unsigned int dst_clus = exfat_bytes_to_cluster(sbi, dst_size);
+ unsigned int src_clus = exfat_bytes_to_cluster_round_up(sbi, src_size);
+ const unsigned int old_start = dst_ei->start_clu;
+ const unsigned char old_flags = dst_ei->flags;
+ unsigned int dst_start = old_start;
+ unsigned char dst_flags = old_flags;
+ bool linked = false, wrote = false;
+ int err, ret;
+
+ /* Step 1: build the new chain of @dst in the FAT. */
+ mutex_lock(&sbi->s_lock);
+ err = exfat_emergency_state(sb);
+ /* A concurrent call may have failed since the caller checked. */
+ if (!err && (sbi->vol_flags_persistent & VOLUME_DIRTY))
+ err = -EUCLEAN;
+ if (err)
+ goto unlock;
+ exfat_set_volume_dirty(sb);
+
+ if (!dst_clus) {
+ dst_start = src_ei->start_clu;
+ dst_flags = src_ei->flags;
+ goto unlock;
+ }
+
+ /*
+ * A contiguous @dst can stay contiguous only if @src is contiguous
+ * and starts right after it. Otherwise build its FAT chain first.
+ */
+ if (dst_flags == ALLOC_NO_FAT_CHAIN &&
+ (src_ei->flags != ALLOC_NO_FAT_CHAIN ||
+ src_ei->start_clu != last_clu + 1)) {
+ err = exfat_chain_cont_cluster(sb, dst_start, dst_clus);
+ if (err)
+ goto unlock;
+ dst_flags = ALLOC_FAT_CHAIN;
+ }
+
+ if (dst_flags == ALLOC_FAT_CHAIN) {
+ if (src_ei->flags == ALLOC_NO_FAT_CHAIN) {
+ err = exfat_chain_cont_cluster(sb, src_ei->start_clu,
+ src_clus);
+ if (err)
+ goto unlock;
+ }
+ err = exfat_ent_set(sb, last_clu, src_ei->start_clu);
+ linked = !err;
+ }
+unlock:
+ mutex_unlock(&sbi->s_lock);
+ if (err)
+ return err;
+
+ err = exfat_combine_flush(sb, meta_since);
+ if (err)
+ goto undo;
+
+ /*
+ * Step 2: publish the new size and chain of @dst. As the rest of
+ * exfat, write nothing more once the volume is in an emergency
+ * state, which leaves what a crash after step 1 leaves.
+ */
+ mutex_lock(&sbi->s_lock);
+ err = exfat_emergency_state(sb);
+ if (!err) {
+ exfat_combine_set_chain(dst, dst_start, dst_flags,
+ dst_clus + src_clus, dst_size + src_size,
+ dst_size + exfat_get_valid_size(src_ei));
+ dst_ei->attr |= EXFAT_ATTR_ARCHIVE;
+ inode_set_mtime_to_ts(dst, inode_set_ctime_current(dst));
+ err = exfat_combine_write_entry(dst, meta_since);
+ if (err) {
+ /*
+ * Keep @src the only owner of its clusters: give @dst
+ * back its old state, and write the old entry back
+ * now, as the failed write may have left the new one
+ * in its buffers or partly on disk. The device has
+ * failed a write of this entry either way, so the
+ * volume is treated as inconsistent below.
+ */
+ wrote = true;
+ exfat_combine_set_chain(dst, old_start, old_flags,
+ dst_clus, dst_size, dst_size);
+ if (exfat_combine_write_entry(dst, meta_since))
+ mark_inode_dirty(dst);
+ }
+ }
+ mutex_unlock(&sbi->s_lock);
+ if (err)
+ goto undo;
+
+ /*
+ * If this fails, the entry of @dst may not have reached the medium:
+ * leave @src as it is, so that its data stays reachable. Both files
+ * own the clusters then.
+ */
+ err = blkdev_issue_flush(sb->s_bdev);
+ if (err) {
+ exfat_combine_inconsistent(sb);
+ return err;
+ }
+
+ /*
+ * Step 3: the clusters now belong to @dst. Write @src as an empty
+ * file. If that fails, its in-memory state no longer owns the
+ * clusters, so evicting it frees nothing, but both entries reference
+ * them on disk. The caller flushes the entry.
+ */
+ mutex_lock(&sbi->s_lock);
+ exfat_combine_set_chain(src, EXFAT_EOF_CLUSTER, ALLOC_NO_FAT_CHAIN,
+ 0, 0, 0);
+ src_ei->attr |= EXFAT_ATTR_ARCHIVE;
+ inode_set_mtime_to_ts(src, inode_set_ctime_current(src));
+ err = exfat_emergency_state(sb);
+ if (!err)
+ err = exfat_combine_write_entry(src, meta_since);
+ if (err)
+ mark_inode_dirty(src);
+ mutex_unlock(&sbi->s_lock);
+ if (err)
+ exfat_combine_inconsistent(sb);
+ return err;
+
+undo:
+ /*
+ * @dst does not own the clusters of @src: cut its chain again and
+ * make sure that this reaches the medium. If it does, and the entry
+ * of @dst was not touched, nothing is left of the attempt.
+ */
+ ret = exfat_emergency_state(sb);
+ if (!ret && linked) {
+ mutex_lock(&sbi->s_lock);
+ ret = exfat_ent_set(sb, last_clu, EXFAT_EOF_CLUSTER);
+ mutex_unlock(&sbi->s_lock);
+ }
+ if (!ret)
+ ret = exfat_combine_flush(sb, meta_since);
+ if (wrote || (ret && linked))
+ exfat_combine_inconsistent(sb);
+ return err;
+}
+
+/*
+ * Write back @inode and check that everything dirtied since @since has
+ * reached the disk. The error flags of a mapping go to whoever checks
+ * them first, a concurrent fsync() included, so a clean return of the
+ * writeback alone does not tell; its errseq does. Mark the error seen,
+ * so that it does not fail later calls.
+ */
+static int exfat_combine_write_back(struct inode *inode, errseq_t since)
+{
+ int err = filemap_write_and_wait(inode->i_mapping);
+ int ret = errseq_check_and_advance(&inode->i_mapping->wb_err, &since);
+
+ return err ? err : ret;
+}
+
+/*
+ * A failed truncate can leave the allocation of a file larger than its
+ * size, or its valid_size above its size, and a corrupt entry can carry
+ * neither chain layout, or a contiguous chain running past the volume.
+ * Refuse such a file before anything is changed, as the valid_size of
+ * @src is carried over to @dst, and Step 1 writes the FAT entries of
+ * contiguous chains.
+ */
+static bool exfat_combine_inode_ok(struct inode *inode)
+{
+ struct exfat_sb_info *sbi = EXFAT_SB(inode->i_sb);
+ struct exfat_inode_info *ei = EXFAT_I(inode);
+ loff_t size = i_size_read(inode);
+
+ if (exfat_ondisk_size(inode) != round_up(size, sbi->cluster_size) ||
+ (!size && ei->start_clu != EXFAT_EOF_CLUSTER) ||
+ (size && ei->start_clu == EXFAT_EOF_CLUSTER) ||
+ exfat_get_valid_size(ei) > size)
+ return false;
+ if (!size || ei->flags == ALLOC_FAT_CHAIN)
+ return true;
+ /* As exfat_validate_vendor_alloc() checks a contiguous range. */
+ return ei->flags == ALLOC_NO_FAT_CHAIN &&
+ DIV_ROUND_UP_ULL(size, sbi->cluster_size) <=
+ sbi->num_clusters - ei->start_clu;
+}
+
+static int exfat_ioctl_combine(struct file *dst_file, unsigned long arg)
+{
+ struct inode *dst = file_inode(dst_file);
+ struct super_block *sb = dst->i_sb;
+ struct exfat_sb_info *sbi = EXFAT_SB(sb);
+ struct exfat_combine_args args;
+ struct file *src_file;
+ struct inode *src;
+ loff_t dst_size, src_size;
+ errseq_t dst_since, src_since, meta_since;
+ unsigned int last_clu;
+ bool moved = false;
+ int err = 0;
+
+ if (copy_from_user(&args, (void __user *)arg, sizeof(args)))
+ return -EFAULT;
+
+ if (args.flags)
+ return -EINVAL;
+
+ CLASS(fd, f)(args.src_fd);
+ if (fd_empty(f))
+ return -EBADF;
+ src_file = fd_file(f);
+ src = file_inode(src_file);
+
+ /* The data of @src becomes readable through @dst. */
+ if (!(dst_file->f_mode & FMODE_WRITE) ||
+ !(src_file->f_mode & FMODE_READ) ||
+ !(src_file->f_mode & FMODE_WRITE))
+ return -EBADF;
+
+ if (dst_file->f_path.mnt != src_file->f_path.mnt)
+ return -EXDEV;
+
+ if (!S_ISREG(dst->i_mode) || !S_ISREG(src->i_mode) || dst == src)
+ return -EINVAL;
+
+ if (unlikely(exfat_forced_shutdown(sb)))
+ return -EIO;
+
+ /*
+ * After an unclean shutdown, the clusters of a source may already
+ * belong to its destination as well, or be linked to it, and any file
+ * may be inconsistent until fsck.exfat has run.
+ */
+ if (sbi->vol_flags_persistent & VOLUME_DIRTY)
+ return -EUCLEAN;
+
+ /* LSM and fanotify permission checks, done before taking any lock. */
+ src_size = i_size_read(src);
+ err = remap_verify_area(src_file, 0, src_size, false);
+ if (err)
+ return err;
+ err = remap_verify_area(src_file, 0, src_size, true);
+ if (err)
+ return err;
+ err = remap_verify_area(dst_file, i_size_read(dst), src_size, true);
+ if (err)
+ return err;
+
+ err = mnt_want_write_file(dst_file);
+ if (err)
+ return err;
+
+ lock_two_nondirectories(dst, src);
+ /* swapon() sets S_SWAPFILE under the inode lock. */
+ if (IS_SWAPFILE(dst) || IS_SWAPFILE(src)) {
+ err = -ETXTBSY;
+ goto out_unlock_inodes;
+ }
+ /* An unlinked @dst is not written back: @src would lose its data. */
+ if (!dst->i_nlink) {
+ err = -ENOENT;
+ goto out_unlock_inodes;
+ }
+ inode_dio_wait(dst);
+ inode_dio_wait(src);
+ if (!exfat_combine_inode_ok(dst) || !exfat_combine_inode_ok(src)) {
+ err = -EIO;
+ goto out_unlock_inodes;
+ }
+
+ src_size = i_size_read(src);
+ if (!src_size)
+ goto out_unlock_inodes;
+
+ err = exfat_emergency_state(sb);
+ if (err)
+ goto out_unlock_inodes;
+
+ /*
+ * Clusters can only be appended whole, and exFAT cannot describe a
+ * gap in the middle of a file, so @dst has to end at a cluster
+ * boundary and be initialized up to there. Padding it is left to
+ * the caller, who knows what the format of the file allows.
+ */
+ dst_size = i_size_read(dst);
+ if ((dst_size & (sbi->cluster_size - 1)) ||
+ exfat_get_valid_size(EXFAT_I(dst)) != dst_size) {
+ err = -EINVAL;
+ goto out_unlock_inodes;
+ }
+ err = inode_newsize_ok(dst, dst_size + src_size);
+ if (err)
+ goto out_unlock_inodes;
+
+ err = exfat_combine_find_last(dst, src, &last_clu);
+ if (err)
+ goto out_unlock_inodes;
+
+ dst_since = filemap_sample_wb_err(dst->i_mapping);
+ src_since = filemap_sample_wb_err(src->i_mapping);
+ meta_since = filemap_sample_wb_err(sb->s_bdev->bd_mapping);
+
+ filemap_invalidate_lock_two(dst->i_mapping, src->i_mapping);
+
+ /*
+ * Dirty data of @src must reach its clusters before they change
+ * owner. All dirty data of @dst must be on disk before its new
+ * valid_size is, and cached folios of @dst past its EOF must not
+ * shadow the data appended from @src.
+ */
+ err = exfat_combine_write_back(src, src_since);
+ if (err)
+ goto out_unlock;
+
+ err = exfat_combine_write_back(dst, dst_since);
+ if (err)
+ goto out_unlock;
+
+ err = invalidate_inode_pages2_range(dst->i_mapping,
+ dst_size >> PAGE_SHIFT, -1);
+ if (err)
+ goto out_unlock;
+
+ err = __exfat_combine(dst, src, last_clu, &meta_since);
+ moved = i_size_read(dst) > dst_size;
+
+ if (moved) {
+ /* @src was emptied, unless flushing the entry of @dst failed. */
+ truncate_pagecache(src, i_size_read(src));
+ fsnotify_modify(dst_file);
+ fsnotify_modify(src_file);
+ }
+
+out_unlock:
+ filemap_invalidate_unlock_two(dst->i_mapping, src->i_mapping);
+out_unlock_inodes:
+ unlock_two_nondirectories(dst, src);
+
+ /*
+ * Make the empty entry of @src, which was written synchronously,
+ * durable, with the inode locks dropped so that writers of either
+ * file are not stalled by the device. Unlinking the emptied @src,
+ * if it is not needed, is up to the caller.
+ */
+ if (!err && moved) {
+ err = blkdev_issue_flush(sb->s_bdev);
+ if (err)
+ exfat_combine_inconsistent(sb);
+ }
+ mnt_drop_write_file(dst_file);
+ return err;
+}
+
long exfat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
struct inode *inode = file_inode(filp);
@@ -722,6 +1257,8 @@ long exfat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
return exfat_ioctl_set_attributes(filp, user_attr);
case EXFAT_IOC_SHUTDOWN:
return exfat_ioctl_shutdown(inode->i_sb, arg);
+ case EXFAT_IOC_COMBINE:
+ return exfat_ioctl_combine(filp, arg);
case FITRIM:
return exfat_ioctl_fitrim(inode, arg);
case FS_IOC_GETFSLABEL:
diff --git a/include/uapi/linux/exfat.h b/include/uapi/linux/exfat.h
index 46d95b16f..7ec6be2f1 100644
--- a/include/uapi/linux/exfat.h
+++ b/include/uapi/linux/exfat.h
@@ -13,6 +13,8 @@
*/
#define EXFAT_IOC_SHUTDOWN _IOR('X', 125, __u32)
+#define EXFAT_IOC_MAGIC 0xEF
+#define EXFAT_IOC_COMBINE _IOW(EXFAT_IOC_MAGIC, 0x10, struct exfat_combine_args)
/*
* Flags used by EXFAT_IOC_SHUTDOWN
@@ -22,4 +24,52 @@
#define EXFAT_GOING_DOWN_FULLSYNC 0x1 /* going down with full sync*/
#define EXFAT_GOING_DOWN_NOSYNC 0x2 /* going down */
+/*
+ * Argument for EXFAT_IOC_COMBINE.
+ *
+ * The ioctl is issued on the destination file. The clusters of @src_fd
+ * are appended to the destination without copying any data, and the
+ * source is left as an empty file, so that only metadata is changed.
+ * The caller unlinks the source afterwards if it is not needed; if the
+ * name of the source has to keep referring to the same file until then,
+ * the caller has to prevent concurrent renames.
+ *
+ * Clusters can only be appended at a cluster boundary, so the size of the
+ * destination has to be a multiple of the cluster size, which stat(2)
+ * reports in st_blksize, and the destination has to be written up to its
+ * size, with no range left uninitialized by truncate(2) or fallocate(2).
+ * Otherwise the call fails with EINVAL. User space pads the destination
+ * before the call with whatever its file format allows.
+ *
+ * An unlinked destination is refused (ENOENT); an unlinked source is
+ * accepted. An empty source leaves the destination unchanged.
+ *
+ * Errors are reported even when the device fails only after the
+ * destination was updated. The clusters may then already belong to the
+ * destination, with the source empty, still to be written as empty, or
+ * still referencing them as well; callers can tell from the sizes of the
+ * two files. When the device fails a write once the FAT or an entry was
+ * changed, the two files may share clusters on disk: the volume is then
+ * treated as after any other filesystem error (see the errors= mount
+ * option, read-only by default), and stays marked dirty until fsck.exfat
+ * has run. Otherwise a failed call leaves both files unchanged. If it
+ * fails because data of either file could not be written back, that data
+ * may be lost, as after a failed fsync(2); the error is reported once, and
+ * a later call does not report it again.
+ *
+ * A crash during the call may leave both files referencing the appended
+ * clusters, or the cluster chain of the destination linked to them while
+ * its size does not cover them yet. fsck.exfat resolves this without
+ * losing data, but neither file may be truncated or removed before fsck
+ * has run: that can free clusters the other file still uses. On a volume
+ * that was not cleanly unmounted, the call fails with EUCLEAN until
+ * fsck.exfat has run. After a crash, an empty source next to a
+ * destination that already contains its data means that the call
+ * completed and only the unlink is left.
+ */
+struct exfat_combine_args {
+ __s32 src_fd; /* file whose clusters are moved */
+ __u32 flags; /* must be zero */
+};
+
#endif /* _UAPI_LINUX_EXFAT_H */
base-commit: e8017d29067fd1310a65c3494ce1a1b492adbac6
--
2.53.0
^ permalink raw reply related [flat|nested] only message in thread
only message in thread, other threads:[~2026-12-01 20:39 UTC | newest]
Thread overview: (only message) (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01 20:38 [PATCH v14] exfat: add EXFAT_IOC_COMBINE to append a file's clusters to another Shaopei Zhu
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox