freebsd-dev/sbin/fsck_msdosfs/dosfs.h
Xin LI 9708ba9f29 Reduce memory footprint of fsck_msdosfs.
This is a re-apply r356249 with changes to make GCC happy.

This utility was initially written for FAT12/16, which were inherently
small. When FAT32 support was added, the old data structure and
algorithms remain used with minimal changes.

With growing size of FAT32 media, the current data structure that
requires 4 32-bit variables per each FAT32 table entry would consume up
to 4 GiB of RAM, which can be too big for systems with limited RAM
available.

Address this by taking a different approach of validating the FAT.

The FAT is essentially a set of linked lists of chains that was
referenced by directory entries, and the checker needs to make sure that
the linked chains of clusters do not have cross-linked chains, and every
chain were referenced by one and only one directory entry.  Instead of
keeping track of the chain's 'head' cluster number, the size of the
chain, the used status of the chain and the "next" pointer which is
content of the FAT table, we create accessors for the FAT table data
for the "next" pointer, and keep only one bit to indicate if the
current cluster is a 'head' node of a cluster chain, in a bitmap.

We further overhaul the FAT checker to find out the possible head nodes
by excluding ones that are not (in other words, nodes that have some
other nodes claiming them as the next node) instead of marking the head
nodes for each node on the chain.  This approach greatly reduced the
complexiety of computation from O(N^2) worst case, to an O(N) scan for
worst case.  The file (cluster chain) length is not useful for the FAT
checker, so don't bother to calculate them in the FAT checker and
instead leave the task to the directory structure check, at which point
we would have non-crossed cluster chains, and we are guaranteed that
each cluster will be visited for at most one time.

When checking the directory structures, we use the head node indicator
to as the visited (used) flag: every cluster chain can only be
referenced by one directory entry, so we clear them when calculating
the length of the chain, and we can immediately tell if there are
anomalies in the directory entry.

As a result, the required RAM size is now 1 bit per each entry of
the FAT table, plus memory needed to hold the FAT table in memory,
instead of 16 bytes (=128 bits) per each entry.  For FAT12 and FAT16,
we will load the whole FAT table into memory as they are smaller than
128KiB, and for FAT32, we first attempt to mmap() it into memory, and
when that fails, we would fall back to a simple LRU cache of 4 MiB of
RAM.

sbin/fsck_msdosfs/boot.c:

 - Added additional sanity checks for valid FAT32/FAT16/FAT12 cluster
   number.
 - FAT32: check if root directory starts with a valid cluster number,
   moved from dir.c.  There is no point to proceed if the filesystem
   is already damaged beyond repair.

sbin/fsck_msdosfs/check.c:

 - Combine phase 1 and phase 2, now that the readfat() is able to
   detect cross chains.

sbin/fsck_msdosfs/dir.c:

 - Refactor code to use FAT accessor instead of accessing the internal
   representation of FAT table.
 - Make use of the cluster chain head bitmap.
 - Clarify and simplify directory entry check, remove unnecessary
   checks that are would be done at a later time (for example, whether
   the directory's second cluster is a valid one, which is examined
   more throughly in a later checkchain() and does not prevent us
   from proceeding further).

sbin/fsck_msdosfs/dosfs.h:

 - Remove internal representation of FAT table, which is replaced by
   the head bitmap that is opaque to other code.
 - Added a special CLUST_DEAD cluster type to indicate errors.

sbin/fsck_msdosfs/ext.h:

 - Added a flag that overrides mmap(2) setting.  The corresponding
   command line option, -M is intentionally undocumented as we do not
   expect users to need it.
 - Added accessors for FAT table and convert existing interface to use
   it.

sbin/fsck_msdosfs/fat.c:

 - Added head bitmap to represent whether a cluster is a head cluster.
 - Converted FAT internal representation to accessors.
 - Implemented a LRU cache for FAT32 when mmap(2) should not or can not
   be used.
 - _readfat: Attempt a mmap(2) and fall back to regular read for
   non-FAT32 file systems; use the LRU cache for FAT32 and prepopulate
   the cache with the first 4MiB of the entries.
 - readfat: Added support of head bitmap and use the population scan to
   detect bogus chains.
 - clusterdiff: removed, FATs are copied from the checked copy via
   writefat()/copyfat().
 - checkchain: calculates the length of a cluster chain and make sure
   that it ends with a valid EOF marker.
 - clearchain: follow and clear a chain and maintain the free cluster
   count.
 - checklost: convert to use head bitmap. At the end of all other scans,
   the remaining 'head' nodes are leaders of lost cluster chains.

sbin/fsck_msdosfs/fat.c:

 - Added a new -M option which is intentionally undocumented, to disable
   the use of mmap().

Reviewed by:	kevlo
MFC after:	1 month
Relnotes:	yes
Differential Revision:	https://reviews.freebsd.org/D22965
2020-01-03 00:31:48 +00:00

134 lines
4.8 KiB
C

/*-
* SPDX-License-Identifier: BSD-2-Clause-FreeBSD
*
* Copyright (C) 1995, 1996, 1997 Wolfgang Solfrank
* Copyright (c) 1995 Martin Husemann
* Some structure declaration borrowed from Paul Popelka
* (paulp@uts.amdahl.com), see /sys/msdosfs/ for reference.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* $NetBSD: dosfs.h,v 1.4 1997/01/03 14:32:48 ws Exp $
* $FreeBSD$
*/
#ifndef DOSFS_H
#define DOSFS_H
/* support 4Kn disk reads */
#define DOSBOOTBLOCKSIZE_REAL 512
#define DOSBOOTBLOCKSIZE 4096
typedef u_int32_t cl_t; /* type holding a cluster number */
/*
* architecture independent description of all the info stored in a
* FAT boot block.
*/
struct bootblock {
u_int bpbBytesPerSec; /* bytes per sector */
u_int bpbSecPerClust; /* sectors per cluster */
u_int bpbResSectors; /* number of reserved sectors */
u_int bpbFATs; /* number of bpbFATs */
u_int bpbRootDirEnts; /* number of root directory entries */
u_int32_t bpbSectors; /* total number of sectors */
u_int bpbMedia; /* media descriptor */
u_int bpbFATsmall; /* number of sectors per FAT */
u_int SecPerTrack; /* sectors per track */
u_int bpbHeads; /* number of heads */
u_int32_t bpbHiddenSecs; /* # of hidden sectors */
u_int32_t bpbHugeSectors; /* # of sectors if bpbbpbSectors == 0 */
cl_t bpbRootClust; /* Start of Root Directory */
u_int bpbFSInfo; /* FSInfo sector */
u_int bpbBackup; /* Backup of Bootblocks */
cl_t FSFree; /* Number of free clusters acc. FSInfo */
cl_t FSNext; /* Next free cluster acc. FSInfo */
/* and some more calculated values */
u_int flags; /* some flags: */
#define FAT32 1 /* this is a FAT32 file system */
/*
* Maybe, we should separate out
* various parts of FAT32? XXX
*/
int ValidFat; /* valid fat if FAT32 non-mirrored */
cl_t ClustMask; /* mask for entries in FAT */
cl_t NumClusters; /* # of entries in a FAT */
u_int32_t NumSectors; /* how many sectors are there */
u_int32_t FATsecs; /* how many sectors are in FAT */
u_int32_t NumFatEntries; /* how many entries really are there */
u_int FirstCluster; /* at what sector is Cluster CLUST_FIRST */
u_int ClusterSize; /* Cluster size in bytes */
/* Now some statistics: */
u_int NumFiles; /* # of plain files */
u_int NumFree; /* # of free clusters */
u_int NumBad; /* # of bad clusters */
};
#define CLUST_FREE 0 /* 0 means cluster is free */
#define CLUST_FIRST 2 /* 2 is the minimum valid cluster number */
#define CLUST_RSRVD 0xfffffff6 /* start of reserved clusters */
#define CLUST_BAD 0xfffffff7 /* a cluster with a defect */
#define CLUST_EOFS 0xfffffff8 /* start of EOF indicators */
#define CLUST_EOF 0xffffffff /* standard value for last cluster */
#define CLUST_DEAD 0xfdeadc0d /* error encountered */
/*
* Masks for cluster values
*/
#define CLUST12_MASK 0xfff
#define CLUST16_MASK 0xffff
#define CLUST32_MASK 0xfffffff
#define DOSLONGNAMELEN 256 /* long name maximal length */
#define LRFIRST 0x40 /* first long name record */
#define LRNOMASK 0x1f /* mask to extract long record
* sequence number */
/*
* Architecture independent description of a directory entry
*/
struct dosDirEntry {
struct dosDirEntry
*parent, /* previous tree level */
*next, /* next brother */
*child; /* if this is a directory */
char name[8+1+3+1]; /* alias name first part */
char lname[DOSLONGNAMELEN]; /* real name */
uint flags; /* attributes */
cl_t head; /* cluster no */
u_int32_t size; /* filesize in bytes */
uint fsckflags; /* flags during fsck */
};
/* Flags in fsckflags: */
#define DIREMPTY 1
#define DIREMPWARN 2
/*
* TODO-list of unread directories
*/
struct dirTodoNode {
struct dosDirEntry *dir;
struct dirTodoNode *next;
};
#endif