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