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