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