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