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/errno.h>
55 
56 #include <assert.h>
57 #include <stdbool.h>
58 #include <stdio.h>
59 #include <string.h>
60 #include <strings.h>
61 
62 #include <vfs/msdosfs/bpb.h>
63 #include "msdos/denode.h"
64 #include <vfs/msdosfs/fat.h>
65 #include <vfs/msdosfs/msdosfsmount.h>
66 
67 #include "makefs.h"
68 #include "msdos.h"
69 
70 #define	FULL_RUN	((u_int)0xffffffff)
71 #define	SYNCHRONOUS_WRITES(pmp)	1
72 
73 static int	chainalloc(struct msdosfsmount *pmp, u_long start,
74 		    u_long count, u_long fillwith, u_long *retcluster,
75 		    u_long *got);
76 static int	chainlength(struct msdosfsmount *pmp, u_long start,
77 		    u_long count);
78 static void	fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp,
79 		    u_long *sizep, u_long *bop);
80 static int	fatchain(struct msdosfsmount *pmp, u_long start, u_long count,
81 		    u_long fillwith);
82 static void	fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp,
83 		    u_long *fsrcnp);
84 static void	updatefats(struct msdosfsmount *pmp, struct m_buf *bp,
85 		    u_long fatbn);
86 static __inline void
87 		usemap_alloc(struct msdosfsmount *pmp, u_long cn);
88 static __inline void
89 		usemap_free(struct msdosfsmount *pmp, u_long cn);
90 static int	clusteralloc1(struct msdosfsmount *pmp, u_long start,
91 		    u_long count, u_long fillwith, u_long *retcluster,
92 		    u_long *got);
93 
94 static void
95 fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep,
96     u_long *bop)
97 {
98 	u_long bn, size;
99 
100 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
101 	size = MIN(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
102 	    * DEV_BSIZE;
103 	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
104 
105 	if (bnp)
106 		*bnp = bn;
107 	if (sizep)
108 		*sizep = size;
109 	if (bop)
110 		*bop = ofs % pmp->pm_fatblocksize;
111 }
112 
113 /*
114  * Map the logical cluster number of a file into a physical disk sector
115  * that is filesystem relative.
116  *
117  * dep	  - address of denode representing the file of interest
118  * findcn - file relative cluster whose filesystem relative cluster number
119  *	    and/or block number are/is to be found
120  * bnp	  - address of where to place the filesystem relative block number.
121  *	    If this pointer is null then don't return this quantity.
122  * cnp	  - address of where to place the filesystem relative cluster number.
123  *	    If this pointer is null then don't return this quantity.
124  * sp     - pointer to returned block size
125  *
126  * NOTE: Either bnp or cnp must be non-null.
127  * This function has one side effect.  If the requested file relative cluster
128  * is beyond the end of file, then the actual number of clusters in the file
129  * is returned in *cnp.  This is useful for determining how long a directory is.
130  *  If cnp is null, nothing is returned.
131  */
132 int
133 pcbmap(struct denode *dep, u_long findcn, daddr_t *bnp, u_long *cnp, int *sp)
134 {
135 	int error;
136 	u_long i;
137 	u_long cn;
138 	u_long prevcn = 0; /* XXX: prevcn could be used unititialized */
139 	u_long byteoffset;
140 	u_long bn;
141 	u_long bo;
142 	struct m_buf *bp = NULL;
143 	u_long bp_bn = -1;
144 	struct msdosfsmount *pmp = dep->de_pmp;
145 	u_long bsize;
146 
147 	assert(bnp != NULL || cnp != NULL || sp != NULL);
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 	 * through 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((void *)pmp->pm_devvp, bn, bsize,
207 			    NOCRED, &bp);
208 			if (error) {
209 				brelse(bp);
210 				return (error);
211 			}
212 			bp_bn = bn;
213 		}
214 		prevcn = cn;
215 		if (bo >= bsize) {
216 			if (bp)
217 				brelse(bp);
218 			return (EIO);
219 		}
220 		if (FAT32(pmp))
221 			cn = getulong(bp->b_data + bo);
222 		else
223 			cn = getushort(bp->b_data + bo);
224 		if (FAT12(pmp) && (prevcn & 1))
225 			cn >>= 4;
226 		cn &= pmp->pm_fatmask;
227 
228 		/*
229 		 * Force the special cluster numbers
230 		 * to be the same for all cluster sizes
231 		 * to let the rest of msdosfs handle
232 		 * all cases the same.
233 		 */
234 		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
235 			cn |= ~pmp->pm_fatmask;
236 	}
237 
238 	if (!MSDOSFSEOF(pmp, cn)) {
239 		if (bp)
240 			brelse(bp);
241 		if (bnp)
242 			*bnp = cntobn(pmp, cn);
243 		if (cnp)
244 			*cnp = cn;
245 		fc_setcache(dep, FC_LASTMAP, i, cn);
246 		return (0);
247 	}
248 
249 hiteof:;
250 	if (cnp)
251 		*cnp = i;
252 	if (bp)
253 		brelse(bp);
254 	/* update last file cluster entry in the FAT cache */
255 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
256 	return (E2BIG);
257 }
258 
259 /*
260  * Find the closest entry in the FAT cache to the cluster we are looking
261  * for.
262  */
263 static void
264 fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
265 {
266 	int i;
267 	u_long cn;
268 	struct fatcache *closest = NULL;
269 
270 	for (i = 0; i < FC_SIZE; i++) {
271 		cn = dep->de_fc[i].fc_frcn;
272 		if (cn != FCE_EMPTY && cn <= findcn) {
273 			if (closest == NULL || cn > closest->fc_frcn)
274 				closest = &dep->de_fc[i];
275 		}
276 	}
277 	if (closest) {
278 		*frcnp = closest->fc_frcn;
279 		*fsrcnp = closest->fc_fsrcn;
280 	}
281 }
282 
283 /*
284  * Purge the FAT cache in denode dep of all entries relating to file
285  * relative cluster frcn and beyond.
286  */
287 void
288 fc_purge(struct denode *dep, u_int frcn)
289 {
290 	int i;
291 	struct fatcache *fcp;
292 
293 	fcp = dep->de_fc;
294 	for (i = 0; i < FC_SIZE; i++, fcp++) {
295 		if (fcp->fc_frcn >= frcn)
296 			fcp->fc_frcn = FCE_EMPTY;
297 	}
298 }
299 
300 /*
301  * Update the FAT.
302  * If mirroring the FAT, update all copies, with the first copy as last.
303  * Else update only the current FAT (ignoring the others).
304  *
305  * pmp	 - msdosfsmount structure for filesystem to update
306  * bp	 - addr of modified FAT block
307  * fatbn - block number relative to begin of filesystem of the modified FAT block.
308  */
309 static void
310 updatefats(struct msdosfsmount *pmp, struct m_buf *bp, u_long fatbn)
311 {
312 	struct m_buf *bpn;
313 	int cleanfat, i;
314 
315 #ifdef MSDOSFS_DEBUG
316 	printf("updatefats(pmp %p, bp %p, fatbn %lu)\n", pmp, bp, fatbn);
317 #endif
318 
319 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
320 		/*
321 		 * Now copy the block(s) of the modified FAT to the other copies of
322 		 * the FAT and write them out.  This is faster than reading in the
323 		 * other FATs and then writing them back out.  This could tie up
324 		 * the FAT for quite a while. Preventing others from accessing it.
325 		 * To prevent us from going after the FAT quite so much we use
326 		 * delayed writes, unless they specified "synchronous" when the
327 		 * filesystem was mounted.  If synch is asked for then use
328 		 * bwrite()'s and really slow things down.
329 		 */
330 		if (fatbn != pmp->pm_fatblk || FAT12(pmp))
331 			cleanfat = 0;
332 		else if (FAT16(pmp))
333 			cleanfat = 16;
334 		else
335 			cleanfat = 32;
336 		for (i = 1; i < pmp->pm_FATs; i++) {
337 			fatbn += pmp->pm_FATsecs;
338 			/* getblk() never fails */
339 			bpn = getblk((void *)pmp->pm_devvp, fatbn,
340 			    bp->b_bcount, 0, 0, 0);
341 			memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
342 			/* Force the clean bit on in the other copies. */
343 			if (cleanfat == 16)
344 				((uint8_t *)bpn->b_data)[3] |= 0x80;
345 			else if (cleanfat == 32)
346 				((uint8_t *)bpn->b_data)[7] |= 0x08;
347 			if (SYNCHRONOUS_WRITES(pmp))
348 				bwrite(bpn);
349 			else
350 				bdwrite(bpn);
351 		}
352 	}
353 
354 	/*
355 	 * Write out the first (or current) FAT last.
356 	 */
357 	if (SYNCHRONOUS_WRITES(pmp))
358 		bwrite(bp);
359 	else
360 		bdwrite(bp);
361 }
362 
363 /*
364  * Updating entries in 12 bit FATs is a pain in the butt.
365  *
366  * The following picture shows where nibbles go when moving from a 12 bit
367  * cluster number into the appropriate bytes in the FAT.
368  *
369  *	byte m        byte m+1      byte m+2
370  *	+----+----+   +----+----+   +----+----+
371  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
372  *	+----+----+   +----+----+   +----+----+
373  *
374  *	+----+----+----+   +----+----+----+
375  *	|  3    0    1 |   |  4    5    2 |
376  *	+----+----+----+   +----+----+----+
377  *	cluster n	   cluster n+1
378  *
379  * Where n is even. m = n + (n >> 2)
380  *
381  */
382 static __inline void
383 usemap_alloc(struct msdosfsmount *pmp, u_long cn)
384 {
385 
386 	assert(cn <= pmp->pm_maxcluster);
387 	assert((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0);
388 	assert((pmp->pm_inusemap[cn / N_INUSEBITS] & (1 << (cn % N_INUSEBITS)))
389 	    == 0);
390 	assert(pmp->pm_freeclustercount > 0);
391 
392 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
393 	pmp->pm_freeclustercount--;
394 	pmp->pm_flags |= MSDOSFS_FSIMOD;
395 }
396 
397 static __inline void
398 usemap_free(struct msdosfsmount *pmp, u_long cn)
399 {
400 
401 	assert(cn <= pmp->pm_maxcluster);
402 	assert((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0);
403 	assert((pmp->pm_inusemap[cn / N_INUSEBITS] & (1 << (cn % N_INUSEBITS)))
404 	    != 0);
405 
406 	pmp->pm_freeclustercount++;
407 	pmp->pm_flags |= MSDOSFS_FSIMOD;
408 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1U << (cn % N_INUSEBITS));
409 }
410 
411 int
412 clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
413 {
414 	int error;
415 	u_long oldcn;
416 
417 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
418 	if (error)
419 		return (error);
420 	/*
421 	 * If the cluster was successfully marked free, then update
422 	 * the count of free clusters, and turn off the "allocated"
423 	 * bit in the "in use" cluster bit map.
424 	 */
425 	usemap_free(pmp, cluster);
426 	if (oldcnp)
427 		*oldcnp = oldcn;
428 	return (0);
429 }
430 
431 /*
432  * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
433  *
434  * function	- whether to get or set a FAT entry
435  * pmp		- address of the msdosfsmount structure for the filesystem
436  *		  whose FAT is to be manipulated.
437  * cn		- which cluster is of interest
438  * oldcontents	- address of a word that is to receive the contents of the
439  *		  cluster'th entry if this is a get function
440  * newcontents	- the new value to be written into the cluster'th element of
441  *		  the FAT if this is a set function.
442  *
443  * This function can also be used to free a cluster by setting the FAT entry
444  * for a cluster to 0.
445  *
446  * All copies of the FAT are updated if this is a set function. NOTE: If
447  * fatentry() marks a cluster as free it does not update the inusemap in
448  * the msdosfsmount structure. This is left to the caller.
449  */
450 int
451 fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents,
452     u_long newcontents)
453 {
454 	int error;
455 	u_long readcn;
456 	u_long bn, bo, bsize, byteoffset;
457 	struct m_buf *bp;
458 
459 #ifdef	MSDOSFS_DEBUG
460 	printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
461 	    function, pmp, cn, oldcontents, newcontents);
462 #endif
463 
464 #ifdef DIAGNOSTIC
465 	/*
466 	 * Be sure they asked us to do something.
467 	 */
468 	if ((function & (FAT_SET | FAT_GET)) == 0) {
469 #ifdef MSDOSFS_DEBUG
470 		printf("fatentry(): function code doesn't specify get or set\n");
471 #endif
472 		return (EINVAL);
473 	}
474 
475 	/*
476 	 * If they asked us to return a cluster number but didn't tell us
477 	 * where to put it, give them an error.
478 	 */
479 	if ((function & FAT_GET) && oldcontents == NULL) {
480 #ifdef MSDOSFS_DEBUG
481 		printf("fatentry(): get function with no place to put result\n");
482 #endif
483 		return (EINVAL);
484 	}
485 #endif
486 
487 	/*
488 	 * Be sure the requested cluster is in the filesystem.
489 	 */
490 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
491 		return (EINVAL);
492 
493 	byteoffset = FATOFS(pmp, cn);
494 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
495 	error = bread((void *)pmp->pm_devvp, bn, bsize, NOCRED, &bp);
496 	if (error) {
497 		brelse(bp);
498 		return (error);
499 	}
500 
501 	if (function & FAT_GET) {
502 		if (FAT32(pmp))
503 			readcn = getulong(bp->b_data + bo);
504 		else
505 			readcn = getushort(bp->b_data + bo);
506 		if (FAT12(pmp) & (cn & 1))
507 			readcn >>= 4;
508 		readcn &= pmp->pm_fatmask;
509 		/* map reserved FAT entries to same values for all FATs */
510 		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
511 			readcn |= ~pmp->pm_fatmask;
512 		*oldcontents = readcn;
513 	}
514 	if (function & FAT_SET) {
515 		switch (pmp->pm_fatmask) {
516 		case FAT12_MASK:
517 			readcn = getushort(bp->b_data + bo);
518 			if (cn & 1) {
519 				readcn &= 0x000f;
520 				readcn |= newcontents << 4;
521 			} else {
522 				readcn &= 0xf000;
523 				readcn |= newcontents & 0xfff;
524 			}
525 			putushort(bp->b_data + bo, readcn);
526 			break;
527 		case FAT16_MASK:
528 			putushort(bp->b_data + bo, newcontents);
529 			break;
530 		case FAT32_MASK:
531 			/*
532 			 * According to spec we have to retain the
533 			 * high order bits of the FAT entry.
534 			 */
535 			readcn = getulong(bp->b_data + bo);
536 			readcn &= ~FAT32_MASK;
537 			readcn |= newcontents & FAT32_MASK;
538 			putulong(bp->b_data + bo, readcn);
539 			break;
540 		}
541 		updatefats(pmp, bp, bn);
542 		bp = NULL;
543 		pmp->pm_fmod = 1;
544 	}
545 	if (bp)
546 		brelse(bp);
547 	return (0);
548 }
549 
550 /*
551  * Update a contiguous cluster chain
552  *
553  * pmp	    - mount point
554  * start    - first cluster of chain
555  * count    - number of clusters in chain
556  * fillwith - what to write into FAT entry of last cluster
557  */
558 static int
559 fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
560 {
561 	int error;
562 	u_long bn, bo, bsize, byteoffset, readcn, newc;
563 	struct m_buf *bp;
564 
565 #ifdef MSDOSFS_DEBUG
566 	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
567 	    pmp, start, count, fillwith);
568 #endif
569 	/*
570 	 * Be sure the clusters are in the filesystem.
571 	 */
572 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
573 		return (EINVAL);
574 
575 	while (count > 0) {
576 		byteoffset = FATOFS(pmp, start);
577 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
578 		error = bread((void *)pmp->pm_devvp, bn, bsize, NOCRED, &bp);
579 		if (error) {
580 			brelse(bp);
581 			return (error);
582 		}
583 		while (count > 0) {
584 			start++;
585 			newc = --count > 0 ? start : fillwith;
586 			switch (pmp->pm_fatmask) {
587 			case FAT12_MASK:
588 				readcn = getushort(bp->b_data + bo);
589 				if (start & 1) {
590 					readcn &= 0xf000;
591 					readcn |= newc & 0xfff;
592 				} else {
593 					readcn &= 0x000f;
594 					readcn |= newc << 4;
595 				}
596 				putushort(bp->b_data + bo, readcn);
597 				bo++;
598 				if (!(start & 1))
599 					bo++;
600 				break;
601 			case FAT16_MASK:
602 				putushort(bp->b_data + bo, newc);
603 				bo += 2;
604 				break;
605 			case FAT32_MASK:
606 				readcn = getulong(bp->b_data + bo);
607 				readcn &= ~pmp->pm_fatmask;
608 				readcn |= newc & pmp->pm_fatmask;
609 				putulong(bp->b_data + bo, readcn);
610 				bo += 4;
611 				break;
612 			}
613 			if (bo >= bsize)
614 				break;
615 		}
616 		updatefats(pmp, bp, bn);
617 	}
618 	pmp->pm_fmod = 1;
619 	return (0);
620 }
621 
622 /*
623  * Check the length of a free cluster chain starting at start.
624  *
625  * pmp	 - mount point
626  * start - start of chain
627  * count - maximum interesting length
628  */
629 static int
630 chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
631 {
632 	u_long idx, max_idx;
633 	u_int map;
634 	u_long len;
635 
636 	if (start > pmp->pm_maxcluster)
637 		return (0);
638 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
639 	idx = start / N_INUSEBITS;
640 	start %= N_INUSEBITS;
641 	map = pmp->pm_inusemap[idx];
642 	map &= ~((1 << start) - 1);
643 	if (map) {
644 		len = ffs(map) - 1 - start;
645 		len = MIN(len, count);
646 		if (start + len > pmp->pm_maxcluster)
647 			len = pmp->pm_maxcluster - start + 1;
648 		return (len);
649 	}
650 	len = N_INUSEBITS - start;
651 	if (len >= count) {
652 		len = count;
653 		if (start + len > pmp->pm_maxcluster)
654 			len = pmp->pm_maxcluster - start + 1;
655 		return (len);
656 	}
657 	while (++idx <= max_idx) {
658 		if (len >= count)
659 			break;
660 		map = pmp->pm_inusemap[idx];
661 		if (map) {
662 			len += ffs(map) - 1;
663 			break;
664 		}
665 		len += N_INUSEBITS;
666 	}
667 	len = MIN(len, count);
668 	if (start + len > pmp->pm_maxcluster)
669 		len = pmp->pm_maxcluster - start + 1;
670 	return (len);
671 }
672 
673 /*
674  * Allocate contigous free clusters.
675  *
676  * pmp	      - mount point.
677  * start      - start of cluster chain.
678  * count      - number of clusters to allocate.
679  * fillwith   - put this value into the FAT entry for the
680  *		last allocated cluster.
681  * retcluster - put the first allocated cluster's number here.
682  * got	      - how many clusters were actually allocated.
683  */
684 static int
685 chainalloc(struct msdosfsmount *pmp, u_long start, u_long count,
686     u_long fillwith, u_long *retcluster, u_long *got)
687 {
688 	int error;
689 	u_long cl, n;
690 
691 	assert((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0);
692 
693 	for (cl = start, n = count; n-- > 0;)
694 		usemap_alloc(pmp, cl++);
695 	pmp->pm_nxtfree = start + count;
696 	if (pmp->pm_nxtfree > pmp->pm_maxcluster)
697 		pmp->pm_nxtfree = CLUST_FIRST;
698 	pmp->pm_flags |= MSDOSFS_FSIMOD;
699 	error = fatchain(pmp, start, count, fillwith);
700 	if (error != 0) {
701 		for (cl = start, n = count; n-- > 0;)
702 			usemap_free(pmp, cl++);
703 		return (error);
704 	}
705 #ifdef MSDOSFS_DEBUG
706 	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
707 	    start, count);
708 #endif
709 	if (retcluster)
710 		*retcluster = start;
711 	if (got)
712 		*got = count;
713 	return (0);
714 }
715 
716 /*
717  * Allocate contiguous free clusters.
718  *
719  * pmp	      - mount point.
720  * start      - preferred start of cluster chain.
721  * count      - number of clusters requested.
722  * fillwith   - put this value into the FAT entry for the
723  *		last allocated cluster.
724  * retcluster - put the first allocated cluster's number here.
725  * got	      - how many clusters were actually allocated.
726  */
727 int
728 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
729     u_long fillwith, u_long *retcluster, u_long *got)
730 {
731 	int error;
732 
733 	error = clusteralloc1(pmp, start, count, fillwith, retcluster, got);
734 	return (error);
735 }
736 
737 static int
738 clusteralloc1(struct msdosfsmount *pmp, u_long start, u_long count,
739     u_long fillwith, u_long *retcluster, u_long *got)
740 {
741 	u_long idx;
742 	u_long len, newst, foundl, cn, l;
743 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
744 	u_int map;
745 
746 	MSDOSFS_DPRINTF(("clusteralloc(): find %lu clusters\n", count));
747 
748 	if (start) {
749 		if ((len = chainlength(pmp, start, count)) >= count)
750 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
751 	} else
752 		len = 0;
753 
754 	newst = pmp->pm_nxtfree;
755 	foundl = 0;
756 
757 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
758 		idx = cn / N_INUSEBITS;
759 		map = pmp->pm_inusemap[idx];
760 		map |= (1U << (cn % N_INUSEBITS)) - 1;
761 		if (map != FULL_RUN) {
762 			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
763 			if ((l = chainlength(pmp, cn, count)) >= count)
764 				return (chainalloc(pmp, cn, count, fillwith, 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, retcluster, got));
782 			if (l > foundl) {
783 				foundcn = cn;
784 				foundl = l;
785 			}
786 			cn += l + 1;
787 			continue;
788 		}
789 		cn += N_INUSEBITS - cn % N_INUSEBITS;
790 	}
791 
792 	if (!foundl)
793 		return (ENOSPC);
794 
795 	if (len)
796 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
797 	else
798 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
799 }
800 
801 
802 /*
803  * Free a chain of clusters.
804  *
805  * pmp		- address of the msdosfs mount structure for the filesystem
806  *		  containing the cluster chain to be freed.
807  * startcluster - number of the 1st cluster in the chain of clusters to be
808  *		  freed.
809  */
810 int
811 freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
812 {
813 	int error;
814 	struct m_buf *bp = NULL;
815 	u_long bn, bo, bsize, byteoffset;
816 	u_long readcn, lbn = -1;
817 
818 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
819 		byteoffset = FATOFS(pmp, cluster);
820 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
821 		if (lbn != bn) {
822 			if (bp)
823 				updatefats(pmp, bp, lbn);
824 			error = bread((void *)pmp->pm_devvp, bn, bsize,
825 			    NOCRED, &bp);
826 			if (error) {
827 				brelse(bp);
828 				return (error);
829 			}
830 			lbn = bn;
831 		}
832 		usemap_free(pmp, cluster);
833 		switch (pmp->pm_fatmask) {
834 		case FAT12_MASK:
835 			readcn = getushort(bp->b_data + bo);
836 			if (cluster & 1) {
837 				cluster = readcn >> 4;
838 				readcn &= 0x000f;
839 				readcn |= MSDOSFSFREE << 4;
840 			} else {
841 				cluster = readcn;
842 				readcn &= 0xf000;
843 				readcn |= MSDOSFSFREE & 0xfff;
844 			}
845 			putushort(bp->b_data + bo, readcn);
846 			break;
847 		case FAT16_MASK:
848 			cluster = getushort(bp->b_data + bo);
849 			putushort(bp->b_data + bo, MSDOSFSFREE);
850 			break;
851 		case FAT32_MASK:
852 			cluster = getulong(bp->b_data + bo);
853 			putulong(bp->b_data + bo,
854 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
855 			break;
856 		}
857 		cluster &= pmp->pm_fatmask;
858 		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
859 			cluster |= pmp->pm_fatmask;
860 	}
861 	if (bp)
862 		updatefats(pmp, bp, bn);
863 	return (0);
864 }
865 
866 /*
867  * Read in FAT blocks looking for free clusters. For every free cluster
868  * found turn off its corresponding bit in the pm_inusemap.
869  */
870 int
871 fillinusemap(struct msdosfsmount *pmp)
872 {
873 	struct m_buf *bp;
874 	u_long bn, bo, bsize, byteoffset, cn, readcn;
875 	int error;
876 
877 	bp = NULL;
878 
879 	/*
880 	 * Mark all clusters in use, we mark the free ones in the FAT scan
881 	 * loop further down.
882 	 */
883 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
884 		pmp->pm_inusemap[cn] = FULL_RUN;
885 
886 	/*
887 	 * Figure how many free clusters are in the filesystem by ripping
888 	 * through the FAT counting the number of entries whose content is
889 	 * zero.  These represent free clusters.
890 	 */
891 	pmp->pm_freeclustercount = 0;
892 	for (cn = 0; cn <= pmp->pm_maxcluster; cn++) {
893 		byteoffset = FATOFS(pmp, cn);
894 		bo = byteoffset % pmp->pm_fatblocksize;
895 		if (bo == 0) {
896 			/* Read new FAT block */
897 			if (bp != NULL)
898 				brelse(bp);
899 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
900 			error = bread((void *)pmp->pm_devvp, bn, bsize,
901 			    NOCRED, &bp);
902 			if (error != 0)
903 				return (error);
904 		}
905 		if (FAT32(pmp))
906 			readcn = getulong(bp->b_data + bo);
907 		else
908 			readcn = getushort(bp->b_data + bo);
909 		if (FAT12(pmp) && (cn & 1))
910 			readcn >>= 4;
911 		readcn &= pmp->pm_fatmask;
912 
913 		/*
914 		 * Check if the FAT ID matches the BPB's media descriptor and
915 		 * all other bits are set to 1.
916 		 */
917 		if (cn == 0 && readcn != ((pmp->pm_fatmask & 0xffffff00) |
918 		    pmp->pm_bpb.bpbMedia)) {
919 #ifdef MSDOSFS_DEBUG
920 			printf("mountmsdosfs(): Media descriptor in BPB"
921 			    "does not match FAT ID\n");
922 #endif
923 			brelse(bp);
924 			return (EINVAL);
925 		} else if (readcn == CLUST_FREE)
926 			usemap_free(pmp, cn);
927 	}
928 	if (bp != NULL)
929 		brelse(bp);
930 
931 	for (cn = pmp->pm_maxcluster + 1; cn < (pmp->pm_maxcluster +
932 	    N_INUSEBITS) / N_INUSEBITS; cn++)
933 		pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
934 
935 	return (0);
936 }
937 
938 /*
939  * Allocate a new cluster and chain it onto the end of the file.
940  *
941  * dep	 - the file to extend
942  * count - number of clusters to allocate
943  * bpp	 - where to return the address of the buf header for the first new
944  *	   file block
945  * ncp	 - where to put cluster number of the first newly allocated cluster
946  *	   If this pointer is 0, do not return the cluster number.
947  * flags - see fat.h
948  *
949  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
950  * the de_flag field of the denode and it does not change the de_FileSize
951  * field.  This is left for the caller to do.
952  */
953 int
954 m_extendfile(struct denode *dep, u_long count, struct m_buf **bpp, u_long *ncp,
955     int flags)
956 {
957 	int error;
958 	u_long frcn;
959 	u_long cn, got;
960 	struct msdosfsmount *pmp = dep->de_pmp;
961 	struct m_buf *bp;
962 
963 	/*
964 	 * Don't try to extend the root directory
965 	 */
966 	if (dep->de_StartCluster == MSDOSFSROOT
967 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
968 #ifdef MSDOSFS_DEBUG
969 		printf("extendfile(): attempt to extend root directory\n");
970 #endif
971 		return (ENOSPC);
972 	}
973 
974 	/*
975 	 * If the "file's last cluster" cache entry is empty, and the file
976 	 * is not empty, then fill the cache entry by calling pcbmap().
977 	 */
978 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
979 	    dep->de_StartCluster != 0) {
980 		error = pcbmap(dep, 0xffff, 0, &cn, 0);
981 		/* we expect it to return E2BIG */
982 		if (error != E2BIG)
983 			return (error);
984 	}
985 
986 	dep->de_fc[FC_NEXTTOLASTFC].fc_frcn =
987 	    dep->de_fc[FC_LASTFC].fc_frcn;
988 	dep->de_fc[FC_NEXTTOLASTFC].fc_fsrcn =
989 	    dep->de_fc[FC_LASTFC].fc_fsrcn;
990 	while (count > 0) {
991 		/*
992 		 * Allocate a new cluster chain and cat onto the end of the
993 		 * file.  If the file is empty we make de_StartCluster point
994 		 * to the new block.  Note that de_StartCluster being 0 is
995 		 * sufficient to be sure the file is empty since we exclude
996 		 * attempts to extend the root directory above, and the root
997 		 * dir is the only file with a startcluster of 0 that has
998 		 * blocks allocated (sort of).
999 		 */
1000 		if (dep->de_StartCluster == 0)
1001 			cn = 0;
1002 		else
1003 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1004 		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1005 		if (error)
1006 			return (error);
1007 
1008 		count -= got;
1009 
1010 		/*
1011 		 * Give them the filesystem relative cluster number if they want
1012 		 * it.
1013 		 */
1014 		if (ncp) {
1015 			*ncp = cn;
1016 			ncp = NULL;
1017 		}
1018 
1019 		if (dep->de_StartCluster == 0) {
1020 			dep->de_StartCluster = cn;
1021 			frcn = 0;
1022 		} else {
1023 			error = fatentry(FAT_SET, pmp,
1024 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
1025 					 0, cn);
1026 			if (error) {
1027 				clusterfree(pmp, cn, NULL);
1028 				return (error);
1029 			}
1030 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1031 		}
1032 
1033 		/*
1034 		 * Update the "last cluster of the file" entry in the
1035 		 * denode's FAT cache.
1036 		 */
1037 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1038 
1039 		if ((flags & DE_CLEAR) &&
1040 		    (dep->de_Attributes & ATTR_DIRECTORY)) {
1041 			while (got-- > 0) {
1042 				bp = getblk((void *)pmp->pm_devvp,
1043 				    cntobn(pmp, cn++),
1044 				    pmp->pm_bpcluster, 0, 0, 0);
1045 				clrbuf(bp);
1046 				if (bpp) {
1047 					*bpp = bp;
1048 					bpp = NULL;
1049 				} else {
1050 					bdwrite(bp);
1051 				}
1052 			}
1053 		}
1054 	}
1055 
1056 	return (0);
1057 }
1058