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