Repository navigation
JFAT FatChain
JFAT's cluster-chain engine: allocation, traversal, truncation, caching and durability for FAT12/16/32.
FatChain (fs/src/fs/org/jnode/fs/jfat/FatChain.java, ~1600 lines) is the layer between a FAT directory entry's startCluster and the bytes of a file. It walks and mutates the on-disk FAT through Fat/FatCache, allocates and frees clusters, and exposes read/write/seek/size/getLength to FatFile.
The 2026-11 JFAT hardening round changed the class substantially. It now keeps an incremental cluster-count/tail cache, validates chain structure with typed exceptions, serialises allocator and free walks on the Fat monitor, and separates a cheap dirty-set flush from the durability boundary in Fat.flush(). The same round added deferred hole zeroing for gap-extending writes: the gap clusters are allocated but never synchronously zeroed; reads through the hole return zeros and flush() realizes the range on the device in bulk multi-sector runs. Contiguous cluster runs are also coalesced into bulk device requests, and directory reads reuse a per-chain cluster scratch.
| Class / File | Role |
|---|---|
fs/src/fs/org/jnode/fs/jfat/FatChain.java |
Chain traversal, allocation, free, read/write, hints and caches |
fs/src/fs/org/jnode/fs/jfat/Fat.java |
FAT metadata, free count, allocator hint, dirty-set entry points |
fs/src/fs/org/jnode/fs/jfat/FatCache.java |
Volume-sized FAT cache (computed ≤ 8192 entries, jnode.fat.cacheSize override); dirty deque; active-FAT copy selection |
fs/src/fs/org/jnode/fs/jfat/ChainException.java |
Base typed chain failure (extends IOException) |
fs/src/fs/org/jnode/fs/jfat/ChainBeyondEndException.java |
Seek/read past end-of-chain |
fs/src/fs/org/jnode/fs/jfat/ChainCorruptException.java |
Cycle, free entry, reserved/bad entry, out-of-range link |
fs/src/fs/org/jnode/fs/jfat/FatFile.java |
Caller: uses FatChain for file I/O and truncation |
FatChain holds a head cluster, a dirty flag, a modificationStamp, per-end read/write ChainHints, and the two cached values:
private volatile int head;
private volatile long modificationStamp;
private volatile ChainHint readHint;
private volatile ChainHint writeHint;
private volatile int cachedClusterCount = -1;
private volatile int cachedTailCluster = -1;Every read and write gets its own ChainPosition/ChainIterator. They are not shared mutable state between calls, so concurrent reads of one chain cannot corrupt each other's cursor.
ChainIterator.next() rejects structurally invalid links:
- a cycle detected once the cursor reaches
fat.size() - a free entry in the middle of a chain
- reserved or bad-cluster markers
- a link outside the valid cluster range
These throw ChainCorruptException, while seeking/reading past the last cluster throws ChainBeyondEndException. Callers can distinguish "file shorter than the requested offset" from "the FAT is corrupt", which the old generic IOException could not express.
size() and getEndCluster() normally serve cachedClusterCount/cachedTailCluster. The cache is maintained incrementally:
-
noteAppendedClusters(n, segmentTail, chainWasEmpty)advances the count (when it was already known, or when the chain was empty) and always records the exact tail from the allocated segment -
freeCounted(n, count)subtracts on truncation -
setStartCluster(0)resets both values - rollback and flush-failure paths invalidate both
A freshly opened chain has no cache, so the first size()/getEndCluster() walks once. The cache trusts only mutations performed by this FatChain; direct FAT edits behind its back are invisible. Tests enable FatChain.debugSizeCacheCheck, which forces a walk and throws IllegalStateException on a cache mismatch.
Fat.getLastFree() is a lower bound, not an exact next-free pointer. FatChain.moveFreeHintPast(last) may raise it only after those clusters are provably consumed by an allocation. Any free transition lowers it via Fat.noteFreeTransition(index, oldValue, newValue).
findFreeSegment scans forward from the hint and then wraps, bounded at firstCluster(), and throws FileSystemFullException if it cannot find the requested run. The scan-and-claim sequence holds the Fat monitor, so two chains cannot both decide the same clusters are free and both claim them.
Allocation paths (allocateAndClear, append) clear the newly claimed clusters before linking them. Fat.clearCluster allocates a fresh zero buffer per call; the old shared clearbuf was racy.
FatFile knows the old cluster count from its directory-entry length. It calls the two-argument overload:
fatChain.free(n, oldClusters);If chainClusters == n, the whole chain is freed. If the entry-derived count is larger, the chain is cut at that index. If the chain ends early, no FAT entry is modified and an IOException is thrown; truncation is all-or-nothing rather than leaving a half-freed chain.
FatChain mutations write through FatCache, which records each changed cache element in a dirtyElements deque in change order. Fat.flushDirty() drains only that deque:
synchronized void flushDirty() throws IOException {
if (isDirty())
cache.flushDirty();
}Fat.flush() remains the durability boundary: it flushes the whole cache, writes the FAT copies, and reaches the block device. If a flushDirty() fails, FatChain invalidates its count/tail cache and Fat rebuilds the dirty set and recomputes the free count, because an element may have been applied to only some FAT copies.
FatCache positions every element at getFirst(getActiveFatIndex()). On a normal (mirrored) volume reads hit FAT copy 0 and dirty elements are written to every copy. When FAT32 BPB_ExtFlags bit 7 is set, only the declared active copy is read and written. See FAT-Boot-Sector.
readHint and writeHint cache the last ChainPosition for sequential I/O. A hint carries the modificationStamp and the chain head it was created under; any mutation invalidates both hints and bumps the stamp, so a stale hint is discarded rather than reused after a truncate, append or free.
FatChain.read/write used to issue one BlockDeviceAPI request per cluster even when the chain walk yielded physically contiguous clusters. Whole-cluster, cluster-aligned I/O now coalesces a contiguous run into one request per 256-sector window:
-
ChainIterator.peekNext()returns the next cluster without advancing; the walk consumes clusters only while the next number isprev + 1. -
extendRun(iterator, firstCluster, remainingBytes, clusterSize)counts the run, bounded by the remaining bytes andFat.getMaxRunClusters(). -
Fat.readClusterRun/writeClusterRunissue a single request per run, chunked internally so no request exceedsMAX_REQUEST_SECTORS = 256(the IDE LBA28 command cap).checkClusterRunrejects a buffer larger thanclusterCount * clusterSizeand an out-of-range cluster (overflow-safe inlong). - Fragmented and single-cluster chains keep the unchanged per-cluster path; the run is the caller's contiguity contract, not a re-validation of the FAT links.
A 1 MiB unfragmented read or write now issues 8 requests with 4 KiB clusters instead of 256; a fragmented chain still issues 256 with byte-identical content (FatClusterRunCoalesceTest). When a write starts inside an existing contiguous run and extends past EOF, the link target must be the run's last cluster, not its first, or the appended tail overwrites FAT[firstCluster] and orphans the rest of the run.
FatChain.readClusterData(clusterIndex) returns a per-chain clusterDataScratch array that is reused between calls and fully overwritten on success. Its only consumer, FatDirectory.getFatDirEntry, byte-copies the 32-byte entry out immediately and never retains the array. On a failed read the scratch may be partially written, so FatDirectory drops its entryClusterBuffer/entryClusterIndex and rethrows rather than serving the stale cluster under the old index.
Gap-extending writes (seek past EOF followed by a write, FatFile.setLength grow) allocate the backing clusters but no longer zero them on the device. The chain records the gap as a hole range in FatChain.holes, a merged, sorted, non-overlapping list of {from, to} byte ranges in chain-offset terms. Any byte exposed beyond the old file length is either written (carved out of the holes) or recorded as a hole, so newly exposed bytes always read as zeros; this also covers pre-existing slack in the current cluster for within-cluster beyond-EOF writes (a case that reads stale bytes even on master):
- reads through a hole return zeros (
hasHoleIntersection/readChunkWithHoles); the underlying on-disk bytes may be stale without leaking into the file. Whenholesis non-empty, read-run coalescing is bypassed so a hole never gets coalesced into a device read; -
write(length, offset, src)(the length-aware overload used byFatFile) defers two ranges as holes after the data copy succeeds:[length, offset)— the beyond-EOF gap a write leaves behind — and[writtenEnd, chain coverage end)— the slack of clusters grown by the write.write(offset, src)(the length-less overload used byFatDirectory) never defers exposure holes because everything in a directory chain is live content; because no hole is recorded for those bytes, every newly linked cluster is zeroed eagerly there instead (stale device bytes never leak into a grown chain); - the freshly written range
[offset, offset + src.remaining())is carved out of the pending holes after the data copy succeeds; - holes recorded by a failed write are handed back by
WriteRollback.deferredZerosinrollbackTo; - every access to
holesis guarded by the per-chainholeLock, and hole realization runs under the same lock as the data-write + hole-carve sequence of the write path (writeInternal), so a concurrent flush can never zero bytes a writer just wrote (FatChainConcurrencyTest.testConcurrentGapWriterAndFlusher); -
FatChain.flush()realizes every pending hole on the device (realizeHoles/zeroHoleRange): whole contiguous clusters are coalesced into one device request pergetMaxRunClusters()run instead of one per cluster, partial edge clusters are zeroed individually, and the holes list is drained range by range so a failure leaves exactly the unrealized ranges behind (re-zeroing is idempotent).
Gap-extend device writes dropped from one device request per 4 KiB cluster (zeroed twice on master, ~2 bytes of device write per gap byte) to one multi-sector run per getMaxRunClusters() clusters at flush time; the seek+write itself issues device writes proportional to the written data (see FatDeferredZeroFillTest.testGapExtendWriteDeviceWritesProportionalToData).
Crash / power-loss contract (pinned by FatDeferredZeroFillTest):
- The hole list is transient, in-memory state guarded by the chain's
holeLock; it is not persisted and is not recovered after a crash. This is sound because a hole is never reachable from the recovered on-disk state. -
FatEntry.flush()callschain.flush()before persisting the directory entry that exposes the extended length, andFatChain.flush()realizes the holes before returning. After any clean flush the gap is zero on the device and reads as zero after remount. - On an unclean shutdown, the recovered file length is the last durably flushed directory-entry length. A gap-extending write that was never flushed is unreachable: the exposing length was never persisted, and neither were the FAT links that would make the gap clusters reachable. A crash during a flush can leave a partially realized gap on the device, but the exposing entry is still the old length, so the gap is unreachable after recovery.
- A failed flush keeps the chain dirty and leaves exactly the unrealized ranges in the hole list; in-memory reads still return zeros and a later flush retries the realization (
FatDeferredZeroFillTest.testCrashDuringGapRealizationKeepsGapUnexposed,testGapFlushesRetryAfterFailure). - FAT metadata can still lag the device (lazy dirty-deque flush); the contract is about the visible file contents, not the FAT's free count.
FatFile.write(offset beyond current length)
→ chain = getChain()
→ chain.write(...)
→ ChainPosition position = new ChainPosition(offset)
→ find the last cluster (cachedTailCluster, or walk once)
→ findFreeSegment(1) under the Fat monitor
→ scan forward from getLastFree(), wrap at firstCluster()
→ clear the cluster, link it from the tail
→ moveFreeHintPast(last)
→ noteAppendedClusters(1, segmentTail, false)
→ write the data into the new cluster
→ invalidateHints() (modificationStamp++)
→ flushDirty() (drains the FAT dirty deque)
If the append fails after the cluster is linked but before the data is written, the chain still owns the cluster; the file length in the directory entry is the authority for how much of that cluster is live. A later truncate to the old length frees it again without walking the whole chain, because the caller passes the entry-derived cluster count.
| Operation | Lock |
|---|---|
| Allocate/free/truncate a chain |
Fat monitor |
FatCache entry read/write |
FatCache instance monitor |
FatChain.size()/getEndCluster() cache read |
volatile fields; no lock |
FatChain read/write cursor |
per-call object; no shared state |
FatChain.holes access, hole realization, write + carve |
per-chain holeLock
|
| Rename/create/delete in a directory |
FatDirectory monitor |
FileDevice host-file I/O |
FileDevice instance monitor |
The lock order is directory → holeLock → FAT monitor. Code must not call back into a FatDirectory while holding the Fat monitor, and holeLock is only ever taken before the Fat monitor, never the other way around. Reads hold holeLock only for the hole-list scan, never for the device transfer.
| Failure | Detection | Result |
|---|---|---|
| Seek/read beyond last cluster |
ChainIterator exhausted, setPosition above length |
ChainBeyondEndException |
| Cycle | cursor reaches fat.size()
|
ChainCorruptException("circular chain at: …") |
| Free entry inside a chain | entry value 0
|
ChainCorruptException("free entry in chain at: …") |
| Reserved/bad cluster | variant-specific reserved markers | ChainCorruptException("corrupt chain entry …") |
| Out-of-range link | link < firstCluster() or >= fat.size()
|
ChainCorruptException |
| No free run | forward + wrap scan exhausts the FAT | FileSystemFullException |
| Short chain during truncate | walked count < n
|
IOException, no FAT entry modified |
| Dirty flush failure |
fat.flushDirty() throws |
chain cache invalidated, dirty set rebuilt |
| Unclean shutdown with pending holes | recovery from last persisted dir entry | gap unreachable; on-disk gap bytes may be stale but are not part of the file |
| Unclean shutdown during hole realization | flush ordering (chain.flush() before entry persist) |
partially realized gap unreachable; entry length still the old one |
| Flush failure during hole realization |
FatChain.flush() retried by caller |
chain stays dirty; unrealized ranges kept; reads still return zeros |
| Stale size/tail cache |
debugSizeCacheCheck walk mismatch |
IllegalStateException (tests only) |
The recovery rule is fail-closed: a chain that cannot be walked or freed exactly is left alone rather than partially unlinked. A partial free would lose reachable clusters and turn a recoverable corruption into capacity loss.
The 2026-11 round added targeted regression classes under fs/src/test/org/jnode/test/fs/jfat/:
| Test | Focus |
|---|---|
FatChainSizeCacheTest |
O(1) count/tail cache and rollback invalidation |
FatChainReadHintTest |
read hint reuse and invalidation |
FatChainShrinkHintTest |
shrink/free drops stale hints |
FatChainFreeWithCountTest |
free(n, chainClusters) fast path and desync policy |
FatChainConcurrencyTest |
parallel reads/allocations; gap writer vs concurrent flusher/reader |
FatClusterRunCoalesceTest |
contiguous run coalescing (8 vs 256 requests), fragmented-chain equivalence, write extending past a coalesced run end |
FatAllocHintTest |
hint lower-bound and wrap behavior |
FatDirtyFlushTest |
dirty-set vs full flush |
FatSizeBoundaryTest |
4 GiB offset/length guards |
FatDeferredZeroFillTest |
deferred hole zeroing: proportional device writes, zero-read invariant, flush-time realization (bulk runs per getMaxRunClusters(), pinned by a large-write counting assertion), crash-contract (mid-flush failure) |
FatLengthlessWriteGapTest |
length-less write(offset, src): grown gap clusters are zeroed eagerly |
FatBeyondEofWriteTest |
beyond-EOF write gap zero-fill, persisted across remount |
FatSetLengthTest |
setLength grow zero-fill semantics |
FatFailurePathTest |
typed errors and short-chain truncate |
- Enable
FatChain.debugSizeCacheCheckin a focused test if a file's length or tail cluster looks wrong after a mutation. - Reproduce with
FatChainConcurrencyTest/FatDirtyFlushTestbefore changing locking; a "fix" that only adds asynchronizedmethod can deadlock with theFatmonitor. - Check
getLastFree()after a free: a hint that did not move down meansnoteFreeTransitionwas bypassed. - For a short read after remount, check whether
Fat.flush()(not justflushDirty()) was reached. - For a 4 GiB failure, inspect the caller for an
intcast before thelongguard inFatFile/ChainPosition.
-
The size/tail cache is local knowledge. Do not mutate FAT entries through another
Fathandle and expect an existingFatChainto notice; enabledebugSizeCacheCheckin tests. -
free(n)still works but is O(n). Preferfree(n, chainClusters)when the entry length is known. -
freedesynchronisation is fail-closed. If the chain is shorter than the directory entry claims, the chain is not partially freed. -
The free hint moves down on frees. Code that treats
getLastFree()as monotonic is wrong; it is only a lower bound and allocation may wrap. -
Allocation is serialised on the
Fatmonitor, not on theFatChain. Two chains of the same file are not a supported concurrency pattern either. -
flushDirty()is not a durability barrier. It only drains the dirty deque; useFat.flush()/BlockDeviceAPI.flush()/syncfor persistence. -
Holes are transient and merged. Do not add a hole for bytes that are actually written; the write path carves
[offset, offset+remaining)out of the pending holes after the data copy succeeds, and the flush + write paths are mutually exclusive underholeLock. - Read-run coalescing is bypassed while holes are pending. It resumes after the flush that realizes them; correctness over speed.
-
FatFile.setLength/seekgrowth no longer flushes eagerly. The gap is realized only at the next flush boundary; in-memory reads between the grow and the flush are served by the hole list. -
4 GiB is a hard FAT32 ceiling.
FatFile.setLength/writeandChainPosition.setPositionreject offsets above0xFFFFFFFFLwith anIOException; the directory-entry length is encoded/decoded as an unsigned 32-bit value. -
FAT32 has no fixed root sector.
Fat32.getClusterPosition(0)throwsIllegalArgumentException, andFat.readClusterrejects clusters belowfirstCluster().
- FAT-Filesystem — parent FAT12/16/32 subsystem
- FAT-Boot-Sector — BPB validation, FSInfo and active-FAT selection
-
Block-Device-Layer —
BlockDeviceAPI.flush()and sector I/O - Filesystem-Layer — filesystem/VFS integration
- VFS-Layer — mount and path resolution