Home | History | Annotate | Line # | Download | only in msdosfs
msdosfs_fat.c revision 1.18
      1 /*	$NetBSD: msdosfs_fat.c,v 1.18 2009/03/14 21:04:23 dsl Exp $	*/
      2 
      3 /*-
      4  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
      5  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
      6  * All rights reserved.
      7  * Original code by Paul Popelka (paulp (at) uts.amdahl.com) (see below).
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *	This product includes software developed by TooLs GmbH.
     20  * 4. The name of TooLs GmbH may not be used to endorse or promote products
     21  *    derived from this software without specific prior written permission.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
     24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     26  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     27  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
     28  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
     29  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
     30  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
     31  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
     32  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 /*
     35  * Written by Paul Popelka (paulp (at) uts.amdahl.com)
     36  *
     37  * You can do anything you want with this software, just don't say you wrote
     38  * it, and don't remove this notice.
     39  *
     40  * This software is provided "as is".
     41  *
     42  * The author supplies this software to be publicly redistributed on the
     43  * understanding that the author is not responsible for the correct
     44  * functioning of this software in any circumstances and is not liable for
     45  * any damages caused by this software.
     46  *
     47  * October 1992
     48  */
     49 
     50 #include <sys/cdefs.h>
     51 __KERNEL_RCSID(0, "$NetBSD: msdosfs_fat.c,v 1.18 2009/03/14 21:04:23 dsl Exp $");
     52 
     53 /*
     54  * kernel include files.
     55  */
     56 #include <sys/param.h>
     57 #include <sys/systm.h>
     58 #include <sys/buf.h>
     59 #include <sys/file.h>
     60 #include <sys/namei.h>
     61 #include <sys/mount.h>		/* to define statvfs structure */
     62 #include <sys/vnode.h>		/* to define vattr structure */
     63 #include <sys/errno.h>
     64 #include <sys/dirent.h>
     65 #include <sys/kauth.h>
     66 
     67 /*
     68  * msdosfs include files.
     69  */
     70 #include <fs/msdosfs/bpb.h>
     71 #include <fs/msdosfs/msdosfsmount.h>
     72 #include <fs/msdosfs/direntry.h>
     73 #include <fs/msdosfs/denode.h>
     74 #include <fs/msdosfs/fat.h>
     75 
     76 /*
     77  * Fat cache stats.
     78  */
     79 int fc_fileextends;		/* # of file extends			 */
     80 int fc_lfcempty;		/* # of time last file cluster cache entry
     81 				 * was empty */
     82 int fc_bmapcalls;		/* # of times pcbmap was called		 */
     83 
     84 #define	LMMAX	20
     85 int fc_lmdistance[LMMAX];	/* counters for how far off the last
     86 				 * cluster mapped entry was. */
     87 int fc_largedistance;		/* off by more than LMMAX		 */
     88 int fc_wherefrom, fc_whereto, fc_lastclust;
     89 int pm_fatblocksize;
     90 
     91 #ifdef MSDOSFS_DEBUG
     92 void print_fat_stats(void);
     93 
     94 void
     95 print_fat_stats(void)
     96 {
     97 	int i;
     98 
     99 	printf("fc_fileextends=%d fc_lfcempty=%d fc_bmapcalls=%d "
    100 	    "fc_largedistance=%d [%d->%d=%d] fc_lastclust=%d pm_fatblocksize=%d\n",
    101 	    fc_fileextends, fc_lfcempty, fc_bmapcalls, fc_largedistance,
    102 	    fc_wherefrom, fc_whereto, fc_whereto-fc_wherefrom,
    103 	    fc_lastclust, pm_fatblocksize);
    104 
    105 	fc_fileextends = fc_lfcempty = fc_bmapcalls = 0;
    106 	fc_wherefrom = fc_whereto = fc_lastclust = 0;
    107 
    108 	for (i = 0; i < LMMAX; i++) {
    109 		printf("%d:%d ", i, fc_lmdistance[i]);
    110 	fc_lmdistance[i] = 0;
    111 	}
    112 
    113 	printf("\n");
    114 }
    115 #endif
    116 
    117 static void fatblock(struct msdosfsmount *, u_long, u_long *, u_long *,
    118 			  u_long *);
    119 void updatefats(struct msdosfsmount *, struct buf *, u_long);
    120 static inline void usemap_free(struct msdosfsmount *, u_long);
    121 static inline void usemap_alloc(struct msdosfsmount *, u_long);
    122 static int fatchain(struct msdosfsmount *, u_long, u_long, u_long);
    123 int chainlength(struct msdosfsmount *, u_long, u_long);
    124 int chainalloc(struct msdosfsmount *, u_long, u_long, u_long, u_long *,
    125 		    u_long *);
    126 
    127 static void
    128 fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep, u_long *bop)
    129 {
    130 	u_long bn, size;
    131 
    132 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
    133 	size = min(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
    134 	    * pmp->pm_BytesPerSec;
    135 	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
    136 
    137 	if (bnp)
    138 		*bnp = bn;
    139 	if (sizep)
    140 		*sizep = size;
    141 	if (bop)
    142 		*bop = ofs % pmp->pm_fatblocksize;
    143 
    144 	pm_fatblocksize =  pmp->pm_fatblocksize;
    145 }
    146 
    147 /*
    148  * Map the logical cluster number of a file into a physical disk sector
    149  * that is filesystem relative.
    150  *
    151  * dep	  - address of denode representing the file of interest
    152  * findcn - file relative cluster whose filesystem relative cluster number
    153  *	    and/or block number are/is to be found
    154  * bnp	  - address of where to place the file system relative block number.
    155  *	    If this pointer is null then don't return this quantity.
    156  * cnp	  - address of where to place the file system relative cluster number.
    157  *	    If this pointer is null then don't return this quantity.
    158  *
    159  * NOTE: Either bnp or cnp must be non-null.
    160  * This function has one side effect.  If the requested file relative cluster
    161  * is beyond the end of file, then the actual number of clusters in the file
    162  * is returned in *cnp.  This is useful for determining how long a directory is.
    163  *  If cnp is null, nothing is returned.
    164  */
    165 int
    166 pcbmap(struct denode *dep, u_long findcn, daddr_t *bnp, u_long *cnp, int *sp)
    167 	/* findcn:		 file relative cluster to get		 */
    168 	/* bnp:		 returned filesys rel sector number	 */
    169 	/* cnp:		 returned cluster number		 */
    170 	/* sp:		 returned block size			 */
    171 {
    172 	int error;
    173 	u_long i;
    174 	u_long cn;
    175 	u_long prevcn = 0; /* XXX: prevcn could be used unititialized */
    176 	u_long byteoffset;
    177 	u_long bn;
    178 	u_long bo;
    179 	struct buf *bp = NULL;
    180 	u_long bp_bn = -1;
    181 	struct msdosfsmount *pmp = dep->de_pmp;
    182 	u_long bsize;
    183 
    184 	fc_bmapcalls++;
    185 
    186 	/*
    187 	 * If they don't give us someplace to return a value then don't
    188 	 * bother doing anything.
    189 	 */
    190 	if (bnp == NULL && cnp == NULL && sp == NULL)
    191 		return (0);
    192 
    193 	cn = dep->de_StartCluster;
    194 	/*
    195 	 * The "file" that makes up the root directory is contiguous,
    196 	 * permanently allocated, of fixed size, and is not made up of
    197 	 * clusters.  If the cluster number is beyond the end of the root
    198 	 * directory, then return the number of clusters in the file.
    199 	 */
    200 	if (cn == MSDOSFSROOT) {
    201 		if (dep->de_Attributes & ATTR_DIRECTORY) {
    202 			if (de_cn2off(pmp, findcn) >= dep->de_FileSize) {
    203 				if (cnp)
    204 					*cnp = de_bn2cn(pmp, pmp->pm_rootdirsize);
    205 				return (E2BIG);
    206 			}
    207 			if (bnp)
    208 				*bnp = pmp->pm_rootdirblk + de_cn2bn(pmp, findcn);
    209 			if (cnp)
    210 				*cnp = MSDOSFSROOT;
    211 			if (sp)
    212 				*sp = min(pmp->pm_bpcluster,
    213 				    dep->de_FileSize - de_cn2off(pmp, findcn));
    214 			return (0);
    215 		} else {		/* just an empty file */
    216 			if (cnp)
    217 				*cnp = 0;
    218 			return (E2BIG);
    219 		}
    220 	}
    221 
    222 	/*
    223 	 * All other files do I/O in cluster sized blocks
    224 	 */
    225 	if (sp)
    226 		*sp = pmp->pm_bpcluster;
    227 
    228 	/*
    229 	 * Rummage around in the fat cache, maybe we can avoid tromping
    230 	 * thru every fat entry for the file. And, keep track of how far
    231 	 * off the cache was from where we wanted to be.
    232 	 */
    233 	i = 0;
    234 	fc_lookup(dep, findcn, &i, &cn);
    235 	if ((bn = findcn - i) >= LMMAX) {
    236 		fc_largedistance++;
    237 		fc_wherefrom = i;
    238 		fc_whereto = findcn;
    239 		fc_lastclust = dep->de_fc[FC_LASTFC].fc_frcn;
    240 	} else
    241 		fc_lmdistance[bn]++;
    242 
    243 	/*
    244 	 * Handle all other files or directories the normal way.
    245 	 */
    246 	for (; i < findcn; i++) {
    247 		/*
    248 		 * Stop with all reserved clusters, not just with EOF.
    249 		 */
    250 		if (cn >= (CLUST_RSRVD & pmp->pm_fatmask))
    251 			goto hiteof;
    252 		byteoffset = FATOFS(pmp, cn);
    253 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
    254 		if (bn != bp_bn) {
    255 			if (bp)
    256 				brelse(bp, 0);
    257 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
    258 			    NOCRED, 0, &bp);
    259 			if (error) {
    260 				brelse(bp, 0);
    261 				return (error);
    262 			}
    263 			bp_bn = bn;
    264 		}
    265 		prevcn = cn;
    266 		if (bo >= bsize) {
    267 			if (bp)
    268 				brelse(bp, 0);
    269 			return (EIO);
    270 		}
    271 		KASSERT(bp != NULL);
    272 		if (FAT32(pmp))
    273 			cn = getulong((char *)bp->b_data + bo);
    274 		else
    275 			cn = getushort((char *)bp->b_data + bo);
    276 		if (FAT12(pmp) && (prevcn & 1))
    277 			cn >>= 4;
    278 		cn &= pmp->pm_fatmask;
    279 	}
    280 
    281 	if (!MSDOSFSEOF(cn, pmp->pm_fatmask)) {
    282 		if (bp)
    283 			brelse(bp, 0);
    284 		if (bnp)
    285 			*bnp = cntobn(pmp, cn);
    286 		if (cnp)
    287 			*cnp = cn;
    288 		fc_setcache(dep, FC_LASTMAP, i, cn);
    289 		return (0);
    290 	}
    291 
    292 hiteof:;
    293 	if (cnp)
    294 		*cnp = i;
    295 	if (bp)
    296 		brelse(bp, 0);
    297 	/* update last file cluster entry in the fat cache */
    298 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
    299 	return (E2BIG);
    300 }
    301 
    302 /*
    303  * Find the closest entry in the fat cache to the cluster we are looking
    304  * for.
    305  */
    306 void
    307 fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
    308 {
    309 	int i;
    310 	u_long cn;
    311 	struct fatcache *closest = 0;
    312 
    313 	for (i = 0; i < FC_SIZE; i++) {
    314 		cn = dep->de_fc[i].fc_frcn;
    315 		if (cn != FCE_EMPTY && cn <= findcn) {
    316 			if (closest == 0 || cn > closest->fc_frcn)
    317 				closest = &dep->de_fc[i];
    318 		}
    319 	}
    320 	if (closest) {
    321 		*frcnp = closest->fc_frcn;
    322 		*fsrcnp = closest->fc_fsrcn;
    323 	}
    324 }
    325 
    326 /*
    327  * Purge the fat cache in denode dep of all entries relating to file
    328  * relative cluster frcn and beyond.
    329  */
    330 void
    331 fc_purge(struct denode *dep, u_int frcn)
    332 {
    333 	int i;
    334 	struct fatcache *fcp;
    335 
    336 	fcp = dep->de_fc;
    337 	for (i = 0; i < FC_SIZE; i++, fcp++) {
    338 		if (fcp->fc_frcn >= frcn)
    339 			fcp->fc_frcn = FCE_EMPTY;
    340 	}
    341 }
    342 
    343 /*
    344  * Update the fat.
    345  * If mirroring the fat, update all copies, with the first copy as last.
    346  * Else update only the current fat (ignoring the others).
    347  *
    348  * pmp	 - msdosfsmount structure for filesystem to update
    349  * bp	 - addr of modified fat block
    350  * fatbn - block number relative to begin of filesystem of the modified fat block.
    351  */
    352 void
    353 updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
    354 {
    355 	int i;
    356 	struct buf *bpn;
    357 
    358 #ifdef MSDOSFS_DEBUG
    359 	printf("updatefats(pmp %p, bp %p, fatbn %lu)\n",
    360 	    pmp, bp, fatbn);
    361 #endif
    362 
    363 	/*
    364 	 * If we have an FSInfo block, update it.
    365 	 */
    366 	if (pmp->pm_fsinfo) {
    367 		u_long cn = pmp->pm_nxtfree;
    368 
    369 		if (pmp->pm_freeclustercount
    370 		    && (pmp->pm_inusemap[cn / N_INUSEBITS]
    371 			& (1 << (cn % N_INUSEBITS)))) {
    372 			/*
    373 			 * The cluster indicated in FSInfo isn't free
    374 			 * any longer.  Got get a new free one.
    375 			 */
    376 			for (cn = 0; cn < pmp->pm_maxcluster; cn++)
    377 				if (pmp->pm_inusemap[cn / N_INUSEBITS] != (u_int)-1)
    378 					break;
    379 			pmp->pm_nxtfree = cn
    380 				+ ffs(pmp->pm_inusemap[cn / N_INUSEBITS]
    381 				      ^ (u_int)-1) - 1;
    382 		}
    383 		/*
    384 		 * XXX  If the fsinfo block is stored on media with
    385 		 *      2KB or larger sectors, is the fsinfo structure
    386 		 *      padded at the end or in the middle?
    387 		 */
    388 		if (bread(pmp->pm_devvp, de_bn2kb(pmp, pmp->pm_fsinfo),
    389 		    pmp->pm_BytesPerSec, NOCRED, B_MODIFY, &bpn) != 0) {
    390 			/*
    391 			 * Ignore the error, but turn off FSInfo update for the future.
    392 			 */
    393 			pmp->pm_fsinfo = 0;
    394 			brelse(bpn, 0);
    395 		} else {
    396 			struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
    397 
    398 			putulong(fp->fsinfree, pmp->pm_freeclustercount);
    399 			putulong(fp->fsinxtfree, pmp->pm_nxtfree);
    400 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
    401 				bwrite(bpn);
    402 			else
    403 				bdwrite(bpn);
    404 		}
    405 	}
    406 
    407 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
    408 		/*
    409 		 * Now copy the block(s) of the modified fat to the other copies of
    410 		 * the fat and write them out.  This is faster than reading in the
    411 		 * other fats and then writing them back out.  This could tie up
    412 		 * the fat for quite a while. Preventing others from accessing it.
    413 		 * To prevent us from going after the fat quite so much we use
    414 		 * delayed writes, unless they specified "synchronous" when the
    415 		 * filesystem was mounted.  If synch is asked for then use
    416 		 * bwrite()'s and really slow things down.
    417 		 */
    418 		for (i = 1; i < pmp->pm_FATs; i++) {
    419 			fatbn += pmp->pm_FATsecs;
    420 			/* getblk() never fails */
    421 			bpn = getblk(pmp->pm_devvp, de_bn2kb(pmp, fatbn),
    422 			    bp->b_bcount, 0, 0);
    423 			memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
    424 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
    425 				bwrite(bpn);
    426 			else
    427 				bdwrite(bpn);
    428 		}
    429 	}
    430 
    431 	/*
    432 	 * Write out the first (or current) fat last.
    433 	 */
    434 	if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
    435 		bwrite(bp);
    436 	else
    437 		bdwrite(bp);
    438 	/*
    439 	 * Maybe update fsinfo sector here?
    440 	 */
    441 }
    442 
    443 /*
    444  * Updating entries in 12 bit fats is a pain in the butt.
    445  *
    446  * The following picture shows where nibbles go when moving from a 12 bit
    447  * cluster number into the appropriate bytes in the FAT.
    448  *
    449  *	byte m        byte m+1      byte m+2
    450  *	+----+----+   +----+----+   +----+----+
    451  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
    452  *	+----+----+   +----+----+   +----+----+
    453  *
    454  *	+----+----+----+   +----+----+----+
    455  *	|  3    0    1 |   |  4    5    2 |
    456  *	+----+----+----+   +----+----+----+
    457  *	cluster n  	   cluster n+1
    458  *
    459  * Where n is even. m = n + (n >> 2)
    460  *
    461  */
    462 static inline void
    463 usemap_alloc(struct msdosfsmount *pmp, u_long cn)
    464 {
    465 
    466 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
    467 	pmp->pm_freeclustercount--;
    468 }
    469 
    470 static inline void
    471 usemap_free(struct msdosfsmount *pmp, u_long cn)
    472 {
    473 
    474 	pmp->pm_freeclustercount++;
    475 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
    476 }
    477 
    478 int
    479 clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
    480 {
    481 	int error;
    482 	u_long oldcn;
    483 
    484 	usemap_free(pmp, cluster);
    485 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
    486 	if (error) {
    487 		usemap_alloc(pmp, cluster);
    488 		return (error);
    489 	}
    490 	/*
    491 	 * If the cluster was successfully marked free, then update
    492 	 * the count of free clusters, and turn off the "allocated"
    493 	 * bit in the "in use" cluster bit map.
    494 	 */
    495 	if (oldcnp)
    496 		*oldcnp = oldcn;
    497 	return (0);
    498 }
    499 
    500 /*
    501  * Get or Set or 'Get and Set' the cluster'th entry in the fat.
    502  *
    503  * function	- whether to get or set a fat entry
    504  * pmp		- address of the msdosfsmount structure for the filesystem
    505  *		  whose fat is to be manipulated.
    506  * cn		- which cluster is of interest
    507  * oldcontents	- address of a word that is to receive the contents of the
    508  *		  cluster'th entry if this is a get function
    509  * newcontents	- the new value to be written into the cluster'th element of
    510  *		  the fat if this is a set function.
    511  *
    512  * This function can also be used to free a cluster by setting the fat entry
    513  * for a cluster to 0.
    514  *
    515  * All copies of the fat are updated if this is a set function. NOTE: If
    516  * fatentry() marks a cluster as free it does not update the inusemap in
    517  * the msdosfsmount structure. This is left to the caller.
    518  */
    519 int
    520 fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents, u_long newcontents)
    521 {
    522 	int error;
    523 	u_long readcn;
    524 	u_long bn, bo, bsize, byteoffset;
    525 	struct buf *bp;
    526 
    527 #ifdef	MSDOSFS_DEBUG
    528 	printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
    529 	     function, pmp, cn, oldcontents, newcontents);
    530 #endif
    531 
    532 #ifdef DIAGNOSTIC
    533 	/*
    534 	 * Be sure they asked us to do something.
    535 	 */
    536 	if ((function & (FAT_SET | FAT_GET)) == 0) {
    537 		printf("fatentry(): function code doesn't specify get or set\n");
    538 		return (EINVAL);
    539 	}
    540 
    541 	/*
    542 	 * If they asked us to return a cluster number but didn't tell us
    543 	 * where to put it, give them an error.
    544 	 */
    545 	if ((function & FAT_GET) && oldcontents == NULL) {
    546 		printf("fatentry(): get function with no place to put result\n");
    547 		return (EINVAL);
    548 	}
    549 #endif
    550 
    551 	/*
    552 	 * Be sure the requested cluster is in the filesystem.
    553 	 */
    554 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
    555 		return (EINVAL);
    556 
    557 	byteoffset = FATOFS(pmp, cn);
    558 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
    559 	if ((error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize, NOCRED,
    560 	    0, &bp)) != 0) {
    561 		brelse(bp, 0);
    562 		return (error);
    563 	}
    564 
    565 	if (function & FAT_GET) {
    566 		if (FAT32(pmp))
    567 			readcn = getulong((char *)bp->b_data + bo);
    568 		else
    569 			readcn = getushort((char *)bp->b_data + bo);
    570 		if (FAT12(pmp) & (cn & 1))
    571 			readcn >>= 4;
    572 		readcn &= pmp->pm_fatmask;
    573 		*oldcontents = readcn;
    574 	}
    575 	if (function & FAT_SET) {
    576 		switch (pmp->pm_fatmask) {
    577 		case FAT12_MASK:
    578 			readcn = getushort((char *)bp->b_data + bo);
    579 			if (cn & 1) {
    580 				readcn &= 0x000f;
    581 				readcn |= newcontents << 4;
    582 			} else {
    583 				readcn &= 0xf000;
    584 				readcn |= newcontents & 0xfff;
    585 			}
    586 			putushort((char *)bp->b_data + bo, readcn);
    587 			break;
    588 		case FAT16_MASK:
    589 			putushort((char *)bp->b_data + bo, newcontents);
    590 			break;
    591 		case FAT32_MASK:
    592 			/*
    593 			 * According to spec we have to retain the
    594 			 * high order bits of the fat entry.
    595 			 */
    596 			readcn = getulong((char *)bp->b_data + bo);
    597 			readcn &= ~FAT32_MASK;
    598 			readcn |= newcontents & FAT32_MASK;
    599 			putulong((char *)bp->b_data + bo, readcn);
    600 			break;
    601 		}
    602 		updatefats(pmp, bp, bn);
    603 		bp = NULL;
    604 		pmp->pm_fmod = 1;
    605 	}
    606 	if (bp)
    607 		brelse(bp, 0);
    608 	return (0);
    609 }
    610 
    611 /*
    612  * Update a contiguous cluster chain
    613  *
    614  * pmp	    - mount point
    615  * start    - first cluster of chain
    616  * count    - number of clusters in chain
    617  * fillwith - what to write into fat entry of last cluster
    618  */
    619 static int
    620 fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
    621 {
    622 	int error;
    623 	u_long bn, bo, bsize, byteoffset, readcn, newc;
    624 	struct buf *bp;
    625 
    626 #ifdef MSDOSFS_DEBUG
    627 	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
    628 	    pmp, start, count, fillwith);
    629 #endif
    630 	/*
    631 	 * Be sure the clusters are in the filesystem.
    632 	 */
    633 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
    634 		return (EINVAL);
    635 
    636 	while (count > 0) {
    637 		byteoffset = FATOFS(pmp, start);
    638 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
    639 		error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize, NOCRED,
    640 		    B_MODIFY, &bp);
    641 		if (error) {
    642 			brelse(bp, 0);
    643 			return (error);
    644 		}
    645 		while (count > 0) {
    646 			start++;
    647 			newc = --count > 0 ? start : fillwith;
    648 			switch (pmp->pm_fatmask) {
    649 			case FAT12_MASK:
    650 				readcn = getushort((char *)bp->b_data + bo);
    651 				if (start & 1) {
    652 					readcn &= 0xf000;
    653 					readcn |= newc & 0xfff;
    654 				} else {
    655 					readcn &= 0x000f;
    656 					readcn |= newc << 4;
    657 				}
    658 				putushort((char *)bp->b_data + bo, readcn);
    659 				bo++;
    660 				if (!(start & 1))
    661 					bo++;
    662 				break;
    663 			case FAT16_MASK:
    664 				putushort((char *)bp->b_data + bo, newc);
    665 				bo += 2;
    666 				break;
    667 			case FAT32_MASK:
    668 				readcn = getulong((char *)bp->b_data + bo);
    669 				readcn &= ~pmp->pm_fatmask;
    670 				readcn |= newc & pmp->pm_fatmask;
    671 				putulong((char *)bp->b_data + bo, readcn);
    672 				bo += 4;
    673 				break;
    674 			}
    675 			if (bo >= bsize)
    676 				break;
    677 		}
    678 		updatefats(pmp, bp, bn);
    679 	}
    680 	pmp->pm_fmod = 1;
    681 	return (0);
    682 }
    683 
    684 /*
    685  * Check the length of a free cluster chain starting at start.
    686  *
    687  * pmp	 - mount point
    688  * start - start of chain
    689  * count - maximum interesting length
    690  */
    691 int
    692 chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
    693 {
    694 	u_long idx, max_idx;
    695 	u_int map;
    696 	u_long len;
    697 
    698 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
    699 	idx = start / N_INUSEBITS;
    700 	start %= N_INUSEBITS;
    701 	map = pmp->pm_inusemap[idx];
    702 	map &= ~((1 << start) - 1);
    703 	if (map) {
    704 		len = ffs(map) - 1 - start;
    705 		return (len > count ? count : len);
    706 	}
    707 	len = N_INUSEBITS - start;
    708 	if (len >= count)
    709 		return (count);
    710 	while (++idx <= max_idx) {
    711 		if (len >= count)
    712 			break;
    713 		if ((map = pmp->pm_inusemap[idx]) != 0) {
    714 			len +=  ffs(map) - 1;
    715 			break;
    716 		}
    717 		len += N_INUSEBITS;
    718 	}
    719 	return (len > count ? count : len);
    720 }
    721 
    722 /*
    723  * Allocate contigous free clusters.
    724  *
    725  * pmp	      - mount point.
    726  * start      - start of cluster chain.
    727  * count      - number of clusters to allocate.
    728  * fillwith   - put this value into the fat entry for the
    729  *		last allocated cluster.
    730  * retcluster - put the first allocated cluster's number here.
    731  * got	      - how many clusters were actually allocated.
    732  */
    733 int
    734 chainalloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith, u_long *retcluster, u_long *got)
    735 {
    736 	int error;
    737 	u_long cl, n;
    738 
    739 	for (cl = start, n = count; n-- > 0;)
    740 		usemap_alloc(pmp, cl++);
    741 	if ((error = fatchain(pmp, start, count, fillwith)) != 0)
    742 		return (error);
    743 #ifdef MSDOSFS_DEBUG
    744 	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
    745 	    start, count);
    746 #endif
    747 	if (retcluster)
    748 		*retcluster = start;
    749 	if (got)
    750 		*got = count;
    751 	return (0);
    752 }
    753 
    754 /*
    755  * Allocate contiguous free clusters.
    756  *
    757  * pmp	      - mount point.
    758  * start      - preferred start of cluster chain.
    759  * count      - number of clusters requested.
    760  * fillwith   - put this value into the fat entry for the
    761  *		last allocated cluster.
    762  * retcluster - put the first allocated cluster's number here.
    763  * got	      - how many clusters were actually allocated.
    764  */
    765 int
    766 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long *retcluster, u_long *got)
    767 {
    768 	u_long idx;
    769 	u_long len, newst, foundl, cn, l;
    770 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
    771 	u_long fillwith = CLUST_EOFE;
    772 	u_int map;
    773 
    774 #ifdef MSDOSFS_DEBUG
    775 	printf("clusteralloc(): find %lu clusters\n",count);
    776 #endif
    777 	if (start) {
    778 		if ((len = chainlength(pmp, start, count)) >= count)
    779 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
    780 	} else {
    781 		/*
    782 		 * This is a new file, initialize start
    783 		 */
    784 		struct timeval tv;
    785 
    786 		microtime(&tv);
    787 		start = (tv.tv_usec >> 10) | tv.tv_usec;
    788 		len = 0;
    789 	}
    790 
    791 	/*
    792 	 * Start at a (pseudo) random place to maximize cluster runs
    793 	 * under multiple writers.
    794 	 */
    795 	newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1);
    796 	foundl = 0;
    797 
    798 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
    799 		idx = cn / N_INUSEBITS;
    800 		map = pmp->pm_inusemap[idx];
    801 		map |= (1 << (cn % N_INUSEBITS)) - 1;
    802 		if (map != (u_int)-1) {
    803 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
    804 			if ((l = chainlength(pmp, cn, count)) >= count)
    805 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
    806 			if (l > foundl) {
    807 				foundcn = cn;
    808 				foundl = l;
    809 			}
    810 			cn += l + 1;
    811 			continue;
    812 		}
    813 		cn += N_INUSEBITS - cn % N_INUSEBITS;
    814 	}
    815 	for (cn = 0; cn < newst;) {
    816 		idx = cn / N_INUSEBITS;
    817 		map = pmp->pm_inusemap[idx];
    818 		map |= (1 << (cn % N_INUSEBITS)) - 1;
    819 		if (map != (u_int)-1) {
    820 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
    821 			if ((l = chainlength(pmp, cn, count)) >= count)
    822 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
    823 			if (l > foundl) {
    824 				foundcn = cn;
    825 				foundl = l;
    826 			}
    827 			cn += l + 1;
    828 			continue;
    829 		}
    830 		cn += N_INUSEBITS - cn % N_INUSEBITS;
    831 	}
    832 
    833 	if (!foundl)
    834 		return (ENOSPC);
    835 
    836 	if (len)
    837 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
    838 	else
    839 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
    840 }
    841 
    842 
    843 /*
    844  * Free a chain of clusters.
    845  *
    846  * pmp		- address of the msdosfs mount structure for the filesystem
    847  *		  containing the cluster chain to be freed.
    848  * startcluster - number of the 1st cluster in the chain of clusters to be
    849  *		  freed.
    850  */
    851 int
    852 freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
    853 {
    854 	int error;
    855 	struct buf *bp = NULL;
    856 	u_long bn, bo, bsize, byteoffset;
    857 	u_long readcn, lbn = -1;
    858 
    859 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
    860 		byteoffset = FATOFS(pmp, cluster);
    861 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
    862 		if (lbn != bn) {
    863 			if (bp)
    864 				updatefats(pmp, bp, lbn);
    865 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
    866 			    NOCRED, B_MODIFY, &bp);
    867 			if (error) {
    868 				brelse(bp, 0);
    869 				return (error);
    870 			}
    871 			lbn = bn;
    872 		}
    873 		usemap_free(pmp, cluster);
    874 		KASSERT(bp != NULL);
    875 		switch (pmp->pm_fatmask) {
    876 		case FAT12_MASK:
    877 			readcn = getushort((char *)bp->b_data + bo);
    878 			if (cluster & 1) {
    879 				cluster = readcn >> 4;
    880 				readcn &= 0x000f;
    881 				readcn |= MSDOSFSFREE << 4;
    882 			} else {
    883 				cluster = readcn;
    884 				readcn &= 0xf000;
    885 				readcn |= MSDOSFSFREE & 0xfff;
    886 			}
    887 			putushort((char *)bp->b_data + bo, readcn);
    888 			break;
    889 		case FAT16_MASK:
    890 			cluster = getushort((char *)bp->b_data + bo);
    891 			putushort((char *)bp->b_data + bo, MSDOSFSFREE);
    892 			break;
    893 		case FAT32_MASK:
    894 			cluster = getulong((char *)bp->b_data + bo);
    895 			putulong((char *)bp->b_data + bo,
    896 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
    897 			break;
    898 		}
    899 		cluster &= pmp->pm_fatmask;
    900 	}
    901 	if (bp)
    902 		updatefats(pmp, bp, bn);
    903 	return (0);
    904 }
    905 
    906 /*
    907  * Read in fat blocks looking for free clusters. For every free cluster
    908  * found turn off its corresponding bit in the pm_inusemap.
    909  */
    910 int
    911 fillinusemap(struct msdosfsmount *pmp)
    912 {
    913 	struct buf *bp = NULL;
    914 	u_long cn, readcn;
    915 	int error;
    916 	u_long bn, bo, bsize, byteoffset;
    917 
    918 	/*
    919 	 * Mark all clusters in use, we mark the free ones in the fat scan
    920 	 * loop further down.
    921 	 */
    922 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
    923 		pmp->pm_inusemap[cn] = (u_int)-1;
    924 
    925 	/*
    926 	 * Figure how many free clusters are in the filesystem by ripping
    927 	 * through the fat counting the number of entries whose content is
    928 	 * zero.  These represent free clusters.
    929 	 */
    930 	pmp->pm_freeclustercount = 0;
    931 	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
    932 		byteoffset = FATOFS(pmp, cn);
    933 		bo = byteoffset % pmp->pm_fatblocksize;
    934 		if (!bo || !bp) {
    935 			/* Read new FAT block */
    936 			if (bp)
    937 				brelse(bp, 0);
    938 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
    939 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
    940 			    NOCRED, 0, &bp);
    941 			if (error) {
    942 				brelse(bp, 0);
    943 				return (error);
    944 			}
    945 		}
    946 		if (FAT32(pmp))
    947 			readcn = getulong((char *)bp->b_data + bo);
    948 		else
    949 			readcn = getushort((char *)bp->b_data + bo);
    950 		if (FAT12(pmp) && (cn & 1))
    951 			readcn >>= 4;
    952 		readcn &= pmp->pm_fatmask;
    953 
    954 		if (readcn == 0)
    955 			usemap_free(pmp, cn);
    956 	}
    957 	brelse(bp, 0);
    958 	return (0);
    959 }
    960 
    961 /*
    962  * Allocate a new cluster and chain it onto the end of the file.
    963  *
    964  * dep	 - the file to extend
    965  * count - number of clusters to allocate
    966  * bpp	 - where to return the address of the buf header for the first new
    967  *	   file block
    968  * ncp	 - where to put cluster number of the first newly allocated cluster
    969  *	   If this pointer is 0, do not return the cluster number.
    970  * flags - see fat.h
    971  *
    972  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
    973  * the de_flag field of the denode and it does not change the de_FileSize
    974  * field.  This is left for the caller to do.
    975  */
    976 
    977 int
    978 extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp, int flags)
    979 {
    980 	int error;
    981 	u_long frcn = 0, cn, got;
    982 	struct msdosfsmount *pmp = dep->de_pmp;
    983 	struct buf *bp;
    984 
    985 	/*
    986 	 * Don't try to extend the root directory
    987 	 */
    988 	if (dep->de_StartCluster == MSDOSFSROOT
    989 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
    990 		printf("extendfile(): attempt to extend root directory\n");
    991 		return (ENOSPC);
    992 	}
    993 
    994 	/*
    995 	 * If the "file's last cluster" cache entry is empty, and the file
    996 	 * is not empty, then fill the cache entry by calling pcbmap().
    997 	 */
    998 	fc_fileextends++;
    999 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
   1000 	    dep->de_StartCluster != 0) {
   1001 		fc_lfcempty++;
   1002 		error = pcbmap(dep, CLUST_END, 0, &cn, 0);
   1003 		/* we expect it to return E2BIG */
   1004 		if (error != E2BIG)
   1005 			return (error);
   1006 	}
   1007 
   1008 	fc_last_to_nexttolast(dep);
   1009 
   1010 	while (count > 0) {
   1011 
   1012 		/*
   1013 		 * Allocate a new cluster chain and cat onto the end of the
   1014 		 * file.  If the file is empty we make de_StartCluster point
   1015 		 * to the new block.  Note that de_StartCluster being 0 is
   1016 		 * sufficient to be sure the file is empty since we exclude
   1017 		 * attempts to extend the root directory above, and the root
   1018 		 * dir is the only file with a startcluster of 0 that has
   1019 		 * blocks allocated (sort of).
   1020 		 */
   1021 
   1022 		if (dep->de_StartCluster == 0)
   1023 			cn = 0;
   1024 		else
   1025 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
   1026 		error = clusteralloc(pmp, cn, count, &cn, &got);
   1027 		if (error)
   1028 			return (error);
   1029 
   1030 		count -= got;
   1031 
   1032 		/*
   1033 		 * Give them the filesystem relative cluster number if they want
   1034 		 * it.
   1035 		 */
   1036 		if (ncp) {
   1037 			*ncp = cn;
   1038 			ncp = NULL;
   1039 		}
   1040 
   1041 		if (dep->de_StartCluster == 0) {
   1042 			dep->de_StartCluster = cn;
   1043 			frcn = 0;
   1044 		} else {
   1045 			error = fatentry(FAT_SET, pmp,
   1046 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
   1047 					 0, cn);
   1048 			if (error) {
   1049 				clusterfree(pmp, cn, NULL);
   1050 				return (error);
   1051 			}
   1052 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
   1053 		}
   1054 
   1055 		/*
   1056 		 * Update the "last cluster of the file" entry in the
   1057 		 * denode's fat cache.
   1058 		 */
   1059 
   1060 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
   1061 		if ((flags & DE_CLEAR) &&
   1062 		    (dep->de_Attributes & ATTR_DIRECTORY)) {
   1063 			while (got-- > 0) {
   1064 				bp = getblk(pmp->pm_devvp,
   1065 				    de_bn2kb(pmp, cntobn(pmp, cn++)),
   1066 				    pmp->pm_bpcluster, 0, 0);
   1067 				clrbuf(bp);
   1068 				if (bpp) {
   1069 					*bpp = bp;
   1070 						bpp = NULL;
   1071 				} else {
   1072 					bdwrite(bp);
   1073 				}
   1074 			}
   1075 		}
   1076 	}
   1077 
   1078 	return (0);
   1079 }
   1080