aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

fat.c (33641B)


      1 /*-
      2  * SPDX-License-Identifier: BSD-2-Clause
      3  *
      4  * Copyright (c) 2019 Google LLC
      5  * Copyright (C) 1995, 1996, 1997 Wolfgang Solfrank
      6  * Copyright (c) 1995 Martin Husemann
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  *
     17  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
     18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     20  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
     26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 #include "freebsd-compat.h"
     30 #if defined(__RCSID) && !defined(lint)
     31 __RCSID("$NetBSD: fat.c,v 1.18 2006/06/05 16:51:18 christos Exp $");
     32 #endif /* not lint */
     33 
     34 #include "queue.h"
     35 
     36 #include <limits.h>
     37 #include <sys/mman.h>
     38 #include <sys/param.h>
     39 
     40 #include <assert.h>
     41 #include <stdbool.h>
     42 #include <stdlib.h>
     43 #include <string.h>
     44 #include <ctype.h>
     45 #include <stdio.h>
     46 #include <unistd.h>
     47 
     48 #include "ext.h"
     49 #include "fsutil.h"
     50 
     51 static int                      _readfat(struct fat_descriptor *);
     52 static inline struct bootblock *boot_of_(struct fat_descriptor *);
     53 static inline int               fd_of_(struct fat_descriptor *);
     54 static inline bool              valid_cl(struct fat_descriptor *, cl_t);
     55 
     56 /*
     57  * Head bitmap for FAT scanning.
     58  *
     59  * FAT32 have up to 2^28 = 256M entries, and FAT16/12 have much less.
     60  * For each cluster, we use 1 bit to represent if it's a head cluster
     61  * (the first cluster of a cluster chain).
     62  *
     63  * Head bitmap
     64  * ===========
     65  * Initially, we set all bits to 1.  In readfat(), we traverse the
     66  * whole FAT and mark each cluster identified as "next" cluster as
     67  * 0.  After the scan, we have a bitmap with 1's to indicate the
     68  * corresponding cluster was a "head" cluster.
     69  *
     70  * We use head bitmap to identify lost chains: a head cluster that was
     71  * not being claimed by any file or directories is the head cluster of
     72  * a lost chain.
     73  *
     74  * Handle of lost chains
     75  * =====================
     76  * At the end of scanning, we can easily find all lost chain's heads
     77  * by finding out the 1's in the head bitmap.
     78  */
     79 
     80 typedef struct long_bitmap {
     81   unsigned long *map;
     82   size_t         count; /* Total set bits in the map */
     83 } long_bitmap_t;
     84 
     85 static inline void
     86 bitmap_clear(long_bitmap_t *lbp, cl_t cl)
     87 {
     88   cl_t          i         = cl / LONG_BIT;
     89   unsigned long clearmask = ~(1UL << (cl % LONG_BIT));
     90 
     91   assert((lbp->map[i] & ~clearmask) != 0);
     92   lbp->map[i] &= clearmask;
     93   lbp->count--;
     94 }
     95 
     96 static inline bool
     97 bitmap_get(long_bitmap_t *lbp, cl_t cl)
     98 {
     99   cl_t          i       = cl / LONG_BIT;
    100   unsigned long usedbit = 1UL << (cl % LONG_BIT);
    101 
    102   return ((lbp->map[i] & usedbit) == usedbit);
    103 }
    104 
    105 static inline bool
    106 bitmap_none_in_range(long_bitmap_t *lbp, cl_t cl)
    107 {
    108   cl_t i = cl / LONG_BIT;
    109 
    110   return (lbp->map[i] == 0);
    111 }
    112 
    113 static inline size_t
    114 bitmap_count(long_bitmap_t *lbp)
    115 {
    116   return (lbp->count);
    117 }
    118 
    119 static int
    120 bitmap_ctor(long_bitmap_t *lbp, size_t bits, bool allone)
    121 {
    122   size_t bitmap_size = roundup2(bits, LONG_BIT) / (LONG_BIT / 8);
    123 
    124   free(lbp->map);
    125   lbp->map = calloc(1, bitmap_size);
    126   if (lbp->map == NULL)
    127     return FSFATAL;
    128 
    129   if (allone) {
    130     memset(lbp->map, 0xff, bitmap_size);
    131     lbp->count = bits;
    132   } else {
    133     lbp->count = 0;
    134   }
    135   return FSOK;
    136 }
    137 
    138 static void
    139 bitmap_dtor(long_bitmap_t *lbp)
    140 {
    141   free(lbp->map);
    142   lbp->map = NULL;
    143 }
    144 
    145 /*
    146  * FAT32 can be as big as 256MiB (2^26 entries * 4 bytes), when we
    147  * can not ask the kernel to manage the access, use a simple LRU
    148  * cache with chunk size of 128 KiB to manage it.
    149  */
    150 struct fat32_cache_entry {
    151   TAILQ_ENTRY(fat32_cache_entry) entries;
    152   uint8_t *chunk; /* pointer to chunk */
    153   off_t    addr;  /* offset */
    154   bool     dirty; /* dirty bit */
    155 };
    156 
    157 static const size_t fat32_cache_chunk_size = 131072; /* MAXPHYS */
    158 static const size_t fat32_cache_size       = 4194304;
    159 static const size_t fat32_cache_entries    = 32; /* XXXgcc: cache_size / cache_chunk_size */
    160 
    161 /*
    162  * FAT table descriptor, represents a FAT table that is already loaded
    163  * into memory.
    164  */
    165 struct fat_descriptor {
    166   struct bootblock *boot;
    167   uint8_t          *fatbuf;
    168   cl_t (*get)(struct fat_descriptor *, cl_t);
    169   int (*set)(struct fat_descriptor *, cl_t, cl_t);
    170   long_bitmap_t headbitmap;
    171   int           fd;
    172   bool          is_mmapped;
    173   bool          use_cache;
    174   size_t        fatsize;
    175 
    176   size_t fat32_cached_chunks;
    177   TAILQ_HEAD(cachehead, fat32_cache_entry) fat32_cache_head;
    178   struct fat32_cache_entry *fat32_cache_allentries;
    179   off_t                     fat32_offset;
    180   off_t                     fat32_lastaddr;
    181 };
    182 
    183 void
    184 fat_clear_cl_head(struct fat_descriptor *fat, cl_t cl)
    185 {
    186   bitmap_clear(&fat->headbitmap, cl);
    187 }
    188 
    189 bool
    190 fat_is_cl_head(struct fat_descriptor *fat, cl_t cl)
    191 {
    192   return (bitmap_get(&fat->headbitmap, cl));
    193 }
    194 
    195 static inline bool
    196 fat_is_cl_head_in_range(struct fat_descriptor *fat, cl_t cl)
    197 {
    198   return (!(bitmap_none_in_range(&fat->headbitmap, cl)));
    199 }
    200 
    201 static size_t
    202 fat_get_head_count(struct fat_descriptor *fat)
    203 {
    204   return (bitmap_count(&fat->headbitmap));
    205 }
    206 
    207 /*
    208  * FAT12 accessors.
    209  *
    210  * FAT12s are sufficiently small, expect it to always fit in the RAM.
    211  */
    212 static inline uint8_t *
    213 fat_get_fat12_ptr(struct fat_descriptor *fat, cl_t cl)
    214 {
    215   return (fat->fatbuf + ((cl + (cl >> 1))));
    216 }
    217 
    218 static cl_t
    219 fat_get_fat12_next(struct fat_descriptor *fat, cl_t cl)
    220 {
    221   const uint8_t *p;
    222   cl_t           retval;
    223 
    224   p      = fat_get_fat12_ptr(fat, cl);
    225   retval = le16dec(p);
    226   /* Odd cluster: lower 4 bits belongs to the subsequent cluster */
    227   if ((cl & 1) == 1)
    228     retval >>= 4;
    229   retval &= CLUST12_MASK;
    230 
    231   if (retval >= (CLUST_BAD & CLUST12_MASK))
    232     retval |= ~CLUST12_MASK;
    233 
    234   return (retval);
    235 }
    236 
    237 static int
    238 fat_set_fat12_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl)
    239 {
    240   uint8_t *p;
    241 
    242   /* Truncate 'nextcl' value, if needed */
    243   nextcl &= CLUST12_MASK;
    244 
    245   p = fat_get_fat12_ptr(fat, cl);
    246 
    247   /*
    248    * Read in the 4 bits from the subsequent (for even clusters)
    249    * or the preceding (for odd clusters) cluster and combine
    250    * it to the nextcl value for encoding
    251    */
    252   if ((cl & 1) == 0) {
    253     nextcl |= ((p[1] & 0xf0) << 8);
    254   } else {
    255     nextcl <<= 4;
    256     nextcl |= (p[0] & 0x0f);
    257   }
    258 
    259   le16enc(p, (uint16_t)nextcl);
    260 
    261   return (0);
    262 }
    263 
    264 /*
    265  * FAT16 accessors.
    266  *
    267  * FAT16s are sufficiently small, expect it to always fit in the RAM.
    268  */
    269 static inline uint8_t *
    270 fat_get_fat16_ptr(struct fat_descriptor *fat, cl_t cl)
    271 {
    272   return (fat->fatbuf + (cl << 1));
    273 }
    274 
    275 static cl_t
    276 fat_get_fat16_next(struct fat_descriptor *fat, cl_t cl)
    277 {
    278   const uint8_t *p;
    279   cl_t           retval;
    280 
    281   p      = fat_get_fat16_ptr(fat, cl);
    282   retval = le16dec(p) & CLUST16_MASK;
    283 
    284   if (retval >= (CLUST_BAD & CLUST16_MASK))
    285     retval |= ~CLUST16_MASK;
    286 
    287   return (retval);
    288 }
    289 
    290 static int
    291 fat_set_fat16_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl)
    292 {
    293   uint8_t *p;
    294 
    295   /* Truncate 'nextcl' value, if needed */
    296   nextcl &= CLUST16_MASK;
    297 
    298   p = fat_get_fat16_ptr(fat, cl);
    299 
    300   le16enc(p, (uint16_t)nextcl);
    301 
    302   return (0);
    303 }
    304 
    305 /*
    306  * FAT32 accessors.
    307  */
    308 static inline uint8_t *
    309 fat_get_fat32_ptr(struct fat_descriptor *fat, cl_t cl)
    310 {
    311   return (fat->fatbuf + (cl << 2));
    312 }
    313 
    314 static cl_t
    315 fat_get_fat32_next(struct fat_descriptor *fat, cl_t cl)
    316 {
    317   const uint8_t *p;
    318   cl_t           retval;
    319 
    320   p      = fat_get_fat32_ptr(fat, cl);
    321   retval = le32dec(p) & CLUST32_MASK;
    322 
    323   if (retval >= (CLUST_BAD & CLUST32_MASK))
    324     retval |= ~CLUST32_MASK;
    325 
    326   return (retval);
    327 }
    328 
    329 static int
    330 fat_set_fat32_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl)
    331 {
    332   uint8_t *p;
    333 
    334   /* Truncate 'nextcl' value, if needed */
    335   nextcl &= CLUST32_MASK;
    336 
    337   p = fat_get_fat32_ptr(fat, cl);
    338 
    339   le32enc(p, (uint32_t)nextcl);
    340 
    341   return (0);
    342 }
    343 
    344 static inline size_t
    345 fat_get_iosize(struct fat_descriptor *fat, off_t address)
    346 {
    347   if (address == fat->fat32_lastaddr) {
    348     return (fat->fatsize & ((off_t)fat32_cache_chunk_size - 1));
    349   } else {
    350     return (fat32_cache_chunk_size);
    351   }
    352 }
    353 
    354 static int
    355 fat_flush_fat32_cache_entry(struct fat_descriptor *fat, struct fat32_cache_entry *entry)
    356 {
    357   int    fd;
    358   off_t  fat_addr;
    359   size_t writesize;
    360 
    361   fd = fd_of_(fat);
    362 
    363   if (!entry->dirty)
    364     return (FSOK);
    365 
    366   writesize = fat_get_iosize(fat, entry->addr);
    367 
    368   fat_addr = fat->fat32_offset + entry->addr;
    369   if (lseek(fd, fat_addr, SEEK_SET) != fat_addr
    370       || (size_t)write(fd, entry->chunk, writesize) != writesize) {
    371     pfatal("Unable to write FAT");
    372     return (FSFATAL);
    373   }
    374 
    375   entry->dirty = false;
    376   return (FSOK);
    377 }
    378 
    379 static struct fat32_cache_entry *
    380 fat_get_fat32_cache_entry(struct fat_descriptor *fat, off_t addr, bool writing)
    381 {
    382   int                       fd;
    383   struct fat32_cache_entry *entry, *first;
    384   off_t                     fat_addr;
    385   size_t                    rwsize;
    386 
    387   addr &= ~(fat32_cache_chunk_size - 1);
    388 
    389   first = TAILQ_FIRST(&fat->fat32_cache_head);
    390 
    391   /*
    392    * Cache hit: if we already have the chunk, move it to list head
    393    */
    394   TAILQ_FOREACH(entry, &fat->fat32_cache_head, entries)
    395   {
    396     if (entry->addr == addr) {
    397       if (writing) {
    398         entry->dirty = true;
    399       }
    400       if (entry != first) {
    401         TAILQ_REMOVE(&fat->fat32_cache_head, entry, entries);
    402         TAILQ_INSERT_HEAD(&fat->fat32_cache_head, entry, entries);
    403       }
    404       return (entry);
    405     }
    406   }
    407 
    408   /*
    409    * Cache miss: detach the chunk at tail of list, overwrite with
    410    * the located chunk, and populate with data from disk.
    411    */
    412   entry = TAILQ_LAST(&fat->fat32_cache_head, cachehead);
    413   TAILQ_REMOVE(&fat->fat32_cache_head, entry, entries);
    414   if (fat_flush_fat32_cache_entry(fat, entry) != FSOK) {
    415     return (NULL);
    416   }
    417 
    418   rwsize      = fat_get_iosize(fat, addr);
    419   fat_addr    = fat->fat32_offset + addr;
    420   entry->addr = addr;
    421   fd          = fd_of_(fat);
    422   if (lseek(fd, fat_addr, SEEK_SET) != fat_addr
    423       || (size_t)read(fd, entry->chunk, rwsize) != rwsize) {
    424     pfatal("Unable to read FAT");
    425     return (NULL);
    426   }
    427   if (writing) {
    428     entry->dirty = true;
    429   }
    430   TAILQ_INSERT_HEAD(&fat->fat32_cache_head, entry, entries);
    431 
    432   return (entry);
    433 }
    434 
    435 static inline uint8_t *
    436 fat_get_fat32_cached_ptr(struct fat_descriptor *fat, cl_t cl, bool writing)
    437 {
    438   off_t                     addr, off;
    439   struct fat32_cache_entry *entry;
    440 
    441   addr  = cl << 2;
    442   entry = fat_get_fat32_cache_entry(fat, addr, writing);
    443 
    444   if (entry != NULL) {
    445     off = addr & (fat32_cache_chunk_size - 1);
    446     return (entry->chunk + off);
    447   } else {
    448     return (NULL);
    449   }
    450 }
    451 
    452 static cl_t
    453 fat_get_fat32_cached_next(struct fat_descriptor *fat, cl_t cl)
    454 {
    455   const uint8_t *p;
    456   cl_t           retval;
    457 
    458   p = fat_get_fat32_cached_ptr(fat, cl, false);
    459   if (p != NULL) {
    460     retval = le32dec(p) & CLUST32_MASK;
    461     if (retval >= (CLUST_BAD & CLUST32_MASK))
    462       retval |= ~CLUST32_MASK;
    463   } else {
    464     retval = CLUST_DEAD;
    465   }
    466 
    467   return (retval);
    468 }
    469 
    470 static int
    471 fat_set_fat32_cached_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl)
    472 {
    473   uint8_t *p;
    474 
    475   /* Truncate 'nextcl' value, if needed */
    476   nextcl &= CLUST32_MASK;
    477 
    478   p = fat_get_fat32_cached_ptr(fat, cl, true);
    479   if (p != NULL) {
    480     le32enc(p, (uint32_t)nextcl);
    481     return FSOK;
    482   } else {
    483     return FSFATAL;
    484   }
    485 }
    486 
    487 cl_t
    488 fat_get_cl_next(struct fat_descriptor *fat, cl_t cl)
    489 {
    490   if (!valid_cl(fat, cl)) {
    491     pfatal("Invalid cluster: %ud", cl);
    492     return CLUST_DEAD;
    493   }
    494 
    495   return (fat->get(fat, cl));
    496 }
    497 
    498 int
    499 fat_set_cl_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl)
    500 {
    501   if (rdonly) {
    502     pwarn(" (NO WRITE)\n");
    503     return FSFATAL;
    504   }
    505 
    506   if (!valid_cl(fat, cl)) {
    507     pfatal("Invalid cluster: %ud", cl);
    508     return FSFATAL;
    509   }
    510 
    511   return (fat->set(fat, cl, nextcl));
    512 }
    513 
    514 static inline struct bootblock *
    515 boot_of_(struct fat_descriptor *fat)
    516 {
    517   return (fat->boot);
    518 }
    519 
    520 struct bootblock *
    521 fat_get_boot(struct fat_descriptor *fat)
    522 {
    523   return (boot_of_(fat));
    524 }
    525 
    526 static inline int
    527 fd_of_(struct fat_descriptor *fat)
    528 {
    529   return (fat->fd);
    530 }
    531 
    532 int
    533 fat_get_fd(struct fat_descriptor *fat)
    534 {
    535   return (fd_of_(fat));
    536 }
    537 
    538 /*
    539  * Whether a cl is in valid data range.
    540  */
    541 bool
    542 fat_is_valid_cl(struct fat_descriptor *fat, cl_t cl)
    543 {
    544   return (valid_cl(fat, cl));
    545 }
    546 
    547 static inline bool
    548 valid_cl(struct fat_descriptor *fat, cl_t cl)
    549 {
    550   const struct bootblock *boot = boot_of_(fat);
    551 
    552   return (cl >= CLUST_FIRST && cl < boot->NumClusters);
    553 }
    554 
    555 /*
    556  * The first 2 FAT entries contain pseudo-cluster numbers with the following
    557  * layout:
    558  *
    559  * 31...... ........ ........ .......0
    560  * rrrr1111 11111111 11111111 mmmmmmmm         FAT32 entry 0
    561  * rrrrsh11 11111111 11111111 11111xxx         FAT32 entry 1
    562  *
    563  *                   11111111 mmmmmmmm         FAT16 entry 0
    564  *                   sh111111 11111xxx         FAT16 entry 1
    565  *
    566  * r = reserved
    567  * m = BPB media ID byte
    568  * s = clean flag (1 = dismounted; 0 = still mounted)
    569  * h = hard error flag (1 = ok; 0 = I/O error)
    570  * x = any value ok
    571  */
    572 int
    573 checkdirty(int fs, struct bootblock *boot)
    574 {
    575   off_t   off;
    576   u_char *buffer;
    577   int     ret = 0;
    578   size_t  len;
    579 
    580   if (boot->ClustMask != CLUST16_MASK && boot->ClustMask != CLUST32_MASK)
    581     return 0;
    582 
    583   off = boot->bpbResSectors;
    584   off *= boot->bpbBytesPerSec;
    585 
    586   buffer = malloc(len = boot->bpbBytesPerSec);
    587   if (buffer == NULL) {
    588     perr("No space for FAT sectors (%zu)", len);
    589     return 1;
    590   }
    591 
    592   if (lseek(fs, off, SEEK_SET) != off) {
    593     perr("Unable to read FAT");
    594     goto err;
    595   }
    596 
    597   if ((size_t)read(fs, buffer, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) {
    598     perr("Unable to read FAT");
    599     goto err;
    600   }
    601 
    602   /*
    603    * If we don't understand the FAT, then the file system must be
    604    * assumed to be unclean.
    605    */
    606   if (buffer[0] != boot->bpbMedia || buffer[1] != 0xff)
    607     goto err;
    608   if (boot->ClustMask == CLUST16_MASK) {
    609     if ((buffer[2] & 0xf8) != 0xf8 || (buffer[3] & 0x3f) != 0x3f)
    610       goto err;
    611   } else {
    612     if (buffer[2] != 0xff || (buffer[3] & 0x0f) != 0x0f || (buffer[4] & 0xf8) != 0xf8
    613         || buffer[5] != 0xff || buffer[6] != 0xff || (buffer[7] & 0x03) != 0x03)
    614       goto err;
    615   }
    616 
    617   /*
    618    * Now check the actual clean flag (and the no-error flag).
    619    */
    620   if (boot->ClustMask == CLUST16_MASK) {
    621     if ((buffer[3] & 0xc0) == 0xc0)
    622       ret = 1;
    623   } else {
    624     if ((buffer[7] & 0x0c) == 0x0c)
    625       ret = 1;
    626   }
    627 
    628 err:
    629   free(buffer);
    630   return ret;
    631 }
    632 
    633 int
    634 cleardirty(struct fat_descriptor *fat)
    635 {
    636   int               fd, ret = FSERROR;
    637   struct bootblock *boot;
    638   u_char           *buffer;
    639   size_t            len;
    640   off_t             off;
    641 
    642   boot = boot_of_(fat);
    643   fd   = fd_of_(fat);
    644 
    645   if (boot->ClustMask != CLUST16_MASK && boot->ClustMask != CLUST32_MASK)
    646     return 0;
    647 
    648   off = boot->bpbResSectors;
    649   off *= boot->bpbBytesPerSec;
    650 
    651   buffer = malloc(len = boot->bpbBytesPerSec);
    652   if (buffer == NULL) {
    653     perr("No memory for FAT sectors (%zu)", len);
    654     return 1;
    655   }
    656 
    657   if ((size_t)pread(fd, buffer, len, off) != len) {
    658     perr("Unable to read FAT");
    659     goto err;
    660   }
    661 
    662   if (boot->ClustMask == CLUST16_MASK) {
    663     buffer[3] |= 0x80;
    664   } else {
    665     buffer[7] |= 0x08;
    666   }
    667 
    668   if ((size_t)pwrite(fd, buffer, len, off) != len) {
    669     perr("Unable to write FAT");
    670     goto err;
    671   }
    672 
    673   ret = FSOK;
    674 
    675 err:
    676   free(buffer);
    677   return ret;
    678 }
    679 
    680 /*
    681  * Read a FAT from disk. Returns 1 if successful, 0 otherwise.
    682  */
    683 static int
    684 _readfat(struct fat_descriptor *fat)
    685 {
    686   int                       fd;
    687   size_t                    i;
    688   off_t                     off;
    689   size_t                    readsize;
    690   struct bootblock         *boot;
    691   struct fat32_cache_entry *entry;
    692 
    693   boot         = boot_of_(fat);
    694   fd           = fd_of_(fat);
    695   fat->fatsize = boot->FATsecs * boot->bpbBytesPerSec;
    696 
    697   off = boot->bpbResSectors;
    698   off *= boot->bpbBytesPerSec;
    699 
    700   fat->is_mmapped = false;
    701   fat->use_cache  = false;
    702 
    703   /* Attempt to mmap() first */
    704   if (allow_mmap) {
    705     fat->fatbuf = mmap(
    706         NULL, fat->fatsize, PROT_READ | (rdonly ? 0 : PROT_WRITE), MAP_SHARED, fd_of_(fat), off
    707     );
    708     if (fat->fatbuf != MAP_FAILED) {
    709       fat->is_mmapped = true;
    710       return 1;
    711     }
    712   }
    713 
    714   /*
    715    * Unfortunately, we were unable to mmap().
    716    *
    717    * Only use the cache manager when it's necessary, that is,
    718    * when the FAT is sufficiently large; in that case, only
    719    * read in the first 4 MiB of FAT into memory, and split the
    720    * buffer into chunks and insert to the LRU queue to populate
    721    * the cache with data.
    722    */
    723   if (boot->ClustMask == CLUST32_MASK && fat->fatsize >= fat32_cache_size) {
    724     readsize       = fat32_cache_size;
    725     fat->use_cache = true;
    726 
    727     fat->fat32_offset   = boot->bpbResSectors * boot->bpbBytesPerSec;
    728     fat->fat32_lastaddr = fat->fatsize & ~(fat32_cache_chunk_size);
    729   } else {
    730     readsize = fat->fatsize;
    731   }
    732   fat->fatbuf = malloc(readsize);
    733   if (fat->fatbuf == NULL) {
    734     perr("No space for FAT (%zu)", readsize);
    735     return 0;
    736   }
    737 
    738   if (lseek(fd, off, SEEK_SET) != off) {
    739     perr("Unable to read FAT");
    740     goto err;
    741   }
    742   if ((size_t)read(fd, fat->fatbuf, readsize) != readsize) {
    743     perr("Unable to read FAT");
    744     goto err;
    745   }
    746 
    747   /*
    748    * When cache is used, split the buffer into chunks, and
    749    * connect the buffer into the cache.
    750    */
    751   if (fat->use_cache) {
    752     TAILQ_INIT(&fat->fat32_cache_head);
    753     entry = calloc(fat32_cache_entries, sizeof(*entry));
    754     if (entry == NULL) {
    755       perr("No space for FAT cache (%zu of %zu)", fat32_cache_entries, sizeof(entry));
    756       goto err;
    757     }
    758     for (i = 0; i < fat32_cache_entries; i++) {
    759       entry[i].addr  = fat32_cache_chunk_size * i;
    760       entry[i].chunk = &fat->fatbuf[entry[i].addr];
    761       TAILQ_INSERT_TAIL(&fat->fat32_cache_head, &entry[i], entries);
    762     }
    763     fat->fat32_cache_allentries = entry;
    764   }
    765 
    766   return 1;
    767 
    768 err:
    769   free(fat->fatbuf);
    770   fat->fatbuf = NULL;
    771   return 0;
    772 }
    773 
    774 static void
    775 releasefat(struct fat_descriptor *fat)
    776 {
    777   if (fat->is_mmapped) {
    778     munmap(fat->fatbuf, fat->fatsize);
    779   } else {
    780     if (fat->use_cache) {
    781       free(fat->fat32_cache_allentries);
    782       fat->fat32_cache_allentries = NULL;
    783     }
    784     free(fat->fatbuf);
    785   }
    786   fat->fatbuf = NULL;
    787   bitmap_dtor(&fat->headbitmap);
    788 }
    789 
    790 /*
    791  * Read or map a FAT and populate head bitmap
    792  */
    793 int
    794 readfat(int fs, struct bootblock *boot, struct fat_descriptor **fp)
    795 {
    796   struct fat_descriptor *fat;
    797   u_char                *buffer, *p;
    798   cl_t                   cl, nextcl;
    799   int                    ret = FSOK;
    800 
    801   boot->NumFree = boot->NumBad = 0;
    802 
    803   fat = calloc(1, sizeof(struct fat_descriptor));
    804   if (fat == NULL) {
    805     perr("No space for FAT descriptor");
    806     return FSFATAL;
    807   }
    808 
    809   fat->fd   = fs;
    810   fat->boot = boot;
    811 
    812   if (!_readfat(fat)) {
    813     free(fat);
    814     return FSFATAL;
    815   }
    816   buffer = fat->fatbuf;
    817 
    818   /* Populate accessors */
    819   switch (boot->ClustMask) {
    820     case CLUST12_MASK:
    821       fat->get = fat_get_fat12_next;
    822       fat->set = fat_set_fat12_next;
    823       break;
    824     case CLUST16_MASK:
    825       fat->get = fat_get_fat16_next;
    826       fat->set = fat_set_fat16_next;
    827       break;
    828     case CLUST32_MASK:
    829       if (fat->is_mmapped || !fat->use_cache) {
    830         fat->get = fat_get_fat32_next;
    831         fat->set = fat_set_fat32_next;
    832       } else {
    833         fat->get = fat_get_fat32_cached_next;
    834         fat->set = fat_set_fat32_cached_next;
    835       }
    836       break;
    837     default:
    838       pfatal("Invalid ClustMask: %d", boot->ClustMask);
    839       releasefat(fat);
    840       free(fat);
    841       return FSFATAL;
    842   }
    843 
    844   if (bitmap_ctor(&fat->headbitmap, boot->NumClusters, true) != FSOK) {
    845     perr("No space for head bitmap for FAT clusters (%zu)", (size_t)boot->NumClusters);
    846     releasefat(fat);
    847     free(fat);
    848     return FSFATAL;
    849   }
    850 
    851   if (buffer[0] != boot->bpbMedia || buffer[1] != 0xff || buffer[2] != 0xff
    852       || (boot->ClustMask == CLUST16_MASK && buffer[3] != 0xff)
    853       || (boot->ClustMask == CLUST32_MASK
    854           && ((buffer[3] & 0x0f) != 0x0f || buffer[4] != 0xff || buffer[5] != 0xff
    855               || buffer[6] != 0xff || (buffer[7] & 0x0f) != 0x0f))) {
    856     /* Windows 95 OSR2 (and possibly any later) changes
    857      * the FAT signature to 0xXXffff7f for FAT16 and to
    858      * 0xXXffff0fffffff07 for FAT32 upon boot, to know that the
    859      * file system is dirty if it doesn't reboot cleanly.
    860      * Check this special condition before errorring out.
    861      */
    862     if (buffer[0] == boot->bpbMedia && buffer[1] == 0xff && buffer[2] == 0xff
    863         && ((boot->ClustMask == CLUST16_MASK && buffer[3] == 0x7f)
    864             || (boot->ClustMask == CLUST32_MASK && buffer[3] == 0x0f && buffer[4] == 0xff
    865                 && buffer[5] == 0xff && buffer[6] == 0xff && buffer[7] == 0x07)))
    866       ret |= FSDIRTY;
    867     else {
    868       /* just some odd byte sequence in FAT */
    869 
    870       switch (boot->ClustMask) {
    871         case CLUST32_MASK:
    872           pwarn(
    873               "%s (%02x%02x%02x%02x%02x%02x%02x%02x)\n",
    874               "FAT starts with odd byte sequence",
    875               buffer[0],
    876               buffer[1],
    877               buffer[2],
    878               buffer[3],
    879               buffer[4],
    880               buffer[5],
    881               buffer[6],
    882               buffer[7]
    883           );
    884           break;
    885         case CLUST16_MASK:
    886           pwarn(
    887               "%s (%02x%02x%02x%02x)\n",
    888               "FAT starts with odd byte sequence",
    889               buffer[0],
    890               buffer[1],
    891               buffer[2],
    892               buffer[3]
    893           );
    894           break;
    895         default:
    896           pwarn(
    897               "%s (%02x%02x%02x)\n",
    898               "FAT starts with odd byte sequence",
    899               buffer[0],
    900               buffer[1],
    901               buffer[2]
    902           );
    903           break;
    904       }
    905 
    906       if (ask(1, "Correct")) {
    907         ret |= FSFATMOD;
    908         p = buffer;
    909 
    910         *p++ = (u_char)boot->bpbMedia;
    911         *p++ = 0xff;
    912         *p++ = 0xff;
    913         switch (boot->ClustMask) {
    914           case CLUST16_MASK:
    915             *p++ = 0xff;
    916             break;
    917           case CLUST32_MASK:
    918             *p++ = 0x0f;
    919             *p++ = 0xff;
    920             *p++ = 0xff;
    921             *p++ = 0xff;
    922             *p++ = 0x0f;
    923             break;
    924           default:
    925             break;
    926         }
    927       }
    928     }
    929   }
    930 
    931   /*
    932    * Traverse the FAT table and populate head map.  Initially, we
    933    * consider all clusters as possible head cluster (beginning of
    934    * a file or directory), and traverse the whole allocation table
    935    * by marking every non-head nodes as such (detailed below) and
    936    * fix obvious issues while we walk.
    937    *
    938    * For each "next" cluster, the possible values are:
    939    *
    940    * a) CLUST_FREE or CLUST_BAD.  The *current* cluster can't be a
    941    *    head node.
    942    * b) An out-of-range value. The only fix would be to truncate at
    943    *    the cluster.
    944    * c) A valid cluster.  It means that cluster (nextcl) is not a
    945    *    head cluster.  Note that during the scan, every cluster is
    946    *    expected to be seen for at most once, and when we saw them
    947    *    twice, it means a cross-linked chain which should be
    948    *    truncated at the current cluster.
    949    *
    950    * After scan, the remaining set bits indicates all possible
    951    * head nodes, because they were never claimed by any other
    952    * node as the next node, but we do not know if these chains
    953    * would end with a valid EOF marker.  We will check that in
    954    * checkchain() at a later time when checking directories,
    955    * where these head nodes would be marked as non-head.
    956    *
    957    * In the final pass, all head nodes should be cleared, and if
    958    * there is still head nodes, these would be leaders of lost
    959    * chain.
    960    */
    961   for (cl = CLUST_FIRST; cl < boot->NumClusters; cl++) {
    962     nextcl = fat_get_cl_next(fat, cl);
    963 
    964     /* Check if the next cluster number is valid */
    965     if (nextcl == CLUST_FREE) {
    966       /* Save a hint for next free cluster */
    967       if (boot->FSNext == 0) {
    968         boot->FSNext = cl;
    969       }
    970       if (fat_is_cl_head(fat, cl)) {
    971         fat_clear_cl_head(fat, cl);
    972       }
    973       boot->NumFree++;
    974     } else if (nextcl == CLUST_BAD) {
    975       if (fat_is_cl_head(fat, cl)) {
    976         fat_clear_cl_head(fat, cl);
    977       }
    978       boot->NumBad++;
    979     } else if (!valid_cl(fat, nextcl) && nextcl < CLUST_RSRVD) {
    980       pwarn(
    981           "Cluster %u continues with out of range "
    982           "cluster number %u\n",
    983           cl,
    984           nextcl & boot->ClustMask
    985       );
    986       if (ask(0, "Truncate")) {
    987         ret |= fat_set_cl_next(fat, cl, CLUST_EOF);
    988         ret |= FSFATMOD;
    989       }
    990     } else if (valid_cl(fat, nextcl)) {
    991       if (fat_is_cl_head(fat, nextcl)) {
    992         fat_clear_cl_head(fat, nextcl);
    993       } else {
    994         pwarn("Cluster %u crossed another chain at %u\n", cl, nextcl);
    995         if (ask(0, "Truncate")) {
    996           ret |= fat_set_cl_next(fat, cl, CLUST_EOF);
    997           ret |= FSFATMOD;
    998         }
    999       }
   1000     }
   1001   }
   1002 
   1003   if (ret & FSFATAL) {
   1004     releasefat(fat);
   1005     free(fat);
   1006     *fp = NULL;
   1007   } else
   1008     *fp = fat;
   1009   return ret;
   1010 }
   1011 
   1012 /*
   1013  * Get type of reserved cluster
   1014  */
   1015 const char *
   1016 rsrvdcltype(cl_t cl)
   1017 {
   1018   if (cl == CLUST_FREE)
   1019     return "free";
   1020   if (cl < CLUST_BAD)
   1021     return "reserved";
   1022   if (cl > CLUST_BAD)
   1023     return "as EOF";
   1024   return "bad";
   1025 }
   1026 
   1027 /*
   1028  * Examine a cluster chain for errors and count its size.
   1029  */
   1030 int
   1031 checkchain(struct fat_descriptor *fat, cl_t head, size_t *chainsize)
   1032 {
   1033   cl_t        prev_cl, current_cl, next_cl;
   1034   const char *op;
   1035 
   1036   /*
   1037    * We expect that the caller to give us a real, unvisited 'head'
   1038    * cluster, and it must be a valid cluster.  While scanning the
   1039    * FAT table, we already excluded all clusters that was claimed
   1040    * as a "next" cluster.  Assert all the three conditions.
   1041    */
   1042   assert(valid_cl(fat, head));
   1043   assert(fat_is_cl_head(fat, head));
   1044 
   1045   /*
   1046    * Immediately mark the 'head' cluster that we are about to visit.
   1047    */
   1048   fat_clear_cl_head(fat, head);
   1049 
   1050   /*
   1051    * The allocation of a non-zero sized file or directory is
   1052    * represented as a singly linked list, and the tail node
   1053    * would be the EOF marker (>=CLUST_EOFS).
   1054    *
   1055    * With a valid head node at hand, we expect all subsequent
   1056    * cluster to be either a not yet seen and valid cluster (we
   1057    * would continue counting), or the EOF marker (we conclude
   1058    * the scan of this chain).
   1059    *
   1060    * For all other cases, the chain is invalid, and the only
   1061    * viable fix would be to truncate at the current node (mark
   1062    * it as EOF) when the next node violates that.
   1063    */
   1064   *chainsize = 0;
   1065   prev_cl = current_cl = head;
   1066   for (next_cl = fat_get_cl_next(fat, current_cl); valid_cl(fat, next_cl);
   1067        prev_cl = current_cl, current_cl = next_cl, next_cl = fat_get_cl_next(fat, current_cl))
   1068     (*chainsize)++;
   1069 
   1070   /* A natural end */
   1071   if (next_cl >= CLUST_EOFS) {
   1072     (*chainsize)++;
   1073     return FSOK;
   1074   }
   1075 
   1076   /*
   1077    * The chain ended with an out-of-range cluster number.
   1078    *
   1079    * If the current node is e.g. CLUST_FREE, CLUST_BAD, etc.,
   1080    * it should not be present in a chain and we has to truncate
   1081    * at the previous node.
   1082    *
   1083    * If the current cluster points to an invalid cluster, the
   1084    * current cluster might have useful data and we truncate at
   1085    * the current cluster instead.
   1086    */
   1087   if (next_cl == CLUST_FREE || next_cl >= CLUST_RSRVD) {
   1088     pwarn("Cluster chain starting at %u ends with cluster marked %s\n", head, rsrvdcltype(next_cl));
   1089     current_cl = prev_cl;
   1090   } else {
   1091     pwarn(
   1092         "Cluster chain starting at %u ends with cluster out of range (%u)\n",
   1093         head,
   1094         next_cl & boot_of_(fat)->ClustMask
   1095     );
   1096     (*chainsize)++;
   1097   }
   1098 
   1099   if (*chainsize > 0) {
   1100     op      = "Truncate";
   1101     next_cl = CLUST_EOF;
   1102   } else {
   1103     op      = "Clear";
   1104     next_cl = CLUST_FREE;
   1105   }
   1106   if (ask(0, "%s", op)) {
   1107     return (fat_set_cl_next(fat, current_cl, next_cl) | FSFATMOD);
   1108   } else {
   1109     return (FSERROR);
   1110   }
   1111 }
   1112 
   1113 /*
   1114  * Clear cluster chain from head.
   1115  */
   1116 void
   1117 clearchain(struct fat_descriptor *fat, cl_t head)
   1118 {
   1119   cl_t              current_cl, next_cl;
   1120   struct bootblock *boot = boot_of_(fat);
   1121 
   1122   current_cl = head;
   1123 
   1124   while (valid_cl(fat, current_cl)) {
   1125     next_cl = fat_get_cl_next(fat, current_cl);
   1126     (void)fat_set_cl_next(fat, current_cl, CLUST_FREE);
   1127     boot->NumFree++;
   1128     current_cl = next_cl;
   1129   }
   1130 }
   1131 
   1132 /*
   1133  * Overwrite the n-th FAT with FAT0
   1134  */
   1135 static int
   1136 copyfat(struct fat_descriptor *fat, int n)
   1137 {
   1138   size_t            rwsize, tailsize, blobs, i;
   1139   off_t             dst_off, src_off;
   1140   struct bootblock *boot;
   1141   int               ret, fd;
   1142 
   1143   ret  = FSOK;
   1144   fd   = fd_of_(fat);
   1145   boot = boot_of_(fat);
   1146 
   1147   blobs    = howmany(fat->fatsize, fat32_cache_size);
   1148   tailsize = fat->fatsize % fat32_cache_size;
   1149   if (tailsize == 0) {
   1150     tailsize = fat32_cache_size;
   1151   }
   1152   rwsize = fat32_cache_size;
   1153 
   1154   src_off = fat->fat32_offset;
   1155   dst_off = boot->bpbResSectors + n * boot->FATsecs;
   1156   dst_off *= boot->bpbBytesPerSec;
   1157 
   1158   for (i = 0; i < blobs; i++, src_off += fat32_cache_size, dst_off += fat32_cache_size) {
   1159     if (i == blobs - 1) {
   1160       rwsize = tailsize;
   1161     }
   1162     if ((lseek(fd, src_off, SEEK_SET) != src_off || (size_t)read(fd, fat->fatbuf, rwsize) != rwsize)
   1163         && ret == FSOK) {
   1164       perr("Unable to read FAT0");
   1165       ret = FSFATAL;
   1166       continue;
   1167     }
   1168     if ((lseek(fd, dst_off, SEEK_SET) != dst_off
   1169          || (size_t)write(fd, fat->fatbuf, rwsize) != rwsize)
   1170         && ret == FSOK) {
   1171       perr("Unable to write FAT %d", n);
   1172       ret = FSERROR;
   1173     }
   1174   }
   1175   return (ret);
   1176 }
   1177 
   1178 /*
   1179  * Write out FAT
   1180  */
   1181 int
   1182 writefat(struct fat_descriptor *fat)
   1183 {
   1184   u_int                     i;
   1185   size_t                    writesz;
   1186   off_t                     dst_base;
   1187   int                       ret = FSOK, fd;
   1188   struct bootblock         *boot;
   1189   struct fat32_cache_entry *entry;
   1190 
   1191   boot = boot_of_(fat);
   1192   fd   = fd_of_(fat);
   1193 
   1194   if (fat->use_cache) {
   1195     /*
   1196      * Attempt to flush all in-flight cache, and bail out
   1197      * if we encountered an error (but only emit error
   1198      * message once).  Stop proceeding with copyfat()
   1199      * if any flush failed.
   1200      */
   1201     TAILQ_FOREACH(entry, &fat->fat32_cache_head, entries)
   1202     {
   1203       if (fat_flush_fat32_cache_entry(fat, entry) != FSOK) {
   1204         if (ret == FSOK) {
   1205           perr("Unable to write FAT");
   1206           ret = FSFATAL;
   1207         }
   1208       }
   1209     }
   1210     if (ret != FSOK)
   1211       return (ret);
   1212 
   1213     /* Update backup copies of FAT, error is not fatal */
   1214     for (i = 1; i < boot->bpbFATs; i++) {
   1215       if (copyfat(fat, i) != FSOK)
   1216         ret = FSERROR;
   1217     }
   1218   } else {
   1219     writesz = fat->fatsize;
   1220 
   1221     for (i = fat->is_mmapped ? 1 : 0; i < boot->bpbFATs; i++) {
   1222       dst_base = boot->bpbResSectors + i * boot->FATsecs;
   1223       dst_base *= boot->bpbBytesPerSec;
   1224       if ((lseek(fd, dst_base, SEEK_SET) != dst_base
   1225            || (size_t)write(fd, fat->fatbuf, writesz) != writesz)
   1226           && ret == FSOK) {
   1227         perr("Unable to write FAT %d", i);
   1228         ret = ((i == 0) ? FSFATAL : FSERROR);
   1229       }
   1230     }
   1231   }
   1232 
   1233   return ret;
   1234 }
   1235 
   1236 /*
   1237  * Check a complete in-memory FAT for lost cluster chains
   1238  */
   1239 int
   1240 checklost(struct fat_descriptor *fat)
   1241 {
   1242   cl_t              head;
   1243   int               mod = FSOK;
   1244   int               dosfs, ret;
   1245   size_t            chains, chainlength;
   1246   struct bootblock *boot;
   1247 
   1248   dosfs = fd_of_(fat);
   1249   boot  = boot_of_(fat);
   1250 
   1251   /*
   1252    * At this point, we have already traversed all directories.
   1253    * All remaining chain heads in the bitmap are heads of lost
   1254    * chains.
   1255    */
   1256   chains = fat_get_head_count(fat);
   1257   for (head = CLUST_FIRST; chains > 0 && head < boot->NumClusters;) {
   1258     /*
   1259      * We expect the bitmap to be very sparse, so skip if
   1260      * the range is full of 0's
   1261      */
   1262     if (head % LONG_BIT == 0 && !fat_is_cl_head_in_range(fat, head)) {
   1263       head += LONG_BIT;
   1264       continue;
   1265     }
   1266     if (fat_is_cl_head(fat, head)) {
   1267       ret = checkchain(fat, head, &chainlength);
   1268       if (ret != FSERROR && chainlength > 0) {
   1269         pwarn(
   1270             "Lost cluster chain at cluster %u\n"
   1271             "%zd Cluster(s) lost\n",
   1272             head,
   1273             chainlength
   1274         );
   1275         mod |= ret = reconnect(fat, head, chainlength);
   1276       }
   1277       if (mod & FSFATAL)
   1278         break;
   1279       if (ret == FSERROR && ask(0, "Clear")) {
   1280         clearchain(fat, head);
   1281         mod |= FSFATMOD;
   1282       }
   1283       chains--;
   1284     }
   1285     head++;
   1286   }
   1287 
   1288   finishlf();
   1289 
   1290   if (boot->bpbFSInfo) {
   1291     ret = 0;
   1292     if (boot->FSFree != 0xffffffffU && boot->FSFree != boot->NumFree) {
   1293       pwarn("Free space in FSInfo block (%u) not correct (%u)\n", boot->FSFree, boot->NumFree);
   1294       if (ask(1, "Fix")) {
   1295         boot->FSFree = boot->NumFree;
   1296         ret          = 1;
   1297       }
   1298     }
   1299     if (boot->FSNext != 0xffffffffU
   1300         && (boot->FSNext >= boot->NumClusters
   1301             || (boot->NumFree && fat_get_cl_next(fat, boot->FSNext) != CLUST_FREE))) {
   1302       pwarn(
   1303           "Next free cluster in FSInfo block (%u) %s\n",
   1304           boot->FSNext,
   1305           (boot->FSNext >= boot->NumClusters) ? "invalid" : "not free"
   1306       );
   1307       if (ask(1, "Fix"))
   1308         for (head = CLUST_FIRST; head < boot->NumClusters; head++)
   1309           if (fat_get_cl_next(fat, head) == CLUST_FREE) {
   1310             boot->FSNext = head;
   1311             ret          = 1;
   1312             break;
   1313           }
   1314     }
   1315     if (ret)
   1316       mod |= writefsinfo(dosfs, boot);
   1317   }
   1318 
   1319   return mod;
   1320 }