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