xref: /freebsd/sys/fs/msdosfs/msdosfs_fat.c (revision aa0a1e58)
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 	int i;
325 	struct buf *bpn;
326 
327 #ifdef MSDOSFS_DEBUG
328 	printf("updatefats(pmp %p, bp %p, fatbn %lu)\n", pmp, bp, fatbn);
329 #endif
330 
331 	/*
332 	 * If we have an FSInfo block, update it.
333 	 */
334 	if (pmp->pm_fsinfo) {
335 		if (bread(pmp->pm_devvp, pmp->pm_fsinfo, pmp->pm_BytesPerSec,
336 		    NOCRED, &bpn) != 0) {
337 			/*
338 			 * Ignore the error, but turn off FSInfo update for the future.
339 			 */
340 			pmp->pm_fsinfo = 0;
341 			brelse(bpn);
342 		} else {
343 			struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
344 
345 			putulong(fp->fsinfree, pmp->pm_freeclustercount);
346 			putulong(fp->fsinxtfree, pmp->pm_nxtfree);
347 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
348 				bwrite(bpn);
349 			else
350 				bdwrite(bpn);
351 		}
352 	}
353 
354 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
355 		/*
356 		 * Now copy the block(s) of the modified fat to the other copies of
357 		 * the fat and write them out.  This is faster than reading in the
358 		 * other fats and then writing them back out.  This could tie up
359 		 * the fat for quite a while. Preventing others from accessing it.
360 		 * To prevent us from going after the fat quite so much we use
361 		 * delayed writes, unless they specfied "synchronous" when the
362 		 * filesystem was mounted.  If synch is asked for then use
363 		 * bwrite()'s and really slow things down.
364 		 */
365 		for (i = 1; i < pmp->pm_FATs; i++) {
366 			fatbn += pmp->pm_FATsecs;
367 			/* getblk() never fails */
368 			bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount,
369 			    0, 0, 0);
370 			bcopy(bp->b_data, bpn->b_data, bp->b_bcount);
371 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
372 				bwrite(bpn);
373 			else
374 				bdwrite(bpn);
375 		}
376 	}
377 
378 	/*
379 	 * Write out the first (or current) fat last.
380 	 */
381 	if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
382 		bwrite(bp);
383 	else
384 		bdwrite(bp);
385 	/*
386 	 * Maybe update fsinfo sector here?
387 	 */
388 }
389 
390 /*
391  * Updating entries in 12 bit fats is a pain in the butt.
392  *
393  * The following picture shows where nibbles go when moving from a 12 bit
394  * cluster number into the appropriate bytes in the FAT.
395  *
396  *	byte m        byte m+1      byte m+2
397  *	+----+----+   +----+----+   +----+----+
398  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
399  *	+----+----+   +----+----+   +----+----+
400  *
401  *	+----+----+----+   +----+----+----+
402  *	|  3    0    1 |   |  4    5    2 |
403  *	+----+----+----+   +----+----+----+
404  *	cluster n  	   cluster n+1
405  *
406  * Where n is even. m = n + (n >> 2)
407  *
408  */
409 static __inline void
410 usemap_alloc(pmp, cn)
411 	struct msdosfsmount *pmp;
412 	u_long cn;
413 {
414 
415 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
416 
417 	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] & (1 << (cn % N_INUSEBITS)))
418 	    == 0, ("Allocating used sector %ld %ld %x", cn, cn % N_INUSEBITS,
419 		(unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
420 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
421 	KASSERT(pmp->pm_freeclustercount > 0, ("usemap_alloc: too little"));
422 	pmp->pm_freeclustercount--;
423 }
424 
425 static __inline void
426 usemap_free(pmp, cn)
427 	struct msdosfsmount *pmp;
428 	u_long cn;
429 {
430 
431 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
432 	pmp->pm_freeclustercount++;
433 	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] & (1 << (cn % N_INUSEBITS)))
434 	    != 0, ("Freeing unused sector %ld %ld %x", cn, cn % N_INUSEBITS,
435 		(unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
436 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
437 }
438 
439 int
440 clusterfree(pmp, cluster, oldcnp)
441 	struct msdosfsmount *pmp;
442 	u_long cluster;
443 	u_long *oldcnp;
444 {
445 	int error;
446 	u_long oldcn;
447 
448 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
449 	if (error)
450 		return (error);
451 	/*
452 	 * If the cluster was successfully marked free, then update
453 	 * the count of free clusters, and turn off the "allocated"
454 	 * bit in the "in use" cluster bit map.
455 	 */
456 	MSDOSFS_LOCK_MP(pmp);
457 	usemap_free(pmp, cluster);
458 	MSDOSFS_UNLOCK_MP(pmp);
459 	if (oldcnp)
460 		*oldcnp = oldcn;
461 	return (0);
462 }
463 
464 /*
465  * Get or Set or 'Get and Set' the cluster'th entry in the fat.
466  *
467  * function	- whether to get or set a fat entry
468  * pmp		- address of the msdosfsmount structure for the filesystem
469  *		  whose fat is to be manipulated.
470  * cn		- which cluster is of interest
471  * oldcontents	- address of a word that is to receive the contents of the
472  *		  cluster'th entry if this is a get function
473  * newcontents	- the new value to be written into the cluster'th element of
474  *		  the fat if this is a set function.
475  *
476  * This function can also be used to free a cluster by setting the fat entry
477  * for a cluster to 0.
478  *
479  * All copies of the fat are updated if this is a set function. NOTE: If
480  * fatentry() marks a cluster as free it does not update the inusemap in
481  * the msdosfsmount structure. This is left to the caller.
482  */
483 int
484 fatentry(function, pmp, cn, oldcontents, newcontents)
485 	int function;
486 	struct msdosfsmount *pmp;
487 	u_long cn;
488 	u_long *oldcontents;
489 	u_long newcontents;
490 {
491 	int error;
492 	u_long readcn;
493 	u_long bn, bo, bsize, byteoffset;
494 	struct buf *bp;
495 
496 #ifdef	MSDOSFS_DEBUG
497 	printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
498 	    function, pmp, cn, oldcontents, newcontents);
499 #endif
500 
501 #ifdef DIAGNOSTIC
502 	/*
503 	 * Be sure they asked us to do something.
504 	 */
505 	if ((function & (FAT_SET | FAT_GET)) == 0) {
506 		printf("fatentry(): function code doesn't specify get or set\n");
507 		return (EINVAL);
508 	}
509 
510 	/*
511 	 * If they asked us to return a cluster number but didn't tell us
512 	 * where to put it, give them an error.
513 	 */
514 	if ((function & FAT_GET) && oldcontents == NULL) {
515 		printf("fatentry(): get function with no place to put result\n");
516 		return (EINVAL);
517 	}
518 #endif
519 
520 	/*
521 	 * Be sure the requested cluster is in the filesystem.
522 	 */
523 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
524 		return (EINVAL);
525 
526 	byteoffset = FATOFS(pmp, cn);
527 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
528 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
529 	if (error) {
530 		brelse(bp);
531 		return (error);
532 	}
533 
534 	if (function & FAT_GET) {
535 		if (FAT32(pmp))
536 			readcn = getulong(&bp->b_data[bo]);
537 		else
538 			readcn = getushort(&bp->b_data[bo]);
539 		if (FAT12(pmp) & (cn & 1))
540 			readcn >>= 4;
541 		readcn &= pmp->pm_fatmask;
542 		/* map reserved fat entries to same values for all fats */
543 		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
544 			readcn |= ~pmp->pm_fatmask;
545 		*oldcontents = readcn;
546 	}
547 	if (function & FAT_SET) {
548 		switch (pmp->pm_fatmask) {
549 		case FAT12_MASK:
550 			readcn = getushort(&bp->b_data[bo]);
551 			if (cn & 1) {
552 				readcn &= 0x000f;
553 				readcn |= newcontents << 4;
554 			} else {
555 				readcn &= 0xf000;
556 				readcn |= newcontents & 0xfff;
557 			}
558 			putushort(&bp->b_data[bo], readcn);
559 			break;
560 		case FAT16_MASK:
561 			putushort(&bp->b_data[bo], newcontents);
562 			break;
563 		case FAT32_MASK:
564 			/*
565 			 * According to spec we have to retain the
566 			 * high order bits of the fat entry.
567 			 */
568 			readcn = getulong(&bp->b_data[bo]);
569 			readcn &= ~FAT32_MASK;
570 			readcn |= newcontents & FAT32_MASK;
571 			putulong(&bp->b_data[bo], readcn);
572 			break;
573 		}
574 		updatefats(pmp, bp, bn);
575 		bp = NULL;
576 		pmp->pm_fmod = 1;
577 	}
578 	if (bp)
579 		brelse(bp);
580 	return (0);
581 }
582 
583 /*
584  * Update a contiguous cluster chain
585  *
586  * pmp	    - mount point
587  * start    - first cluster of chain
588  * count    - number of clusters in chain
589  * fillwith - what to write into fat entry of last cluster
590  */
591 static int
592 fatchain(pmp, start, count, fillwith)
593 	struct msdosfsmount *pmp;
594 	u_long start;
595 	u_long count;
596 	u_long fillwith;
597 {
598 	int error;
599 	u_long bn, bo, bsize, byteoffset, readcn, newc;
600 	struct buf *bp;
601 
602 #ifdef MSDOSFS_DEBUG
603 	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
604 	    pmp, start, count, fillwith);
605 #endif
606 	/*
607 	 * Be sure the clusters are in the filesystem.
608 	 */
609 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
610 		return (EINVAL);
611 
612 	while (count > 0) {
613 		byteoffset = FATOFS(pmp, start);
614 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
615 		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
616 		if (error) {
617 			brelse(bp);
618 			return (error);
619 		}
620 		while (count > 0) {
621 			start++;
622 			newc = --count > 0 ? start : fillwith;
623 			switch (pmp->pm_fatmask) {
624 			case FAT12_MASK:
625 				readcn = getushort(&bp->b_data[bo]);
626 				if (start & 1) {
627 					readcn &= 0xf000;
628 					readcn |= newc & 0xfff;
629 				} else {
630 					readcn &= 0x000f;
631 					readcn |= newc << 4;
632 				}
633 				putushort(&bp->b_data[bo], readcn);
634 				bo++;
635 				if (!(start & 1))
636 					bo++;
637 				break;
638 			case FAT16_MASK:
639 				putushort(&bp->b_data[bo], newc);
640 				bo += 2;
641 				break;
642 			case FAT32_MASK:
643 				readcn = getulong(&bp->b_data[bo]);
644 				readcn &= ~pmp->pm_fatmask;
645 				readcn |= newc & pmp->pm_fatmask;
646 				putulong(&bp->b_data[bo], readcn);
647 				bo += 4;
648 				break;
649 			}
650 			if (bo >= bsize)
651 				break;
652 		}
653 		updatefats(pmp, bp, bn);
654 	}
655 	pmp->pm_fmod = 1;
656 	return (0);
657 }
658 
659 /*
660  * Check the length of a free cluster chain starting at start.
661  *
662  * pmp	 - mount point
663  * start - start of chain
664  * count - maximum interesting length
665  */
666 static int
667 chainlength(pmp, start, count)
668 	struct msdosfsmount *pmp;
669 	u_long start;
670 	u_long count;
671 {
672 	u_long idx, max_idx;
673 	u_int map;
674 	u_long len;
675 
676 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
677 
678 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
679 	idx = start / N_INUSEBITS;
680 	start %= N_INUSEBITS;
681 	map = pmp->pm_inusemap[idx];
682 	map &= ~((1 << start) - 1);
683 	if (map) {
684 		len = ffs(map) - 1 - start;
685 		return (len > count ? count : len);
686 	}
687 	len = N_INUSEBITS - start;
688 	if (len >= count)
689 		return (count);
690 	while (++idx <= max_idx) {
691 		if (len >= count)
692 			break;
693 		map = pmp->pm_inusemap[idx];
694 		if (map) {
695 			len += ffs(map) - 1;
696 			break;
697 		}
698 		len += N_INUSEBITS;
699 	}
700 	return (len > count ? count : len);
701 }
702 
703 /*
704  * Allocate contigous free clusters.
705  *
706  * pmp	      - mount point.
707  * start      - start of cluster chain.
708  * count      - number of clusters to allocate.
709  * fillwith   - put this value into the fat entry for the
710  *		last allocated cluster.
711  * retcluster - put the first allocated cluster's number here.
712  * got	      - how many clusters were actually allocated.
713  */
714 static int
715 chainalloc(pmp, start, count, fillwith, retcluster, got)
716 	struct msdosfsmount *pmp;
717 	u_long start;
718 	u_long count;
719 	u_long fillwith;
720 	u_long *retcluster;
721 	u_long *got;
722 {
723 	int error;
724 	u_long cl, n;
725 
726 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
727 
728 	for (cl = start, n = count; n-- > 0;)
729 		usemap_alloc(pmp, cl++);
730 
731 	error = fatchain(pmp, start, count, fillwith);
732 	if (error != 0)
733 		return (error);
734 #ifdef MSDOSFS_DEBUG
735 	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
736 	    start, count);
737 #endif
738 	if (retcluster)
739 		*retcluster = start;
740 	if (got)
741 		*got = count;
742 	pmp->pm_nxtfree = start + count;
743 	if (pmp->pm_nxtfree > pmp->pm_maxcluster)
744 		pmp->pm_nxtfree = CLUST_FIRST;
745 	return (0);
746 }
747 
748 /*
749  * Allocate contiguous free clusters.
750  *
751  * pmp	      - mount point.
752  * start      - preferred start of cluster chain.
753  * count      - number of clusters requested.
754  * fillwith   - put this value into the fat entry for the
755  *		last allocated cluster.
756  * retcluster - put the first allocated cluster's number here.
757  * got	      - how many clusters were actually allocated.
758  */
759 int
760 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
761     u_long fillwith, u_long *retcluster, u_long *got)
762 {
763 	int error;
764 
765 	MSDOSFS_LOCK_MP(pmp);
766 	error = clusteralloc1(pmp, start, count, fillwith, retcluster, got);
767 	MSDOSFS_UNLOCK_MP(pmp);
768 	return (error);
769 }
770 
771 static int
772 clusteralloc1(struct msdosfsmount *pmp, u_long start, u_long count,
773     u_long fillwith, u_long *retcluster, u_long *got)
774 {
775 	u_long idx;
776 	u_long len, newst, foundl, cn, l;
777 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
778 	u_int map;
779 
780 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
781 
782 #ifdef MSDOSFS_DEBUG
783 	printf("clusteralloc(): find %lu clusters\n", count);
784 #endif
785 	if (start) {
786 		if ((len = chainlength(pmp, start, count)) >= count)
787 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
788 	} else
789 		len = 0;
790 
791 	newst = pmp->pm_nxtfree;
792 	foundl = 0;
793 
794 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
795 		idx = cn / N_INUSEBITS;
796 		map = pmp->pm_inusemap[idx];
797 		map |= (1 << (cn % N_INUSEBITS)) - 1;
798 		if (map != (u_int)-1) {
799 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
800 			if ((l = chainlength(pmp, cn, count)) >= count)
801 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
802 			if (l > foundl) {
803 				foundcn = cn;
804 				foundl = l;
805 			}
806 			cn += l + 1;
807 			continue;
808 		}
809 		cn += N_INUSEBITS - cn % N_INUSEBITS;
810 	}
811 	for (cn = 0; cn < newst;) {
812 		idx = cn / N_INUSEBITS;
813 		map = pmp->pm_inusemap[idx];
814 		map |= (1 << (cn % N_INUSEBITS)) - 1;
815 		if (map != (u_int)-1) {
816 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
817 			if ((l = chainlength(pmp, cn, count)) >= count)
818 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
819 			if (l > foundl) {
820 				foundcn = cn;
821 				foundl = l;
822 			}
823 			cn += l + 1;
824 			continue;
825 		}
826 		cn += N_INUSEBITS - cn % N_INUSEBITS;
827 	}
828 
829 	if (!foundl)
830 		return (ENOSPC);
831 
832 	if (len)
833 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
834 	else
835 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
836 }
837 
838 
839 /*
840  * Free a chain of clusters.
841  *
842  * pmp		- address of the msdosfs mount structure for the filesystem
843  *		  containing the cluster chain to be freed.
844  * startcluster - number of the 1st cluster in the chain of clusters to be
845  *		  freed.
846  */
847 int
848 freeclusterchain(pmp, cluster)
849 	struct msdosfsmount *pmp;
850 	u_long cluster;
851 {
852 	int error;
853 	struct buf *bp = NULL;
854 	u_long bn, bo, bsize, byteoffset;
855 	u_long readcn, lbn = -1;
856 
857 	MSDOSFS_LOCK_MP(pmp);
858 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
859 		byteoffset = FATOFS(pmp, cluster);
860 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
861 		if (lbn != bn) {
862 			if (bp)
863 				updatefats(pmp, bp, lbn);
864 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
865 			if (error) {
866 				brelse(bp);
867 				MSDOSFS_UNLOCK_MP(pmp);
868 				return (error);
869 			}
870 			lbn = bn;
871 		}
872 		usemap_free(pmp, cluster);
873 		switch (pmp->pm_fatmask) {
874 		case FAT12_MASK:
875 			readcn = getushort(&bp->b_data[bo]);
876 			if (cluster & 1) {
877 				cluster = readcn >> 4;
878 				readcn &= 0x000f;
879 				readcn |= MSDOSFSFREE << 4;
880 			} else {
881 				cluster = readcn;
882 				readcn &= 0xf000;
883 				readcn |= MSDOSFSFREE & 0xfff;
884 			}
885 			putushort(&bp->b_data[bo], readcn);
886 			break;
887 		case FAT16_MASK:
888 			cluster = getushort(&bp->b_data[bo]);
889 			putushort(&bp->b_data[bo], MSDOSFSFREE);
890 			break;
891 		case FAT32_MASK:
892 			cluster = getulong(&bp->b_data[bo]);
893 			putulong(&bp->b_data[bo],
894 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
895 			break;
896 		}
897 		cluster &= pmp->pm_fatmask;
898 		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
899 			cluster |= pmp->pm_fatmask;
900 	}
901 	if (bp)
902 		updatefats(pmp, bp, bn);
903 	MSDOSFS_UNLOCK_MP(pmp);
904 	return (0);
905 }
906 
907 /*
908  * Read in fat blocks looking for free clusters. For every free cluster
909  * found turn off its corresponding bit in the pm_inusemap.
910  */
911 int
912 fillinusemap(pmp)
913 	struct msdosfsmount *pmp;
914 {
915 	struct buf *bp = NULL;
916 	u_long cn, readcn;
917 	int error;
918 	u_long bn, bo, bsize, byteoffset;
919 
920 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
921 
922 	/*
923 	 * Mark all clusters in use, we mark the free ones in the fat scan
924 	 * loop further down.
925 	 */
926 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
927 		pmp->pm_inusemap[cn] = (u_int)-1;
928 
929 	/*
930 	 * Figure how many free clusters are in the filesystem by ripping
931 	 * through the fat counting the number of entries whose content is
932 	 * zero.  These represent free clusters.
933 	 */
934 	pmp->pm_freeclustercount = 0;
935 	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
936 		byteoffset = FATOFS(pmp, cn);
937 		bo = byteoffset % pmp->pm_fatblocksize;
938 		if (!bo || !bp) {
939 			/* Read new FAT block */
940 			if (bp)
941 				brelse(bp);
942 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
943 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
944 			if (error) {
945 				brelse(bp);
946 				return (error);
947 			}
948 		}
949 		if (FAT32(pmp))
950 			readcn = getulong(&bp->b_data[bo]);
951 		else
952 			readcn = getushort(&bp->b_data[bo]);
953 		if (FAT12(pmp) && (cn & 1))
954 			readcn >>= 4;
955 		readcn &= pmp->pm_fatmask;
956 
957 		if (readcn == 0)
958 			usemap_free(pmp, cn);
959 	}
960 	if (bp != NULL)
961 		brelse(bp);
962 	return (0);
963 }
964 
965 /*
966  * Allocate a new cluster and chain it onto the end of the file.
967  *
968  * dep	 - the file to extend
969  * count - number of clusters to allocate
970  * bpp	 - where to return the address of the buf header for the first new
971  *	   file block
972  * ncp	 - where to put cluster number of the first newly allocated cluster
973  *	   If this pointer is 0, do not return the cluster number.
974  * flags - see fat.h
975  *
976  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
977  * the de_flag field of the denode and it does not change the de_FileSize
978  * field.  This is left for the caller to do.
979  */
980 int
981 extendfile(dep, count, bpp, ncp, flags)
982 	struct denode *dep;
983 	u_long count;
984 	struct buf **bpp;
985 	u_long *ncp;
986 	int flags;
987 {
988 	int error;
989 	u_long frcn;
990 	u_long cn, got;
991 	struct msdosfsmount *pmp = dep->de_pmp;
992 	struct buf *bp;
993 	daddr_t blkno;
994 
995 	/*
996 	 * Don't try to extend the root directory
997 	 */
998 	if (dep->de_StartCluster == MSDOSFSROOT
999 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
1000 		printf("extendfile(): attempt to extend root directory\n");
1001 		return (ENOSPC);
1002 	}
1003 
1004 	/*
1005 	 * If the "file's last cluster" cache entry is empty, and the file
1006 	 * is not empty, then fill the cache entry by calling pcbmap().
1007 	 */
1008 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
1009 	    dep->de_StartCluster != 0) {
1010 		error = pcbmap(dep, 0xffff, 0, &cn, 0);
1011 		/* we expect it to return E2BIG */
1012 		if (error != E2BIG)
1013 			return (error);
1014 	}
1015 
1016 	dep->de_fc[FC_NEXTTOLASTFC].fc_frcn =
1017 	    dep->de_fc[FC_LASTFC].fc_frcn;
1018 	dep->de_fc[FC_NEXTTOLASTFC].fc_fsrcn =
1019 	    dep->de_fc[FC_LASTFC].fc_fsrcn;
1020 	while (count > 0) {
1021 		/*
1022 		 * Allocate a new cluster chain and cat onto the end of the
1023 		 * file.  * If the file is empty we make de_StartCluster point
1024 		 * to the new block.  Note that de_StartCluster being 0 is
1025 		 * sufficient to be sure the file is empty since we exclude
1026 		 * attempts to extend the root directory above, and the root
1027 		 * dir is the only file with a startcluster of 0 that has
1028 		 * blocks allocated (sort of).
1029 		 */
1030 		if (dep->de_StartCluster == 0)
1031 			cn = 0;
1032 		else
1033 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1034 		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1035 		if (error)
1036 			return (error);
1037 
1038 		count -= got;
1039 
1040 		/*
1041 		 * Give them the filesystem relative cluster number if they want
1042 		 * it.
1043 		 */
1044 		if (ncp) {
1045 			*ncp = cn;
1046 			ncp = NULL;
1047 		}
1048 
1049 		if (dep->de_StartCluster == 0) {
1050 			dep->de_StartCluster = cn;
1051 			frcn = 0;
1052 		} else {
1053 			error = fatentry(FAT_SET, pmp,
1054 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
1055 					 0, cn);
1056 			if (error) {
1057 				clusterfree(pmp, cn, NULL);
1058 				return (error);
1059 			}
1060 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1061 		}
1062 
1063 		/*
1064 		 * Update the "last cluster of the file" entry in the denode's fat
1065 		 * cache.
1066 		 */
1067 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1068 
1069 		if (flags & DE_CLEAR) {
1070 			while (got-- > 0) {
1071 				/*
1072 				 * Get the buf header for the new block of the file.
1073 				 */
1074 				if (dep->de_Attributes & ATTR_DIRECTORY)
1075 					bp = getblk(pmp->pm_devvp,
1076 					    cntobn(pmp, cn++),
1077 					    pmp->pm_bpcluster, 0, 0, 0);
1078 				else {
1079 					bp = getblk(DETOV(dep),
1080 					    frcn++,
1081 					    pmp->pm_bpcluster, 0, 0, 0);
1082 					/*
1083 					 * Do the bmap now, as in msdosfs_write
1084 					 */
1085 					if (pcbmap(dep,
1086 					    bp->b_lblkno,
1087 					    &blkno, 0, 0))
1088 						bp->b_blkno = -1;
1089 					if (bp->b_blkno == -1)
1090 						panic("extendfile: pcbmap");
1091 					else
1092 						bp->b_blkno = blkno;
1093 				}
1094 				vfs_bio_clrbuf(bp);
1095 				if (bpp) {
1096 					*bpp = bp;
1097 					bpp = NULL;
1098 				} else
1099 					bdwrite(bp);
1100 			}
1101 		}
1102 	}
1103 
1104 	return (0);
1105 }
1106 
1107 /*-
1108  * Routine to mark a FAT16 or FAT32 volume as "clean" or "dirty" by
1109  * manipulating the upper bit of the FAT entry for cluster 1.  Note that
1110  * this bit is not defined for FAT12 volumes, which are always assumed to
1111  * be dirty.
1112  *
1113  * The fatentry() routine only works on cluster numbers that a file could
1114  * occupy, so it won't manipulate the entry for cluster 1.  So we have to do
1115  * it here.  The code was stolen from fatentry() and tailored for cluster 1.
1116  *
1117  * Inputs:
1118  *	pmp	The MS-DOS volume to mark
1119  *	dirty	Non-zero if the volume should be marked dirty; zero if it
1120  *		should be marked clean
1121  *
1122  * Result:
1123  *	0	Success
1124  *	EROFS	Volume is read-only
1125  *	?	(other errors from called routines)
1126  */
1127 int
1128 markvoldirty(struct msdosfsmount *pmp, int dirty)
1129 {
1130 	struct buf *bp;
1131 	u_long bn, bo, bsize, byteoffset, fatval;
1132 	int error;
1133 
1134 	/*
1135 	 * FAT12 does not support a "clean" bit, so don't do anything for
1136 	 * FAT12.
1137 	 */
1138 	if (FAT12(pmp))
1139 		return (0);
1140 
1141 	/* Can't change the bit on a read-only filesystem. */
1142 	if (pmp->pm_flags & MSDOSFSMNT_RONLY)
1143 		return (EROFS);
1144 
1145 	/*
1146 	 * Fetch the block containing the FAT entry.  It is given by the
1147 	 * pseudo-cluster 1.
1148 	 */
1149 	byteoffset = FATOFS(pmp, 1);
1150 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
1151 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
1152 	if (error) {
1153 		brelse(bp);
1154 		return (error);
1155 	}
1156 
1157 	/*
1158 	 * Get the current value of the FAT entry and set/clear the relevant
1159 	 * bit.  Dirty means clear the "clean" bit; clean means set the
1160 	 * "clean" bit.
1161 	 */
1162 	if (FAT32(pmp)) {
1163 		/* FAT32 uses bit 27. */
1164 		fatval = getulong(&bp->b_data[bo]);
1165 		if (dirty)
1166 			fatval &= 0xF7FFFFFF;
1167 		else
1168 			fatval |= 0x08000000;
1169 		putulong(&bp->b_data[bo], fatval);
1170 	} else {
1171 		/* Must be FAT16; use bit 15. */
1172 		fatval = getushort(&bp->b_data[bo]);
1173 		if (dirty)
1174 			fatval &= 0x7FFF;
1175 		else
1176 			fatval |= 0x8000;
1177 		putushort(&bp->b_data[bo], fatval);
1178 	}
1179 
1180 	/* Write out the modified FAT block synchronously. */
1181 	return (bwrite(bp));
1182 }
1183