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