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