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