Skip to content

FAT Filesystem

opencode-agent[bot] edited this page Nov 22, 2026 · 6 revisions

FAT Filesystem

JNode's FAT12/FAT16/FAT32 implementation (jfat) with Long File Name support and 2026-11 hardening.

Overview

The FAT (File Allocation Table) filesystem in JNode provides read-write support for FAT12, FAT16 and FAT32. Two implementations live under fs/src/fs/org/jnode/fs/:

  • fat/ — the original implementation; legacy, less actively maintained.
  • jfat/ — the active implementation, registered through FatFileSystemType and used by the installer and boot images.

jfat integrates with the VFS through FatFileSystemType and talks to storage through BlockDeviceAPI. The 2026-11 hardening round (roughly #876–#979) turned a permissive parser into a strict, concurrency-safe filesystem: BPB validation, a 512-byte-sector guard, active-FAT selection, typed chain errors, serialized FAT cache access, O(1) chain size, real setName() renames, a directory index and buffered root-directory reads. The later pass (#970–#979) added lazy directory-entry decode, batched directory writes, contiguous-run coalescing, volume-sized FAT caches and deferred hole zeroing.

Key Components

fat Package (Legacy)

Class / File Purpose
fs/src/fs/org/jnode/fs/fat/ Original FAT12/FAT16/FAT32 implementation — legacy

jfat Package (Active)

Class / File Purpose
FatFileSystemType.java Factory implementing FileSystemType; probes block devices and creates FatFileSystem
FatFileSystem.java Main filesystem: FAT instance, root directory, flush, free space
BootSector.java BPB decode and validation; geometry computation; FAT type detection
Fat.java FAT metadata: free count, allocator hint, dirty-set flush, FAT copy comparison
FatCache.java Volume-sized FAT cache (computed default, jnode.fat.cacheSize override) with a dirty deque and active-copy routing
Fat32.java, Fat16.java, Fat12.java Variant-specific entry encoding, EOF markers, cluster positions
FatChain.java Cluster-chain traversal/allocation/free; typed errors; size/tail caches
FatFile.java File I/O, 4 GiB limit, slack space
FatDirectory.java Directory entries, lazy index, short-name allocation, rename
FatRootDirectory.java FAT12/16 fixed root region (buffered) and FAT32 root chain
FatEntriesFactory.java, FatEntriesIterator.java Directory scanning and iteration
FatShortDirEntry.java, FatLongDirEntry.java 8.3 and LFN directory entries
FatName.java Short-name generation, numeric tails, fold
FatRecord.java Short+long entry pair for one logical name
FatFormatter.java, FatFileSystemFormatter.java Format-time geometry, FSInfo, DOS serial
FatFsInfo.java FSInfo sector structure
ChainException.java, ChainBeyondEndException.java, ChainCorruptException.java Typed chain failures

Deep dives: JFAT-FatChain and FAT-Boot-Sector.

How It Works

Mounting and validation

FatFileSystem constructor:
1. Fat.create(device) — check 512-byte sectors, read boot sector
2. BootSector.decode() — validateBpb → compute → validateGeometry → validateFat32
3. Compare FAT copies (unless single-active-FAT is declared)
4. Seed the free-cluster count and allocator hint
5. Read the root directory (fixed region for FAT12/16, cluster chain for FAT32)

A malformed BPB fails at mount with FileSystemException and the offending field/value. See FAT-Boot-Sector for the full validation table.

FAT table, cache and free space

Fat owns a FatCache and a free-cluster count. The count is not read from FSInfo: it is seeded by a full scan at mount and maintained incrementally by noteFreeTransition. getFreeSpace() is built on it and must not regress to an O(n) scan. The formatter writes FSInfo free count/next-free as 0xFFFFFFFF ("unknown") for foreign readers.

FatCache keys every element to the active FAT copy. With mirroring enabled, reads hit copy 0 and dirty elements are written to all copies; with FAT32 BPB_ExtFlags bit 7 set, only the declared active copy is read and written, and copy comparison reports no divergence.

The cache is no longer a fixed 8192 entries. Fat sizes it with FatCache.resolveCacheSize(bootSector.getSectorsPerFat(), jnode.fat.cacheSize):

  • the computed default is the FAT's sector count, clamped to [256, 8192] (computeCacheSize), so small volumes keep the whole FAT resident and large ones stop at the cap;
  • a jnode.fat.cacheSize property wins when it parses as an integer, clamped to [16, 65536] with a warning; an unparseable value falls back to the computed default with a warning;
  • the cache-resident FAT is required for the failed-flush recompute to rescan without evicting dirty elements against a dead device. The free list is an ArrayDeque (the old java.util.Stack was replaced). getCacheStat() is logged at INFO on flush.

Cluster chains

Allocation, append, truncate and traversal live in FatChain. The 2026-11 changes include:

  • incrementally maintained cachedClusterCount/cachedTailCluster, making size() and getEndCluster() O(1)
  • per-call ChainPosition/ChainIterator (no shared cursor state)
  • typed errors: ChainCorruptException for cycles/free/reserved/out-of-range links; ChainBeyondEndException for past-end seeks
  • allocation/free walks serialized on the Fat monitor
  • a lower-bound free hint that moves down on frees and up only after a provable allocation
  • truncate using the directory-entry cluster count, avoiding a chain walk
  • coalescing of physically contiguous cluster runs into one device request per 256-sector window (Fat.readClusterRun/writeClusterRun, extendRun/peekNext), so a 1 MiB unfragmented transfer issues 8 requests instead of 256
  • a hard 0xFFFFFFFF (4 GiB) limit on file offset/length

See JFAT-FatChain.

Directory index and insertion

FatDirectory.ensureIndex() lazily builds one include-deleted index, reconciling dirty or byte-identical cached entries, and populates:

  • children (FatTable)
  • idMap (entry ID → entry)
  • shortNames (short-name key → entry)
  • tailFamilies (numeric-tail allocation state)

getFatFreeEntries uses a freeSlotHint and ChainEndException; MAXENTRIES = 65535 still applies, and FAT12/16 fixed roots enforce the BPB entry count. The index is invalidated by writes and renames rather than maintained piecemeal.

Directory entry reads are buffered per cluster (entryClusterBuffer), so a 4 KiB cluster costs one disk read instead of 128 small reads. The buffer aliases the chain's per-chain readClusterData scratch on cluster change; each 32-byte entry is copied out immediately before the scratch can be recycled, and a failed read drops the buffer and cluster index rather than serving a partially written scratch.

FatShortDirEntry/FatLongDirEntry no longer decode in the constructor. Decoding is deferred to the first accessor via ensureDecoded(); a scanned entry owns its 32 bytes (there is no pool or view, because idMap-cached entries outlive the scan). A malformed field such as the FAT32 FstClusHi guard therefore fires on first access, not at construction.

Batched directory-entry writes

FatDirectory.setFatDirEntries(Collection<FatDirEntry>) groups entries by the cluster that holds them, splices each group into a span [minIndex*32, (maxIndex+1)*32), and issues one chain write per touched cluster. The create path (a FatRecord's LFN entries plus the short entry), FatEntry.delete(), the rename batches and FatDirectory.initialize() all route through it; FatRootDirectory overrides it for the fixed FAT12/16 root region. A create or delete with an LFN of n components now performs at most ceil((n+1)/entriesPerCluster) device writes instead of n+1. onShortEntryWritten is invoked once per entry written, not once per batch. Ordering is unchanged: chain data, then FAT, then directory entries; callers must pass entries whose target bytes are already durable. The single-entry setFatDirEntry remains for genuinely single-entry callers.

Short names and numeric tails

FatName generates the 8.3 alias:

  • FatUtils.toUpperCase and short-name decode are pinned to Locale.ROOT, so generation and lookup agree regardless of host locale
  • numericTail() writes the ~N tail directly into the 11-byte basis and probes FatDirectory.shortNameInUse
  • tailStart(p, tailLength) returns Math.min(p + 1, 7 - tailLength), keeping the digits out of the extension; the previous off-by-one could write tail digits into the extension
  • FatDirectory tracks per-family released/blocked tails, so a freed FOO~1 is reused before a fresh number

Rename (setName)

FatEntry.setName() is a real on-disk rename, not a no-op:

  1. Validate the new long name and check collisions against long names and the generated short name (self excluded, so case-only renames work).
  2. Build a new FatRecord (short + LFN entries) and copy created/modified/accessed timestamps, start cluster, length and attributes.
  3. Write the new short and long entries.
  4. Delete the old long entries and the old short entry.
  5. Update children, idMap and the index.

Failure between steps can leave duplicate or missing entries; there is no transactional rollback.

LFN handling

Long names are stored in FatLongDirEntry records immediately preceding their 8.3 alias, with a checksum tying them together. The 2026-11 fold fix made uppercase normalisation consistent (Locale.ROOT) between LFN encoding and short-name lookup, fixing names whose generated alias did not match the scanned alias.

Root directory buffering

FatRootDirectory.rootEntryOffset(bootSector, index) centralises the fixed-root bounds check and 32L * index offset arithmetic. FAT12/16 root reads buffer one cluster at a time, bounded by the root region, and invalidate that buffer on write. FAT32 delegates to FatDirectory, because the FAT32 root is an ordinary cluster chain.

Writing and durability

FatFileSystem.flush():
1. Write the dirty boot sector
2. Flush open FatFile chains
3. Flush the FAT dirty set / FAT copies
4. Flush dirty directories
5. Reach BlockDeviceAPI.flush()

Fat.flushDirty() drains only the ordered dirty deque and is used by chain operations; Fat.flush() is the durability boundary. A failed flushDirty() invalidates the chain cache and rebuilds the dirty set/free count. IDE write-back default and sync are covered in IDEDisk-Driver.

File access and write path

FatFile.getData():
1. Get the starting cluster from FatRecord/FatShortDirEntry
2. FatChain(listIterator(startCluster)) maps chain index → cluster
3. Map cluster → sector offset via variant-specific getClusterPosition()
4. Read/write through FatFileSystem.getApi()

FatFile.flush():
1. FatChain.flushDirty() (FAT cache dirty set)
2. Fat.flush() (FAT copies + block device)

The chain-to-cluster map is computed on demand; only the count/tail are cached. A directory entry's 32-bit length is the only authority for how much of the last cluster is live, which is why getSlackSpace() is defined for live entries only.

Hardening Map (2026-11)

Area Change Page
4 GiB boundary FatFile/FatChain/FatShortDirEntry reject > 0xFFFFFFFF JFAT-FatChain
BPB validation strict field sets and FAT32 version/root checks FAT-Boot-Sector
Sector size 512-byte guard on mount and format FAT-Boot-Sector
FSInfo write 0xFFFFFFFF, never read at runtime FAT-Boot-Sector
Active FAT honour ExtFlags bit 7 and validate the index FAT-Boot-Sector
Chain size/tail O(1) cache, typed errors, serialized allocation JFAT-FatChain
Truncate free(n, chainClusters), fail-closed on desync JFAT-FatChain
Dirty set flushDirty() for chain ops, flush() for durability JFAT-FatChain
Directory index lazy children/idMap/shortNames/tailFamilies this page
Rename real on-disk setName() with collision checks this page
Short names Locale.ROOT fold, numeric-tail off-by-one fix this page
Root directory cluster-buffered FAT12/16 reads this page
FAT cache sizing volume-derived default, jnode.fat.cacheSize override, ArrayDeque free list this page
Coalesced I/O contiguous cluster runs, 256-sector request cap JFAT-FatChain
Lazy decode ensureDecoded(); scanned entries own their 32 bytes this page
Batched dir writes setFatDirEntries, one device write per touched cluster this page
Formatter long geometry, DOS serial from epoch millis FAT-Boot-Sector
Dates Calendar-free DOS time/date encoding this page
Concurrency Fat monitor, FatCache synchronization, per-call cursors JFAT-FatChain
Descriptor remove atomics then accessDeclaredMembers this page

Test coverage

New or extended JFAT test classes include:

  • BootSectorValidationTest, FatSectorSizeGuardTest, FatApiConsistencyTest
  • FatFormatterRawStructureTest, FatFormatterRoundTripTest, FatFsInfoRuntimeTest, FatCopyComparisonTest
  • FatChainSizeCacheTest, FatChainReadHintTest, FatChainShrinkHintTest, FatChainFreeWithCountTest, FatChainConcurrencyTest, FatAllocHintTest, FatDirtyFlushTest, FatSizeBoundaryTest
  • FatDirectoryIndexTest, FatDirectoryExtensionTest, FatDirectoryConcurrencyTest, FatSetNameTest, FatShortNameGoldenTest, FatShortNameScanCountTest, FatNumericTailTest, JFatLongFileNameTest
  • FatRootDirectoryBufferTest, FatRootDirectoryWriteTest, FatSlackSpaceTest, FatUtilsConcurrencyTest, FatDosDateTimeEncodingTest, JfatDescriptorPermissionTest
  • FatCacheSizeTest, FatClusterRunCoalesceTest, FatDirectoryBatchWriteTest, FatScanOwnershipTest, FatDeferredZeroFillTest, FatLengthlessWriteGapTest

Fat32ImageBuilder is the shared raw-image helper for several of these.

Gotchas & Non-Obvious Behavior

  • Root directory: FAT12/16 root is a fixed BPB-sized region; FAT32 root is a cluster chain. Fat32.getClusterPosition(0) throws.
  • Cluster size: bytesPerSector * sectorsPerCluster; only 512-byte sectors are supported.
  • FAT copies: mirrored volumes read copy 0 and write all copies; single-active-FAT volumes read/write only the declared copy. Divergence on a mirrored volume is logged but never repaired.
  • Free count is authoritative in memory, not FSInfo. Do not read FSInfo at runtime.
  • Free hint is a lower bound. It can move down on frees; allocation scans forward then wraps and is bounded at firstCluster().
  • 4 GiB limit: FatFile.setLength/write and ChainPosition.setPosition reject values above 0xFFFFFFFFL; FatShortDirEntry encodes/decodes the length as unsigned 32-bit.
  • Slack space is live-entry only: FatFile.getSlackSpace() throws for deleted entries.
  • Rename is not atomic. A crash between writing the new record and deleting the old one can leave duplicates.
  • Directory index is lazy. The first insert/rename after mount pays a full directory scan.
  • Directory entries decode lazily. FatShortDirEntry/FatLongDirEntry validate on first access, so a malformed field surfaces at use, not at construction; scanned entries own their 32 bytes because idMap-cached entries outlive the scan.
  • The cluster read buffer is a shared scratch. FatDirectory.entryClusterBuffer aliases FatChain.readClusterData's per-chain scratch; copy entry bytes out immediately and drop the buffer after a failed read.
  • The FAT cache size follows the volume. Do not assume 8192 entries; jnode.fat.cacheSize is clamped to [16, 65536] and a small volume keeps only its own FAT sectors.
  • Run coalescing assumes contiguity. Fat.readClusterRun/writeClusterRun trust the caller's contiguous-cluster contract and never re-validate the FAT links; a write that extends past a coalesced run must link from the run's last cluster.
  • Case-only rename is supported because the collision check excludes self.
  • clearbuf is gone: Fat.clearCluster allocates a fresh zero buffer per call; sharing one buffer was racy.
  • jfat descriptor permissions: jfat no longer imports java.util.concurrent.atomic; the accessDeclaredMembers grant is gone. Removing the atomics was required before the permission could be removed.

Related Pages

Clone this wiki locally