xref: /dflybsd-src/sys/vfs/msdosfs/msdosfs_fat.c (revision 28e81a2874cc70f7840d5527a55b62f8caed09b8)
1 /* $FreeBSD: src/sys/msdosfs/msdosfs_fat.c,v 1.23 2000/01/27 14:43:06 nyan Exp $ */
2 /* $DragonFly: src/sys/vfs/msdosfs/msdosfs_fat.c,v 1.11 2006/12/23 00:41:29 swildner Exp $ */
3 /*	$NetBSD: msdosfs_fat.c,v 1.28 1997/11/17 15:36:49 ws Exp $	*/
4 
5 /*-
6  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
7  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
8  * All rights reserved.
9  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by TooLs GmbH.
22  * 4. The name of TooLs GmbH may not be used to endorse or promote products
23  *    derived from this software without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
26  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
27  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
28  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
29  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
31  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
32  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
33  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
34  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35  */
36 /*
37  * Written by Paul Popelka (paulp@uts.amdahl.com)
38  *
39  * You can do anything you want with this software, just don't say you wrote
40  * it, and don't remove this notice.
41  *
42  * This software is provided "as is".
43  *
44  * The author supplies this software to be publicly redistributed on the
45  * understanding that the author is not responsible for the correct
46  * functioning of this software in any circumstances and is not liable for
47  * any damages caused by this software.
48  *
49  * October 1992
50  */
51 
52 /*
53  * kernel include files.
54  */
55 #include <sys/param.h>
56 #include <sys/systm.h>
57 #include <sys/buf.h>
58 #include <sys/mount.h>		/* to define statfs structure */
59 #include <sys/vnode.h>		/* to define vattr structure */
60 
61 #include <sys/buf2.h>
62 
63 /*
64  * msdosfs include files.
65  */
66 #include "bpb.h"
67 #include "msdosfsmount.h"
68 #include "direntry.h"
69 #include "denode.h"
70 #include "fat.h"
71 
72 /*
73  * Fat cache stats.
74  */
75 static int fc_fileextends;	/* # of file extends			 */
76 static int fc_lfcempty;		/* # of time last file cluster cache entry
77 				 * was empty */
78 static int fc_bmapcalls;		/* # of times pcbmap was called		 */
79 
80 #define	LMMAX	20
81 static int fc_lmdistance[LMMAX];/* counters for how far off the last
82 				 * cluster mapped entry was. */
83 static int fc_largedistance;	/* off by more than LMMAX		 */
84 
85 static int	chainalloc (struct msdosfsmount *pmp, u_long start,
86 				u_long count, u_long fillwith,
87 				u_long *retcluster, u_long *got);
88 static int	chainlength (struct msdosfsmount *pmp, u_long start,
89 				 u_long count);
90 static void	fatblock (struct msdosfsmount *pmp, u_long ofs,
91 			      u_long *bnp, u_long *sizep, u_long *bop);
92 static int	fatchain (struct msdosfsmount *pmp, u_long start,
93 			      u_long count, u_long fillwith);
94 static void	fc_lookup (struct denode *dep, u_long findcn,
95 			       u_long *frcnp, u_long *fsrcnp);
96 static void	updatefats (struct msdosfsmount *pmp, struct buf *bp,
97 				u_long fatbn);
98 static __inline void
99 		usemap_alloc (struct msdosfsmount *pmp, u_long cn);
100 static __inline void
101 		usemap_free (struct msdosfsmount *pmp, u_long cn);
102 
103 static void
104 fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep,
105 	 u_long *bop)
106 {
107 	u_long bn, size;
108 
109 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
110 	size = min(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
111 	    * DEV_BSIZE;
112 	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
113 
114 	if (bnp)
115 		*bnp = bn;
116 	if (sizep)
117 		*sizep = size;
118 	if (bop)
119 		*bop = ofs % pmp->pm_fatblocksize;
120 }
121 
122 /*
123  * Map the logical cluster number of a file into a physical disk sector
124  * that is filesystem relative.
125  *
126  * dep	  - address of denode representing the file of interest
127  * findcn - file relative cluster whose filesystem relative cluster number
128  *	    and/or block number are/is to be found
129  * bnp	  - address of where to place the file system relative block number.
130  *	    If this pointer is null then don't return this quantity.
131  * cnp	  - address of where to place the file system relative cluster number.
132  *	    If this pointer is null then don't return this quantity.
133  *
134  * NOTE: Either bnp or cnp must be non-null.
135  * This function has one side effect.  If the requested file relative cluster
136  * is beyond the end of file, then the actual number of clusters in the file
137  * is returned in *cnp.  This is useful for determining how long a directory is.
138  *  If cnp is null, nothing is returned.
139  */
140 int
141 pcbmap(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 | ~pmp->pm_fatmask) >= CLUST_RSRVD)
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, de_bntodoff(pmp, bn), bsize, &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 		 * Force the special cluster numbers
247 		 * to be the same for all cluster sizes
248 		 * to let the rest of msdosfs handle
249 		 * all cases the same.
250 		 */
251 		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
252 			cn |= ~pmp->pm_fatmask;
253 	}
254 
255 	if (!MSDOSFSEOF(pmp, cn)) {
256 		if (bp)
257 			brelse(bp);
258 		if (bnp)
259 			*bnp = xcntobn(pmp, cn);
260 		if (cnp)
261 			*cnp = cn;
262 		fc_setcache(dep, FC_LASTMAP, i, cn);
263 		return (0);
264 	}
265 
266 hiteof:;
267 	if (cnp)
268 		*cnp = i;
269 	if (bp)
270 		brelse(bp);
271 	/* update last file cluster entry in the fat cache */
272 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
273 	return (E2BIG);
274 }
275 
276 /*
277  * Find the closest entry in the fat cache to the cluster we are looking
278  * for.
279  */
280 static void
281 fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
282 {
283 	int i;
284 	u_long cn;
285 	struct fatcache *closest = 0;
286 
287 	for (i = 0; i < FC_SIZE; i++) {
288 		cn = dep->de_fc[i].fc_frcn;
289 		if (cn != FCE_EMPTY && cn <= findcn) {
290 			if (closest == 0 || cn > closest->fc_frcn)
291 				closest = &dep->de_fc[i];
292 		}
293 	}
294 	if (closest) {
295 		*frcnp = closest->fc_frcn;
296 		*fsrcnp = closest->fc_fsrcn;
297 	}
298 }
299 
300 /*
301  * Purge the fat cache in denode dep of all entries relating to file
302  * relative cluster frcn and beyond.
303  */
304 void
305 fc_purge(struct denode *dep, u_int frcn)
306 {
307 	int i;
308 	struct fatcache *fcp;
309 
310 	fcp = dep->de_fc;
311 	for (i = 0; i < FC_SIZE; i++, fcp++) {
312 		if (fcp->fc_frcn >= frcn)
313 			fcp->fc_frcn = FCE_EMPTY;
314 	}
315 }
316 
317 /*
318  * Update the fat.
319  * If mirroring the fat, update all copies, with the first copy as last.
320  * Else update only the current fat (ignoring the others).
321  *
322  * pmp	 - msdosfsmount structure for filesystem to update
323  * bp	 - addr of modified fat block
324  * fatbn - block number relative to begin of filesystem of the modified fat block.
325  */
326 static void
327 updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
328 {
329 	int i;
330 	struct buf *bpn;
331 
332 #ifdef MSDOSFS_DEBUG
333 	kprintf("updatefats(pmp %p, bp %p, fatbn %lu)\n", pmp, bp, fatbn);
334 #endif
335 
336 	/*
337 	 * If we have an FSInfo block, update it.
338 	 */
339 	if (pmp->pm_fsinfo) {
340 		u_long cn = pmp->pm_nxtfree;
341 
342 		if (pmp->pm_freeclustercount
343 		    && (pmp->pm_inusemap[cn / N_INUSEBITS]
344 			& (1 << (cn % N_INUSEBITS)))) {
345 			/*
346 			 * The cluster indicated in FSInfo isn't free
347 			 * any longer.  Got get a new free one.
348 			 */
349 			for (cn = 0; cn < pmp->pm_maxcluster; cn += N_INUSEBITS)
350 				if (pmp->pm_inusemap[cn / N_INUSEBITS] != (u_int)-1)
351 					break;
352 			pmp->pm_nxtfree = cn
353 				+ ffs(pmp->pm_inusemap[cn / N_INUSEBITS]
354 				      ^ (u_int)-1) - 1;
355 		}
356 		if (bread(pmp->pm_devvp, de_bntodoff(pmp, pmp->pm_fsinfo), fsi_size(pmp), &bpn) != 0) {
357 			/*
358 			 * Ignore the error, but turn off FSInfo update for the future.
359 			 */
360 			pmp->pm_fsinfo = 0;
361 			brelse(bpn);
362 		} else {
363 			struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
364 
365 			putulong(fp->fsinfree, pmp->pm_freeclustercount);
366 			putulong(fp->fsinxtfree, pmp->pm_nxtfree);
367 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
368 				bwrite(bpn);
369 			else
370 				bdwrite(bpn);
371 		}
372 	}
373 
374 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
375 		/*
376 		 * Now copy the block(s) of the modified fat to the other copies of
377 		 * the fat and write them out.  This is faster than reading in the
378 		 * other fats and then writing them back out.  This could tie up
379 		 * the fat for quite a while. Preventing others from accessing it.
380 		 * To prevent us from going after the fat quite so much we use
381 		 * delayed writes, unless they specfied "synchronous" when the
382 		 * filesystem was mounted.  If synch is asked for then use
383 		 * bwrite()'s and really slow things down.
384 		 */
385 		for (i = 1; i < pmp->pm_FATs; i++) {
386 			fatbn += pmp->pm_FATsecs;
387 			/* getblk() never fails */
388 			bpn = getblk(pmp->pm_devvp, de_bntodoff(pmp, fatbn),
389 				     bp->b_bcount, 0, 0);
390 			bcopy(bp->b_data, bpn->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(struct msdosfsmount *pmp, u_long cn)
431 {
432 
433 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
434 	pmp->pm_freeclustercount--;
435 }
436 
437 static __inline void
438 usemap_free(struct msdosfsmount *pmp, u_long cn)
439 {
440 
441 	pmp->pm_freeclustercount++;
442 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
443 }
444 
445 int
446 clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
447 {
448 	int error;
449 	u_long oldcn;
450 
451 	usemap_free(pmp, cluster);
452 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
453 	if (error) {
454 		usemap_alloc(pmp, cluster);
455 		return (error);
456 	}
457 	/*
458 	 * If the cluster was successfully marked free, then update
459 	 * the count of free clusters, and turn off the "allocated"
460 	 * bit in the "in use" cluster bit map.
461 	 */
462 	if (oldcnp)
463 		*oldcnp = oldcn;
464 	return (0);
465 }
466 
467 /*
468  * Get or Set or 'Get and Set' the cluster'th entry in the fat.
469  *
470  * function	- whether to get or set a fat entry
471  * pmp		- address of the msdosfsmount structure for the filesystem
472  *		  whose fat is to be manipulated.
473  * cn		- which cluster is of interest
474  * oldcontents	- address of a word that is to receive the contents of the
475  *		  cluster'th entry if this is a get function
476  * newcontents	- the new value to be written into the cluster'th element of
477  *		  the fat if this is a set function.
478  *
479  * This function can also be used to free a cluster by setting the fat entry
480  * for a cluster to 0.
481  *
482  * All copies of the fat are updated if this is a set function. NOTE: If
483  * fatentry() marks a cluster as free it does not update the inusemap in
484  * the msdosfsmount structure. This is left to the caller.
485  */
486 int
487 fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents,
488 	 u_long newcontents)
489 {
490 	int error;
491 	u_long readcn;
492 	u_long bn, bo, bsize, byteoffset;
493 	struct buf *bp;
494 
495 #ifdef	MSDOSFS_DEBUG
496 	kprintf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
497 	     function, pmp, cn, oldcontents, newcontents);
498 #endif
499 
500 #ifdef DIAGNOSTIC
501 	/*
502 	 * Be sure they asked us to do something.
503 	 */
504 	if ((function & (FAT_SET | FAT_GET)) == 0) {
505 		kprintf("fatentry(): function code doesn't specify get or set\n");
506 		return (EINVAL);
507 	}
508 
509 	/*
510 	 * If they asked us to return a cluster number but didn't tell us
511 	 * where to put it, give them an error.
512 	 */
513 	if ((function & FAT_GET) && oldcontents == NULL) {
514 		kprintf("fatentry(): get function with no place to put result\n");
515 		return (EINVAL);
516 	}
517 #endif
518 
519 	/*
520 	 * Be sure the requested cluster is in the filesystem.
521 	 */
522 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
523 		return (EINVAL);
524 
525 	byteoffset = FATOFS(pmp, cn);
526 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
527 	error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
528 	if (error) {
529 		brelse(bp);
530 		return (error);
531 	}
532 
533 	if (function & FAT_GET) {
534 		if (FAT32(pmp))
535 			readcn = getulong(&bp->b_data[bo]);
536 		else
537 			readcn = getushort(&bp->b_data[bo]);
538 		if (FAT12(pmp) & (cn & 1))
539 			readcn >>= 4;
540 		readcn &= pmp->pm_fatmask;
541 		/* map reserved fat entries to same values for all fats */
542 		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
543 			readcn |= ~pmp->pm_fatmask;
544 		*oldcontents = readcn;
545 	}
546 	if (function & FAT_SET) {
547 		switch (pmp->pm_fatmask) {
548 		case FAT12_MASK:
549 			readcn = getushort(&bp->b_data[bo]);
550 			if (cn & 1) {
551 				readcn &= 0x000f;
552 				readcn |= newcontents << 4;
553 			} else {
554 				readcn &= 0xf000;
555 				readcn |= newcontents & 0xfff;
556 			}
557 			putushort(&bp->b_data[bo], readcn);
558 			break;
559 		case FAT16_MASK:
560 			putushort(&bp->b_data[bo], newcontents);
561 			break;
562 		case FAT32_MASK:
563 			/*
564 			 * According to spec we have to retain the
565 			 * high order bits of the fat entry.
566 			 */
567 			readcn = getulong(&bp->b_data[bo]);
568 			readcn &= ~FAT32_MASK;
569 			readcn |= newcontents & FAT32_MASK;
570 			putulong(&bp->b_data[bo], readcn);
571 			break;
572 		}
573 		updatefats(pmp, bp, bn);
574 		bp = NULL;
575 		pmp->pm_fmod = 1;
576 	}
577 	if (bp)
578 		brelse(bp);
579 	return (0);
580 }
581 
582 /*
583  * Update a contiguous cluster chain
584  *
585  * pmp	    - mount point
586  * start    - first cluster of chain
587  * count    - number of clusters in chain
588  * fillwith - what to write into fat entry of last cluster
589  */
590 static int
591 fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
592 {
593 	int error;
594 	u_long bn, bo, bsize, byteoffset, readcn, newc;
595 	struct buf *bp;
596 
597 #ifdef MSDOSFS_DEBUG
598 	kprintf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
599 	    pmp, start, count, fillwith);
600 #endif
601 	/*
602 	 * Be sure the clusters are in the filesystem.
603 	 */
604 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
605 		return (EINVAL);
606 
607 	while (count > 0) {
608 		byteoffset = FATOFS(pmp, start);
609 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
610 		error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
611 		if (error) {
612 			brelse(bp);
613 			return (error);
614 		}
615 		while (count > 0) {
616 			start++;
617 			newc = --count > 0 ? start : fillwith;
618 			switch (pmp->pm_fatmask) {
619 			case FAT12_MASK:
620 				readcn = getushort(&bp->b_data[bo]);
621 				if (start & 1) {
622 					readcn &= 0xf000;
623 					readcn |= newc & 0xfff;
624 				} else {
625 					readcn &= 0x000f;
626 					readcn |= newc << 4;
627 				}
628 				putushort(&bp->b_data[bo], readcn);
629 				bo++;
630 				if (!(start & 1))
631 					bo++;
632 				break;
633 			case FAT16_MASK:
634 				putushort(&bp->b_data[bo], newc);
635 				bo += 2;
636 				break;
637 			case FAT32_MASK:
638 				readcn = getulong(&bp->b_data[bo]);
639 				readcn &= ~pmp->pm_fatmask;
640 				readcn |= newc & pmp->pm_fatmask;
641 				putulong(&bp->b_data[bo], readcn);
642 				bo += 4;
643 				break;
644 			}
645 			if (bo >= bsize)
646 				break;
647 		}
648 		updatefats(pmp, bp, bn);
649 	}
650 	pmp->pm_fmod = 1;
651 	return (0);
652 }
653 
654 /*
655  * Check the length of a free cluster chain starting at start.
656  *
657  * pmp	 - mount point
658  * start - start of chain
659  * count - maximum interesting length
660  */
661 static int
662 chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
663 {
664 	u_long idx, max_idx;
665 	u_int map;
666 	u_long len;
667 
668 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
669 	idx = start / N_INUSEBITS;
670 	start %= N_INUSEBITS;
671 	map = pmp->pm_inusemap[idx];
672 	map &= ~((1 << start) - 1);
673 	if (map) {
674 		len = ffs(map) - 1 - start;
675 		return (len > count ? count : len);
676 	}
677 	len = N_INUSEBITS - start;
678 	if (len >= count)
679 		return (count);
680 	while (++idx <= max_idx) {
681 		if (len >= count)
682 			break;
683 		map = pmp->pm_inusemap[idx];
684 		if (map) {
685 			len +=  ffs(map) - 1;
686 			break;
687 		}
688 		len += N_INUSEBITS;
689 	}
690 	return (len > count ? count : len);
691 }
692 
693 /*
694  * Allocate contigous free clusters.
695  *
696  * pmp	      - mount point.
697  * start      - start of cluster chain.
698  * count      - number of clusters to allocate.
699  * fillwith   - put this value into the fat entry for the
700  *		last allocated cluster.
701  * retcluster - put the first allocated cluster's number here.
702  * got	      - how many clusters were actually allocated.
703  */
704 static int
705 chainalloc(struct msdosfsmount *pmp, u_long start, u_long count,
706 	   u_long fillwith, u_long *retcluster, u_long *got)
707 {
708 	int error;
709 	u_long cl, n;
710 
711 	for (cl = start, n = count; n-- > 0;)
712 		usemap_alloc(pmp, cl++);
713 
714 	error = fatchain(pmp, start, count, fillwith);
715 	if (error != 0)
716 		return (error);
717 #ifdef MSDOSFS_DEBUG
718 	kprintf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
719 	    start, count);
720 #endif
721 	if (retcluster)
722 		*retcluster = start;
723 	if (got)
724 		*got = count;
725 	return (0);
726 }
727 
728 /*
729  * Allocate contiguous free clusters.
730  *
731  * pmp	      - mount point.
732  * start      - preferred start of cluster chain.
733  * count      - number of clusters requested.
734  * fillwith   - put this value into the fat entry for the
735  *		last allocated cluster.
736  * retcluster - put the first allocated cluster's number here.
737  * got	      - how many clusters were actually allocated.
738  */
739 int
740 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
741 	     u_long fillwith, u_long *retcluster, u_long *got)
742 {
743 	u_long idx;
744 	u_long len, newst, foundl, cn, l;
745 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
746 	u_int map;
747 
748 #ifdef MSDOSFS_DEBUG
749 	kprintf("clusteralloc(): find %lu clusters\n",count);
750 #endif
751 	if (start) {
752 		if ((len = chainlength(pmp, start, count)) >= count)
753 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
754 	} else
755 		len = 0;
756 
757 	/*
758 	 * Start at a (pseudo) random place to maximize cluster runs
759 	 * under multiple writers.
760 	 */
761 	newst = krandom() % (pmp->pm_maxcluster + 1);
762 	foundl = 0;
763 
764 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
765 		idx = cn / N_INUSEBITS;
766 		map = pmp->pm_inusemap[idx];
767 		map |= (1 << (cn % N_INUSEBITS)) - 1;
768 		if (map != (u_int)-1) {
769 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
770 			if ((l = chainlength(pmp, cn, count)) >= count)
771 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
772 			if (l > foundl) {
773 				foundcn = cn;
774 				foundl = l;
775 			}
776 			cn += l + 1;
777 			continue;
778 		}
779 		cn += N_INUSEBITS - cn % N_INUSEBITS;
780 	}
781 	for (cn = 0; cn < newst;) {
782 		idx = cn / N_INUSEBITS;
783 		map = pmp->pm_inusemap[idx];
784 		map |= (1 << (cn % N_INUSEBITS)) - 1;
785 		if (map != (u_int)-1) {
786 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
787 			if ((l = chainlength(pmp, cn, count)) >= count)
788 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
789 			if (l > foundl) {
790 				foundcn = cn;
791 				foundl = l;
792 			}
793 			cn += l + 1;
794 			continue;
795 		}
796 		cn += N_INUSEBITS - cn % N_INUSEBITS;
797 	}
798 
799 	if (!foundl)
800 		return (ENOSPC);
801 
802 	if (len)
803 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
804 	else
805 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
806 }
807 
808 
809 /*
810  * Free a chain of clusters.
811  *
812  * pmp		- address of the msdosfs mount structure for the filesystem
813  *		  containing the cluster chain to be freed.
814  * startcluster - number of the 1st cluster in the chain of clusters to be
815  *		  freed.
816  */
817 int
818 freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
819 {
820 	int error;
821 	struct buf *bp = NULL;
822 	u_long bn, bo, bsize, byteoffset;
823 	u_long readcn, lbn = -1;
824 
825 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
826 		byteoffset = FATOFS(pmp, cluster);
827 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
828 		if (lbn != bn) {
829 			if (bp)
830 				updatefats(pmp, bp, lbn);
831 			error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
832 			if (error) {
833 				brelse(bp);
834 				return (error);
835 			}
836 			lbn = bn;
837 		}
838 		usemap_free(pmp, cluster);
839 		switch (pmp->pm_fatmask) {
840 		case FAT12_MASK:
841 			readcn = getushort(&bp->b_data[bo]);
842 			if (cluster & 1) {
843 				cluster = readcn >> 4;
844 				readcn &= 0x000f;
845 				readcn |= MSDOSFSFREE << 4;
846 			} else {
847 				cluster = readcn;
848 				readcn &= 0xf000;
849 				readcn |= MSDOSFSFREE & 0xfff;
850 			}
851 			putushort(&bp->b_data[bo], readcn);
852 			break;
853 		case FAT16_MASK:
854 			cluster = getushort(&bp->b_data[bo]);
855 			putushort(&bp->b_data[bo], MSDOSFSFREE);
856 			break;
857 		case FAT32_MASK:
858 			cluster = getulong(&bp->b_data[bo]);
859 			putulong(&bp->b_data[bo],
860 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
861 			break;
862 		}
863 		cluster &= pmp->pm_fatmask;
864 		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
865 			cluster |= pmp->pm_fatmask;
866 	}
867 	if (bp)
868 		updatefats(pmp, bp, bn);
869 	return (0);
870 }
871 
872 /*
873  * Read in fat blocks looking for free clusters. For every free cluster
874  * found turn off its corresponding bit in the pm_inusemap.
875  */
876 int
877 fillinusemap(struct msdosfsmount *pmp)
878 {
879 	struct buf *bp = NULL;
880 	u_long cn, readcn;
881 	int error;
882 	u_long bn, bo, bsize, byteoffset;
883 
884 	/*
885 	 * Mark all clusters in use, we mark the free ones in the fat scan
886 	 * loop further down.
887 	 */
888 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
889 		pmp->pm_inusemap[cn] = (u_int)-1;
890 
891 	/*
892 	 * Figure how many free clusters are in the filesystem by ripping
893 	 * through the fat counting the number of entries whose content is
894 	 * zero.  These represent free clusters.
895 	 */
896 	pmp->pm_freeclustercount = 0;
897 	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
898 		byteoffset = FATOFS(pmp, cn);
899 		bo = byteoffset % pmp->pm_fatblocksize;
900 		if (!bo || !bp) {
901 			/* Read new FAT block */
902 			if (bp)
903 				brelse(bp);
904 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
905 			error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
906 			if (error) {
907 				brelse(bp);
908 				return (error);
909 			}
910 		}
911 		if (FAT32(pmp))
912 			readcn = getulong(&bp->b_data[bo]);
913 		else
914 			readcn = getushort(&bp->b_data[bo]);
915 		if (FAT12(pmp) && (cn & 1))
916 			readcn >>= 4;
917 		readcn &= pmp->pm_fatmask;
918 
919 		if (readcn == 0)
920 			usemap_free(pmp, cn);
921 	}
922 	brelse(bp);
923 	return (0);
924 }
925 
926 /*
927  * Allocate a new cluster and chain it onto the end of the file.
928  *
929  * dep	 - the file to extend
930  * count - number of clusters to allocate
931  * bpp	 - where to return the address of the buf header for the first new
932  *	   file block
933  * ncp	 - where to put cluster number of the first newly allocated cluster
934  *	   If this pointer is 0, do not return the cluster number.
935  * flags - see fat.h
936  *
937  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
938  * the de_flag field of the denode and it does not change the de_FileSize
939  * field.  This is left for the caller to do.
940  */
941 int
942 extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp,
943 	   int flags)
944 {
945 	int error;
946 	u_long frcn;
947 	u_long cn, got;
948 	struct msdosfsmount *pmp = dep->de_pmp;
949 	struct buf *bp;
950 
951 	/*
952 	 * Don't try to extend the root directory
953 	 */
954 	if (dep->de_StartCluster == MSDOSFSROOT
955 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
956 		kprintf("extendfile(): attempt to extend root directory\n");
957 		return (ENOSPC);
958 	}
959 
960 	/*
961 	 * If the "file's last cluster" cache entry is empty, and the file
962 	 * is not empty, then fill the cache entry by calling pcbmap().
963 	 */
964 	fc_fileextends++;
965 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
966 	    dep->de_StartCluster != 0) {
967 		fc_lfcempty++;
968 		error = pcbmap(dep, 0xffff, NULL, &cn, NULL);
969 		/* we expect it to return E2BIG */
970 		if (error != E2BIG)
971 			return (error);
972 	}
973 
974 	while (count > 0) {
975 		/*
976 		 * Allocate a new cluster chain and cat onto the end of the
977 		 * file.  * If the file is empty we make de_StartCluster point
978 		 * to the new block.  Note that de_StartCluster being 0 is
979 		 * sufficient to be sure the file is empty since we exclude
980 		 * attempts to extend the root directory above, and the root
981 		 * dir is the only file with a startcluster of 0 that has
982 		 * blocks allocated (sort of).
983 		 */
984 		if (dep->de_StartCluster == 0)
985 			cn = 0;
986 		else
987 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
988 		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
989 		if (error)
990 			return (error);
991 
992 		count -= got;
993 
994 		/*
995 		 * Give them the filesystem relative cluster number if they want
996 		 * it.
997 		 */
998 		if (ncp) {
999 			*ncp = cn;
1000 			ncp = NULL;
1001 		}
1002 
1003 		if (dep->de_StartCluster == 0) {
1004 			dep->de_StartCluster = cn;
1005 			frcn = 0;
1006 		} else {
1007 			error = fatentry(FAT_SET, pmp,
1008 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
1009 					 0, cn);
1010 			if (error) {
1011 				clusterfree(pmp, cn, NULL);
1012 				return (error);
1013 			}
1014 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1015 		}
1016 
1017 		/*
1018 		 * Update the "last cluster of the file" entry in the
1019 		 * denode's fat cache.
1020 		 */
1021 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1022 
1023 		if (flags & DE_CLEAR) {
1024 			while (got-- > 0) {
1025 				/*
1026 				 * Get the buf header for the new block of the file.
1027 				 */
1028 				if (dep->de_Attributes & ATTR_DIRECTORY) {
1029 					bp = getblk(pmp->pm_devvp,
1030 						    xcntodoff(pmp, cn),
1031 						    pmp->pm_bpcluster, 0, 0);
1032 					++cn;
1033 				} else {
1034 					daddr_t dblkno;
1035 
1036 					bp = getblk(DETOV(dep),
1037 						    de_cn2doff(pmp, frcn),
1038 						    pmp->pm_bpcluster, 0, 0);
1039 					++frcn;
1040 					/*
1041 					 * Do the bmap now, as in msdosfs_write
1042 					 */
1043 					if (pcbmap(dep,
1044 					    de_bn2cn(pmp, de_off2bn(pmp, bp->b_bio1.bio_offset)),
1045 					    &dblkno, NULL, NULL)) {
1046 						bp->b_bio2.bio_offset = NOOFFSET;
1047 					} else {
1048 						bp->b_bio2.bio_offset = de_bntodoff(pmp, dblkno);
1049 					}
1050 					if (bp->b_bio2.bio_offset == NOOFFSET)
1051 						panic("extendfile: pcbmap");
1052 				}
1053 				clrbuf(bp);
1054 				if (bpp) {
1055 					*bpp = bp;
1056 					bpp = NULL;
1057 				} else
1058 					bdwrite(bp);
1059 			}
1060 		}
1061 	}
1062 
1063 	return (0);
1064 }
1065