xref: /freebsd/sys/fs/msdosfs/msdosfs_fat.c (revision c6ec7d31830ab1c80edae95ad5e4b9dba10c47ac)
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 #ifdef MSDOSFS_DEBUG
507 		printf("fatentry(): function code doesn't specify get or set\n");
508 #endif
509 		return (EINVAL);
510 	}
511 
512 	/*
513 	 * If they asked us to return a cluster number but didn't tell us
514 	 * where to put it, give them an error.
515 	 */
516 	if ((function & FAT_GET) && oldcontents == NULL) {
517 #ifdef MSDOSFS_DEBUG
518 		printf("fatentry(): get function with no place to put result\n");
519 #endif
520 		return (EINVAL);
521 	}
522 #endif
523 
524 	/*
525 	 * Be sure the requested cluster is in the filesystem.
526 	 */
527 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
528 		return (EINVAL);
529 
530 	byteoffset = FATOFS(pmp, cn);
531 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
532 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
533 	if (error) {
534 		brelse(bp);
535 		return (error);
536 	}
537 
538 	if (function & FAT_GET) {
539 		if (FAT32(pmp))
540 			readcn = getulong(&bp->b_data[bo]);
541 		else
542 			readcn = getushort(&bp->b_data[bo]);
543 		if (FAT12(pmp) & (cn & 1))
544 			readcn >>= 4;
545 		readcn &= pmp->pm_fatmask;
546 		/* map reserved fat entries to same values for all fats */
547 		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
548 			readcn |= ~pmp->pm_fatmask;
549 		*oldcontents = readcn;
550 	}
551 	if (function & FAT_SET) {
552 		switch (pmp->pm_fatmask) {
553 		case FAT12_MASK:
554 			readcn = getushort(&bp->b_data[bo]);
555 			if (cn & 1) {
556 				readcn &= 0x000f;
557 				readcn |= newcontents << 4;
558 			} else {
559 				readcn &= 0xf000;
560 				readcn |= newcontents & 0xfff;
561 			}
562 			putushort(&bp->b_data[bo], readcn);
563 			break;
564 		case FAT16_MASK:
565 			putushort(&bp->b_data[bo], newcontents);
566 			break;
567 		case FAT32_MASK:
568 			/*
569 			 * According to spec we have to retain the
570 			 * high order bits of the fat entry.
571 			 */
572 			readcn = getulong(&bp->b_data[bo]);
573 			readcn &= ~FAT32_MASK;
574 			readcn |= newcontents & FAT32_MASK;
575 			putulong(&bp->b_data[bo], readcn);
576 			break;
577 		}
578 		updatefats(pmp, bp, bn);
579 		bp = NULL;
580 		pmp->pm_fmod = 1;
581 	}
582 	if (bp)
583 		brelse(bp);
584 	return (0);
585 }
586 
587 /*
588  * Update a contiguous cluster chain
589  *
590  * pmp	    - mount point
591  * start    - first cluster of chain
592  * count    - number of clusters in chain
593  * fillwith - what to write into fat entry of last cluster
594  */
595 static int
596 fatchain(pmp, start, count, fillwith)
597 	struct msdosfsmount *pmp;
598 	u_long start;
599 	u_long count;
600 	u_long fillwith;
601 {
602 	int error;
603 	u_long bn, bo, bsize, byteoffset, readcn, newc;
604 	struct buf *bp;
605 
606 #ifdef MSDOSFS_DEBUG
607 	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
608 	    pmp, start, count, fillwith);
609 #endif
610 	/*
611 	 * Be sure the clusters are in the filesystem.
612 	 */
613 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
614 		return (EINVAL);
615 
616 	while (count > 0) {
617 		byteoffset = FATOFS(pmp, start);
618 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
619 		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
620 		if (error) {
621 			brelse(bp);
622 			return (error);
623 		}
624 		while (count > 0) {
625 			start++;
626 			newc = --count > 0 ? start : fillwith;
627 			switch (pmp->pm_fatmask) {
628 			case FAT12_MASK:
629 				readcn = getushort(&bp->b_data[bo]);
630 				if (start & 1) {
631 					readcn &= 0xf000;
632 					readcn |= newc & 0xfff;
633 				} else {
634 					readcn &= 0x000f;
635 					readcn |= newc << 4;
636 				}
637 				putushort(&bp->b_data[bo], readcn);
638 				bo++;
639 				if (!(start & 1))
640 					bo++;
641 				break;
642 			case FAT16_MASK:
643 				putushort(&bp->b_data[bo], newc);
644 				bo += 2;
645 				break;
646 			case FAT32_MASK:
647 				readcn = getulong(&bp->b_data[bo]);
648 				readcn &= ~pmp->pm_fatmask;
649 				readcn |= newc & pmp->pm_fatmask;
650 				putulong(&bp->b_data[bo], readcn);
651 				bo += 4;
652 				break;
653 			}
654 			if (bo >= bsize)
655 				break;
656 		}
657 		updatefats(pmp, bp, bn);
658 	}
659 	pmp->pm_fmod = 1;
660 	return (0);
661 }
662 
663 /*
664  * Check the length of a free cluster chain starting at start.
665  *
666  * pmp	 - mount point
667  * start - start of chain
668  * count - maximum interesting length
669  */
670 static int
671 chainlength(pmp, start, count)
672 	struct msdosfsmount *pmp;
673 	u_long start;
674 	u_long count;
675 {
676 	u_long idx, max_idx;
677 	u_int map;
678 	u_long len;
679 
680 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
681 
682 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
683 	idx = start / N_INUSEBITS;
684 	start %= N_INUSEBITS;
685 	map = pmp->pm_inusemap[idx];
686 	map &= ~((1 << start) - 1);
687 	if (map) {
688 		len = ffs(map) - 1 - start;
689 		return (len > count ? count : len);
690 	}
691 	len = N_INUSEBITS - start;
692 	if (len >= count)
693 		return (count);
694 	while (++idx <= max_idx) {
695 		if (len >= count)
696 			break;
697 		map = pmp->pm_inusemap[idx];
698 		if (map) {
699 			len += ffs(map) - 1;
700 			break;
701 		}
702 		len += N_INUSEBITS;
703 	}
704 	return (len > count ? count : len);
705 }
706 
707 /*
708  * Allocate contigous free clusters.
709  *
710  * pmp	      - mount point.
711  * start      - start of cluster chain.
712  * count      - number of clusters to allocate.
713  * fillwith   - put this value into the fat entry for the
714  *		last allocated cluster.
715  * retcluster - put the first allocated cluster's number here.
716  * got	      - how many clusters were actually allocated.
717  */
718 static int
719 chainalloc(pmp, start, count, fillwith, retcluster, got)
720 	struct msdosfsmount *pmp;
721 	u_long start;
722 	u_long count;
723 	u_long fillwith;
724 	u_long *retcluster;
725 	u_long *got;
726 {
727 	int error;
728 	u_long cl, n;
729 
730 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
731 
732 	for (cl = start, n = count; n-- > 0;)
733 		usemap_alloc(pmp, cl++);
734 
735 	error = fatchain(pmp, start, count, fillwith);
736 	if (error != 0)
737 		return (error);
738 #ifdef MSDOSFS_DEBUG
739 	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
740 	    start, count);
741 #endif
742 	if (retcluster)
743 		*retcluster = start;
744 	if (got)
745 		*got = count;
746 	pmp->pm_nxtfree = start + count;
747 	if (pmp->pm_nxtfree > pmp->pm_maxcluster)
748 		pmp->pm_nxtfree = CLUST_FIRST;
749 	return (0);
750 }
751 
752 /*
753  * Allocate contiguous free clusters.
754  *
755  * pmp	      - mount point.
756  * start      - preferred start of cluster chain.
757  * count      - number of clusters requested.
758  * fillwith   - put this value into the fat entry for the
759  *		last allocated cluster.
760  * retcluster - put the first allocated cluster's number here.
761  * got	      - how many clusters were actually allocated.
762  */
763 int
764 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
765     u_long fillwith, u_long *retcluster, u_long *got)
766 {
767 	int error;
768 
769 	MSDOSFS_LOCK_MP(pmp);
770 	error = clusteralloc1(pmp, start, count, fillwith, retcluster, got);
771 	MSDOSFS_UNLOCK_MP(pmp);
772 	return (error);
773 }
774 
775 static int
776 clusteralloc1(struct msdosfsmount *pmp, u_long start, u_long count,
777     u_long fillwith, u_long *retcluster, u_long *got)
778 {
779 	u_long idx;
780 	u_long len, newst, foundl, cn, l;
781 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
782 	u_int map;
783 
784 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
785 
786 #ifdef MSDOSFS_DEBUG
787 	printf("clusteralloc(): find %lu clusters\n", count);
788 #endif
789 	if (start) {
790 		if ((len = chainlength(pmp, start, count)) >= count)
791 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
792 	} else
793 		len = 0;
794 
795 	newst = pmp->pm_nxtfree;
796 	foundl = 0;
797 
798 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
799 		idx = cn / N_INUSEBITS;
800 		map = pmp->pm_inusemap[idx];
801 		map |= (1 << (cn % N_INUSEBITS)) - 1;
802 		if (map != (u_int)-1) {
803 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
804 			if ((l = chainlength(pmp, cn, count)) >= count)
805 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
806 			if (l > foundl) {
807 				foundcn = cn;
808 				foundl = l;
809 			}
810 			cn += l + 1;
811 			continue;
812 		}
813 		cn += N_INUSEBITS - cn % N_INUSEBITS;
814 	}
815 	for (cn = 0; cn < newst;) {
816 		idx = cn / N_INUSEBITS;
817 		map = pmp->pm_inusemap[idx];
818 		map |= (1 << (cn % N_INUSEBITS)) - 1;
819 		if (map != (u_int)-1) {
820 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
821 			if ((l = chainlength(pmp, cn, count)) >= count)
822 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
823 			if (l > foundl) {
824 				foundcn = cn;
825 				foundl = l;
826 			}
827 			cn += l + 1;
828 			continue;
829 		}
830 		cn += N_INUSEBITS - cn % N_INUSEBITS;
831 	}
832 
833 	if (!foundl)
834 		return (ENOSPC);
835 
836 	if (len)
837 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
838 	else
839 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
840 }
841 
842 
843 /*
844  * Free a chain of clusters.
845  *
846  * pmp		- address of the msdosfs mount structure for the filesystem
847  *		  containing the cluster chain to be freed.
848  * startcluster - number of the 1st cluster in the chain of clusters to be
849  *		  freed.
850  */
851 int
852 freeclusterchain(pmp, cluster)
853 	struct msdosfsmount *pmp;
854 	u_long cluster;
855 {
856 	int error;
857 	struct buf *bp = NULL;
858 	u_long bn, bo, bsize, byteoffset;
859 	u_long readcn, lbn = -1;
860 
861 	MSDOSFS_LOCK_MP(pmp);
862 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
863 		byteoffset = FATOFS(pmp, cluster);
864 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
865 		if (lbn != bn) {
866 			if (bp)
867 				updatefats(pmp, bp, lbn);
868 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
869 			if (error) {
870 				brelse(bp);
871 				MSDOSFS_UNLOCK_MP(pmp);
872 				return (error);
873 			}
874 			lbn = bn;
875 		}
876 		usemap_free(pmp, cluster);
877 		switch (pmp->pm_fatmask) {
878 		case FAT12_MASK:
879 			readcn = getushort(&bp->b_data[bo]);
880 			if (cluster & 1) {
881 				cluster = readcn >> 4;
882 				readcn &= 0x000f;
883 				readcn |= MSDOSFSFREE << 4;
884 			} else {
885 				cluster = readcn;
886 				readcn &= 0xf000;
887 				readcn |= MSDOSFSFREE & 0xfff;
888 			}
889 			putushort(&bp->b_data[bo], readcn);
890 			break;
891 		case FAT16_MASK:
892 			cluster = getushort(&bp->b_data[bo]);
893 			putushort(&bp->b_data[bo], MSDOSFSFREE);
894 			break;
895 		case FAT32_MASK:
896 			cluster = getulong(&bp->b_data[bo]);
897 			putulong(&bp->b_data[bo],
898 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
899 			break;
900 		}
901 		cluster &= pmp->pm_fatmask;
902 		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
903 			cluster |= pmp->pm_fatmask;
904 	}
905 	if (bp)
906 		updatefats(pmp, bp, bn);
907 	MSDOSFS_UNLOCK_MP(pmp);
908 	return (0);
909 }
910 
911 /*
912  * Read in fat blocks looking for free clusters. For every free cluster
913  * found turn off its corresponding bit in the pm_inusemap.
914  */
915 int
916 fillinusemap(pmp)
917 	struct msdosfsmount *pmp;
918 {
919 	struct buf *bp = NULL;
920 	u_long cn, readcn;
921 	int error;
922 	u_long bn, bo, bsize, byteoffset;
923 
924 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
925 
926 	/*
927 	 * Mark all clusters in use, we mark the free ones in the fat scan
928 	 * loop further down.
929 	 */
930 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
931 		pmp->pm_inusemap[cn] = (u_int)-1;
932 
933 	/*
934 	 * Figure how many free clusters are in the filesystem by ripping
935 	 * through the fat counting the number of entries whose content is
936 	 * zero.  These represent free clusters.
937 	 */
938 	pmp->pm_freeclustercount = 0;
939 	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
940 		byteoffset = FATOFS(pmp, cn);
941 		bo = byteoffset % pmp->pm_fatblocksize;
942 		if (!bo || !bp) {
943 			/* Read new FAT block */
944 			if (bp)
945 				brelse(bp);
946 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
947 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
948 			if (error) {
949 				brelse(bp);
950 				return (error);
951 			}
952 		}
953 		if (FAT32(pmp))
954 			readcn = getulong(&bp->b_data[bo]);
955 		else
956 			readcn = getushort(&bp->b_data[bo]);
957 		if (FAT12(pmp) && (cn & 1))
958 			readcn >>= 4;
959 		readcn &= pmp->pm_fatmask;
960 
961 		if (readcn == 0)
962 			usemap_free(pmp, cn);
963 	}
964 	if (bp != NULL)
965 		brelse(bp);
966 	return (0);
967 }
968 
969 /*
970  * Allocate a new cluster and chain it onto the end of the file.
971  *
972  * dep	 - the file to extend
973  * count - number of clusters to allocate
974  * bpp	 - where to return the address of the buf header for the first new
975  *	   file block
976  * ncp	 - where to put cluster number of the first newly allocated cluster
977  *	   If this pointer is 0, do not return the cluster number.
978  * flags - see fat.h
979  *
980  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
981  * the de_flag field of the denode and it does not change the de_FileSize
982  * field.  This is left for the caller to do.
983  */
984 int
985 extendfile(dep, count, bpp, ncp, flags)
986 	struct denode *dep;
987 	u_long count;
988 	struct buf **bpp;
989 	u_long *ncp;
990 	int flags;
991 {
992 	int error;
993 	u_long frcn;
994 	u_long cn, got;
995 	struct msdosfsmount *pmp = dep->de_pmp;
996 	struct buf *bp;
997 	daddr_t blkno;
998 
999 	/*
1000 	 * Don't try to extend the root directory
1001 	 */
1002 	if (dep->de_StartCluster == MSDOSFSROOT
1003 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
1004 #ifdef MSDOSFS_DEBUG
1005 		printf("extendfile(): attempt to extend root directory\n");
1006 #endif
1007 		return (ENOSPC);
1008 	}
1009 
1010 	/*
1011 	 * If the "file's last cluster" cache entry is empty, and the file
1012 	 * is not empty, then fill the cache entry by calling pcbmap().
1013 	 */
1014 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
1015 	    dep->de_StartCluster != 0) {
1016 		error = pcbmap(dep, 0xffff, 0, &cn, 0);
1017 		/* we expect it to return E2BIG */
1018 		if (error != E2BIG)
1019 			return (error);
1020 	}
1021 
1022 	dep->de_fc[FC_NEXTTOLASTFC].fc_frcn =
1023 	    dep->de_fc[FC_LASTFC].fc_frcn;
1024 	dep->de_fc[FC_NEXTTOLASTFC].fc_fsrcn =
1025 	    dep->de_fc[FC_LASTFC].fc_fsrcn;
1026 	while (count > 0) {
1027 		/*
1028 		 * Allocate a new cluster chain and cat onto the end of the
1029 		 * file.  * If the file is empty we make de_StartCluster point
1030 		 * to the new block.  Note that de_StartCluster being 0 is
1031 		 * sufficient to be sure the file is empty since we exclude
1032 		 * attempts to extend the root directory above, and the root
1033 		 * dir is the only file with a startcluster of 0 that has
1034 		 * blocks allocated (sort of).
1035 		 */
1036 		if (dep->de_StartCluster == 0)
1037 			cn = 0;
1038 		else
1039 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1040 		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1041 		if (error)
1042 			return (error);
1043 
1044 		count -= got;
1045 
1046 		/*
1047 		 * Give them the filesystem relative cluster number if they want
1048 		 * it.
1049 		 */
1050 		if (ncp) {
1051 			*ncp = cn;
1052 			ncp = NULL;
1053 		}
1054 
1055 		if (dep->de_StartCluster == 0) {
1056 			dep->de_StartCluster = cn;
1057 			frcn = 0;
1058 		} else {
1059 			error = fatentry(FAT_SET, pmp,
1060 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
1061 					 0, cn);
1062 			if (error) {
1063 				clusterfree(pmp, cn, NULL);
1064 				return (error);
1065 			}
1066 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1067 		}
1068 
1069 		/*
1070 		 * Update the "last cluster of the file" entry in the denode's fat
1071 		 * cache.
1072 		 */
1073 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1074 
1075 		if (flags & DE_CLEAR) {
1076 			while (got-- > 0) {
1077 				/*
1078 				 * Get the buf header for the new block of the file.
1079 				 */
1080 				if (dep->de_Attributes & ATTR_DIRECTORY)
1081 					bp = getblk(pmp->pm_devvp,
1082 					    cntobn(pmp, cn++),
1083 					    pmp->pm_bpcluster, 0, 0, 0);
1084 				else {
1085 					bp = getblk(DETOV(dep),
1086 					    frcn++,
1087 					    pmp->pm_bpcluster, 0, 0, 0);
1088 					/*
1089 					 * Do the bmap now, as in msdosfs_write
1090 					 */
1091 					if (pcbmap(dep,
1092 					    bp->b_lblkno,
1093 					    &blkno, 0, 0))
1094 						bp->b_blkno = -1;
1095 					if (bp->b_blkno == -1)
1096 						panic("extendfile: pcbmap");
1097 					else
1098 						bp->b_blkno = blkno;
1099 				}
1100 				vfs_bio_clrbuf(bp);
1101 				if (bpp) {
1102 					*bpp = bp;
1103 					bpp = NULL;
1104 				} else
1105 					bdwrite(bp);
1106 			}
1107 		}
1108 	}
1109 
1110 	return (0);
1111 }
1112 
1113 /*-
1114  * Routine to mark a FAT16 or FAT32 volume as "clean" or "dirty" by
1115  * manipulating the upper bit of the FAT entry for cluster 1.  Note that
1116  * this bit is not defined for FAT12 volumes, which are always assumed to
1117  * be dirty.
1118  *
1119  * The fatentry() routine only works on cluster numbers that a file could
1120  * occupy, so it won't manipulate the entry for cluster 1.  So we have to do
1121  * it here.  The code was stolen from fatentry() and tailored for cluster 1.
1122  *
1123  * Inputs:
1124  *	pmp	The MS-DOS volume to mark
1125  *	dirty	Non-zero if the volume should be marked dirty; zero if it
1126  *		should be marked clean
1127  *
1128  * Result:
1129  *	0	Success
1130  *	EROFS	Volume is read-only
1131  *	?	(other errors from called routines)
1132  */
1133 int
1134 markvoldirty(struct msdosfsmount *pmp, int dirty)
1135 {
1136 	struct buf *bp;
1137 	u_long bn, bo, bsize, byteoffset, fatval;
1138 	int error;
1139 
1140 	/*
1141 	 * FAT12 does not support a "clean" bit, so don't do anything for
1142 	 * FAT12.
1143 	 */
1144 	if (FAT12(pmp))
1145 		return (0);
1146 
1147 	/* Can't change the bit on a read-only filesystem. */
1148 	if (pmp->pm_flags & MSDOSFSMNT_RONLY)
1149 		return (EROFS);
1150 
1151 	/*
1152 	 * Fetch the block containing the FAT entry.  It is given by the
1153 	 * pseudo-cluster 1.
1154 	 */
1155 	byteoffset = FATOFS(pmp, 1);
1156 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
1157 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
1158 	if (error) {
1159 		brelse(bp);
1160 		return (error);
1161 	}
1162 
1163 	/*
1164 	 * Get the current value of the FAT entry and set/clear the relevant
1165 	 * bit.  Dirty means clear the "clean" bit; clean means set the
1166 	 * "clean" bit.
1167 	 */
1168 	if (FAT32(pmp)) {
1169 		/* FAT32 uses bit 27. */
1170 		fatval = getulong(&bp->b_data[bo]);
1171 		if (dirty)
1172 			fatval &= 0xF7FFFFFF;
1173 		else
1174 			fatval |= 0x08000000;
1175 		putulong(&bp->b_data[bo], fatval);
1176 	} else {
1177 		/* Must be FAT16; use bit 15. */
1178 		fatval = getushort(&bp->b_data[bo]);
1179 		if (dirty)
1180 			fatval &= 0x7FFF;
1181 		else
1182 			fatval |= 0x8000;
1183 		putushort(&bp->b_data[bo], fatval);
1184 	}
1185 
1186 	/* Write out the modified FAT block synchronously. */
1187 	return (bwrite(bp));
1188 }
1189