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