# FAT filesystem

The unit at [fs/fat.fs] implements the Filesystem API [fs/core] for the FAT
filesystem. It supports FAT12 and FAT16 but is still quite rough around the
edges.

* No FAT32
* No long filenames. It does gracefully ignore their presence though.
* No cluster reallocation. You are constantly leaking them through usage.

## Usage

You mount a FAT through "newfatfs ( blk -- fs )". For a given Blk [io/blk]
"blk" where the first sector has a proper FAT header, this call will yield a
struct that extends Filesystem and implements in entirely.

You might also be interested in [doc/fs/fatt], the "FAT tools" unit.

## direntry

In the code, a "direntry" is the address of a FAT entry structure in memory.
These references are short-lived because they're an address in the FAT sector
buffer which is very very often being overwritten.

File and directory IDs in FAT are the offset, on disk, of their corresponding
direntry.

## API

newfatfs ( blk -- fs )
  Initialize a new FATFS structure and yield it.

fatstorage! ( blk fs -- )
  Change the underlying storage for FAT fs "fs". You generally don't need to do
  that, but there's an exception with PCs, which boot using [drv/pc/int13h] and
  later need to upgrade to a "real" storage driver. Rather than creating a new
  FS structure entirely, it's better to just swap the underlying storage.

## Private API

### Structures

extends FS struct FATFS
  fields fatpart lastfreecluster
  fields fatsecsz secpercluster reservedseccnt FATcnt rootentcnt fatseccnt FATsz
endstruct

fatpart         A [io/part] targeting the FAT sectors
lastfreecluster Cache of last findfreecluster result

fields below are read-only unpacking of FAT header fields

fatsecsz       +11 BPB_BytsPerSec
secpercluster  +13 BPB_SecPerClus
reservedseccnt +14 BPB_RsvdSecCnt
FATcnt         +16 BPB_NumFATs
rootentcnt     +17 BPB_RootEntCnt
fatseccnt      +19 BPB_TotSec16
FATsz          +22 BPB_FATsz16

extends Stream struct FATFile
  fields cl0 clidx curcl adirty id fat
endstruct

cl0    First cluster of the file
clidx  Index in the chain where "curcl" is
curcl  Cluster containing current position
adirty Attributes dirty. When 1, must update entry on flush
id     FSID (offset in disk) of file
fat    Pointer to parent FATFS struct

## See also

* FAT: General Overview of On-Disk Format
