xref: /freebsd/sys/fs/msdosfs/msdosfs_fat.c (revision 17ee9d00bc1ae1e598c38f25826f861e4bc6c3ce)
1 /*	$Id: msdosfs_fat.c,v 1.4 1994/12/12 12:35:45 bde Exp $ */
2 /*	$NetBSD: msdosfs_fat.c,v 1.12 1994/08/21 18:44:04 ws Exp $	*/
3 
4 /*-
5  * Copyright (C) 1994 Wolfgang Solfrank.
6  * Copyright (C) 1994 TooLs GmbH.
7  * All rights reserved.
8  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by TooLs GmbH.
21  * 4. The name of TooLs GmbH may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
29  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
30  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
31  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
32  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 /*
36  * Written by Paul Popelka (paulp@uts.amdahl.com)
37  *
38  * You can do anything you want with this software, just don't say you wrote
39  * it, and don't remove this notice.
40  *
41  * This software is provided "as is".
42  *
43  * The author supplies this software to be publicly redistributed on the
44  * understanding that the author is not responsible for the correct
45  * functioning of this software in any circumstances and is not liable for
46  * any damages caused by this software.
47  *
48  * October 1992
49  */
50 
51 /*
52  * kernel include files.
53  */
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/buf.h>
57 #include <sys/file.h>
58 #include <sys/namei.h>
59 #include <sys/mount.h>		/* to define statfs structure */
60 #include <sys/vnode.h>		/* to define vattr structure */
61 #include <sys/errno.h>
62 
63 /*
64  * msdosfs include files.
65  */
66 #include <msdosfs/bpb.h>
67 #include <msdosfs/msdosfsmount.h>
68 #include <msdosfs/direntry.h>
69 #include <msdosfs/denode.h>
70 #include <msdosfs/fat.h>
71 
72 /*
73  * Fat cache stats.
74  */
75 int fc_fileextends;		/* # of file extends			 */
76 int fc_lfcempty;		/* # of time last file cluster cache entry
77 				 * was empty */
78 int fc_bmapcalls;		/* # of times pcbmap was called		 */
79 
80 #define	LMMAX	20
81 int fc_lmdistance[LMMAX];	/* counters for how far off the last
82 				 * cluster mapped entry was. */
83 int fc_largedistance;		/* off by more than LMMAX		 */
84 
85 /* Byte offset in FAT on filesystem pmp, cluster cn */
86 #define	FATOFS(pmp, cn)	(FAT12(pmp) ? (cn) * 3 / 2 : (cn) * 2)
87 
88 static void
89 fatblock(pmp, ofs, bnp, sizep, bop)
90 	struct msdosfsmount *pmp;
91 	u_long ofs;
92 	u_long *bnp;
93 	u_long *sizep;
94 	u_long *bop;
95 {
96 	u_long bn, size;
97 
98 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
99 	size = min(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
100 	    * pmp->pm_BytesPerSec;
101 	bn += pmp->pm_fatblk;
102 	if (bnp)
103 		*bnp = bn;
104 	if (sizep)
105 		*sizep = size;
106 	if (bop)
107 		*bop = ofs % pmp->pm_fatblocksize;
108 }
109 
110 /*
111  * Map the logical cluster number of a file into a physical disk sector
112  * that is filesystem relative.
113  *
114  * dep	  - address of denode representing the file of interest
115  * findcn - file relative cluster whose filesystem relative cluster number
116  *	    and/or block number are/is to be found
117  * bnp	  - address of where to place the file system relative block number.
118  *	    If this pointer is null then don't return this quantity.
119  * cnp	  - address of where to place the file system relative cluster number.
120  *	    If this pointer is null then don't return this quantity.
121  *
122  * NOTE: Either bnp or cnp must be non-null.
123  * This function has one side effect.  If the requested file relative cluster
124  * is beyond the end of file, then the actual number of clusters in the file
125  * is returned in *cnp.  This is useful for determining how long a directory is.
126  *  If cnp is null, nothing is returned.
127  */
128 int
129 pcbmap(dep, findcn, bnp, cnp)
130 	struct denode *dep;
131 	u_long findcn;		/* file relative cluster to get		 */
132 	daddr_t *bnp;		/* returned filesys relative blk number	 */
133 	u_long *cnp;		/* returned cluster number		 */
134 {
135 	int error;
136 	u_long i;
137 	u_long cn;
138 	u_long prevcn;
139 	u_long byteoffset;
140 	u_long bn;
141 	u_long bo;
142 	struct buf *bp = NULL;
143 	u_long bp_bn = -1;
144 	struct msdosfsmount *pmp = dep->de_pmp;
145 	u_long bsize;
146 	int fat12 = FAT12(pmp);	/* 12 bit fat	 */
147 
148 	fc_bmapcalls++;
149 
150 	/*
151 	 * If they don't give us someplace to return a value then don't
152 	 * bother doing anything.
153 	 */
154 	if (bnp == NULL && cnp == NULL)
155 		return 0;
156 
157 	cn = dep->de_StartCluster;
158 	/*
159 	 * The "file" that makes up the root directory is contiguous,
160 	 * permanently allocated, of fixed size, and is not made up of
161 	 * clusters.  If the cluster number is beyond the end of the root
162 	 * directory, then return the number of clusters in the file.
163 	 */
164 	if (cn == MSDOSFSROOT) {
165 		if (dep->de_Attributes & ATTR_DIRECTORY) {
166 			if (findcn * pmp->pm_SectPerClust > pmp->pm_rootdirsize) {
167 				if (cnp)
168 					*cnp = pmp->pm_rootdirsize / pmp->pm_SectPerClust;
169 				return E2BIG;
170 			}
171 			if (bnp)
172 				*bnp = pmp->pm_rootdirblk + (findcn * pmp->pm_SectPerClust);
173 			if (cnp)
174 				*cnp = MSDOSFSROOT;
175 			return 0;
176 		} else {		/* just an empty file */
177 			if (cnp)
178 				*cnp = 0;
179 			return E2BIG;
180 		}
181 	}
182 
183 	/*
184 	 * Rummage around in the fat cache, maybe we can avoid tromping
185 	 * thru every fat entry for the file. And, keep track of how far
186 	 * off the cache was from where we wanted to be.
187 	 */
188 	i = 0;
189 	fc_lookup(dep, findcn, &i, &cn);
190 	if ((bn = findcn - i) >= LMMAX)
191 		fc_largedistance++;
192 	else
193 		fc_lmdistance[bn]++;
194 
195 	/*
196 	 * Handle all other files or directories the normal way.
197 	 */
198 	prevcn = 0;
199 	for (; i < findcn; i++) {
200 		if (MSDOSFSEOF(cn))
201 			goto hiteof;
202 		byteoffset = FATOFS(pmp, cn);
203 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
204 		if (bn != bp_bn) {
205 			if (bp)
206 				brelse(bp);
207 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
208 			if (error)
209 				return error;
210 			bp_bn = bn;
211 		}
212 		prevcn = cn;
213 		cn = getushort(&bp->b_data[bo]);
214 		if (fat12) {
215 			if (prevcn & 1)
216 				cn >>= 4;
217 			cn &= 0x0fff;
218 			/*
219 			 * Force the special cluster numbers in the range
220 			 * 0x0ff0-0x0fff to be the same as for 16 bit
221 			 * cluster numbers to let the rest of msdosfs think
222 			 * it is always dealing with 16 bit fats.
223 			 */
224 			if ((cn & 0x0ff0) == 0x0ff0)
225 				cn |= 0xf000;
226 		}
227 	}
228 
229 	if (!MSDOSFSEOF(cn)) {
230 		if (bp)
231 			brelse(bp);
232 		if (bnp)
233 			*bnp = cntobn(pmp, cn);
234 		if (cnp)
235 			*cnp = cn;
236 		fc_setcache(dep, FC_LASTMAP, i, cn);
237 		return 0;
238 	}
239 
240 hiteof:;
241 	if (cnp)
242 		*cnp = i;
243 	if (bp)
244 		brelse(bp);
245 	/* update last file cluster entry in the fat cache */
246 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
247 	return E2BIG;
248 }
249 
250 /*
251  * Find the closest entry in the fat cache to the cluster we are looking
252  * for.
253  */
254 void
255 fc_lookup(dep, findcn, frcnp, fsrcnp)
256 	struct denode *dep;
257 	u_long findcn;
258 	u_long *frcnp;
259 	u_long *fsrcnp;
260 {
261 	int i;
262 	u_long cn;
263 	struct fatcache *closest = 0;
264 
265 	for (i = 0; i < FC_SIZE; i++) {
266 		cn = dep->de_fc[i].fc_frcn;
267 		if (cn != FCE_EMPTY && cn <= findcn) {
268 			if (closest == 0 || cn > closest->fc_frcn)
269 				closest = &dep->de_fc[i];
270 		}
271 	}
272 	if (closest) {
273 		*frcnp = closest->fc_frcn;
274 		*fsrcnp = closest->fc_fsrcn;
275 	}
276 }
277 
278 /*
279  * Purge the fat cache in denode dep of all entries relating to file
280  * relative cluster frcn and beyond.
281  */
282 void fc_purge(dep, frcn)
283 	struct denode *dep;
284 	u_int frcn;
285 {
286 	int i;
287 	struct fatcache *fcp;
288 
289 	fcp = dep->de_fc;
290 	for (i = 0; i < FC_SIZE; i++, fcp++) {
291 		if (fcp->fc_frcn >= frcn)
292 			fcp->fc_frcn = FCE_EMPTY;
293 	}
294 }
295 
296 /*
297  * Update all copies of the fat. The first copy is updated last.
298  *
299  * pmp	 - msdosfsmount structure for filesystem to update
300  * bp	 - addr of modified fat block
301  * fatbn - block number relative to begin of filesystem of the modified fat block.
302  */
303 void
304 updatefats(pmp, bp, fatbn)
305 	struct msdosfsmount *pmp;
306 	struct buf *bp;
307 	u_long fatbn;
308 {
309 	int i;
310 	struct buf *bpn;
311 
312 #ifdef MSDOSFS_DEBUG
313 	printf("updatefats(pmp %p, bp %p, fatbn %ld)\n", pmp, bp, fatbn);
314 #endif
315 
316 	/*
317 	 * Now copy the block(s) of the modified fat to the other copies of
318 	 * the fat and write them out.  This is faster than reading in the
319 	 * other fats and then writing them back out.  This could tie up
320 	 * the fat for quite a while. Preventing others from accessing it.
321 	 * To prevent us from going after the fat quite so much we use
322 	 * delayed writes, unless they specfied "synchronous" when the
323 	 * filesystem was mounted.  If synch is asked for then use
324 	 * bwrite()'s and really slow things down.
325 	 */
326 	for (i = 1; i < pmp->pm_FATs; i++) {
327 		fatbn += pmp->pm_FATsecs;
328 		/* getblk() never fails */
329 		bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount, 0, 0);
330 		bcopy(bp->b_data, bpn->b_data, bp->b_bcount);
331 		if (pmp->pm_waitonfat)
332 			bwrite(bpn);
333 		else
334 			bdwrite(bpn);
335 	}
336 	/*
337 	 * Write out the first fat last.
338 	 */
339 	if (pmp->pm_waitonfat)
340 		bwrite(bp);
341 	else
342 		bdwrite(bp);
343 }
344 
345 /*
346  * Updating entries in 12 bit fats is a pain in the butt.
347  *
348  * The following picture shows where nibbles go when moving from a 12 bit
349  * cluster number into the appropriate bytes in the FAT.
350  *
351  *	byte m        byte m+1      byte m+2
352  *	+----+----+   +----+----+   +----+----+
353  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
354  *	+----+----+   +----+----+   +----+----+
355  *
356  *	+----+----+----+   +----+----+----+
357  *	|  3    0    1 |   |  4    5    2 |
358  *	+----+----+----+   +----+----+----+
359  *	cluster n  	   cluster n+1
360  *
361  * Where n is even. m = n + (n >> 2)
362  *
363  */
364 static inline void
365 usemap_alloc(pmp, cn)
366 	struct msdosfsmount *pmp;
367 	u_long cn;
368 {
369 	pmp->pm_inusemap[cn / N_INUSEBITS]
370 			 |= 1 << (cn % N_INUSEBITS);
371 	pmp->pm_freeclustercount--;
372 }
373 
374 static inline void
375 usemap_free(pmp, cn)
376 	struct msdosfsmount *pmp;
377 	u_long cn;
378 {
379 	pmp->pm_freeclustercount++;
380 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
381 }
382 
383 int
384 clusterfree(pmp, cluster, oldcnp)
385 	struct msdosfsmount *pmp;
386 	u_long cluster;
387 	u_long *oldcnp;
388 {
389 	int error;
390 	u_long oldcn;
391 
392 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
393 	if (error == 0) {
394 		/*
395 		 * If the cluster was successfully marked free, then update
396 		 * the count of free clusters, and turn off the "allocated"
397 		 * bit in the "in use" cluster bit map.
398 		 */
399 		usemap_free(pmp, cluster);
400 		if (oldcnp)
401 			*oldcnp = oldcn;
402 	}
403 	return error;
404 }
405 
406 /*
407  * Get or Set or 'Get and Set' the cluster'th entry in the fat.
408  *
409  * function	- whether to get or set a fat entry
410  * pmp		- address of the msdosfsmount structure for the filesystem
411  *		  whose fat is to be manipulated.
412  * cn		- which cluster is of interest
413  * oldcontents	- address of a word that is to receive the contents of the
414  *		  cluster'th entry if this is a get function
415  * newcontents	- the new value to be written into the cluster'th element of
416  *		  the fat if this is a set function.
417  *
418  * This function can also be used to free a cluster by setting the fat entry
419  * for a cluster to 0.
420  *
421  * All copies of the fat are updated if this is a set function. NOTE: If
422  * fatentry() marks a cluster as free it does not update the inusemap in
423  * the msdosfsmount structure. This is left to the caller.
424  */
425 int
426 fatentry(function, pmp, cn, oldcontents, newcontents)
427 	int function;
428 	struct msdosfsmount *pmp;
429 	u_long cn;
430 	u_long *oldcontents;
431 	u_long newcontents;
432 {
433 	int error;
434 	u_long readcn;
435 	u_long bn, bo, bsize, byteoffset;
436 	struct buf *bp;
437 
438 	/*
439 	 * printf("fatentry(func %d, pmp %08x, clust %d, oldcon %08x, newcon %d)\n",
440 	 *	  function, pmp, cluster, oldcontents, newcontents);
441 	 */
442 
443 #ifdef DIAGNOSTIC
444 	/*
445 	 * Be sure they asked us to do something.
446 	 */
447 	if ((function & (FAT_SET | FAT_GET)) == 0) {
448 		printf("fatentry(): function code doesn't specify get or set\n");
449 		return EINVAL;
450 	}
451 
452 	/*
453 	 * If they asked us to return a cluster number but didn't tell us
454 	 * where to put it, give them an error.
455 	 */
456 	if ((function & FAT_GET) && oldcontents == NULL) {
457 		printf("fatentry(): get function with no place to put result\n");
458 		return EINVAL;
459 	}
460 #endif
461 
462 	/*
463 	 * Be sure the requested cluster is in the filesystem.
464 	 */
465 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
466 		return EINVAL;
467 
468 	byteoffset = FATOFS(pmp, cn);
469 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
470 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
471 	if (error)
472 		return error;
473 
474 	if (function & FAT_GET) {
475 		readcn = getushort(&bp->b_data[bo]);
476 		if (FAT12(pmp)) {
477 			if (cn & 1)
478 				readcn >>= 4;
479 			readcn &= 0x0fff;
480 			/* map certain 12 bit fat entries to 16 bit */
481 			if ((readcn & 0x0ff0) == 0x0ff0)
482 				readcn |= 0xf000;
483 		}
484 		*oldcontents = readcn;
485 	}
486 	if (function & FAT_SET) {
487 		if (FAT12(pmp)) {
488 			readcn = getushort(&bp->b_data[bo]);
489 			if (cn & 1) {
490 				readcn &= 0x000f;
491 				readcn |= newcontents << 4;
492 			} else {
493 				readcn &= 0xf000;
494 				readcn |= newcontents & 0xfff;
495 			}
496 			putushort(&bp->b_data[bo], readcn);
497 		} else
498 			putushort(&bp->b_data[bo], newcontents);
499 		updatefats(pmp, bp, bn);
500 		bp = NULL;
501 		pmp->pm_fmod = 1;
502 	}
503 	if (bp)
504 		brelse(bp);
505 	return 0;
506 }
507 
508 /*
509  * Update a contiguous cluster chain
510  *
511  * pmp	    - mount point
512  * start    - first cluster of chain
513  * count    - number of clusters in chain
514  * fillwith - what to write into fat entry of last cluster
515  */
516 static int
517 fatchain(pmp, start, count, fillwith)
518 	struct msdosfsmount *pmp;
519 	u_long start;
520 	u_long count;
521 	u_long fillwith;
522 {
523 	int error;
524 	u_long bn, bo, bsize, byteoffset, readcn, newc;
525 	struct buf *bp;
526 
527 #ifdef MSDOSFS_DEBUG
528 	printf("fatchain(pmp %p, start %ld, count %ld, fillwith %ld)\n",
529 	       pmp, start, count, fillwith);
530 #endif
531 	/*
532 	 * Be sure the clusters are in the filesystem.
533 	 */
534 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
535 		return EINVAL;
536 
537 	while (count > 0) {
538 		byteoffset = FATOFS(pmp, start);
539 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
540 		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
541 		if (error)
542 			return error;
543 		while (count > 0) {
544 			start++;
545 			newc = --count > 0 ? start : fillwith;
546 			if (FAT12(pmp)) {
547 				readcn = getushort(&bp->b_data[bo]);
548 				if (start & 1) {
549 					readcn &= 0xf000;
550 					readcn |= newc & 0xfff;
551 				} else {
552 					readcn &= 0x000f;
553 					readcn |= newc << 4;
554 				}
555 				putushort(&bp->b_data[bo], readcn);
556 				bo++;
557 				if (!(start & 1))
558 					bo++;
559 			} else {
560 				putushort(&bp->b_data[bo], newc);
561 				bo += 2;
562 			}
563 			if (bo >= bsize)
564 				break;
565 		}
566 		updatefats(pmp, bp, bn);
567 	}
568 	pmp->pm_fmod = 1;
569 	return 0;
570 }
571 
572 /*
573  * Check the length of a free cluster chain starting at start.
574  *
575  * pmp	 - mount point
576  * start - start of chain
577  * count - maximum interesting length
578  */
579 int
580 chainlength(pmp, start, count)
581 	struct msdosfsmount *pmp;
582 	u_long start;
583 	u_long count;
584 {
585 	u_long idx, max_idx;
586 	u_int map;
587 	u_long len;
588 
589 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
590 	idx = start / N_INUSEBITS;
591 	start %= N_INUSEBITS;
592 	map = pmp->pm_inusemap[idx];
593 	map &= ~((1 << start) - 1);
594 	if (map) {
595 		len = ffs(map) - 1 - start;
596 		return len > count ? count : len;
597 	}
598 	len = N_INUSEBITS - start;
599 	if (len >= count)
600 		return count;
601 	while (++idx <= max_idx) {
602 		if (len >= count)
603 			break;
604 		map = pmp->pm_inusemap[idx];
605 		if (map) {
606 			len +=  ffs(map) - 1;
607 			break;
608 		}
609 		len += N_INUSEBITS;
610 	}
611 	return len > count ? count : len;
612 }
613 
614 /*
615  * Allocate contigous free clusters.
616  *
617  * pmp	      - mount point.
618  * start      - start of cluster chain.
619  * count      - number of clusters to allocate.
620  * fillwith   - put this value into the fat entry for the
621  *		last allocated cluster.
622  * retcluster - put the first allocated cluster's number here.
623  * got	      - how many clusters were actually allocated.
624  */
625 int
626 chainalloc(pmp, start, count, fillwith, retcluster, got)
627 	struct msdosfsmount *pmp;
628 	u_long start;
629 	u_long count;
630 	u_long fillwith;
631 	u_long *retcluster;
632 	u_long *got;
633 {
634 	int error;
635 
636 	error = fatchain(pmp, start, count, fillwith);
637 	if (error == 0) {
638 #ifdef MSDOSFS_DEBUG
639 		printf("clusteralloc(): allocated cluster chain at %ld (%ld clusters)\n",
640 		       start, count);
641 #endif
642 		if (retcluster)
643 			*retcluster = start;
644 		if (got)
645 			*got = count;
646 		while (count-- > 0)
647 			usemap_alloc(pmp, start++);
648 	}
649 	return error;
650 }
651 
652 /*
653  * Allocate contiguous free clusters.
654  *
655  * pmp	      - mount point.
656  * start      - preferred start of cluster chain.
657  * count      - number of clusters requested.
658  * fillwith   - put this value into the fat entry for the
659  *		last allocated cluster.
660  * retcluster - put the first allocated cluster's number here.
661  * got	      - how many clusters were actually allocated.
662  */
663 int
664 clusteralloc(pmp, start, count, fillwith, retcluster, got)
665 	struct msdosfsmount *pmp;
666 	u_long start;
667 	u_long count;
668 	u_long fillwith;
669 	u_long *retcluster;
670 	u_long *got;
671 {
672 	u_long idx;
673 	u_long len, newst, foundcn, foundl, cn, l;
674 	u_int map;
675 
676 #ifdef MSDOSFS_DEBUG
677 	printf("clusteralloc(): find %d clusters\n",count);
678 #endif
679 	if (start) {
680 		if ((len = chainlength(pmp, start, count)) >= count)
681 			return chainalloc(pmp, start, count, fillwith, retcluster, got);
682 	} else {
683 		/*
684 		 * This is a new file, initialize start
685 		 */
686 		struct timeval tv;
687 
688 		microtime(&tv);
689 		start = (tv.tv_usec >> 10)|tv.tv_usec;
690 		len = 0;
691 	}
692 
693 	/*
694 	 * Start at a (pseudo) random place to maximize cluster runs
695 	 * under multiple writers.
696 	 */
697 	foundcn = newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1);
698 	foundl = 0;
699 
700 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
701 		idx = cn / N_INUSEBITS;
702 		map = pmp->pm_inusemap[idx];
703 		map |= (1 << (cn % N_INUSEBITS)) - 1;
704 		if (map != (u_int)-1) {
705 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
706 			if ((l = chainlength(pmp, cn, count)) >= count)
707 				return chainalloc(pmp, cn, count, fillwith, retcluster, got);
708 			if (l > foundl) {
709 				foundcn = cn;
710 				foundl = l;
711 			}
712 			cn += l + 1;
713 			continue;
714 		}
715 		cn += N_INUSEBITS - cn % N_INUSEBITS;
716 	}
717 	for (cn = 0; cn < newst;) {
718 		idx = cn / N_INUSEBITS;
719 		map = pmp->pm_inusemap[idx];
720 		map |= (1 << (cn % N_INUSEBITS)) - 1;
721 		if (map != (u_int)-1) {
722 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
723 			if ((l = chainlength(pmp, cn, count)) >= count)
724 				return chainalloc(pmp, cn, count, fillwith, retcluster, got);
725 			if (l > foundl) {
726 				foundcn = cn;
727 				foundl = l;
728 			}
729 			cn += l + 1;
730 			continue;
731 		}
732 		cn += N_INUSEBITS - cn % N_INUSEBITS;
733 	}
734 
735 	if (!foundl)
736 		return ENOSPC;
737 
738 	if (len)
739 		return chainalloc(pmp, start, len, fillwith, retcluster, got);
740 	else
741 		return chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got);
742 }
743 
744 
745 /*
746  * Free a chain of clusters.
747  *
748  * pmp		- address of the msdosfs mount structure for the filesystem
749  *		  containing the cluster chain to be freed.
750  * startcluster - number of the 1st cluster in the chain of clusters to be
751  *		  freed.
752  */
753 int
754 freeclusterchain(pmp, cluster)
755 	struct msdosfsmount *pmp;
756 	u_long cluster;
757 {
758 	int error = 0;
759 	struct buf *bp = NULL;
760 	u_long bn, bo, bsize, byteoffset;
761 	u_long readcn, lbn = -1;
762 
763 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
764 		byteoffset = FATOFS(pmp, cluster);
765 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
766 		if (lbn != bn) {
767 			if (bp)
768 				updatefats(pmp, bp, lbn);
769 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
770 			if (error)
771 				return error;
772 			lbn = bn;
773 		}
774 		usemap_free(pmp, cluster);
775 		readcn = getushort(&bp->b_data[bo]);
776 		if (FAT12(pmp)) {
777 			if (cluster & 1) {
778 				cluster = readcn >> 4;
779 				readcn &= 0x000f;
780 				readcn |= MSDOSFSFREE << 4;
781 			} else {
782 				cluster = readcn;
783 				readcn &= 0xf000;
784 				readcn |= MSDOSFSFREE & 0xfff;
785 			}
786 			putushort(&bp->b_data[bo], readcn);
787 			cluster &= 0x0fff;
788 			if ((cluster&0x0ff0) == 0x0ff0)
789 				cluster |= 0xf000;
790 		} else {
791 			cluster = readcn;
792 			putushort(&bp->b_data[bo], MSDOSFSFREE);
793 		}
794 	}
795 	if (bp)
796 		updatefats(pmp, bp, bn);
797 	return error;
798 }
799 
800 /*
801  * Read in fat blocks looking for free clusters. For every free cluster
802  * found turn off its corresponding bit in the pm_inusemap.
803  */
804 int
805 fillinusemap(pmp)
806 	struct msdosfsmount *pmp;
807 {
808 	struct buf *bp = NULL;
809 	u_long cn, readcn;
810 	int error;
811 	int fat12 = FAT12(pmp);
812 	u_long bn, bo, bsize, byteoffset;
813 
814 	/*
815 	 * Mark all clusters in use, we mark the free ones in the fat scan
816 	 * loop further down.
817 	 */
818 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
819 		pmp->pm_inusemap[cn] = (u_int)-1;
820 
821 	/*
822 	 * Figure how many free clusters are in the filesystem by ripping
823 	 * through the fat counting the number of entries whose content is
824 	 * zero.  These represent free clusters.
825 	 */
826 	pmp->pm_freeclustercount = 0;
827 	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
828 		byteoffset = FATOFS(pmp, cn);
829 		bo = byteoffset % pmp->pm_fatblocksize;
830 		if (!bo || !bp) {
831 			/* Read new FAT block */
832 			if (bp)
833 				brelse(bp);
834 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
835 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
836 			if (error)
837 				return error;
838 		}
839 		readcn = getushort(&bp->b_data[bo]);
840 		if (fat12) {
841 			if (cn & 1)
842 				readcn >>= 4;
843 			readcn &= 0x0fff;
844 		}
845 
846 		if (readcn == 0)
847 			usemap_free(pmp, cn);
848 	}
849 	brelse(bp);
850 	return 0;
851 }
852 
853 /*
854  * Allocate a new cluster and chain it onto the end of the file.
855  *
856  * dep	 - the file to extend
857  * count - number of clusters to allocate
858  * bpp	 - where to return the address of the buf header for the first new
859  *	   file block
860  * ncp	 - where to put cluster number of the first newly allocated cluster
861  *	   If this pointer is 0, do not return the cluster number.
862  * flags - see fat.h
863  *
864  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
865  * the de_flag field of the denode and it does not change the de_FileSize
866  * field.  This is left for the caller to do.
867  */
868 int
869 extendfile(dep, count, bpp, ncp, flags)
870 	struct denode *dep;
871 	u_long count;
872 	struct buf **bpp;
873 	u_long *ncp;
874 	int flags;
875 {
876 	int error = 0;
877 	u_long frcn;
878 	u_long cn, got;
879 	struct msdosfsmount *pmp = dep->de_pmp;
880 	struct buf *bp;
881 
882 	/*
883 	 * Don't try to extend the root directory
884 	 */
885 	if (DETOV(dep)->v_flag & VROOT) {
886 		printf("extendfile(): attempt to extend root directory\n");
887 		return ENOSPC;
888 	}
889 
890 	/*
891 	 * If the "file's last cluster" cache entry is empty, and the file
892 	 * is not empty, then fill the cache entry by calling pcbmap().
893 	 */
894 	fc_fileextends++;
895 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
896 	    dep->de_StartCluster != 0) {
897 		fc_lfcempty++;
898 		error = pcbmap(dep, 0xffff, 0, &cn);
899 		/* we expect it to return E2BIG */
900 		if (error != E2BIG)
901 			return error;
902 		error = 0;
903 	}
904 
905 	while (count > 0) {
906 		/*
907 		 * Allocate a new cluster chain and cat onto the end of the file.
908 		 * If the file is empty we make de_StartCluster point to the new
909 		 * block.  Note that de_StartCluster being 0 is sufficient to be
910 		 * sure the file is empty since we exclude attempts to extend the
911 		 * root directory above, and the root dir is the only file with a
912 		 * startcluster of 0 that has blocks allocated (sort of).
913 		 */
914 		if (dep->de_StartCluster == 0)
915 			cn = 0;
916 		else
917 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
918 		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
919 		if (error)
920 			return error;
921 
922 		count -= got;
923 
924 		/*
925 		 * Give them the filesystem relative cluster number if they want
926 		 * it.
927 		 */
928 		if (ncp) {
929 			*ncp = cn;
930 			ncp = NULL;
931 		}
932 
933 		if (dep->de_StartCluster == 0) {
934 			dep->de_StartCluster = cn;
935 			frcn = 0;
936 		} else {
937 			error = fatentry(FAT_SET, pmp, dep->de_fc[FC_LASTFC].fc_fsrcn,
938 					 0, cn);
939 			if (error) {
940 				clusterfree(pmp, cn, NULL);
941 				return error;
942 			}
943 
944 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
945 		}
946 
947 		/*
948 		 * Update the "last cluster of the file" entry in the denode's fat
949 		 * cache.
950 		 */
951 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
952 
953 		if (flags & DE_CLEAR) {
954 			while (got-- > 0) {
955 				/*
956 				 * Get the buf header for the new block of the file.
957 				 */
958 				if (dep->de_Attributes & ATTR_DIRECTORY)
959 					bp = getblk(pmp->pm_devvp, cntobn(pmp, cn++),
960 						    pmp->pm_bpcluster, 0, 0);
961 				else {
962 					bp = getblk(DETOV(dep), frcn++, pmp->pm_bpcluster, 0, 0);
963 					/*
964 					 * Do the bmap now, as in msdosfs_write
965 					 */
966 					if (pcbmap(dep, bp->b_lblkno, &bp->b_blkno, 0))
967 						bp->b_blkno = -1;
968 					if (bp->b_blkno == -1)
969 						panic("extendfile: pcbmap");
970 				}
971 				clrbuf(bp);
972 				if (bpp) {
973 					*bpp = bp;
974 					bpp = NULL;
975 				} else {
976 					bp->b_flags |= B_AGE;
977 					bawrite(bp);
978 				}
979 			}
980 		}
981 	}
982 
983 	return 0;
984 }
985