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