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