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