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