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