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