xref: /netbsd-src/sys/fs/msdosfs/msdosfs_fat.c (revision a11cd6f1fb04891b1fae0eb570078322b75142f5)
1*a11cd6f1Smsaitoh /*	$NetBSD: msdosfs_fat.c,v 1.37 2024/05/13 00:24:19 msaitoh Exp $	*/
298d58548Sjdolecek 
398d58548Sjdolecek /*-
498d58548Sjdolecek  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
598d58548Sjdolecek  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
698d58548Sjdolecek  * All rights reserved.
798d58548Sjdolecek  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
898d58548Sjdolecek  *
998d58548Sjdolecek  * Redistribution and use in source and binary forms, with or without
1098d58548Sjdolecek  * modification, are permitted provided that the following conditions
1198d58548Sjdolecek  * are met:
1298d58548Sjdolecek  * 1. Redistributions of source code must retain the above copyright
1398d58548Sjdolecek  *    notice, this list of conditions and the following disclaimer.
1498d58548Sjdolecek  * 2. Redistributions in binary form must reproduce the above copyright
1598d58548Sjdolecek  *    notice, this list of conditions and the following disclaimer in the
1698d58548Sjdolecek  *    documentation and/or other materials provided with the distribution.
1798d58548Sjdolecek  * 3. All advertising materials mentioning features or use of this software
1898d58548Sjdolecek  *    must display the following acknowledgement:
1998d58548Sjdolecek  *	This product includes software developed by TooLs GmbH.
2098d58548Sjdolecek  * 4. The name of TooLs GmbH may not be used to endorse or promote products
2198d58548Sjdolecek  *    derived from this software without specific prior written permission.
2298d58548Sjdolecek  *
2398d58548Sjdolecek  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
2498d58548Sjdolecek  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2598d58548Sjdolecek  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2698d58548Sjdolecek  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2798d58548Sjdolecek  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
2898d58548Sjdolecek  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
2998d58548Sjdolecek  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
3098d58548Sjdolecek  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
3198d58548Sjdolecek  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
3298d58548Sjdolecek  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3398d58548Sjdolecek  */
3498d58548Sjdolecek /*
3598d58548Sjdolecek  * Written by Paul Popelka (paulp@uts.amdahl.com)
3698d58548Sjdolecek  *
3798d58548Sjdolecek  * You can do anything you want with this software, just don't say you wrote
3898d58548Sjdolecek  * it, and don't remove this notice.
3998d58548Sjdolecek  *
4098d58548Sjdolecek  * This software is provided "as is".
4198d58548Sjdolecek  *
4298d58548Sjdolecek  * The author supplies this software to be publicly redistributed on the
4398d58548Sjdolecek  * understanding that the author is not responsible for the correct
4498d58548Sjdolecek  * functioning of this software in any circumstances and is not liable for
4598d58548Sjdolecek  * any damages caused by this software.
4698d58548Sjdolecek  *
4798d58548Sjdolecek  * October 1992
4898d58548Sjdolecek  */
4998d58548Sjdolecek 
50929f8943Schristos #if HAVE_NBTOOL_CONFIG_H
51929f8943Schristos #include "nbtool_config.h"
52929f8943Schristos #endif
53929f8943Schristos 
5498d58548Sjdolecek #include <sys/cdefs.h>
55*a11cd6f1Smsaitoh __KERNEL_RCSID(0, "$NetBSD: msdosfs_fat.c,v 1.37 2024/05/13 00:24:19 msaitoh Exp $");
5698d58548Sjdolecek 
5798d58548Sjdolecek /*
5898d58548Sjdolecek  * kernel include files.
5998d58548Sjdolecek  */
6098d58548Sjdolecek #include <sys/param.h>
6198d58548Sjdolecek #include <sys/file.h>
62929f8943Schristos #ifdef _KERNEL
6350df1c7dSchristos #include <sys/mount.h>		/* to define statvfs structure */
64691bcd5dSchristos #include <sys/errno.h>
65691bcd5dSchristos #include <sys/systm.h>
66691bcd5dSchristos #include <sys/kauth.h>
67691bcd5dSchristos #include <sys/dirent.h>
68929f8943Schristos #include <sys/namei.h>
69929f8943Schristos #include <sys/buf.h>
70929f8943Schristos #include <sys/vnode.h>		/* to define vattr structure */
71929f8943Schristos #else
7287ebd86eSsevan #include <strings.h>
73929f8943Schristos #include <ffs/buf.h>
74929f8943Schristos #endif
7598d58548Sjdolecek 
7698d58548Sjdolecek /*
7798d58548Sjdolecek  * msdosfs include files.
7898d58548Sjdolecek  */
7998d58548Sjdolecek #include <fs/msdosfs/bpb.h>
8098d58548Sjdolecek #include <fs/msdosfs/msdosfsmount.h>
8198d58548Sjdolecek #include <fs/msdosfs/direntry.h>
8298d58548Sjdolecek #include <fs/msdosfs/denode.h>
8398d58548Sjdolecek #include <fs/msdosfs/fat.h>
8498d58548Sjdolecek 
8598d58548Sjdolecek /*
8698d58548Sjdolecek  * Fat cache stats.
8798d58548Sjdolecek  */
8898d58548Sjdolecek int fc_fileextends;		/* # of file extends			 */
8998d58548Sjdolecek int fc_lfcempty;		/* # of time last file cluster cache entry
9098d58548Sjdolecek 				 * was empty */
9198d58548Sjdolecek int fc_bmapcalls;		/* # of times pcbmap was called		 */
9298d58548Sjdolecek 
9398d58548Sjdolecek #define	LMMAX	20
9498d58548Sjdolecek int fc_lmdistance[LMMAX];	/* counters for how far off the last
9598d58548Sjdolecek 				 * cluster mapped entry was. */
9698d58548Sjdolecek int fc_largedistance;		/* off by more than LMMAX		 */
97729d0a01Sxtraeme int fc_wherefrom, fc_whereto, fc_lastclust;
98729d0a01Sxtraeme int pm_fatblocksize;
99729d0a01Sxtraeme 
100729d0a01Sxtraeme #ifdef MSDOSFS_DEBUG
1013c0f9bd4Schristos #define DPRINTF(a) printf a
1023c0f9bd4Schristos #else
1033c0f9bd4Schristos #define DPRINTF(a)
1043c0f9bd4Schristos #endif
1053c0f9bd4Schristos #ifdef MSDOSFS_DEBUG
106729d0a01Sxtraeme void print_fat_stats(void);
107729d0a01Sxtraeme 
108729d0a01Sxtraeme void
print_fat_stats(void)109729d0a01Sxtraeme print_fat_stats(void)
110729d0a01Sxtraeme {
111729d0a01Sxtraeme 	int i;
112729d0a01Sxtraeme 
113729d0a01Sxtraeme 	printf("fc_fileextends=%d fc_lfcempty=%d fc_bmapcalls=%d "
114729d0a01Sxtraeme 	    "fc_largedistance=%d [%d->%d=%d] fc_lastclust=%d pm_fatblocksize=%d\n",
115729d0a01Sxtraeme 	    fc_fileextends, fc_lfcempty, fc_bmapcalls, fc_largedistance,
116729d0a01Sxtraeme 	    fc_wherefrom, fc_whereto, fc_whereto-fc_wherefrom,
117729d0a01Sxtraeme 	    fc_lastclust, pm_fatblocksize);
118729d0a01Sxtraeme 
119729d0a01Sxtraeme 	fc_fileextends = fc_lfcempty = fc_bmapcalls = 0;
120729d0a01Sxtraeme 	fc_wherefrom = fc_whereto = fc_lastclust = 0;
121729d0a01Sxtraeme 
122729d0a01Sxtraeme 	for (i = 0; i < LMMAX; i++) {
123729d0a01Sxtraeme 		printf("%d:%d ", i, fc_lmdistance[i]);
124729d0a01Sxtraeme 	fc_lmdistance[i] = 0;
125729d0a01Sxtraeme 	}
126729d0a01Sxtraeme 
127729d0a01Sxtraeme 	printf("\n");
128729d0a01Sxtraeme }
129729d0a01Sxtraeme #endif
13098d58548Sjdolecek 
13147216f84Sxtraeme static void fatblock(struct msdosfsmount *, u_long, u_long *, u_long *,
13247216f84Sxtraeme 			  u_long *);
13347216f84Sxtraeme void updatefats(struct msdosfsmount *, struct buf *, u_long);
1340f0296d8Sperry static inline void usemap_free(struct msdosfsmount *, u_long);
1350f0296d8Sperry static inline void usemap_alloc(struct msdosfsmount *, u_long);
13647216f84Sxtraeme static int fatchain(struct msdosfsmount *, u_long, u_long, u_long);
13747216f84Sxtraeme int chainlength(struct msdosfsmount *, u_long, u_long);
13847216f84Sxtraeme int chainalloc(struct msdosfsmount *, u_long, u_long, u_long, u_long *,
13947216f84Sxtraeme 		    u_long *);
14098d58548Sjdolecek 
14198d58548Sjdolecek static void
fatblock(struct msdosfsmount * pmp,u_long ofs,u_long * bnp,u_long * sizep,u_long * bop)142454af1c0Sdsl fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep, u_long *bop)
14398d58548Sjdolecek {
14498d58548Sjdolecek 	u_long bn, size;
14598d58548Sjdolecek 
14698d58548Sjdolecek 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
147d1579b2dSriastradh 	size = uimin(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
14898d58548Sjdolecek 	    * pmp->pm_BytesPerSec;
14998d58548Sjdolecek 	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
15098d58548Sjdolecek 
151db2e6548Schristos 	DPRINTF(("%s(ofs=%lu bn=%lu, size=%lu, bo=%lu)\n", __func__, ofs, bn,
152db2e6548Schristos 	    size, ofs % pmp->pm_fatblocksize));
15398d58548Sjdolecek 	if (bnp)
15498d58548Sjdolecek 		*bnp = bn;
15598d58548Sjdolecek 	if (sizep)
15698d58548Sjdolecek 		*sizep = size;
15798d58548Sjdolecek 	if (bop)
15898d58548Sjdolecek 		*bop = ofs % pmp->pm_fatblocksize;
159729d0a01Sxtraeme 
160729d0a01Sxtraeme 	pm_fatblocksize = pmp->pm_fatblocksize;
16198d58548Sjdolecek }
16298d58548Sjdolecek 
16398d58548Sjdolecek /*
16498d58548Sjdolecek  * Map the logical cluster number of a file into a physical disk sector
16598d58548Sjdolecek  * that is filesystem relative.
16698d58548Sjdolecek  *
16798d58548Sjdolecek  * dep	  - address of denode representing the file of interest
16898d58548Sjdolecek  * findcn - file relative cluster whose filesystem relative cluster number
16998d58548Sjdolecek  *	    and/or block number are/is to be found
17098d58548Sjdolecek  * bnp	  - address of where to place the file system relative block number.
17198d58548Sjdolecek  *	    If this pointer is null then don't return this quantity.
17298d58548Sjdolecek  * cnp	  - address of where to place the file system relative cluster number.
17398d58548Sjdolecek  *	    If this pointer is null then don't return this quantity.
17498d58548Sjdolecek  *
17598d58548Sjdolecek  * NOTE: Either bnp or cnp must be non-null.
17698d58548Sjdolecek  * This function has one side effect.  If the requested file relative cluster
17798d58548Sjdolecek  * is beyond the end of file, then the actual number of clusters in the file
17898d58548Sjdolecek  * is returned in *cnp.  This is useful for determining how long a directory is.
17998d58548Sjdolecek  *  If cnp is null, nothing is returned.
18098d58548Sjdolecek  */
18198d58548Sjdolecek int
msdosfs_pcbmap(struct denode * dep,u_long findcn,daddr_t * bnp,u_long * cnp,int * sp)1828086f46eSthorpej msdosfs_pcbmap(struct denode *dep,
1838086f46eSthorpej     u_long findcn,	/* file relative cluster to get */
1848086f46eSthorpej     daddr_t *bnp,	/* returned filesys rel sector number */
1858086f46eSthorpej     u_long *cnp,	/* returned cluster number */
1868086f46eSthorpej     int *sp)		/* returned block size */
18798d58548Sjdolecek {
18898d58548Sjdolecek 	int error;
18998d58548Sjdolecek 	u_long i;
19098d58548Sjdolecek 	u_long cn;
19198d58548Sjdolecek 	u_long prevcn = 0; /* XXX: prevcn could be used unititialized */
19298d58548Sjdolecek 	u_long byteoffset;
19398d58548Sjdolecek 	u_long bn;
19498d58548Sjdolecek 	u_long bo;
19598d58548Sjdolecek 	struct buf *bp = NULL;
19698d58548Sjdolecek 	u_long bp_bn = -1;
19798d58548Sjdolecek 	struct msdosfsmount *pmp = dep->de_pmp;
19898d58548Sjdolecek 	u_long bsize;
19998d58548Sjdolecek 
20098d58548Sjdolecek 	fc_bmapcalls++;
20198d58548Sjdolecek 
20298d58548Sjdolecek 	/*
20398d58548Sjdolecek 	 * If they don't give us someplace to return a value then don't
20498d58548Sjdolecek 	 * bother doing anything.
20598d58548Sjdolecek 	 */
20698d58548Sjdolecek 	if (bnp == NULL && cnp == NULL && sp == NULL)
20798d58548Sjdolecek 		return (0);
20898d58548Sjdolecek 
20998d58548Sjdolecek 	cn = dep->de_StartCluster;
2103c0f9bd4Schristos 	DPRINTF(("%s(start cluster=%lu)\n", __func__, cn));
21198d58548Sjdolecek 	/*
21298d58548Sjdolecek 	 * The "file" that makes up the root directory is contiguous,
21398d58548Sjdolecek 	 * permanently allocated, of fixed size, and is not made up of
21498d58548Sjdolecek 	 * clusters.  If the cluster number is beyond the end of the root
21598d58548Sjdolecek 	 * directory, then return the number of clusters in the file.
21698d58548Sjdolecek 	 */
21798d58548Sjdolecek 	if (cn == MSDOSFSROOT) {
21898d58548Sjdolecek 		if (dep->de_Attributes & ATTR_DIRECTORY) {
21998d58548Sjdolecek 			if (de_cn2off(pmp, findcn) >= dep->de_FileSize) {
22098d58548Sjdolecek 				if (cnp)
22198d58548Sjdolecek 					*cnp = de_bn2cn(pmp, pmp->pm_rootdirsize);
2223c0f9bd4Schristos 				DPRINTF(("%s(root, %lu ETOOBIG)\n", __func__,
2233c0f9bd4Schristos 				    de_cn2off(pmp, findcn)));
22498d58548Sjdolecek 				return (E2BIG);
22598d58548Sjdolecek 			}
22698d58548Sjdolecek 			if (bnp)
22798d58548Sjdolecek 				*bnp = pmp->pm_rootdirblk + de_cn2bn(pmp, findcn);
22898d58548Sjdolecek 			if (cnp)
22998d58548Sjdolecek 				*cnp = MSDOSFSROOT;
23098d58548Sjdolecek 			if (sp)
231d1579b2dSriastradh 				*sp = uimin(pmp->pm_bpcluster,
23298d58548Sjdolecek 				    dep->de_FileSize - de_cn2off(pmp, findcn));
2333c0f9bd4Schristos 			DPRINTF(("%s(root, bn=%lu, cn=%u)\n", __func__,
2343c0f9bd4Schristos 			    pmp->pm_rootdirblk + de_cn2bn(pmp, findcn),
2353c0f9bd4Schristos 			    MSDOSFSROOT));
23698d58548Sjdolecek 			return (0);
23798d58548Sjdolecek 		} else {		/* just an empty file */
23898d58548Sjdolecek 			if (cnp)
23998d58548Sjdolecek 				*cnp = 0;
2403c0f9bd4Schristos 			DPRINTF(("%s(root, empty ETOOBIG)\n", __func__));
24198d58548Sjdolecek 			return (E2BIG);
24298d58548Sjdolecek 		}
24398d58548Sjdolecek 	}
24498d58548Sjdolecek 
24598d58548Sjdolecek 	/*
24698d58548Sjdolecek 	 * All other files do I/O in cluster sized blocks
24798d58548Sjdolecek 	 */
24898d58548Sjdolecek 	if (sp)
24998d58548Sjdolecek 		*sp = pmp->pm_bpcluster;
25098d58548Sjdolecek 
25198d58548Sjdolecek 	/*
25248958e52Sjakllsch 	 * Rummage around in the FAT cache, maybe we can avoid tromping
25348958e52Sjakllsch 	 * thru every FAT entry for the file. And, keep track of how far
25498d58548Sjdolecek 	 * off the cache was from where we wanted to be.
25598d58548Sjdolecek 	 */
25698d58548Sjdolecek 	i = 0;
2578086f46eSthorpej 	msdosfs_fc_lookup(dep, findcn, &i, &cn);
2583c0f9bd4Schristos 	DPRINTF(("%s(bpcluster=%lu i=%lu cn=%lu\n", __func__, pmp->pm_bpcluster,
2593c0f9bd4Schristos 	    i, cn));
260729d0a01Sxtraeme 	if ((bn = findcn - i) >= LMMAX) {
26198d58548Sjdolecek 		fc_largedistance++;
262729d0a01Sxtraeme 		fc_wherefrom = i;
263729d0a01Sxtraeme 		fc_whereto = findcn;
264729d0a01Sxtraeme 		fc_lastclust = dep->de_fc[FC_LASTFC].fc_frcn;
265729d0a01Sxtraeme 	} else
26698d58548Sjdolecek 		fc_lmdistance[bn]++;
26798d58548Sjdolecek 
26898d58548Sjdolecek 	/*
26998d58548Sjdolecek 	 * Handle all other files or directories the normal way.
27098d58548Sjdolecek 	 */
27198d58548Sjdolecek 	for (; i < findcn; i++) {
27298d58548Sjdolecek 		/*
27398d58548Sjdolecek 		 * Stop with all reserved clusters, not just with EOF.
27498d58548Sjdolecek 		 */
27598d58548Sjdolecek 		if (cn >= (CLUST_RSRVD & pmp->pm_fatmask))
27698d58548Sjdolecek 			goto hiteof;
277e01ac002Smlelstv 
278e01ac002Smlelstv 		/*
279e01ac002Smlelstv 		 * Also stop when cluster is not in the filesystem
280e01ac002Smlelstv 		 */
281e01ac002Smlelstv 		if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster) {
282e01ac002Smlelstv 			DPRINTF(("%s(cn, %lu not in %lu..%lu)\n", __func__,
28309123a68Smlelstv 				cn, (u_long)CLUST_FIRST, pmp->pm_maxcluster));
284e01ac002Smlelstv 			if (bp)
285e01ac002Smlelstv 				brelse(bp, 0);
286e01ac002Smlelstv 			return (EINVAL);
287e01ac002Smlelstv 		}
288e01ac002Smlelstv 
28998d58548Sjdolecek 		byteoffset = FATOFS(pmp, cn);
29098d58548Sjdolecek 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
29198d58548Sjdolecek 		if (bn != bp_bn) {
29298d58548Sjdolecek 			if (bp)
2939f56dfa5Sad 				brelse(bp, 0);
2941a15b095Shannken 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
2956e392401Smaxv 			    0, &bp);
29698d58548Sjdolecek 			if (error) {
2973c0f9bd4Schristos 				DPRINTF(("%s(bread, %d)\n", __func__, error));
2981a15b095Shannken 				return (error);
29998d58548Sjdolecek 			}
30098d58548Sjdolecek 			bp_bn = bn;
30198d58548Sjdolecek 		}
30298d58548Sjdolecek 		prevcn = cn;
30333a79483Sbriggs 		if (bo >= bsize) {
30433a79483Sbriggs 			if (bp)
3059f56dfa5Sad 				brelse(bp, 0);
3063c0f9bd4Schristos 			DPRINTF(("%s(block, %lu >= %lu)\n", __func__, bo,
3073c0f9bd4Schristos 			    bsize));
30833a79483Sbriggs 			return (EIO);
30933a79483Sbriggs 		}
310f16f3462Schristos 		KASSERT(bp != NULL);
31198d58548Sjdolecek 		if (FAT32(pmp))
31253524e44Schristos 			cn = getulong((char *)bp->b_data + bo);
31398d58548Sjdolecek 		else
31453524e44Schristos 			cn = getushort((char *)bp->b_data + bo);
31598d58548Sjdolecek 		if (FAT12(pmp) && (prevcn & 1))
31698d58548Sjdolecek 			cn >>= 4;
317db2e6548Schristos 		DPRINTF(("%s(cn=%lu masked=%lu)\n", __func__, cn,
318db2e6548Schristos 		    cn & pmp->pm_fatmask));
31998d58548Sjdolecek 		cn &= pmp->pm_fatmask;
32098d58548Sjdolecek 	}
32198d58548Sjdolecek 
32298d58548Sjdolecek 	if (!MSDOSFSEOF(cn, pmp->pm_fatmask)) {
32398d58548Sjdolecek 		if (bp)
3249f56dfa5Sad 			brelse(bp, 0);
32598d58548Sjdolecek 		if (bnp)
32698d58548Sjdolecek 			*bnp = cntobn(pmp, cn);
32798d58548Sjdolecek 		if (cnp)
32898d58548Sjdolecek 			*cnp = cn;
3293c0f9bd4Schristos 		DPRINTF(("%s(bn=%lu, cn=%lu)\n", __func__, cntobn(pmp, cn),
3303c0f9bd4Schristos 		    cn));
33198d58548Sjdolecek 		fc_setcache(dep, FC_LASTMAP, i, cn);
33298d58548Sjdolecek 		return (0);
33398d58548Sjdolecek 	}
33498d58548Sjdolecek 
33598d58548Sjdolecek hiteof:;
33698d58548Sjdolecek 	if (cnp)
33798d58548Sjdolecek 		*cnp = i;
33898d58548Sjdolecek 	if (bp)
3399f56dfa5Sad 		brelse(bp, 0);
34048958e52Sjakllsch 	/* update last file cluster entry in the FAT cache */
34198d58548Sjdolecek 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
3423c0f9bd4Schristos 	DPRINTF(("%s(eof, %lu)\n", __func__, i));
34398d58548Sjdolecek 	return (E2BIG);
34498d58548Sjdolecek }
34598d58548Sjdolecek 
34698d58548Sjdolecek /*
34748958e52Sjakllsch  * Find the closest entry in the FAT cache to the cluster we are looking
34898d58548Sjdolecek  * for.
34998d58548Sjdolecek  */
35098d58548Sjdolecek void
msdosfs_fc_lookup(struct denode * dep,u_long findcn,u_long * frcnp,u_long * fsrcnp)3518086f46eSthorpej msdosfs_fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp,
3528086f46eSthorpej     u_long *fsrcnp)
35398d58548Sjdolecek {
35498d58548Sjdolecek 	int i;
35598d58548Sjdolecek 	u_long cn;
35698d58548Sjdolecek 	struct fatcache *closest = 0;
35798d58548Sjdolecek 
35898d58548Sjdolecek 	for (i = 0; i < FC_SIZE; i++) {
35998d58548Sjdolecek 		cn = dep->de_fc[i].fc_frcn;
36098d58548Sjdolecek 		if (cn != FCE_EMPTY && cn <= findcn) {
36198d58548Sjdolecek 			if (closest == 0 || cn > closest->fc_frcn)
36298d58548Sjdolecek 				closest = &dep->de_fc[i];
36398d58548Sjdolecek 		}
36498d58548Sjdolecek 	}
36598d58548Sjdolecek 	if (closest) {
36698d58548Sjdolecek 		*frcnp = closest->fc_frcn;
36798d58548Sjdolecek 		*fsrcnp = closest->fc_fsrcn;
36898d58548Sjdolecek 	}
36998d58548Sjdolecek }
37098d58548Sjdolecek 
37198d58548Sjdolecek /*
37248958e52Sjakllsch  * Purge the FAT cache in denode dep of all entries relating to file
37398d58548Sjdolecek  * relative cluster frcn and beyond.
37498d58548Sjdolecek  */
37598d58548Sjdolecek void
msdosfs_fc_purge(struct denode * dep,u_int frcn)3768086f46eSthorpej msdosfs_fc_purge(struct denode *dep, u_int frcn)
37798d58548Sjdolecek {
37898d58548Sjdolecek 	int i;
37998d58548Sjdolecek 	struct fatcache *fcp;
38098d58548Sjdolecek 
38198d58548Sjdolecek 	fcp = dep->de_fc;
38298d58548Sjdolecek 	for (i = 0; i < FC_SIZE; i++, fcp++) {
38398d58548Sjdolecek 		if (fcp->fc_frcn >= frcn)
38498d58548Sjdolecek 			fcp->fc_frcn = FCE_EMPTY;
38598d58548Sjdolecek 	}
38698d58548Sjdolecek }
38798d58548Sjdolecek 
38898d58548Sjdolecek /*
38948958e52Sjakllsch  * Update the FAT.
39048958e52Sjakllsch  * If mirroring the FAT, update all copies, with the first copy as last.
39148958e52Sjakllsch  * Else update only the current FAT (ignoring the others).
39298d58548Sjdolecek  *
39398d58548Sjdolecek  * pmp	 - msdosfsmount structure for filesystem to update
39448958e52Sjakllsch  * bp	 - addr of modified FAT block
39548958e52Sjakllsch  * fatbn - block number relative to begin of filesystem of the modified FAT block.
39698d58548Sjdolecek  */
39798d58548Sjdolecek void
updatefats(struct msdosfsmount * pmp,struct buf * bp,u_long fatbn)398454af1c0Sdsl updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
39998d58548Sjdolecek {
400e01ac002Smlelstv 	int i, error;
40198d58548Sjdolecek 	struct buf *bpn;
40298d58548Sjdolecek 
4033c0f9bd4Schristos 	DPRINTF(("%s(pmp %p, bp %p, fatbn %lu)\n", __func__, pmp, bp, fatbn));
40498d58548Sjdolecek 
40598d58548Sjdolecek 	/*
40698d58548Sjdolecek 	 * If we have an FSInfo block, update it.
40798d58548Sjdolecek 	 */
40898d58548Sjdolecek 	if (pmp->pm_fsinfo) {
40998d58548Sjdolecek 		u_long cn = pmp->pm_nxtfree;
41098d58548Sjdolecek 
41198d58548Sjdolecek 		if (pmp->pm_freeclustercount
41298d58548Sjdolecek 		    && (pmp->pm_inusemap[cn / N_INUSEBITS]
413417e06a6Skamil 			& (1U << (cn % N_INUSEBITS)))) {
41498d58548Sjdolecek 			/*
41598d58548Sjdolecek 			 * The cluster indicated in FSInfo isn't free
41698d58548Sjdolecek 			 * any longer.  Got get a new free one.
41798d58548Sjdolecek 			 */
41898d58548Sjdolecek 			for (cn = 0; cn < pmp->pm_maxcluster; cn++)
41998d58548Sjdolecek 				if (pmp->pm_inusemap[cn / N_INUSEBITS] != (u_int)-1)
42098d58548Sjdolecek 					break;
42198d58548Sjdolecek 			pmp->pm_nxtfree = cn
42298d58548Sjdolecek 				+ ffs(pmp->pm_inusemap[cn / N_INUSEBITS]
42398d58548Sjdolecek 				      ^ (u_int)-1) - 1;
42498d58548Sjdolecek 		}
4254f0ca272Sscw 		/*
4264f0ca272Sscw 		 * XXX  If the fsinfo block is stored on media with
4274f0ca272Sscw 		 *      2KB or larger sectors, is the fsinfo structure
4284f0ca272Sscw 		 *      padded at the end or in the middle?
4294f0ca272Sscw 		 */
4304f0ca272Sscw 		if (bread(pmp->pm_devvp, de_bn2kb(pmp, pmp->pm_fsinfo),
4316e392401Smaxv 		    pmp->pm_BytesPerSec, B_MODIFY, &bpn) != 0) {
43298d58548Sjdolecek 			/*
43398d58548Sjdolecek 			 * Ignore the error, but turn off FSInfo update for the future.
43498d58548Sjdolecek 			 */
43598d58548Sjdolecek 			pmp->pm_fsinfo = 0;
43698d58548Sjdolecek 		} else {
43798d58548Sjdolecek 			struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
43898d58548Sjdolecek 
43998d58548Sjdolecek 			putulong(fp->fsinfree, pmp->pm_freeclustercount);
44098d58548Sjdolecek 			putulong(fp->fsinxtfree, pmp->pm_nxtfree);
44198d58548Sjdolecek 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
44298d58548Sjdolecek 				bwrite(bpn);
44398d58548Sjdolecek 			else
44498d58548Sjdolecek 				bdwrite(bpn);
44598d58548Sjdolecek 		}
44698d58548Sjdolecek 	}
44798d58548Sjdolecek 
44898d58548Sjdolecek 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
44998d58548Sjdolecek 		/*
45048958e52Sjakllsch 		 * Now copy the block(s) of the modified FAT to the other copies of
45148958e52Sjakllsch 		 * the FAT and write them out.  This is faster than reading in the
45248958e52Sjakllsch 		 * other FATs and then writing them back out.  This could tie up
45348958e52Sjakllsch 		 * the FAT for quite a while. Preventing others from accessing it.
45448958e52Sjakllsch 		 * To prevent us from going after the FAT quite so much we use
4558ce1f4ffSmsaitoh 		 * delayed writes, unless they specified "synchronous" when the
45698d58548Sjdolecek 		 * filesystem was mounted.  If synch is asked for then use
45798d58548Sjdolecek 		 * bwrite()'s and really slow things down.
45898d58548Sjdolecek 		 */
45998d58548Sjdolecek 		for (i = 1; i < pmp->pm_FATs; i++) {
46098d58548Sjdolecek 			fatbn += pmp->pm_FATsecs;
46198d58548Sjdolecek 			/* getblk() never fails */
4624f0ca272Sscw 			bpn = getblk(pmp->pm_devvp, de_bn2kb(pmp, fatbn),
4634f0ca272Sscw 			    bp->b_bcount, 0, 0);
46498d58548Sjdolecek 			memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
465e01ac002Smlelstv 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT) {
466e01ac002Smlelstv 				error = bwrite(bpn);
467e01ac002Smlelstv 				if (error)
468e01ac002Smlelstv 					printf("%s: copy FAT %d (error=%d)\n",
469e01ac002Smlelstv 						 __func__, i, error);
470e01ac002Smlelstv 			} else
47198d58548Sjdolecek 				bdwrite(bpn);
47298d58548Sjdolecek 		}
47398d58548Sjdolecek 	}
47498d58548Sjdolecek 
47598d58548Sjdolecek 	/*
47648958e52Sjakllsch 	 * Write out the first (or current) FAT last.
47798d58548Sjdolecek 	 */
478e01ac002Smlelstv 	if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT) {
479e01ac002Smlelstv 		error =  bwrite(bp);
480e01ac002Smlelstv 		if (error)
481e01ac002Smlelstv 			printf("%s: write FAT (error=%d)\n",
482e01ac002Smlelstv 				__func__, error);
483e01ac002Smlelstv 	} else
48498d58548Sjdolecek 		bdwrite(bp);
48598d58548Sjdolecek 	/*
48698d58548Sjdolecek 	 * Maybe update fsinfo sector here?
48798d58548Sjdolecek 	 */
48898d58548Sjdolecek }
48998d58548Sjdolecek 
49098d58548Sjdolecek /*
49148958e52Sjakllsch  * Updating entries in 12 bit FATs is a pain in the butt.
49298d58548Sjdolecek  *
49398d58548Sjdolecek  * The following picture shows where nibbles go when moving from a 12 bit
49498d58548Sjdolecek  * cluster number into the appropriate bytes in the FAT.
49598d58548Sjdolecek  *
49698d58548Sjdolecek  *	byte m        byte m+1      byte m+2
49798d58548Sjdolecek  *	+----+----+   +----+----+   +----+----+
49898d58548Sjdolecek  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
49998d58548Sjdolecek  *	+----+----+   +----+----+   +----+----+
50098d58548Sjdolecek  *
50198d58548Sjdolecek  *	+----+----+----+   +----+----+----+
50298d58548Sjdolecek  *	|  3    0    1 |   |  4    5    2 |
50398d58548Sjdolecek  *	+----+----+----+   +----+----+----+
50498d58548Sjdolecek  *	cluster n  	   cluster n+1
50598d58548Sjdolecek  *
50698d58548Sjdolecek  * Where n is even. m = n + (n >> 2)
50798d58548Sjdolecek  *
50898d58548Sjdolecek  */
5090f0296d8Sperry static inline void
usemap_alloc(struct msdosfsmount * pmp,u_long cn)510454af1c0Sdsl usemap_alloc(struct msdosfsmount *pmp, u_long cn)
51198d58548Sjdolecek {
51298d58548Sjdolecek 
513417e06a6Skamil 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
51498d58548Sjdolecek 	pmp->pm_freeclustercount--;
51598d58548Sjdolecek }
51698d58548Sjdolecek 
5170f0296d8Sperry static inline void
usemap_free(struct msdosfsmount * pmp,u_long cn)518454af1c0Sdsl usemap_free(struct msdosfsmount *pmp, u_long cn)
51998d58548Sjdolecek {
52098d58548Sjdolecek 
52198d58548Sjdolecek 	pmp->pm_freeclustercount++;
522417e06a6Skamil 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1U << (cn % N_INUSEBITS));
52398d58548Sjdolecek }
52498d58548Sjdolecek 
52598d58548Sjdolecek int
msdosfs_clusterfree(struct msdosfsmount * pmp,u_long cluster,u_long * oldcnp)5268086f46eSthorpej msdosfs_clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
52798d58548Sjdolecek {
52898d58548Sjdolecek 	int error;
52998d58548Sjdolecek 	u_long oldcn;
53098d58548Sjdolecek 
53198d58548Sjdolecek 	usemap_free(pmp, cluster);
5328086f46eSthorpej 	error = msdosfs_fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn,
5338086f46eSthorpej 	    MSDOSFSFREE);
53498d58548Sjdolecek 	if (error) {
53598d58548Sjdolecek 		usemap_alloc(pmp, cluster);
53698d58548Sjdolecek 		return (error);
53798d58548Sjdolecek 	}
53898d58548Sjdolecek 	/*
53998d58548Sjdolecek 	 * If the cluster was successfully marked free, then update
54098d58548Sjdolecek 	 * the count of free clusters, and turn off the "allocated"
54198d58548Sjdolecek 	 * bit in the "in use" cluster bit map.
54298d58548Sjdolecek 	 */
54398d58548Sjdolecek 	if (oldcnp)
54498d58548Sjdolecek 		*oldcnp = oldcn;
54598d58548Sjdolecek 	return (0);
54698d58548Sjdolecek }
54798d58548Sjdolecek 
54898d58548Sjdolecek /*
54948958e52Sjakllsch  * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
55098d58548Sjdolecek  *
55198d58548Sjdolecek  * function	- whether to get or set a fat entry
55298d58548Sjdolecek  * pmp		- address of the msdosfsmount structure for the filesystem
55348958e52Sjakllsch  *		  whose FAT is to be manipulated.
55498d58548Sjdolecek  * cn		- which cluster is of interest
55598d58548Sjdolecek  * oldcontents	- address of a word that is to receive the contents of the
55698d58548Sjdolecek  *		  cluster'th entry if this is a get function
55798d58548Sjdolecek  * newcontents	- the new value to be written into the cluster'th element of
55848958e52Sjakllsch  *		  the FAT if this is a set function.
55998d58548Sjdolecek  *
56048958e52Sjakllsch  * This function can also be used to free a cluster by setting the FAT entry
56198d58548Sjdolecek  * for a cluster to 0.
56298d58548Sjdolecek  *
56348958e52Sjakllsch  * All copies of the FAT are updated if this is a set function. NOTE: If
56498d58548Sjdolecek  * fatentry() marks a cluster as free it does not update the inusemap in
56598d58548Sjdolecek  * the msdosfsmount structure. This is left to the caller.
56698d58548Sjdolecek  */
56798d58548Sjdolecek int
msdosfs_fatentry(int function,struct msdosfsmount * pmp,u_long cn,u_long * oldcontents,u_long newcontents)5688086f46eSthorpej msdosfs_fatentry(int function, struct msdosfsmount *pmp, u_long cn,
5698086f46eSthorpej     u_long *oldcontents, u_long newcontents)
57098d58548Sjdolecek {
57198d58548Sjdolecek 	int error;
57298d58548Sjdolecek 	u_long readcn;
57398d58548Sjdolecek 	u_long bn, bo, bsize, byteoffset;
57498d58548Sjdolecek 	struct buf *bp;
57598d58548Sjdolecek 
5763c0f9bd4Schristos 	DPRINTF(("%s(func %d, pmp %p, clust %lu, oldcon %p, newcon " "%lx)\n",
5773c0f9bd4Schristos 	    __func__, function, pmp, cn, oldcontents, newcontents));
57898d58548Sjdolecek 
57998d58548Sjdolecek #ifdef DIAGNOSTIC
58098d58548Sjdolecek 	/*
58198d58548Sjdolecek 	 * Be sure they asked us to do something.
58298d58548Sjdolecek 	 */
58398d58548Sjdolecek 	if ((function & (FAT_SET | FAT_GET)) == 0) {
5843c0f9bd4Schristos 		DPRINTF(("%s(): function code doesn't specify get or set\n",
5853c0f9bd4Schristos 		    __func__));
58698d58548Sjdolecek 		return (EINVAL);
58798d58548Sjdolecek 	}
58898d58548Sjdolecek 
58998d58548Sjdolecek 	/*
59098d58548Sjdolecek 	 * If they asked us to return a cluster number but didn't tell us
59198d58548Sjdolecek 	 * where to put it, give them an error.
59298d58548Sjdolecek 	 */
59398d58548Sjdolecek 	if ((function & FAT_GET) && oldcontents == NULL) {
5943c0f9bd4Schristos 		DPRINTF(("%s(): get function with no place to put result\n",
5953c0f9bd4Schristos 			__func__));
59698d58548Sjdolecek 		return (EINVAL);
59798d58548Sjdolecek 	}
59898d58548Sjdolecek #endif
59998d58548Sjdolecek 
60098d58548Sjdolecek 	/*
60198d58548Sjdolecek 	 * Be sure the requested cluster is in the filesystem.
60298d58548Sjdolecek 	 */
60398d58548Sjdolecek 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
60498d58548Sjdolecek 		return (EINVAL);
60598d58548Sjdolecek 
60698d58548Sjdolecek 	byteoffset = FATOFS(pmp, cn);
60798d58548Sjdolecek 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
6086e392401Smaxv 	if ((error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
6095d2bff06Shannken 	    0, &bp)) != 0) {
61098d58548Sjdolecek 		return (error);
61198d58548Sjdolecek 	}
61298d58548Sjdolecek 
61398d58548Sjdolecek 	if (function & FAT_GET) {
61498d58548Sjdolecek 		if (FAT32(pmp))
61553524e44Schristos 			readcn = getulong((char *)bp->b_data + bo);
61698d58548Sjdolecek 		else
61753524e44Schristos 			readcn = getushort((char *)bp->b_data + bo);
61898d58548Sjdolecek 		if (FAT12(pmp) & (cn & 1))
61998d58548Sjdolecek 			readcn >>= 4;
62098d58548Sjdolecek 		readcn &= pmp->pm_fatmask;
62198d58548Sjdolecek 		*oldcontents = readcn;
62298d58548Sjdolecek 	}
62398d58548Sjdolecek 	if (function & FAT_SET) {
62498d58548Sjdolecek 		switch (pmp->pm_fatmask) {
62598d58548Sjdolecek 		case FAT12_MASK:
62653524e44Schristos 			readcn = getushort((char *)bp->b_data + bo);
62798d58548Sjdolecek 			if (cn & 1) {
62898d58548Sjdolecek 				readcn &= 0x000f;
62998d58548Sjdolecek 				readcn |= newcontents << 4;
63098d58548Sjdolecek 			} else {
63198d58548Sjdolecek 				readcn &= 0xf000;
63298d58548Sjdolecek 				readcn |= newcontents & 0xfff;
63398d58548Sjdolecek 			}
63453524e44Schristos 			putushort((char *)bp->b_data + bo, readcn);
63598d58548Sjdolecek 			break;
63698d58548Sjdolecek 		case FAT16_MASK:
63753524e44Schristos 			putushort((char *)bp->b_data + bo, newcontents);
63898d58548Sjdolecek 			break;
63998d58548Sjdolecek 		case FAT32_MASK:
64098d58548Sjdolecek 			/*
64198d58548Sjdolecek 			 * According to spec we have to retain the
64248958e52Sjakllsch 			 * high order bits of the FAT entry.
64398d58548Sjdolecek 			 */
64453524e44Schristos 			readcn = getulong((char *)bp->b_data + bo);
64598d58548Sjdolecek 			readcn &= ~FAT32_MASK;
64698d58548Sjdolecek 			readcn |= newcontents & FAT32_MASK;
64753524e44Schristos 			putulong((char *)bp->b_data + bo, readcn);
64898d58548Sjdolecek 			break;
64998d58548Sjdolecek 		}
65098d58548Sjdolecek 		updatefats(pmp, bp, bn);
65198d58548Sjdolecek 		bp = NULL;
65298d58548Sjdolecek 		pmp->pm_fmod = 1;
65398d58548Sjdolecek 	}
65498d58548Sjdolecek 	if (bp)
6559f56dfa5Sad 		brelse(bp, 0);
65698d58548Sjdolecek 	return (0);
65798d58548Sjdolecek }
65898d58548Sjdolecek 
65998d58548Sjdolecek /*
66098d58548Sjdolecek  * Update a contiguous cluster chain
66198d58548Sjdolecek  *
66298d58548Sjdolecek  * pmp	    - mount point
66398d58548Sjdolecek  * start    - first cluster of chain
66498d58548Sjdolecek  * count    - number of clusters in chain
66548958e52Sjakllsch  * fillwith - what to write into FAT entry of last cluster
66698d58548Sjdolecek  */
66798d58548Sjdolecek static int
fatchain(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith)668454af1c0Sdsl fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
66998d58548Sjdolecek {
67098d58548Sjdolecek 	int error;
67198d58548Sjdolecek 	u_long bn, bo, bsize, byteoffset, readcn, newc;
67298d58548Sjdolecek 	struct buf *bp;
67398d58548Sjdolecek 
6743c0f9bd4Schristos 	DPRINTF(("%s(pmp %p, start %lu, count %lu, fillwith %lx)\n", __func__,
6753c0f9bd4Schristos 	    pmp, start, count, fillwith));
67698d58548Sjdolecek 	/*
67798d58548Sjdolecek 	 * Be sure the clusters are in the filesystem.
67898d58548Sjdolecek 	 */
67998d58548Sjdolecek 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
68098d58548Sjdolecek 		return (EINVAL);
68198d58548Sjdolecek 
68298d58548Sjdolecek 	while (count > 0) {
68398d58548Sjdolecek 		byteoffset = FATOFS(pmp, start);
68498d58548Sjdolecek 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
6856e392401Smaxv 		error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
6865d2bff06Shannken 		    B_MODIFY, &bp);
68798d58548Sjdolecek 		if (error) {
68898d58548Sjdolecek 			return (error);
68998d58548Sjdolecek 		}
69098d58548Sjdolecek 		while (count > 0) {
69198d58548Sjdolecek 			start++;
69298d58548Sjdolecek 			newc = --count > 0 ? start : fillwith;
69398d58548Sjdolecek 			switch (pmp->pm_fatmask) {
69498d58548Sjdolecek 			case FAT12_MASK:
69553524e44Schristos 				readcn = getushort((char *)bp->b_data + bo);
69698d58548Sjdolecek 				if (start & 1) {
69798d58548Sjdolecek 					readcn &= 0xf000;
69898d58548Sjdolecek 					readcn |= newc & 0xfff;
69998d58548Sjdolecek 				} else {
70098d58548Sjdolecek 					readcn &= 0x000f;
70198d58548Sjdolecek 					readcn |= newc << 4;
70298d58548Sjdolecek 				}
70353524e44Schristos 				putushort((char *)bp->b_data + bo, readcn);
70498d58548Sjdolecek 				bo++;
70598d58548Sjdolecek 				if (!(start & 1))
70698d58548Sjdolecek 					bo++;
70798d58548Sjdolecek 				break;
70898d58548Sjdolecek 			case FAT16_MASK:
70953524e44Schristos 				putushort((char *)bp->b_data + bo, newc);
71098d58548Sjdolecek 				bo += 2;
71198d58548Sjdolecek 				break;
71298d58548Sjdolecek 			case FAT32_MASK:
71353524e44Schristos 				readcn = getulong((char *)bp->b_data + bo);
71498d58548Sjdolecek 				readcn &= ~pmp->pm_fatmask;
71598d58548Sjdolecek 				readcn |= newc & pmp->pm_fatmask;
71653524e44Schristos 				putulong((char *)bp->b_data + bo, readcn);
71798d58548Sjdolecek 				bo += 4;
71898d58548Sjdolecek 				break;
71998d58548Sjdolecek 			}
72098d58548Sjdolecek 			if (bo >= bsize)
72198d58548Sjdolecek 				break;
72298d58548Sjdolecek 		}
72398d58548Sjdolecek 		updatefats(pmp, bp, bn);
72498d58548Sjdolecek 	}
72598d58548Sjdolecek 	pmp->pm_fmod = 1;
72698d58548Sjdolecek 	return (0);
72798d58548Sjdolecek }
72898d58548Sjdolecek 
72998d58548Sjdolecek /*
73098d58548Sjdolecek  * Check the length of a free cluster chain starting at start.
73198d58548Sjdolecek  *
73298d58548Sjdolecek  * pmp	 - mount point
73398d58548Sjdolecek  * start - start of chain
73498d58548Sjdolecek  * count - maximum interesting length
73598d58548Sjdolecek  */
73698d58548Sjdolecek int
chainlength(struct msdosfsmount * pmp,u_long start,u_long count)737454af1c0Sdsl chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
73898d58548Sjdolecek {
73998d58548Sjdolecek 	u_long idx, max_idx;
74098d58548Sjdolecek 	u_int map;
74198d58548Sjdolecek 	u_long len;
74298d58548Sjdolecek 
74398d58548Sjdolecek 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
74498d58548Sjdolecek 	idx = start / N_INUSEBITS;
74598d58548Sjdolecek 	start %= N_INUSEBITS;
74698d58548Sjdolecek 	map = pmp->pm_inusemap[idx];
747417e06a6Skamil 	map &= ~((1U << start) - 1);
74898d58548Sjdolecek 	if (map) {
74998d58548Sjdolecek 		len = ffs(map) - 1 - start;
75098d58548Sjdolecek 		return (len > count ? count : len);
75198d58548Sjdolecek 	}
75298d58548Sjdolecek 	len = N_INUSEBITS - start;
75398d58548Sjdolecek 	if (len >= count)
75498d58548Sjdolecek 		return (count);
75598d58548Sjdolecek 	while (++idx <= max_idx) {
75698d58548Sjdolecek 		if (len >= count)
75798d58548Sjdolecek 			break;
75898d58548Sjdolecek 		if ((map = pmp->pm_inusemap[idx]) != 0) {
75998d58548Sjdolecek 			len +=  ffs(map) - 1;
76098d58548Sjdolecek 			break;
76198d58548Sjdolecek 		}
76298d58548Sjdolecek 		len += N_INUSEBITS;
76398d58548Sjdolecek 	}
76498d58548Sjdolecek 	return (len > count ? count : len);
76598d58548Sjdolecek }
76698d58548Sjdolecek 
76798d58548Sjdolecek /*
768*a11cd6f1Smsaitoh  * Allocate contiguous free clusters.
76998d58548Sjdolecek  *
77098d58548Sjdolecek  * pmp	      - mount point.
77198d58548Sjdolecek  * start      - start of cluster chain.
77298d58548Sjdolecek  * count      - number of clusters to allocate.
77348958e52Sjakllsch  * fillwith   - put this value into the FAT entry for the
77498d58548Sjdolecek  *		last allocated cluster.
77598d58548Sjdolecek  * retcluster - put the first allocated cluster's number here.
77698d58548Sjdolecek  * got	      - how many clusters were actually allocated.
77798d58548Sjdolecek  */
77898d58548Sjdolecek int
chainalloc(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith,u_long * retcluster,u_long * got)779454af1c0Sdsl chainalloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith, u_long *retcluster, u_long *got)
78098d58548Sjdolecek {
78198d58548Sjdolecek 	int error;
78298d58548Sjdolecek 	u_long cl, n;
78398d58548Sjdolecek 
78498d58548Sjdolecek 	for (cl = start, n = count; n-- > 0;)
78598d58548Sjdolecek 		usemap_alloc(pmp, cl++);
78698d58548Sjdolecek 	if ((error = fatchain(pmp, start, count, fillwith)) != 0)
78798d58548Sjdolecek 		return (error);
7883c0f9bd4Schristos 
7893c0f9bd4Schristos 	DPRINTF(("%s(): allocated cluster chain at %lu (%lu clusters)\n",
7903c0f9bd4Schristos 	    __func__, start, count));
79198d58548Sjdolecek 	if (retcluster)
79298d58548Sjdolecek 		*retcluster = start;
79398d58548Sjdolecek 	if (got)
79498d58548Sjdolecek 		*got = count;
79598d58548Sjdolecek 	return (0);
79698d58548Sjdolecek }
79798d58548Sjdolecek 
79898d58548Sjdolecek /*
79998d58548Sjdolecek  * Allocate contiguous free clusters.
80098d58548Sjdolecek  *
80198d58548Sjdolecek  * pmp	      - mount point.
80298d58548Sjdolecek  * start      - preferred start of cluster chain.
80398d58548Sjdolecek  * count      - number of clusters requested.
80448958e52Sjakllsch  * fillwith   - put this value into the FAT entry for the
80598d58548Sjdolecek  *		last allocated cluster.
80698d58548Sjdolecek  * retcluster - put the first allocated cluster's number here.
80798d58548Sjdolecek  * got	      - how many clusters were actually allocated.
80898d58548Sjdolecek  */
80998d58548Sjdolecek int
msdosfs_clusteralloc(struct msdosfsmount * pmp,u_long start,u_long count,u_long * retcluster,u_long * got)8108086f46eSthorpej msdosfs_clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
8118086f46eSthorpej     u_long *retcluster, u_long *got)
81298d58548Sjdolecek {
81398d58548Sjdolecek 	u_long idx;
81498d58548Sjdolecek 	u_long len, newst, foundl, cn, l;
81598d58548Sjdolecek 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
81698d58548Sjdolecek 	u_long fillwith = CLUST_EOFE;
81798d58548Sjdolecek 	u_int map;
81898d58548Sjdolecek 
8193c0f9bd4Schristos 	DPRINTF(("%s(): find %lu clusters\n", __func__, count));
82098d58548Sjdolecek 	if (start) {
82198d58548Sjdolecek 		if ((len = chainlength(pmp, start, count)) >= count)
82298d58548Sjdolecek 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
82398d58548Sjdolecek 	} else {
82498d58548Sjdolecek 		/*
82598d58548Sjdolecek 		 * This is a new file, initialize start
82698d58548Sjdolecek 		 */
82798d58548Sjdolecek 		struct timeval tv;
82898d58548Sjdolecek 
82998d58548Sjdolecek 		microtime(&tv);
83098d58548Sjdolecek 		start = (tv.tv_usec >> 10) | tv.tv_usec;
83198d58548Sjdolecek 		len = 0;
83298d58548Sjdolecek 	}
83398d58548Sjdolecek 
83498d58548Sjdolecek 	/*
83598d58548Sjdolecek 	 * Start at a (pseudo) random place to maximize cluster runs
83698d58548Sjdolecek 	 * under multiple writers.
83798d58548Sjdolecek 	 */
83898d58548Sjdolecek 	newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1);
83998d58548Sjdolecek 	foundl = 0;
84098d58548Sjdolecek 
84198d58548Sjdolecek 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
84298d58548Sjdolecek 		idx = cn / N_INUSEBITS;
84398d58548Sjdolecek 		map = pmp->pm_inusemap[idx];
844417e06a6Skamil 		map |= (1U << (cn % N_INUSEBITS)) - 1;
84598d58548Sjdolecek 		if (map != (u_int)-1) {
84698d58548Sjdolecek 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
84798d58548Sjdolecek 			if ((l = chainlength(pmp, cn, count)) >= count)
84898d58548Sjdolecek 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
84998d58548Sjdolecek 			if (l > foundl) {
85098d58548Sjdolecek 				foundcn = cn;
85198d58548Sjdolecek 				foundl = l;
85298d58548Sjdolecek 			}
85398d58548Sjdolecek 			cn += l + 1;
85498d58548Sjdolecek 			continue;
85598d58548Sjdolecek 		}
85698d58548Sjdolecek 		cn += N_INUSEBITS - cn % N_INUSEBITS;
85798d58548Sjdolecek 	}
85898d58548Sjdolecek 	for (cn = 0; cn < newst;) {
85998d58548Sjdolecek 		idx = cn / N_INUSEBITS;
86098d58548Sjdolecek 		map = pmp->pm_inusemap[idx];
861417e06a6Skamil 		map |= (1U << (cn % N_INUSEBITS)) - 1;
86298d58548Sjdolecek 		if (map != (u_int)-1) {
86398d58548Sjdolecek 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
86498d58548Sjdolecek 			if ((l = chainlength(pmp, cn, count)) >= count)
86598d58548Sjdolecek 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
86698d58548Sjdolecek 			if (l > foundl) {
86798d58548Sjdolecek 				foundcn = cn;
86898d58548Sjdolecek 				foundl = l;
86998d58548Sjdolecek 			}
87098d58548Sjdolecek 			cn += l + 1;
87198d58548Sjdolecek 			continue;
87298d58548Sjdolecek 		}
87398d58548Sjdolecek 		cn += N_INUSEBITS - cn % N_INUSEBITS;
87498d58548Sjdolecek 	}
87598d58548Sjdolecek 
87698d58548Sjdolecek 	if (!foundl)
87798d58548Sjdolecek 		return (ENOSPC);
87898d58548Sjdolecek 
87998d58548Sjdolecek 	if (len)
88098d58548Sjdolecek 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
88198d58548Sjdolecek 	else
88298d58548Sjdolecek 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
88398d58548Sjdolecek }
88498d58548Sjdolecek 
88598d58548Sjdolecek 
88698d58548Sjdolecek /*
88798d58548Sjdolecek  * Free a chain of clusters.
88898d58548Sjdolecek  *
88998d58548Sjdolecek  * pmp		- address of the msdosfs mount structure for the filesystem
89098d58548Sjdolecek  *		  containing the cluster chain to be freed.
89198d58548Sjdolecek  * startcluster - number of the 1st cluster in the chain of clusters to be
89298d58548Sjdolecek  *		  freed.
89398d58548Sjdolecek  */
89498d58548Sjdolecek int
msdosfs_freeclusterchain(struct msdosfsmount * pmp,u_long cluster)8958086f46eSthorpej msdosfs_freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
89698d58548Sjdolecek {
89798d58548Sjdolecek 	int error;
89898d58548Sjdolecek 	struct buf *bp = NULL;
89998d58548Sjdolecek 	u_long bn, bo, bsize, byteoffset;
90098d58548Sjdolecek 	u_long readcn, lbn = -1;
90198d58548Sjdolecek 
902931f53ceSmrg 	bn = 0; /* XXXgcc */
90398d58548Sjdolecek 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
90498d58548Sjdolecek 		byteoffset = FATOFS(pmp, cluster);
90598d58548Sjdolecek 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
90698d58548Sjdolecek 		if (lbn != bn) {
90798d58548Sjdolecek 			if (bp)
90898d58548Sjdolecek 				updatefats(pmp, bp, lbn);
9094f0ca272Sscw 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
9106e392401Smaxv 			    B_MODIFY, &bp);
91198d58548Sjdolecek 			if (error) {
91298d58548Sjdolecek 				return (error);
91398d58548Sjdolecek 			}
91498d58548Sjdolecek 			lbn = bn;
91598d58548Sjdolecek 		}
91698d58548Sjdolecek 		usemap_free(pmp, cluster);
9179e36ae3bSchristos 		KASSERT(bp != NULL);
91898d58548Sjdolecek 		switch (pmp->pm_fatmask) {
91998d58548Sjdolecek 		case FAT12_MASK:
92053524e44Schristos 			readcn = getushort((char *)bp->b_data + bo);
92198d58548Sjdolecek 			if (cluster & 1) {
92298d58548Sjdolecek 				cluster = readcn >> 4;
92398d58548Sjdolecek 				readcn &= 0x000f;
92498d58548Sjdolecek 				readcn |= MSDOSFSFREE << 4;
92598d58548Sjdolecek 			} else {
92698d58548Sjdolecek 				cluster = readcn;
92798d58548Sjdolecek 				readcn &= 0xf000;
92898d58548Sjdolecek 				readcn |= MSDOSFSFREE & 0xfff;
92998d58548Sjdolecek 			}
93053524e44Schristos 			putushort((char *)bp->b_data + bo, readcn);
93198d58548Sjdolecek 			break;
93298d58548Sjdolecek 		case FAT16_MASK:
93353524e44Schristos 			cluster = getushort((char *)bp->b_data + bo);
93453524e44Schristos 			putushort((char *)bp->b_data + bo, MSDOSFSFREE);
93598d58548Sjdolecek 			break;
93698d58548Sjdolecek 		case FAT32_MASK:
93753524e44Schristos 			cluster = getulong((char *)bp->b_data + bo);
93853524e44Schristos 			putulong((char *)bp->b_data + bo,
93998d58548Sjdolecek 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
94098d58548Sjdolecek 			break;
94198d58548Sjdolecek 		}
94298d58548Sjdolecek 		cluster &= pmp->pm_fatmask;
94398d58548Sjdolecek 	}
94498d58548Sjdolecek 	if (bp)
94598d58548Sjdolecek 		updatefats(pmp, bp, bn);
94698d58548Sjdolecek 	return (0);
94798d58548Sjdolecek }
94898d58548Sjdolecek 
94998d58548Sjdolecek /*
95048958e52Sjakllsch  * Read in FAT blocks looking for free clusters. For every free cluster
95198d58548Sjdolecek  * found turn off its corresponding bit in the pm_inusemap.
95298d58548Sjdolecek  */
95398d58548Sjdolecek int
msdosfs_fillinusemap(struct msdosfsmount * pmp)9548086f46eSthorpej msdosfs_fillinusemap(struct msdosfsmount *pmp)
95598d58548Sjdolecek {
95698d58548Sjdolecek 	struct buf *bp = NULL;
95798d58548Sjdolecek 	u_long cn, readcn;
95898d58548Sjdolecek 	int error;
95998d58548Sjdolecek 	u_long bn, bo, bsize, byteoffset;
96098d58548Sjdolecek 
96198d58548Sjdolecek 	/*
96248958e52Sjakllsch 	 * Mark all clusters in use, we mark the free ones in the FAT scan
96398d58548Sjdolecek 	 * loop further down.
96498d58548Sjdolecek 	 */
96598d58548Sjdolecek 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
96698d58548Sjdolecek 		pmp->pm_inusemap[cn] = (u_int)-1;
96798d58548Sjdolecek 
96898d58548Sjdolecek 	/*
96998d58548Sjdolecek 	 * Figure how many free clusters are in the filesystem by ripping
97048958e52Sjakllsch 	 * through the FAT counting the number of entries whose content is
97198d58548Sjdolecek 	 * zero.  These represent free clusters.
97298d58548Sjdolecek 	 */
97398d58548Sjdolecek 	pmp->pm_freeclustercount = 0;
97498d58548Sjdolecek 	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
97598d58548Sjdolecek 		byteoffset = FATOFS(pmp, cn);
97698d58548Sjdolecek 		bo = byteoffset % pmp->pm_fatblocksize;
97798d58548Sjdolecek 		if (!bo || !bp) {
97898d58548Sjdolecek 			/* Read new FAT block */
97998d58548Sjdolecek 			if (bp)
9809f56dfa5Sad 				brelse(bp, 0);
98198d58548Sjdolecek 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
9824f0ca272Sscw 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
9836e392401Smaxv 			    0, &bp);
98498d58548Sjdolecek 			if (error) {
98598d58548Sjdolecek 				return (error);
98698d58548Sjdolecek 			}
98798d58548Sjdolecek 		}
98898d58548Sjdolecek 		if (FAT32(pmp))
98953524e44Schristos 			readcn = getulong((char *)bp->b_data + bo);
99098d58548Sjdolecek 		else
99153524e44Schristos 			readcn = getushort((char *)bp->b_data + bo);
99298d58548Sjdolecek 		if (FAT12(pmp) && (cn & 1))
99398d58548Sjdolecek 			readcn >>= 4;
99498d58548Sjdolecek 		readcn &= pmp->pm_fatmask;
99598d58548Sjdolecek 
99698d58548Sjdolecek 		if (readcn == 0)
99798d58548Sjdolecek 			usemap_free(pmp, cn);
99898d58548Sjdolecek 	}
999816eaf94Sjoerg 	if (bp)
10009f56dfa5Sad 		brelse(bp, 0);
100198d58548Sjdolecek 	return (0);
100298d58548Sjdolecek }
100398d58548Sjdolecek 
100498d58548Sjdolecek /*
100598d58548Sjdolecek  * Allocate a new cluster and chain it onto the end of the file.
100698d58548Sjdolecek  *
100798d58548Sjdolecek  * dep	 - the file to extend
100898d58548Sjdolecek  * count - number of clusters to allocate
100998d58548Sjdolecek  * bpp	 - where to return the address of the buf header for the first new
101098d58548Sjdolecek  *	   file block
101198d58548Sjdolecek  * ncp	 - where to put cluster number of the first newly allocated cluster
101298d58548Sjdolecek  *	   If this pointer is 0, do not return the cluster number.
101398d58548Sjdolecek  * flags - see fat.h
101498d58548Sjdolecek  *
101598d58548Sjdolecek  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
101698d58548Sjdolecek  * the de_flag field of the denode and it does not change the de_FileSize
101798d58548Sjdolecek  * field.  This is left for the caller to do.
101898d58548Sjdolecek  */
101998d58548Sjdolecek 
102098d58548Sjdolecek int
msdosfs_extendfile(struct denode * dep,u_long count,struct buf ** bpp,u_long * ncp,int flags)10218086f46eSthorpej msdosfs_extendfile(struct denode *dep, u_long count, struct buf **bpp,
10228086f46eSthorpej     u_long *ncp, int flags)
102398d58548Sjdolecek {
102498d58548Sjdolecek 	int error;
102598d58548Sjdolecek 	u_long frcn = 0, cn, got;
102698d58548Sjdolecek 	struct msdosfsmount *pmp = dep->de_pmp;
102798d58548Sjdolecek 	struct buf *bp;
102898d58548Sjdolecek 
102998d58548Sjdolecek 	/*
103098d58548Sjdolecek 	 * Don't try to extend the root directory
103198d58548Sjdolecek 	 */
103298d58548Sjdolecek 	if (dep->de_StartCluster == MSDOSFSROOT
103398d58548Sjdolecek 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
10343c0f9bd4Schristos 		DPRINTF(("%s(): attempt to extend root directory\n", __func__));
103598d58548Sjdolecek 		return (ENOSPC);
103698d58548Sjdolecek 	}
103798d58548Sjdolecek 
103898d58548Sjdolecek 	/*
103998d58548Sjdolecek 	 * If the "file's last cluster" cache entry is empty, and the file
104098d58548Sjdolecek 	 * is not empty, then fill the cache entry by calling pcbmap().
104198d58548Sjdolecek 	 */
104298d58548Sjdolecek 	fc_fileextends++;
104398d58548Sjdolecek 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
104498d58548Sjdolecek 	    dep->de_StartCluster != 0) {
104598d58548Sjdolecek 		fc_lfcempty++;
10468086f46eSthorpej 		error = msdosfs_pcbmap(dep, CLUST_END, 0, &cn, 0);
104798d58548Sjdolecek 		/* we expect it to return E2BIG */
104898d58548Sjdolecek 		if (error != E2BIG)
104998d58548Sjdolecek 			return (error);
105098d58548Sjdolecek 	}
105198d58548Sjdolecek 
1052729d0a01Sxtraeme 	fc_last_to_nexttolast(dep);
1053729d0a01Sxtraeme 
105498d58548Sjdolecek 	while (count > 0) {
105598d58548Sjdolecek 
105698d58548Sjdolecek 		/*
105798d58548Sjdolecek 		 * Allocate a new cluster chain and cat onto the end of the
105898d58548Sjdolecek 		 * file.  If the file is empty we make de_StartCluster point
105998d58548Sjdolecek 		 * to the new block.  Note that de_StartCluster being 0 is
106098d58548Sjdolecek 		 * sufficient to be sure the file is empty since we exclude
106198d58548Sjdolecek 		 * attempts to extend the root directory above, and the root
106298d58548Sjdolecek 		 * dir is the only file with a startcluster of 0 that has
106398d58548Sjdolecek 		 * blocks allocated (sort of).
106498d58548Sjdolecek 		 */
106598d58548Sjdolecek 
106698d58548Sjdolecek 		if (dep->de_StartCluster == 0)
106798d58548Sjdolecek 			cn = 0;
106898d58548Sjdolecek 		else
106998d58548Sjdolecek 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
10708086f46eSthorpej 		error = msdosfs_clusteralloc(pmp, cn, count, &cn, &got);
107198d58548Sjdolecek 		if (error)
107298d58548Sjdolecek 			return (error);
107398d58548Sjdolecek 
107498d58548Sjdolecek 		count -= got;
107598d58548Sjdolecek 
107698d58548Sjdolecek 		/*
107798d58548Sjdolecek 		 * Give them the filesystem relative cluster number if they want
107898d58548Sjdolecek 		 * it.
107998d58548Sjdolecek 		 */
108098d58548Sjdolecek 		if (ncp) {
108198d58548Sjdolecek 			*ncp = cn;
108298d58548Sjdolecek 			ncp = NULL;
108398d58548Sjdolecek 		}
108498d58548Sjdolecek 
108598d58548Sjdolecek 		if (dep->de_StartCluster == 0) {
108698d58548Sjdolecek 			dep->de_StartCluster = cn;
108798d58548Sjdolecek 			frcn = 0;
108898d58548Sjdolecek 		} else {
10898086f46eSthorpej 			error = msdosfs_fatentry(FAT_SET, pmp,
109098d58548Sjdolecek 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
109198d58548Sjdolecek 					 0, cn);
109298d58548Sjdolecek 			if (error) {
10938086f46eSthorpej 				msdosfs_clusterfree(pmp, cn, NULL);
109498d58548Sjdolecek 				return (error);
109598d58548Sjdolecek 			}
109698d58548Sjdolecek 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
109798d58548Sjdolecek 		}
109898d58548Sjdolecek 
109998d58548Sjdolecek 		/*
110098d58548Sjdolecek 		 * Update the "last cluster of the file" entry in the
110148958e52Sjakllsch 		 * denode's FAT cache.
110298d58548Sjdolecek 		 */
110398d58548Sjdolecek 
110498d58548Sjdolecek 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
110598d58548Sjdolecek 		if ((flags & DE_CLEAR) &&
110698d58548Sjdolecek 		    (dep->de_Attributes & ATTR_DIRECTORY)) {
110798d58548Sjdolecek 			while (got-- > 0) {
11084f0ca272Sscw 				bp = getblk(pmp->pm_devvp,
11094f0ca272Sscw 				    de_bn2kb(pmp, cntobn(pmp, cn++)),
111098d58548Sjdolecek 				    pmp->pm_bpcluster, 0, 0);
111198d58548Sjdolecek 				clrbuf(bp);
111298d58548Sjdolecek 				if (bpp) {
111398d58548Sjdolecek 					*bpp = bp;
111498d58548Sjdolecek 						bpp = NULL;
111598d58548Sjdolecek 				} else {
111698d58548Sjdolecek 					bdwrite(bp);
111798d58548Sjdolecek 				}
111898d58548Sjdolecek 			}
111998d58548Sjdolecek 		}
112098d58548Sjdolecek 	}
112198d58548Sjdolecek 
112298d58548Sjdolecek 	return (0);
112398d58548Sjdolecek }
1124