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