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