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