xref: /openbsd-src/usr.sbin/makefs/msdos/msdosfs_fat.c (revision e6c7c102cf5d9891f32552a42895134a59937045)
1*e6c7c102Sjsg /*	$OpenBSD: msdosfs_fat.c,v 1.8 2024/04/23 13:34:51 jsg Exp $	*/
272290da1Snatano /*	$NetBSD: msdosfs_fat.c,v 1.31 2016/05/07 16:43:02 mlelstv Exp $	*/
372290da1Snatano 
472290da1Snatano /*-
572290da1Snatano  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
672290da1Snatano  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
772290da1Snatano  * All rights reserved.
872290da1Snatano  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
972290da1Snatano  *
1072290da1Snatano  * Redistribution and use in source and binary forms, with or without
1172290da1Snatano  * modification, are permitted provided that the following conditions
1272290da1Snatano  * are met:
1372290da1Snatano  * 1. Redistributions of source code must retain the above copyright
1472290da1Snatano  *    notice, this list of conditions and the following disclaimer.
1572290da1Snatano  * 2. Redistributions in binary form must reproduce the above copyright
1672290da1Snatano  *    notice, this list of conditions and the following disclaimer in the
1772290da1Snatano  *    documentation and/or other materials provided with the distribution.
1872290da1Snatano  * 3. All advertising materials mentioning features or use of this software
1972290da1Snatano  *    must display the following acknowledgement:
2072290da1Snatano  *	This product includes software developed by TooLs GmbH.
2172290da1Snatano  * 4. The name of TooLs GmbH may not be used to endorse or promote products
2272290da1Snatano  *    derived from this software without specific prior written permission.
2372290da1Snatano  *
2472290da1Snatano  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
2572290da1Snatano  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2672290da1Snatano  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2772290da1Snatano  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2872290da1Snatano  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
2972290da1Snatano  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
3072290da1Snatano  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
3172290da1Snatano  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
3272290da1Snatano  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
3372290da1Snatano  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3472290da1Snatano  */
3572290da1Snatano /*
3672290da1Snatano  * Written by Paul Popelka (paulp@uts.amdahl.com)
3772290da1Snatano  *
3872290da1Snatano  * You can do anything you want with this software, just don't say you wrote
3972290da1Snatano  * it, and don't remove this notice.
4072290da1Snatano  *
4172290da1Snatano  * This software is provided "as is".
4272290da1Snatano  *
4372290da1Snatano  * The author supplies this software to be publicly redistributed on the
4472290da1Snatano  * understanding that the author is not responsible for the correct
4572290da1Snatano  * functioning of this software in any circumstances and is not liable for
4672290da1Snatano  * any damages caused by this software.
4772290da1Snatano  *
4872290da1Snatano  * October 1992
4972290da1Snatano  */
5072290da1Snatano 
514874b543Sderaadt #include <sys/types.h>
524874b543Sderaadt #include <sys/time.h>
534874b543Sderaadt 
5472290da1Snatano /*
5572290da1Snatano  * kernel include files.
5672290da1Snatano  */
5772290da1Snatano 
5872290da1Snatano #include "ffs/buf.h"
5972290da1Snatano 
6072290da1Snatano /*
6172290da1Snatano  * msdosfs include files.
6272290da1Snatano  */
63bb19b730Snatano #include <msdosfs/bpb.h>
6472290da1Snatano #include "msdos/msdosfsmount.h"
6572290da1Snatano #include "msdos/direntry.h"
6672290da1Snatano #include "msdos/denode.h"
6772290da1Snatano #include "msdos/fat.h"
684874b543Sderaadt #include "makefs.h"
6972290da1Snatano 
7072290da1Snatano /*
7172290da1Snatano  * Fat cache stats.
7272290da1Snatano  */
7372290da1Snatano int fc_fileextends;		/* # of file extends			 */
7472290da1Snatano int fc_lfcempty;		/* # of time last file cluster cache entry
7572290da1Snatano 				 * was empty */
7672290da1Snatano int fc_bmapcalls;		/* # of times pcbmap was called		 */
7772290da1Snatano 
7872290da1Snatano #define	LMMAX	20
7972290da1Snatano int fc_lmdistance[LMMAX];	/* counters for how far off the last
8072290da1Snatano 				 * cluster mapped entry was. */
8172290da1Snatano int fc_largedistance;		/* off by more than LMMAX		 */
8272290da1Snatano int fc_wherefrom, fc_whereto, fc_lastclust;
8372290da1Snatano int pm_fatblocksize;
8472290da1Snatano 
8572290da1Snatano #ifdef MSDOSFS_DEBUG
8672290da1Snatano #define DPRINTF(a) printf a
8772290da1Snatano #else
8872290da1Snatano #define DPRINTF(a)
8972290da1Snatano #endif
9072290da1Snatano 
9172290da1Snatano static void fatblock(struct msdosfsmount *, u_long, u_long *, u_long *,
9272290da1Snatano 			  u_long *);
9372290da1Snatano void updatefats(struct msdosfsmount *, struct mkfsbuf *, u_long);
9472290da1Snatano static inline void usemap_free(struct msdosfsmount *, u_long);
9572290da1Snatano static inline void usemap_alloc(struct msdosfsmount *, u_long);
9672290da1Snatano static int fatchain(struct msdosfsmount *, u_long, u_long, u_long);
9772290da1Snatano int chainlength(struct msdosfsmount *, u_long, u_long);
9872290da1Snatano int chainalloc(struct msdosfsmount *, u_long, u_long, u_long, u_long *,
9972290da1Snatano 		    u_long *);
10072290da1Snatano 
10172290da1Snatano static void
fatblock(struct msdosfsmount * pmp,u_long ofs,u_long * bnp,u_long * sizep,u_long * bop)10272290da1Snatano fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep, u_long *bop)
10372290da1Snatano {
10472290da1Snatano 	u_long bn, size;
10572290da1Snatano 
10672290da1Snatano 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
1074874b543Sderaadt 	size = MINIMUM(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
10872290da1Snatano 	    * pmp->pm_BytesPerSec;
10972290da1Snatano 	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
11072290da1Snatano 
11172290da1Snatano 	DPRINTF(("%s(ofs=%lu bn=%lu, size=%lu, bo=%lu)\n", __func__, ofs, bn,
11272290da1Snatano 	    size, ofs % pmp->pm_fatblocksize));
11372290da1Snatano 	if (bnp)
11472290da1Snatano 		*bnp = bn;
11572290da1Snatano 	if (sizep)
11672290da1Snatano 		*sizep = size;
11772290da1Snatano 	if (bop)
11872290da1Snatano 		*bop = ofs % pmp->pm_fatblocksize;
11972290da1Snatano 
12072290da1Snatano 	pm_fatblocksize = pmp->pm_fatblocksize;
12172290da1Snatano }
12272290da1Snatano 
12372290da1Snatano /*
12472290da1Snatano  * Map the logical cluster number of a file into a physical disk sector
12572290da1Snatano  * that is filesystem relative.
12672290da1Snatano  *
12772290da1Snatano  * dep	  - address of denode representing the file of interest
12872290da1Snatano  * findcn - file relative cluster whose filesystem relative cluster number
12972290da1Snatano  *	    and/or block number are/is to be found
13072290da1Snatano  * bnp	  - address of where to place the file system relative block number.
13172290da1Snatano  *	    If this pointer is null then don't return this quantity.
13272290da1Snatano  * cnp	  - address of where to place the file system relative cluster number.
13372290da1Snatano  *	    If this pointer is null then don't return this quantity.
13472290da1Snatano  *
13572290da1Snatano  * NOTE: Either bnp or cnp must be non-null.
13672290da1Snatano  * This function has one side effect.  If the requested file relative cluster
13772290da1Snatano  * is beyond the end of file, then the actual number of clusters in the file
13872290da1Snatano  * is returned in *cnp.  This is useful for determining how long a directory is.
13972290da1Snatano  *  If cnp is null, nothing is returned.
14072290da1Snatano  */
14172290da1Snatano int
pcbmap(struct denode * dep,u_long findcn,daddr_t * bnp,u_long * cnp,int * sp)14272290da1Snatano pcbmap(struct denode *dep, u_long findcn, daddr_t *bnp, u_long *cnp, int *sp)
14372290da1Snatano 	/* findcn:		 file relative cluster to get		 */
14472290da1Snatano 	/* bnp:		 returned filesys rel sector number	 */
14572290da1Snatano 	/* cnp:		 returned cluster number		 */
14672290da1Snatano 	/* sp:		 returned block size			 */
14772290da1Snatano {
14872290da1Snatano 	int error;
14972290da1Snatano 	u_long i;
15072290da1Snatano 	u_long cn;
1518e544e80Sjsg 	u_long prevcn = 0; /* XXX: prevcn could be used uninitialized */
15272290da1Snatano 	u_long byteoffset;
15372290da1Snatano 	u_long bn;
15472290da1Snatano 	u_long bo;
15572290da1Snatano 	struct mkfsbuf *bp = NULL;
15672290da1Snatano 	u_long bp_bn = -1;
15772290da1Snatano 	struct msdosfsmount *pmp = dep->de_pmp;
15872290da1Snatano 	u_long bsize;
15972290da1Snatano 
16072290da1Snatano 	fc_bmapcalls++;
16172290da1Snatano 
16272290da1Snatano 	/*
16372290da1Snatano 	 * If they don't give us someplace to return a value then don't
16472290da1Snatano 	 * bother doing anything.
16572290da1Snatano 	 */
16672290da1Snatano 	if (bnp == NULL && cnp == NULL && sp == NULL)
16772290da1Snatano 		return (0);
16872290da1Snatano 
16972290da1Snatano 	cn = dep->de_StartCluster;
17072290da1Snatano 	DPRINTF(("%s(start cluster=%lu)\n", __func__, cn));
17172290da1Snatano 	/*
17272290da1Snatano 	 * The "file" that makes up the root directory is contiguous,
17372290da1Snatano 	 * permanently allocated, of fixed size, and is not made up of
17472290da1Snatano 	 * clusters.  If the cluster number is beyond the end of the root
17572290da1Snatano 	 * directory, then return the number of clusters in the file.
17672290da1Snatano 	 */
17772290da1Snatano 	if (cn == MSDOSFSROOT) {
17872290da1Snatano 		if (dep->de_Attributes & ATTR_DIRECTORY) {
17972290da1Snatano 			if (de_cn2off(pmp, findcn) >= dep->de_FileSize) {
18072290da1Snatano 				if (cnp)
18172290da1Snatano 					*cnp = de_bn2cn(pmp, pmp->pm_rootdirsize);
18272290da1Snatano 				DPRINTF(("%s(root, %lu ETOOBIG)\n", __func__,
18372290da1Snatano 				    de_cn2off(pmp, findcn)));
18472290da1Snatano 				return (E2BIG);
18572290da1Snatano 			}
18672290da1Snatano 			if (bnp)
18772290da1Snatano 				*bnp = pmp->pm_rootdirblk + de_cn2bn(pmp, findcn);
18872290da1Snatano 			if (cnp)
18972290da1Snatano 				*cnp = MSDOSFSROOT;
19072290da1Snatano 			if (sp)
1914874b543Sderaadt 				*sp = MINIMUM(pmp->pm_bpcluster,
19272290da1Snatano 				    dep->de_FileSize - de_cn2off(pmp, findcn));
19372290da1Snatano 			DPRINTF(("%s(root, bn=%lu, cn=%u)\n", __func__,
19472290da1Snatano 			    pmp->pm_rootdirblk + de_cn2bn(pmp, findcn),
19572290da1Snatano 			    MSDOSFSROOT));
19672290da1Snatano 			return (0);
19772290da1Snatano 		} else {		/* just an empty file */
19872290da1Snatano 			if (cnp)
19972290da1Snatano 				*cnp = 0;
20072290da1Snatano 			DPRINTF(("%s(root, empty ETOOBIG)\n", __func__));
20172290da1Snatano 			return (E2BIG);
20272290da1Snatano 		}
20372290da1Snatano 	}
20472290da1Snatano 
20572290da1Snatano 	/*
20672290da1Snatano 	 * All other files do I/O in cluster sized blocks
20772290da1Snatano 	 */
20872290da1Snatano 	if (sp)
20972290da1Snatano 		*sp = pmp->pm_bpcluster;
21072290da1Snatano 
21172290da1Snatano 	/*
21272290da1Snatano 	 * Rummage around in the FAT cache, maybe we can avoid tromping
21372290da1Snatano 	 * thru every FAT entry for the file. And, keep track of how far
21472290da1Snatano 	 * off the cache was from where we wanted to be.
21572290da1Snatano 	 */
21672290da1Snatano 	i = 0;
21772290da1Snatano 	fc_lookup(dep, findcn, &i, &cn);
21872290da1Snatano 	DPRINTF(("%s(bpcluster=%lu i=%lu cn=%lu\n", __func__, pmp->pm_bpcluster,
21972290da1Snatano 	    i, cn));
22072290da1Snatano 	if ((bn = findcn - i) >= LMMAX) {
22172290da1Snatano 		fc_largedistance++;
22272290da1Snatano 		fc_wherefrom = i;
22372290da1Snatano 		fc_whereto = findcn;
22472290da1Snatano 		fc_lastclust = dep->de_fc[FC_LASTFC].fc_frcn;
22572290da1Snatano 	} else
22672290da1Snatano 		fc_lmdistance[bn]++;
22772290da1Snatano 
22872290da1Snatano 	/*
22972290da1Snatano 	 * Handle all other files or directories the normal way.
23072290da1Snatano 	 */
23172290da1Snatano 	for (; i < findcn; i++) {
23272290da1Snatano 		/*
23372290da1Snatano 		 * Stop with all reserved clusters, not just with EOF.
23472290da1Snatano 		 */
23572290da1Snatano 		if (cn >= (CLUST_RSRVD & pmp->pm_fatmask))
23672290da1Snatano 			goto hiteof;
23772290da1Snatano 
23872290da1Snatano 		/*
23972290da1Snatano 		 * Also stop when cluster is not in the filesystem
24072290da1Snatano 		 */
24172290da1Snatano 		if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster) {
24272290da1Snatano 			DPRINTF(("%s(cn, %lu not in %lu..%lu)\n", __func__,
24372290da1Snatano 				cn, (u_long)CLUST_FIRST, pmp->pm_maxcluster));
24472290da1Snatano 			if (bp)
24572290da1Snatano 				brelse(bp, 0);
24672290da1Snatano 			return (EINVAL);
24772290da1Snatano 		}
24872290da1Snatano 
24972290da1Snatano 		byteoffset = FATOFS(pmp, cn);
25072290da1Snatano 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
25172290da1Snatano 		if (bn != bp_bn) {
25272290da1Snatano 			if (bp)
25372290da1Snatano 				brelse(bp, 0);
25472290da1Snatano 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
25572290da1Snatano 			    0, &bp);
25672290da1Snatano 			if (error) {
25772290da1Snatano 				DPRINTF(("%s(bread, %d)\n", __func__, error));
25872290da1Snatano 				return (error);
25972290da1Snatano 			}
26072290da1Snatano 			bp_bn = bn;
26172290da1Snatano 		}
26272290da1Snatano 		prevcn = cn;
26372290da1Snatano 		if (bo >= bsize) {
26472290da1Snatano 			if (bp)
26572290da1Snatano 				brelse(bp, 0);
26672290da1Snatano 			DPRINTF(("%s(block, %lu >= %lu)\n", __func__, bo,
26772290da1Snatano 			    bsize));
26872290da1Snatano 			return (EIO);
26972290da1Snatano 		}
27072290da1Snatano 		KASSERT(bp != NULL);
27172290da1Snatano 		if (FAT32(pmp))
27272290da1Snatano 			cn = getulong((char *)bp->b_data + bo);
27372290da1Snatano 		else
27472290da1Snatano 			cn = getushort((char *)bp->b_data + bo);
27572290da1Snatano 		if (FAT12(pmp) && (prevcn & 1))
27672290da1Snatano 			cn >>= 4;
27772290da1Snatano 		DPRINTF(("%s(cn=%lu masked=%lu)\n", __func__, cn,
27872290da1Snatano 		    cn & pmp->pm_fatmask));
27972290da1Snatano 		cn &= pmp->pm_fatmask;
28072290da1Snatano 	}
28172290da1Snatano 
28272290da1Snatano 	if (!MSDOSFSEOF(cn, pmp->pm_fatmask)) {
28372290da1Snatano 		if (bp)
28472290da1Snatano 			brelse(bp, 0);
28572290da1Snatano 		if (bnp)
28672290da1Snatano 			*bnp = cntobn(pmp, cn);
28772290da1Snatano 		if (cnp)
28872290da1Snatano 			*cnp = cn;
28972290da1Snatano 		DPRINTF(("%s(bn=%lu, cn=%lu)\n", __func__, cntobn(pmp, cn),
29072290da1Snatano 		    cn));
29172290da1Snatano 		fc_setcache(dep, FC_LASTMAP, i, cn);
29272290da1Snatano 		return (0);
29372290da1Snatano 	}
29472290da1Snatano 
29572290da1Snatano hiteof:;
29672290da1Snatano 	if (cnp)
29772290da1Snatano 		*cnp = i;
29872290da1Snatano 	if (bp)
29972290da1Snatano 		brelse(bp, 0);
30072290da1Snatano 	/* update last file cluster entry in the FAT cache */
30172290da1Snatano 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
30272290da1Snatano 	DPRINTF(("%s(eof, %lu)\n", __func__, i));
30372290da1Snatano 	return (E2BIG);
30472290da1Snatano }
30572290da1Snatano 
30672290da1Snatano /*
30772290da1Snatano  * Find the closest entry in the FAT cache to the cluster we are looking
30872290da1Snatano  * for.
30972290da1Snatano  */
31072290da1Snatano void
fc_lookup(struct denode * dep,u_long findcn,u_long * frcnp,u_long * fsrcnp)31172290da1Snatano fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
31272290da1Snatano {
31372290da1Snatano 	int i;
31472290da1Snatano 	u_long cn;
31572290da1Snatano 	struct fatcache *closest = 0;
31672290da1Snatano 
31772290da1Snatano 	for (i = 0; i < FC_SIZE; i++) {
31872290da1Snatano 		cn = dep->de_fc[i].fc_frcn;
31972290da1Snatano 		if (cn != FCE_EMPTY && cn <= findcn) {
32072290da1Snatano 			if (closest == 0 || cn > closest->fc_frcn)
32172290da1Snatano 				closest = &dep->de_fc[i];
32272290da1Snatano 		}
32372290da1Snatano 	}
32472290da1Snatano 	if (closest) {
32572290da1Snatano 		*frcnp = closest->fc_frcn;
32672290da1Snatano 		*fsrcnp = closest->fc_fsrcn;
32772290da1Snatano 	}
32872290da1Snatano }
32972290da1Snatano 
33072290da1Snatano /*
33172290da1Snatano  * Purge the FAT cache in denode dep of all entries relating to file
33272290da1Snatano  * relative cluster frcn and beyond.
33372290da1Snatano  */
33472290da1Snatano void
fc_purge(struct denode * dep,u_int frcn)33572290da1Snatano fc_purge(struct denode *dep, u_int frcn)
33672290da1Snatano {
33772290da1Snatano 	int i;
33872290da1Snatano 	struct fatcache *fcp;
33972290da1Snatano 
34072290da1Snatano 	fcp = dep->de_fc;
34172290da1Snatano 	for (i = 0; i < FC_SIZE; i++, fcp++) {
34272290da1Snatano 		if (fcp->fc_frcn >= frcn)
34372290da1Snatano 			fcp->fc_frcn = FCE_EMPTY;
34472290da1Snatano 	}
34572290da1Snatano }
34672290da1Snatano 
34772290da1Snatano /*
34872290da1Snatano  * Update the FAT.
34972290da1Snatano  * If mirroring the FAT, update all copies, with the first copy as last.
35072290da1Snatano  * Else update only the current FAT (ignoring the others).
35172290da1Snatano  *
35272290da1Snatano  * pmp	 - msdosfsmount structure for filesystem to update
35372290da1Snatano  * bp	 - addr of modified FAT block
35472290da1Snatano  * fatbn - block number relative to begin of filesystem of the modified FAT block.
35572290da1Snatano  */
35672290da1Snatano void
updatefats(struct msdosfsmount * pmp,struct mkfsbuf * bp,u_long fatbn)35772290da1Snatano updatefats(struct msdosfsmount *pmp, struct mkfsbuf *bp, u_long fatbn)
35872290da1Snatano {
35972290da1Snatano 	int i, error;
36072290da1Snatano 	struct mkfsbuf *bpn;
36172290da1Snatano 
36272290da1Snatano 	DPRINTF(("%s(pmp %p, bp %p, fatbn %lu)\n", __func__, pmp, bp, fatbn));
36372290da1Snatano 
36472290da1Snatano 	/*
36572290da1Snatano 	 * If we have an FSInfo block, update it.
36672290da1Snatano 	 */
36772290da1Snatano 	if (pmp->pm_fsinfo) {
36872290da1Snatano 		u_long cn = pmp->pm_nxtfree;
36972290da1Snatano 
37072290da1Snatano 		if (pmp->pm_freeclustercount
37172290da1Snatano 		    && (pmp->pm_inusemap[cn / N_INUSEBITS]
37272290da1Snatano 			& (1 << (cn % N_INUSEBITS)))) {
37372290da1Snatano 			/*
37472290da1Snatano 			 * The cluster indicated in FSInfo isn't free
37572290da1Snatano 			 * any longer.  Got get a new free one.
37672290da1Snatano 			 */
37772290da1Snatano 			for (cn = 0; cn < pmp->pm_maxcluster; cn++)
37872290da1Snatano 				if (pmp->pm_inusemap[cn / N_INUSEBITS] != (u_int)-1)
37972290da1Snatano 					break;
38072290da1Snatano 			pmp->pm_nxtfree = cn
38172290da1Snatano 				+ ffs(pmp->pm_inusemap[cn / N_INUSEBITS]
38272290da1Snatano 				      ^ (u_int)-1) - 1;
38372290da1Snatano 		}
38472290da1Snatano 		/*
38572290da1Snatano 		 * XXX  If the fsinfo block is stored on media with
38672290da1Snatano 		 *      2KB or larger sectors, is the fsinfo structure
38772290da1Snatano 		 *      padded at the end or in the middle?
38872290da1Snatano 		 */
38972290da1Snatano 		if (bread(pmp->pm_devvp, de_bn2kb(pmp, pmp->pm_fsinfo),
39072290da1Snatano 		    pmp->pm_BytesPerSec, B_MODIFY, &bpn) != 0) {
39172290da1Snatano 			/*
39272290da1Snatano 			 * Ignore the error, but turn off FSInfo update for the future.
39372290da1Snatano 			 */
39472290da1Snatano 			pmp->pm_fsinfo = 0;
39572290da1Snatano 		} else {
39672290da1Snatano 			struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
39772290da1Snatano 
39872290da1Snatano 			putulong(fp->fsinfree, pmp->pm_freeclustercount);
39972290da1Snatano 			putulong(fp->fsinxtfree, pmp->pm_nxtfree);
40072290da1Snatano 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
40172290da1Snatano 				bwrite(bpn);
40272290da1Snatano 			else
40372290da1Snatano 				bdwrite(bpn);
40472290da1Snatano 		}
40572290da1Snatano 	}
40672290da1Snatano 
40772290da1Snatano 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
40872290da1Snatano 		/*
40972290da1Snatano 		 * Now copy the block(s) of the modified FAT to the other copies of
41072290da1Snatano 		 * the FAT and write them out.  This is faster than reading in the
41172290da1Snatano 		 * other FATs and then writing them back out.  This could tie up
41272290da1Snatano 		 * the FAT for quite a while. Preventing others from accessing it.
41372290da1Snatano 		 * To prevent us from going after the FAT quite so much we use
41472290da1Snatano 		 * delayed writes, unless they specified "synchronous" when the
41572290da1Snatano 		 * filesystem was mounted.  If synch is asked for then use
41672290da1Snatano 		 * bwrite()'s and really slow things down.
41772290da1Snatano 		 */
41872290da1Snatano 		for (i = 1; i < pmp->pm_FATs; i++) {
41972290da1Snatano 			fatbn += pmp->pm_FATsecs;
42072290da1Snatano 			/* getblk() never fails */
42172290da1Snatano 			bpn = getblk(pmp->pm_devvp, de_bn2kb(pmp, fatbn),
42272290da1Snatano 			    bp->b_bcount, 0, 0);
42372290da1Snatano 			memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
42472290da1Snatano 			if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT) {
42572290da1Snatano 				error = bwrite(bpn);
42672290da1Snatano 				if (error)
42772290da1Snatano 					printf("%s: copy FAT %d (error=%d)\n",
42872290da1Snatano 						 __func__, i, error);
42972290da1Snatano 			} else
43072290da1Snatano 				bdwrite(bpn);
43172290da1Snatano 		}
43272290da1Snatano 	}
43372290da1Snatano 
43472290da1Snatano 	/*
43572290da1Snatano 	 * Write out the first (or current) FAT last.
43672290da1Snatano 	 */
43772290da1Snatano 	if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT) {
43872290da1Snatano 		error =  bwrite(bp);
43972290da1Snatano 		if (error)
44072290da1Snatano 			printf("%s: write FAT (error=%d)\n",
44172290da1Snatano 				__func__, error);
44272290da1Snatano 	} else
44372290da1Snatano 		bdwrite(bp);
44472290da1Snatano 	/*
44572290da1Snatano 	 * Maybe update fsinfo sector here?
44672290da1Snatano 	 */
44772290da1Snatano }
44872290da1Snatano 
44972290da1Snatano /*
45072290da1Snatano  * Updating entries in 12 bit FATs is a pain in the butt.
45172290da1Snatano  *
45272290da1Snatano  * The following picture shows where nibbles go when moving from a 12 bit
45372290da1Snatano  * cluster number into the appropriate bytes in the FAT.
45472290da1Snatano  *
45572290da1Snatano  *	byte m        byte m+1      byte m+2
45672290da1Snatano  *	+----+----+   +----+----+   +----+----+
45772290da1Snatano  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
45872290da1Snatano  *	+----+----+   +----+----+   +----+----+
45972290da1Snatano  *
46072290da1Snatano  *	+----+----+----+   +----+----+----+
46172290da1Snatano  *	|  3    0    1 |   |  4    5    2 |
46272290da1Snatano  *	+----+----+----+   +----+----+----+
46372290da1Snatano  *	cluster n	   cluster n+1
46472290da1Snatano  *
46572290da1Snatano  * Where n is even. m = n + (n >> 2)
46672290da1Snatano  *
46772290da1Snatano  */
46872290da1Snatano static inline void
usemap_alloc(struct msdosfsmount * pmp,u_long cn)46972290da1Snatano usemap_alloc(struct msdosfsmount *pmp, u_long cn)
47072290da1Snatano {
47172290da1Snatano 
47272290da1Snatano 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
47372290da1Snatano 	pmp->pm_freeclustercount--;
47472290da1Snatano }
47572290da1Snatano 
47672290da1Snatano static inline void
usemap_free(struct msdosfsmount * pmp,u_long cn)47772290da1Snatano usemap_free(struct msdosfsmount *pmp, u_long cn)
47872290da1Snatano {
47972290da1Snatano 
48072290da1Snatano 	pmp->pm_freeclustercount++;
48172290da1Snatano 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
48272290da1Snatano }
48372290da1Snatano 
48472290da1Snatano int
clusterfree(struct msdosfsmount * pmp,u_long cluster,u_long * oldcnp)48572290da1Snatano clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
48672290da1Snatano {
48772290da1Snatano 	int error;
48872290da1Snatano 	u_long oldcn;
48972290da1Snatano 
49072290da1Snatano 	usemap_free(pmp, cluster);
49172290da1Snatano 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
49272290da1Snatano 	if (error) {
49372290da1Snatano 		usemap_alloc(pmp, cluster);
49472290da1Snatano 		return (error);
49572290da1Snatano 	}
49672290da1Snatano 	/*
49772290da1Snatano 	 * If the cluster was successfully marked free, then update
49872290da1Snatano 	 * the count of free clusters, and turn off the "allocated"
49972290da1Snatano 	 * bit in the "in use" cluster bit map.
50072290da1Snatano 	 */
50172290da1Snatano 	if (oldcnp)
50272290da1Snatano 		*oldcnp = oldcn;
50372290da1Snatano 	return (0);
50472290da1Snatano }
50572290da1Snatano 
50672290da1Snatano /*
50772290da1Snatano  * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
50872290da1Snatano  *
50972290da1Snatano  * function	- whether to get or set a fat entry
51072290da1Snatano  * pmp		- address of the msdosfsmount structure for the filesystem
51172290da1Snatano  *		  whose FAT is to be manipulated.
51272290da1Snatano  * cn		- which cluster is of interest
51372290da1Snatano  * oldcontents	- address of a word that is to receive the contents of the
51472290da1Snatano  *		  cluster'th entry if this is a get function
51572290da1Snatano  * newcontents	- the new value to be written into the cluster'th element of
51672290da1Snatano  *		  the FAT if this is a set function.
51772290da1Snatano  *
51872290da1Snatano  * This function can also be used to free a cluster by setting the FAT entry
51972290da1Snatano  * for a cluster to 0.
52072290da1Snatano  *
52172290da1Snatano  * All copies of the FAT are updated if this is a set function. NOTE: If
52272290da1Snatano  * fatentry() marks a cluster as free it does not update the inusemap in
52372290da1Snatano  * the msdosfsmount structure. This is left to the caller.
52472290da1Snatano  */
52572290da1Snatano int
fatentry(int function,struct msdosfsmount * pmp,u_long cn,u_long * oldcontents,u_long newcontents)52672290da1Snatano fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents, u_long newcontents)
52772290da1Snatano {
52872290da1Snatano 	int error;
52972290da1Snatano 	u_long readcn;
53072290da1Snatano 	u_long bn, bo, bsize, byteoffset;
53172290da1Snatano 	struct mkfsbuf *bp;
53272290da1Snatano 
53372290da1Snatano 	DPRINTF(("%s(func %d, pmp %p, clust %lu, oldcon %p, newcon " "%lx)\n",
53472290da1Snatano 	    __func__, function, pmp, cn, oldcontents, newcontents));
53572290da1Snatano 
53672290da1Snatano #ifdef DIAGNOSTIC
53772290da1Snatano 	/*
53872290da1Snatano 	 * Be sure they asked us to do something.
53972290da1Snatano 	 */
54072290da1Snatano 	if ((function & (FAT_SET | FAT_GET)) == 0) {
54172290da1Snatano 		DPRINTF(("%s(): function code doesn't specify get or set\n",
54272290da1Snatano 		    __func__));
54372290da1Snatano 		return (EINVAL);
54472290da1Snatano 	}
54572290da1Snatano 
54672290da1Snatano 	/*
54772290da1Snatano 	 * If they asked us to return a cluster number but didn't tell us
54872290da1Snatano 	 * where to put it, give them an error.
54972290da1Snatano 	 */
55072290da1Snatano 	if ((function & FAT_GET) && oldcontents == NULL) {
55172290da1Snatano 		DPRINTF(("%s(): get function with no place to put result\n",
55272290da1Snatano 			__func__));
55372290da1Snatano 		return (EINVAL);
55472290da1Snatano 	}
55572290da1Snatano #endif
55672290da1Snatano 
55772290da1Snatano 	/*
55872290da1Snatano 	 * Be sure the requested cluster is in the filesystem.
55972290da1Snatano 	 */
56072290da1Snatano 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
56172290da1Snatano 		return (EINVAL);
56272290da1Snatano 
56372290da1Snatano 	byteoffset = FATOFS(pmp, cn);
56472290da1Snatano 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
56572290da1Snatano 	if ((error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
56672290da1Snatano 	    0, &bp)) != 0) {
56772290da1Snatano 		return (error);
56872290da1Snatano 	}
56972290da1Snatano 
57072290da1Snatano 	if (function & FAT_GET) {
57172290da1Snatano 		if (FAT32(pmp))
57272290da1Snatano 			readcn = getulong((char *)bp->b_data + bo);
57372290da1Snatano 		else
57472290da1Snatano 			readcn = getushort((char *)bp->b_data + bo);
57572290da1Snatano 		if (FAT12(pmp) & (cn & 1))
57672290da1Snatano 			readcn >>= 4;
57772290da1Snatano 		readcn &= pmp->pm_fatmask;
57872290da1Snatano 		*oldcontents = readcn;
57972290da1Snatano 	}
58072290da1Snatano 	if (function & FAT_SET) {
58172290da1Snatano 		switch (pmp->pm_fatmask) {
58272290da1Snatano 		case FAT12_MASK:
58372290da1Snatano 			readcn = getushort((char *)bp->b_data + bo);
58472290da1Snatano 			if (cn & 1) {
58572290da1Snatano 				readcn &= 0x000f;
58672290da1Snatano 				readcn |= newcontents << 4;
58772290da1Snatano 			} else {
58872290da1Snatano 				readcn &= 0xf000;
58972290da1Snatano 				readcn |= newcontents & 0xfff;
59072290da1Snatano 			}
59172290da1Snatano 			putushort((char *)bp->b_data + bo, readcn);
59272290da1Snatano 			break;
59372290da1Snatano 		case FAT16_MASK:
59472290da1Snatano 			putushort((char *)bp->b_data + bo, newcontents);
59572290da1Snatano 			break;
59672290da1Snatano 		case FAT32_MASK:
59772290da1Snatano 			/*
59872290da1Snatano 			 * According to spec we have to retain the
59972290da1Snatano 			 * high order bits of the FAT entry.
60072290da1Snatano 			 */
60172290da1Snatano 			readcn = getulong((char *)bp->b_data + bo);
60272290da1Snatano 			readcn &= ~FAT32_MASK;
60372290da1Snatano 			readcn |= newcontents & FAT32_MASK;
60472290da1Snatano 			putulong((char *)bp->b_data + bo, readcn);
60572290da1Snatano 			break;
60672290da1Snatano 		}
60772290da1Snatano 		updatefats(pmp, bp, bn);
60872290da1Snatano 		bp = NULL;
60972290da1Snatano 		pmp->pm_fmod = 1;
61072290da1Snatano 	}
61172290da1Snatano 	if (bp)
61272290da1Snatano 		brelse(bp, 0);
61372290da1Snatano 	return (0);
61472290da1Snatano }
61572290da1Snatano 
61672290da1Snatano /*
61772290da1Snatano  * Update a contiguous cluster chain
61872290da1Snatano  *
61972290da1Snatano  * pmp	    - mount point
62072290da1Snatano  * start    - first cluster of chain
62172290da1Snatano  * count    - number of clusters in chain
62272290da1Snatano  * fillwith - what to write into FAT entry of last cluster
62372290da1Snatano  */
62472290da1Snatano static int
fatchain(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith)62572290da1Snatano fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
62672290da1Snatano {
62772290da1Snatano 	int error;
62872290da1Snatano 	u_long bn, bo, bsize, byteoffset, readcn, newc;
62972290da1Snatano 	struct mkfsbuf *bp;
63072290da1Snatano 
63172290da1Snatano 	DPRINTF(("%s(pmp %p, start %lu, count %lu, fillwith %lx)\n", __func__,
63272290da1Snatano 	    pmp, start, count, fillwith));
63372290da1Snatano 	/*
63472290da1Snatano 	 * Be sure the clusters are in the filesystem.
63572290da1Snatano 	 */
63672290da1Snatano 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
63772290da1Snatano 		return (EINVAL);
63872290da1Snatano 
63972290da1Snatano 	while (count > 0) {
64072290da1Snatano 		byteoffset = FATOFS(pmp, start);
64172290da1Snatano 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
64272290da1Snatano 		error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
64372290da1Snatano 		    B_MODIFY, &bp);
64472290da1Snatano 		if (error) {
64572290da1Snatano 			return (error);
64672290da1Snatano 		}
64772290da1Snatano 		while (count > 0) {
64872290da1Snatano 			start++;
64972290da1Snatano 			newc = --count > 0 ? start : fillwith;
65072290da1Snatano 			switch (pmp->pm_fatmask) {
65172290da1Snatano 			case FAT12_MASK:
65272290da1Snatano 				readcn = getushort((char *)bp->b_data + bo);
65372290da1Snatano 				if (start & 1) {
65472290da1Snatano 					readcn &= 0xf000;
65572290da1Snatano 					readcn |= newc & 0xfff;
65672290da1Snatano 				} else {
65772290da1Snatano 					readcn &= 0x000f;
65872290da1Snatano 					readcn |= newc << 4;
65972290da1Snatano 				}
66072290da1Snatano 				putushort((char *)bp->b_data + bo, readcn);
66172290da1Snatano 				bo++;
66272290da1Snatano 				if (!(start & 1))
66372290da1Snatano 					bo++;
66472290da1Snatano 				break;
66572290da1Snatano 			case FAT16_MASK:
66672290da1Snatano 				putushort((char *)bp->b_data + bo, newc);
66772290da1Snatano 				bo += 2;
66872290da1Snatano 				break;
66972290da1Snatano 			case FAT32_MASK:
67072290da1Snatano 				readcn = getulong((char *)bp->b_data + bo);
67172290da1Snatano 				readcn &= ~pmp->pm_fatmask;
67272290da1Snatano 				readcn |= newc & pmp->pm_fatmask;
67372290da1Snatano 				putulong((char *)bp->b_data + bo, readcn);
67472290da1Snatano 				bo += 4;
67572290da1Snatano 				break;
67672290da1Snatano 			}
67772290da1Snatano 			if (bo >= bsize)
67872290da1Snatano 				break;
67972290da1Snatano 		}
68072290da1Snatano 		updatefats(pmp, bp, bn);
68172290da1Snatano 	}
68272290da1Snatano 	pmp->pm_fmod = 1;
68372290da1Snatano 	return (0);
68472290da1Snatano }
68572290da1Snatano 
68672290da1Snatano /*
68772290da1Snatano  * Check the length of a free cluster chain starting at start.
68872290da1Snatano  *
68972290da1Snatano  * pmp	 - mount point
69072290da1Snatano  * start - start of chain
69172290da1Snatano  * count - maximum interesting length
69272290da1Snatano  */
69372290da1Snatano int
chainlength(struct msdosfsmount * pmp,u_long start,u_long count)69472290da1Snatano chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
69572290da1Snatano {
69672290da1Snatano 	u_long idx, max_idx;
69772290da1Snatano 	u_int map;
69872290da1Snatano 	u_long len;
69972290da1Snatano 
70072290da1Snatano 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
70172290da1Snatano 	idx = start / N_INUSEBITS;
70272290da1Snatano 	start %= N_INUSEBITS;
70372290da1Snatano 	map = pmp->pm_inusemap[idx];
70472290da1Snatano 	map &= ~((1 << start) - 1);
70572290da1Snatano 	if (map) {
70672290da1Snatano 		len = ffs(map) - 1 - start;
70772290da1Snatano 		return (len > count ? count : len);
70872290da1Snatano 	}
70972290da1Snatano 	len = N_INUSEBITS - start;
71072290da1Snatano 	if (len >= count)
71172290da1Snatano 		return (count);
71272290da1Snatano 	while (++idx <= max_idx) {
71372290da1Snatano 		if (len >= count)
71472290da1Snatano 			break;
71572290da1Snatano 		if ((map = pmp->pm_inusemap[idx]) != 0) {
71672290da1Snatano 			len +=  ffs(map) - 1;
71772290da1Snatano 			break;
71872290da1Snatano 		}
71972290da1Snatano 		len += N_INUSEBITS;
72072290da1Snatano 	}
72172290da1Snatano 	return (len > count ? count : len);
72272290da1Snatano }
72372290da1Snatano 
72472290da1Snatano /*
7258e544e80Sjsg  * Allocate contiguous free clusters.
72672290da1Snatano  *
72772290da1Snatano  * pmp	      - mount point.
72872290da1Snatano  * start      - start of cluster chain.
72972290da1Snatano  * count      - number of clusters to allocate.
73072290da1Snatano  * fillwith   - put this value into the FAT entry for the
73172290da1Snatano  *		last allocated cluster.
73272290da1Snatano  * retcluster - put the first allocated cluster's number here.
73372290da1Snatano  * got	      - how many clusters were actually allocated.
73472290da1Snatano  */
73572290da1Snatano int
chainalloc(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith,u_long * retcluster,u_long * got)73672290da1Snatano chainalloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith, u_long *retcluster, u_long *got)
73772290da1Snatano {
73872290da1Snatano 	int error;
73972290da1Snatano 	u_long cl, n;
74072290da1Snatano 
74172290da1Snatano 	for (cl = start, n = count; n-- > 0;)
74272290da1Snatano 		usemap_alloc(pmp, cl++);
74372290da1Snatano 	if ((error = fatchain(pmp, start, count, fillwith)) != 0)
74472290da1Snatano 		return (error);
74572290da1Snatano 
74672290da1Snatano 	DPRINTF(("%s(): allocated cluster chain at %lu (%lu clusters)\n",
74772290da1Snatano 	    __func__, start, count));
74872290da1Snatano 	if (retcluster)
74972290da1Snatano 		*retcluster = start;
75072290da1Snatano 	if (got)
75172290da1Snatano 		*got = count;
75272290da1Snatano 	return (0);
75372290da1Snatano }
75472290da1Snatano 
75572290da1Snatano /*
75672290da1Snatano  * Allocate contiguous free clusters.
75772290da1Snatano  *
75872290da1Snatano  * pmp	      - mount point.
75972290da1Snatano  * start      - preferred start of cluster chain.
76072290da1Snatano  * count      - number of clusters requested.
76172290da1Snatano  * fillwith   - put this value into the FAT entry for the
76272290da1Snatano  *		last allocated cluster.
76372290da1Snatano  * retcluster - put the first allocated cluster's number here.
76472290da1Snatano  * got	      - how many clusters were actually allocated.
76572290da1Snatano  */
76672290da1Snatano int
clusteralloc(struct msdosfsmount * pmp,u_long start,u_long count,u_long * retcluster,u_long * got)76772290da1Snatano clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long *retcluster, u_long *got)
76872290da1Snatano {
76972290da1Snatano 	u_long idx;
77072290da1Snatano 	u_long len, newst, foundl, cn, l;
7718e544e80Sjsg 	u_long foundcn = 0; /* XXX: foundcn could be used uninitialized */
77272290da1Snatano 	u_long fillwith = CLUST_EOFE;
77372290da1Snatano 	u_int map;
77472290da1Snatano 
77572290da1Snatano 	DPRINTF(("%s(): find %lu clusters\n", __func__, count));
77672290da1Snatano 	if (start) {
77772290da1Snatano 		if ((len = chainlength(pmp, start, count)) >= count)
77872290da1Snatano 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
77972290da1Snatano 	} else {
78072290da1Snatano 		/*
78172290da1Snatano 		 * This is a new file, initialize start
78272290da1Snatano 		 */
78372290da1Snatano 		struct timeval tv;
78472290da1Snatano 
78572290da1Snatano 		microtime(&tv);
78672290da1Snatano 		start = (tv.tv_usec >> 10) | tv.tv_usec;
78772290da1Snatano 		len = 0;
78872290da1Snatano 	}
78972290da1Snatano 
79072290da1Snatano 	/*
79172290da1Snatano 	 * Start at a (pseudo) random place to maximize cluster runs
79272290da1Snatano 	 * under multiple writers.
79372290da1Snatano 	 */
79472290da1Snatano 	newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1);
79572290da1Snatano 	foundl = 0;
79672290da1Snatano 
79772290da1Snatano 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
79872290da1Snatano 		idx = cn / N_INUSEBITS;
79972290da1Snatano 		map = pmp->pm_inusemap[idx];
80072290da1Snatano 		map |= (1 << (cn % N_INUSEBITS)) - 1;
80172290da1Snatano 		if (map != (u_int)-1) {
80272290da1Snatano 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
80372290da1Snatano 			if ((l = chainlength(pmp, cn, count)) >= count)
80472290da1Snatano 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
80572290da1Snatano 			if (l > foundl) {
80672290da1Snatano 				foundcn = cn;
80772290da1Snatano 				foundl = l;
80872290da1Snatano 			}
80972290da1Snatano 			cn += l + 1;
81072290da1Snatano 			continue;
81172290da1Snatano 		}
81272290da1Snatano 		cn += N_INUSEBITS - cn % N_INUSEBITS;
81372290da1Snatano 	}
81472290da1Snatano 	for (cn = 0; cn < newst;) {
81572290da1Snatano 		idx = cn / N_INUSEBITS;
81672290da1Snatano 		map = pmp->pm_inusemap[idx];
81772290da1Snatano 		map |= (1 << (cn % N_INUSEBITS)) - 1;
81872290da1Snatano 		if (map != (u_int)-1) {
81972290da1Snatano 			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
82072290da1Snatano 			if ((l = chainlength(pmp, cn, count)) >= count)
82172290da1Snatano 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
82272290da1Snatano 			if (l > foundl) {
82372290da1Snatano 				foundcn = cn;
82472290da1Snatano 				foundl = l;
82572290da1Snatano 			}
82672290da1Snatano 			cn += l + 1;
82772290da1Snatano 			continue;
82872290da1Snatano 		}
82972290da1Snatano 		cn += N_INUSEBITS - cn % N_INUSEBITS;
83072290da1Snatano 	}
83172290da1Snatano 
83272290da1Snatano 	if (!foundl)
83372290da1Snatano 		return (ENOSPC);
83472290da1Snatano 
83572290da1Snatano 	if (len)
83672290da1Snatano 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
83772290da1Snatano 	else
83872290da1Snatano 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
83972290da1Snatano }
84072290da1Snatano 
84172290da1Snatano 
84272290da1Snatano /*
84372290da1Snatano  * Free a chain of clusters.
84472290da1Snatano  *
84572290da1Snatano  * pmp		- address of the msdosfs mount structure for the filesystem
84672290da1Snatano  *		  containing the cluster chain to be freed.
84772290da1Snatano  * startcluster - number of the 1st cluster in the chain of clusters to be
84872290da1Snatano  *		  freed.
84972290da1Snatano  */
85072290da1Snatano int
freeclusterchain(struct msdosfsmount * pmp,u_long cluster)85172290da1Snatano freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
85272290da1Snatano {
85372290da1Snatano 	int error;
85472290da1Snatano 	struct mkfsbuf *bp = NULL;
85572290da1Snatano 	u_long bn, bo, bsize, byteoffset;
85672290da1Snatano 	u_long readcn, lbn = -1;
85772290da1Snatano 
85872290da1Snatano 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
85972290da1Snatano 		byteoffset = FATOFS(pmp, cluster);
86072290da1Snatano 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
86172290da1Snatano 		if (lbn != bn) {
86272290da1Snatano 			if (bp)
86372290da1Snatano 				updatefats(pmp, bp, lbn);
86472290da1Snatano 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
86572290da1Snatano 			    B_MODIFY, &bp);
86672290da1Snatano 			if (error) {
86772290da1Snatano 				return (error);
86872290da1Snatano 			}
86972290da1Snatano 			lbn = bn;
87072290da1Snatano 		}
87172290da1Snatano 		usemap_free(pmp, cluster);
87272290da1Snatano 		KASSERT(bp != NULL);
87372290da1Snatano 		switch (pmp->pm_fatmask) {
87472290da1Snatano 		case FAT12_MASK:
87572290da1Snatano 			readcn = getushort((char *)bp->b_data + bo);
87672290da1Snatano 			if (cluster & 1) {
87772290da1Snatano 				cluster = readcn >> 4;
87872290da1Snatano 				readcn &= 0x000f;
87972290da1Snatano 				readcn |= MSDOSFSFREE << 4;
88072290da1Snatano 			} else {
88172290da1Snatano 				cluster = readcn;
88272290da1Snatano 				readcn &= 0xf000;
88372290da1Snatano 				readcn |= MSDOSFSFREE & 0xfff;
88472290da1Snatano 			}
88572290da1Snatano 			putushort((char *)bp->b_data + bo, readcn);
88672290da1Snatano 			break;
88772290da1Snatano 		case FAT16_MASK:
88872290da1Snatano 			cluster = getushort((char *)bp->b_data + bo);
88972290da1Snatano 			putushort((char *)bp->b_data + bo, MSDOSFSFREE);
89072290da1Snatano 			break;
89172290da1Snatano 		case FAT32_MASK:
89272290da1Snatano 			cluster = getulong((char *)bp->b_data + bo);
89372290da1Snatano 			putulong((char *)bp->b_data + bo,
89472290da1Snatano 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
89572290da1Snatano 			break;
89672290da1Snatano 		}
89772290da1Snatano 		cluster &= pmp->pm_fatmask;
89872290da1Snatano 	}
89972290da1Snatano 	if (bp)
90072290da1Snatano 		updatefats(pmp, bp, bn);
90172290da1Snatano 	return (0);
90272290da1Snatano }
90372290da1Snatano 
90472290da1Snatano /*
90572290da1Snatano  * Read in FAT blocks looking for free clusters. For every free cluster
90672290da1Snatano  * found turn off its corresponding bit in the pm_inusemap.
90772290da1Snatano  */
90872290da1Snatano int
fillinusemap(struct msdosfsmount * pmp)90972290da1Snatano fillinusemap(struct msdosfsmount *pmp)
91072290da1Snatano {
91172290da1Snatano 	struct mkfsbuf *bp = NULL;
91272290da1Snatano 	u_long cn, readcn;
91372290da1Snatano 	int error;
91472290da1Snatano 	u_long bn, bo, bsize, byteoffset;
91572290da1Snatano 
91672290da1Snatano 	/*
91772290da1Snatano 	 * Mark all clusters in use, we mark the free ones in the FAT scan
91872290da1Snatano 	 * loop further down.
91972290da1Snatano 	 */
92072290da1Snatano 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
92172290da1Snatano 		pmp->pm_inusemap[cn] = (u_int)-1;
92272290da1Snatano 
92372290da1Snatano 	/*
92472290da1Snatano 	 * Figure how many free clusters are in the filesystem by ripping
92572290da1Snatano 	 * through the FAT counting the number of entries whose content is
92672290da1Snatano 	 * zero.  These represent free clusters.
92772290da1Snatano 	 */
92872290da1Snatano 	pmp->pm_freeclustercount = 0;
92972290da1Snatano 	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
93072290da1Snatano 		byteoffset = FATOFS(pmp, cn);
93172290da1Snatano 		bo = byteoffset % pmp->pm_fatblocksize;
93272290da1Snatano 		if (!bo || !bp) {
93372290da1Snatano 			/* Read new FAT block */
93472290da1Snatano 			if (bp)
93572290da1Snatano 				brelse(bp, 0);
93672290da1Snatano 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
93772290da1Snatano 			error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
93872290da1Snatano 			    0, &bp);
93972290da1Snatano 			if (error) {
94072290da1Snatano 				return (error);
94172290da1Snatano 			}
94272290da1Snatano 		}
94372290da1Snatano 		if (FAT32(pmp))
94472290da1Snatano 			readcn = getulong((char *)bp->b_data + bo);
94572290da1Snatano 		else
94672290da1Snatano 			readcn = getushort((char *)bp->b_data + bo);
94772290da1Snatano 		if (FAT12(pmp) && (cn & 1))
94872290da1Snatano 			readcn >>= 4;
94972290da1Snatano 		readcn &= pmp->pm_fatmask;
95072290da1Snatano 
95172290da1Snatano 		if (readcn == 0)
95272290da1Snatano 			usemap_free(pmp, cn);
95372290da1Snatano 	}
95472290da1Snatano 	if (bp)
95572290da1Snatano 		brelse(bp, 0);
95672290da1Snatano 	return (0);
95772290da1Snatano }
95872290da1Snatano 
95972290da1Snatano /*
96072290da1Snatano  * Allocate a new cluster and chain it onto the end of the file.
96172290da1Snatano  *
96272290da1Snatano  * dep	 - the file to extend
96372290da1Snatano  * count - number of clusters to allocate
96472290da1Snatano  * bpp	 - where to return the address of the buf header for the first new
96572290da1Snatano  *	   file block
96672290da1Snatano  * ncp	 - where to put cluster number of the first newly allocated cluster
96772290da1Snatano  *	   If this pointer is 0, do not return the cluster number.
96872290da1Snatano  * flags - see fat.h
96972290da1Snatano  *
97072290da1Snatano  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
97172290da1Snatano  * the de_flag field of the denode and it does not change the de_FileSize
97272290da1Snatano  * field.  This is left for the caller to do.
97372290da1Snatano  */
97472290da1Snatano 
97572290da1Snatano int
extendfile(struct denode * dep,u_long count,struct mkfsbuf ** bpp,u_long * ncp,int flags)97672290da1Snatano extendfile(struct denode *dep, u_long count, struct mkfsbuf **bpp, u_long *ncp, int flags)
97772290da1Snatano {
97872290da1Snatano 	int error;
97972290da1Snatano 	u_long frcn = 0, cn, got;
98072290da1Snatano 	struct msdosfsmount *pmp = dep->de_pmp;
98172290da1Snatano 	struct mkfsbuf *bp;
98272290da1Snatano 
98372290da1Snatano 	/*
98472290da1Snatano 	 * Don't try to extend the root directory
98572290da1Snatano 	 */
98672290da1Snatano 	if (dep->de_StartCluster == MSDOSFSROOT
98772290da1Snatano 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
98872290da1Snatano 		DPRINTF(("%s(): attempt to extend root directory\n", __func__));
98972290da1Snatano 		return (ENOSPC);
99072290da1Snatano 	}
99172290da1Snatano 
99272290da1Snatano 	/*
99372290da1Snatano 	 * If the "file's last cluster" cache entry is empty, and the file
99472290da1Snatano 	 * is not empty, then fill the cache entry by calling pcbmap().
99572290da1Snatano 	 */
99672290da1Snatano 	fc_fileextends++;
99772290da1Snatano 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
99872290da1Snatano 	    dep->de_StartCluster != 0) {
99972290da1Snatano 		fc_lfcempty++;
100072290da1Snatano 		error = pcbmap(dep, CLUST_END, 0, &cn, 0);
100172290da1Snatano 		/* we expect it to return E2BIG */
100272290da1Snatano 		if (error != E2BIG)
100372290da1Snatano 			return (error);
100472290da1Snatano 	}
100572290da1Snatano 
100672290da1Snatano 	fc_last_to_nexttolast(dep);
100772290da1Snatano 
100872290da1Snatano 	while (count > 0) {
100972290da1Snatano 
101072290da1Snatano 		/*
101172290da1Snatano 		 * Allocate a new cluster chain and cat onto the end of the
101272290da1Snatano 		 * file.  If the file is empty we make de_StartCluster point
101372290da1Snatano 		 * to the new block.  Note that de_StartCluster being 0 is
101472290da1Snatano 		 * sufficient to be sure the file is empty since we exclude
101572290da1Snatano 		 * attempts to extend the root directory above, and the root
101672290da1Snatano 		 * dir is the only file with a startcluster of 0 that has
101772290da1Snatano 		 * blocks allocated (sort of).
101872290da1Snatano 		 */
101972290da1Snatano 
102072290da1Snatano 		if (dep->de_StartCluster == 0)
102172290da1Snatano 			cn = 0;
102272290da1Snatano 		else
102372290da1Snatano 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
102472290da1Snatano 		error = clusteralloc(pmp, cn, count, &cn, &got);
102572290da1Snatano 		if (error)
102672290da1Snatano 			return (error);
102772290da1Snatano 
102872290da1Snatano 		count -= got;
102972290da1Snatano 
103072290da1Snatano 		/*
103172290da1Snatano 		 * Give them the filesystem relative cluster number if they want
103272290da1Snatano 		 * it.
103372290da1Snatano 		 */
103472290da1Snatano 		if (ncp) {
103572290da1Snatano 			*ncp = cn;
103672290da1Snatano 			ncp = NULL;
103772290da1Snatano 		}
103872290da1Snatano 
103972290da1Snatano 		if (dep->de_StartCluster == 0) {
104072290da1Snatano 			dep->de_StartCluster = cn;
104172290da1Snatano 			frcn = 0;
104272290da1Snatano 		} else {
104372290da1Snatano 			error = fatentry(FAT_SET, pmp,
104472290da1Snatano 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
104572290da1Snatano 					 0, cn);
104672290da1Snatano 			if (error) {
104772290da1Snatano 				clusterfree(pmp, cn, NULL);
104872290da1Snatano 				return (error);
104972290da1Snatano 			}
105072290da1Snatano 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
105172290da1Snatano 		}
105272290da1Snatano 
105372290da1Snatano 		/*
105472290da1Snatano 		 * Update the "last cluster of the file" entry in the
105572290da1Snatano 		 * denode's FAT cache.
105672290da1Snatano 		 */
105772290da1Snatano 
105872290da1Snatano 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
105972290da1Snatano 		if ((flags & DE_CLEAR) &&
106072290da1Snatano 		    (dep->de_Attributes & ATTR_DIRECTORY)) {
106172290da1Snatano 			while (got-- > 0) {
106272290da1Snatano 				bp = getblk(pmp->pm_devvp,
106372290da1Snatano 				    de_bn2kb(pmp, cntobn(pmp, cn++)),
106472290da1Snatano 				    pmp->pm_bpcluster, 0, 0);
106572290da1Snatano 				clrbuf(bp);
106672290da1Snatano 				if (bpp) {
106772290da1Snatano 					*bpp = bp;
106872290da1Snatano 					bpp = NULL;
106972290da1Snatano 				} else {
107072290da1Snatano 					bdwrite(bp);
107172290da1Snatano 				}
107272290da1Snatano 			}
107372290da1Snatano 		}
107472290da1Snatano 	}
107572290da1Snatano 
107672290da1Snatano 	return (0);
107772290da1Snatano }
1078