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