xref: /freebsd/sys/fs/msdosfs/msdosfs_fat.c (revision 41e85eeab90dec540c7aa3973ba601bae1f16c10)
1c3aac50fSPeter Wemm /* $FreeBSD$ */
2952a6212SJordan K. Hubbard /*	$NetBSD: msdosfs_fat.c,v 1.28 1997/11/17 15:36:49 ws Exp $	*/
327a0bc89SDoug Rabson 
427a0bc89SDoug Rabson /*-
5d63027b6SPedro F. Giffuni  * SPDX-License-Identifier: BSD-4-Clause
6d63027b6SPedro F. Giffuni  *
7952a6212SJordan K. Hubbard  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
8952a6212SJordan K. Hubbard  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
927a0bc89SDoug Rabson  * All rights reserved.
1027a0bc89SDoug Rabson  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
1127a0bc89SDoug Rabson  *
1227a0bc89SDoug Rabson  * Redistribution and use in source and binary forms, with or without
1327a0bc89SDoug Rabson  * modification, are permitted provided that the following conditions
1427a0bc89SDoug Rabson  * are met:
1527a0bc89SDoug Rabson  * 1. Redistributions of source code must retain the above copyright
1627a0bc89SDoug Rabson  *    notice, this list of conditions and the following disclaimer.
1727a0bc89SDoug Rabson  * 2. Redistributions in binary form must reproduce the above copyright
1827a0bc89SDoug Rabson  *    notice, this list of conditions and the following disclaimer in the
1927a0bc89SDoug Rabson  *    documentation and/or other materials provided with the distribution.
2027a0bc89SDoug Rabson  * 3. All advertising materials mentioning features or use of this software
2127a0bc89SDoug Rabson  *    must display the following acknowledgement:
2227a0bc89SDoug Rabson  *	This product includes software developed by TooLs GmbH.
2327a0bc89SDoug Rabson  * 4. The name of TooLs GmbH may not be used to endorse or promote products
2427a0bc89SDoug Rabson  *    derived from this software without specific prior written permission.
2527a0bc89SDoug Rabson  *
2627a0bc89SDoug Rabson  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
2727a0bc89SDoug Rabson  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2827a0bc89SDoug Rabson  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2927a0bc89SDoug Rabson  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3027a0bc89SDoug Rabson  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
3127a0bc89SDoug Rabson  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
3227a0bc89SDoug Rabson  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
3327a0bc89SDoug Rabson  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
3427a0bc89SDoug Rabson  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
3527a0bc89SDoug Rabson  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3627a0bc89SDoug Rabson  */
37d167cf6fSWarner Losh /*-
3827a0bc89SDoug Rabson  * Written by Paul Popelka (paulp@uts.amdahl.com)
3927a0bc89SDoug Rabson  *
4027a0bc89SDoug Rabson  * You can do anything you want with this software, just don't say you wrote
4127a0bc89SDoug Rabson  * it, and don't remove this notice.
4227a0bc89SDoug Rabson  *
4327a0bc89SDoug Rabson  * This software is provided "as is".
4427a0bc89SDoug Rabson  *
4527a0bc89SDoug Rabson  * The author supplies this software to be publicly redistributed on the
4627a0bc89SDoug Rabson  * understanding that the author is not responsible for the correct
4727a0bc89SDoug Rabson  * functioning of this software in any circumstances and is not liable for
4827a0bc89SDoug Rabson  * any damages caused by this software.
4927a0bc89SDoug Rabson  *
5027a0bc89SDoug Rabson  * October 1992
5127a0bc89SDoug Rabson  */
5227a0bc89SDoug Rabson 
5327a0bc89SDoug Rabson #include <sys/param.h>
5427a0bc89SDoug Rabson #include <sys/systm.h>
5527a0bc89SDoug Rabson #include <sys/buf.h>
565696c6e0SBruce Evans #include <sys/mount.h>
57997febb1SKonstantin Belousov #include <sys/vmmeter.h>
585696c6e0SBruce Evans #include <sys/vnode.h>
5927a0bc89SDoug Rabson 
601166fb51SRuslan Ermilov #include <fs/msdosfs/bpb.h>
611166fb51SRuslan Ermilov #include <fs/msdosfs/direntry.h>
621166fb51SRuslan Ermilov #include <fs/msdosfs/denode.h>
631166fb51SRuslan Ermilov #include <fs/msdosfs/fat.h>
645696c6e0SBruce Evans #include <fs/msdosfs/msdosfsmount.h>
6527a0bc89SDoug Rabson 
66f33d62b2SKonstantin Belousov #define	FULL_RUN	((u_int)0xffffffff)
67f33d62b2SKonstantin Belousov 
6811caded3SAlfred Perlstein static int	chainalloc(struct msdosfsmount *pmp, u_long start,
69b76d0b32SBruce Evans 		    u_long count, u_long fillwith, u_long *retcluster,
70b76d0b32SBruce Evans 		    u_long *got);
7111caded3SAlfred Perlstein static int	chainlength(struct msdosfsmount *pmp, u_long start,
7211caded3SAlfred Perlstein 		    u_long count);
73b76d0b32SBruce Evans static void	fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp,
74b76d0b32SBruce Evans 		    u_long *sizep, u_long *bop);
75b76d0b32SBruce Evans static int	fatchain(struct msdosfsmount *pmp, u_long start, u_long count,
76b76d0b32SBruce Evans 		    u_long fillwith);
77b76d0b32SBruce Evans static void	fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp,
78b76d0b32SBruce Evans 		    u_long *fsrcnp);
7911caded3SAlfred Perlstein static void	updatefats(struct msdosfsmount *pmp, struct buf *bp,
8011caded3SAlfred Perlstein 		    u_long fatbn);
81c1087c13SBruce Evans static __inline void
8211caded3SAlfred Perlstein 		usemap_alloc(struct msdosfsmount *pmp, u_long cn);
832c9a1c22SKonstantin Belousov static int	usemap_free(struct msdosfsmount *pmp, u_long cn);
846be1a4ccSKonstantin Belousov static int	clusteralloc1(struct msdosfsmount *pmp, u_long start,
856be1a4ccSKonstantin Belousov 		    u_long count, u_long fillwith, u_long *retcluster,
866be1a4ccSKonstantin Belousov 		    u_long *got);
8758c27bcfSBruce Evans 
8827a0bc89SDoug Rabson static void
8910c9700fSEd Maste fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep,
9010c9700fSEd Maste     u_long *bop)
9127a0bc89SDoug Rabson {
9227a0bc89SDoug Rabson 	u_long bn, size;
9327a0bc89SDoug Rabson 
9427a0bc89SDoug Rabson 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
9527a0bc89SDoug Rabson 	size = min(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
9601f6cfbaSYoshihiro Takahashi 	    * DEV_BSIZE;
97952a6212SJordan K. Hubbard 	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
98952a6212SJordan K. Hubbard 
9927a0bc89SDoug Rabson 	if (bnp)
10027a0bc89SDoug Rabson 		*bnp = bn;
10127a0bc89SDoug Rabson 	if (sizep)
10227a0bc89SDoug Rabson 		*sizep = size;
10327a0bc89SDoug Rabson 	if (bop)
10427a0bc89SDoug Rabson 		*bop = ofs % pmp->pm_fatblocksize;
10527a0bc89SDoug Rabson }
10627a0bc89SDoug Rabson 
10727a0bc89SDoug Rabson /*
10827a0bc89SDoug Rabson  * Map the logical cluster number of a file into a physical disk sector
10927a0bc89SDoug Rabson  * that is filesystem relative.
11027a0bc89SDoug Rabson  *
11127a0bc89SDoug Rabson  * dep	  - address of denode representing the file of interest
11227a0bc89SDoug Rabson  * findcn - file relative cluster whose filesystem relative cluster number
11327a0bc89SDoug Rabson  *	    and/or block number are/is to be found
11427a0bc89SDoug Rabson  * bnp	  - address of where to place the filesystem relative block number.
11527a0bc89SDoug Rabson  *	    If this pointer is null then don't return this quantity.
11627a0bc89SDoug Rabson  * cnp	  - address of where to place the filesystem relative cluster number.
11727a0bc89SDoug Rabson  *	    If this pointer is null then don't return this quantity.
1184882501bSEd Maste  * sp     - pointer to returned block size
11927a0bc89SDoug Rabson  *
12027a0bc89SDoug Rabson  * NOTE: Either bnp or cnp must be non-null.
12127a0bc89SDoug Rabson  * This function has one side effect.  If the requested file relative cluster
12227a0bc89SDoug Rabson  * is beyond the end of file, then the actual number of clusters in the file
12327a0bc89SDoug Rabson  * is returned in *cnp.  This is useful for determining how long a directory is.
12427a0bc89SDoug Rabson  *  If cnp is null, nothing is returned.
12527a0bc89SDoug Rabson  */
12627a0bc89SDoug Rabson int
12710c9700fSEd Maste pcbmap(struct denode *dep, u_long findcn, daddr_t *bnp, u_long *cnp, int *sp)
12827a0bc89SDoug Rabson {
12927a0bc89SDoug Rabson 	int error;
13027a0bc89SDoug Rabson 	u_long i;
13127a0bc89SDoug Rabson 	u_long cn;
132952a6212SJordan K. Hubbard 	u_long prevcn = 0; /* XXX: prevcn could be used unititialized */
13327a0bc89SDoug Rabson 	u_long byteoffset;
13427a0bc89SDoug Rabson 	u_long bn;
13527a0bc89SDoug Rabson 	u_long bo;
13627a0bc89SDoug Rabson 	struct buf *bp = NULL;
13727a0bc89SDoug Rabson 	u_long bp_bn = -1;
13827a0bc89SDoug Rabson 	struct msdosfsmount *pmp = dep->de_pmp;
13927a0bc89SDoug Rabson 	u_long bsize;
14027a0bc89SDoug Rabson 
141ef6a2be3SKonstantin Belousov 	KASSERT(bnp != NULL || cnp != NULL || sp != NULL,
142ef6a2be3SKonstantin Belousov 	    ("pcbmap: extra call"));
143ef6a2be3SKonstantin Belousov 	ASSERT_VOP_ELOCKED(DETOV(dep), "pcbmap");
14427a0bc89SDoug Rabson 
14527a0bc89SDoug Rabson 	cn = dep->de_StartCluster;
14627a0bc89SDoug Rabson 	/*
14727a0bc89SDoug Rabson 	 * The "file" that makes up the root directory is contiguous,
14827a0bc89SDoug Rabson 	 * permanently allocated, of fixed size, and is not made up of
14927a0bc89SDoug Rabson 	 * clusters.  If the cluster number is beyond the end of the root
15027a0bc89SDoug Rabson 	 * directory, then return the number of clusters in the file.
15127a0bc89SDoug Rabson 	 */
15227a0bc89SDoug Rabson 	if (cn == MSDOSFSROOT) {
15327a0bc89SDoug Rabson 		if (dep->de_Attributes & ATTR_DIRECTORY) {
154952a6212SJordan K. Hubbard 			if (de_cn2off(pmp, findcn) >= dep->de_FileSize) {
15527a0bc89SDoug Rabson 				if (cnp)
156952a6212SJordan K. Hubbard 					*cnp = de_bn2cn(pmp, pmp->pm_rootdirsize);
157952a6212SJordan K. Hubbard 				return (E2BIG);
15827a0bc89SDoug Rabson 			}
15927a0bc89SDoug Rabson 			if (bnp)
160952a6212SJordan K. Hubbard 				*bnp = pmp->pm_rootdirblk + de_cn2bn(pmp, findcn);
16127a0bc89SDoug Rabson 			if (cnp)
16227a0bc89SDoug Rabson 				*cnp = MSDOSFSROOT;
163952a6212SJordan K. Hubbard 			if (sp)
164952a6212SJordan K. Hubbard 				*sp = min(pmp->pm_bpcluster,
165952a6212SJordan K. Hubbard 				    dep->de_FileSize - de_cn2off(pmp, findcn));
166952a6212SJordan K. Hubbard 			return (0);
16727a0bc89SDoug Rabson 		} else {		/* just an empty file */
16827a0bc89SDoug Rabson 			if (cnp)
16927a0bc89SDoug Rabson 				*cnp = 0;
170952a6212SJordan K. Hubbard 			return (E2BIG);
17127a0bc89SDoug Rabson 		}
17227a0bc89SDoug Rabson 	}
17327a0bc89SDoug Rabson 
17427a0bc89SDoug Rabson 	/*
175952a6212SJordan K. Hubbard 	 * All other files do I/O in cluster sized blocks
176952a6212SJordan K. Hubbard 	 */
177952a6212SJordan K. Hubbard 	if (sp)
178952a6212SJordan K. Hubbard 		*sp = pmp->pm_bpcluster;
179952a6212SJordan K. Hubbard 
180952a6212SJordan K. Hubbard 	/*
1819287dbaaSEd Maste 	 * Rummage around in the FAT cache, maybe we can avoid tromping
1829287dbaaSEd Maste 	 * through every FAT entry for the file. And, keep track of how far
18327a0bc89SDoug Rabson 	 * off the cache was from where we wanted to be.
18427a0bc89SDoug Rabson 	 */
18527a0bc89SDoug Rabson 	i = 0;
18627a0bc89SDoug Rabson 	fc_lookup(dep, findcn, &i, &cn);
18727a0bc89SDoug Rabson 
18827a0bc89SDoug Rabson 	/*
18927a0bc89SDoug Rabson 	 * Handle all other files or directories the normal way.
19027a0bc89SDoug Rabson 	 */
19127a0bc89SDoug Rabson 	for (; i < findcn; i++) {
192952a6212SJordan K. Hubbard 		/*
193952a6212SJordan K. Hubbard 		 * Stop with all reserved clusters, not just with EOF.
194952a6212SJordan K. Hubbard 		 */
195952a6212SJordan K. Hubbard 		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
19627a0bc89SDoug Rabson 			goto hiteof;
19727a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, cn);
19827a0bc89SDoug Rabson 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
19927a0bc89SDoug Rabson 		if (bn != bp_bn) {
20027a0bc89SDoug Rabson 			if (bp)
20127a0bc89SDoug Rabson 				brelse(bp);
20227a0bc89SDoug Rabson 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
203952a6212SJordan K. Hubbard 			if (error) {
204952a6212SJordan K. Hubbard 				return (error);
205952a6212SJordan K. Hubbard 			}
20627a0bc89SDoug Rabson 			bp_bn = bn;
20727a0bc89SDoug Rabson 		}
20827a0bc89SDoug Rabson 		prevcn = cn;
209d23af19aSTim J. Robbins 		if (bo >= bsize) {
210d23af19aSTim J. Robbins 			if (bp)
211d23af19aSTim J. Robbins 				brelse(bp);
212d23af19aSTim J. Robbins 			return (EIO);
213d23af19aSTim J. Robbins 		}
214952a6212SJordan K. Hubbard 		if (FAT32(pmp))
215b257feb2SEd Maste 			cn = getulong(bp->b_data + bo);
216952a6212SJordan K. Hubbard 		else
217b257feb2SEd Maste 			cn = getushort(bp->b_data + bo);
218952a6212SJordan K. Hubbard 		if (FAT12(pmp) && (prevcn & 1))
21927a0bc89SDoug Rabson 			cn >>= 4;
220952a6212SJordan K. Hubbard 		cn &= pmp->pm_fatmask;
221952a6212SJordan K. Hubbard 
22227a0bc89SDoug Rabson 		/*
223952a6212SJordan K. Hubbard 		 * Force the special cluster numbers
224952a6212SJordan K. Hubbard 		 * to be the same for all cluster sizes
225952a6212SJordan K. Hubbard 		 * to let the rest of msdosfs handle
226952a6212SJordan K. Hubbard 		 * all cases the same.
22727a0bc89SDoug Rabson 		 */
228952a6212SJordan K. Hubbard 		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
229952a6212SJordan K. Hubbard 			cn |= ~pmp->pm_fatmask;
23027a0bc89SDoug Rabson 	}
23127a0bc89SDoug Rabson 
232952a6212SJordan K. Hubbard 	if (!MSDOSFSEOF(pmp, cn)) {
23327a0bc89SDoug Rabson 		if (bp)
23427a0bc89SDoug Rabson 			brelse(bp);
23527a0bc89SDoug Rabson 		if (bnp)
23627a0bc89SDoug Rabson 			*bnp = cntobn(pmp, cn);
23727a0bc89SDoug Rabson 		if (cnp)
23827a0bc89SDoug Rabson 			*cnp = cn;
23927a0bc89SDoug Rabson 		fc_setcache(dep, FC_LASTMAP, i, cn);
240952a6212SJordan K. Hubbard 		return (0);
24127a0bc89SDoug Rabson 	}
24227a0bc89SDoug Rabson 
24327a0bc89SDoug Rabson hiteof:;
24427a0bc89SDoug Rabson 	if (cnp)
24527a0bc89SDoug Rabson 		*cnp = i;
24627a0bc89SDoug Rabson 	if (bp)
24727a0bc89SDoug Rabson 		brelse(bp);
2489287dbaaSEd Maste 	/* update last file cluster entry in the FAT cache */
24927a0bc89SDoug Rabson 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
250952a6212SJordan K. Hubbard 	return (E2BIG);
25127a0bc89SDoug Rabson }
25227a0bc89SDoug Rabson 
25327a0bc89SDoug Rabson /*
2549287dbaaSEd Maste  * Find the closest entry in the FAT cache to the cluster we are looking
25527a0bc89SDoug Rabson  * for.
25627a0bc89SDoug Rabson  */
2577fefffeeSPoul-Henning Kamp static void
25810c9700fSEd Maste fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
25927a0bc89SDoug Rabson {
26027a0bc89SDoug Rabson 	int i;
26127a0bc89SDoug Rabson 	u_long cn;
2620d3e502fSPedro F. Giffuni 	struct fatcache *closest = NULL;
26327a0bc89SDoug Rabson 
264ef6a2be3SKonstantin Belousov 	ASSERT_VOP_LOCKED(DETOV(dep), "fc_lookup");
265ef6a2be3SKonstantin Belousov 
26627a0bc89SDoug Rabson 	for (i = 0; i < FC_SIZE; i++) {
26727a0bc89SDoug Rabson 		cn = dep->de_fc[i].fc_frcn;
26827a0bc89SDoug Rabson 		if (cn != FCE_EMPTY && cn <= findcn) {
2690d3e502fSPedro F. Giffuni 			if (closest == NULL || cn > closest->fc_frcn)
27027a0bc89SDoug Rabson 				closest = &dep->de_fc[i];
27127a0bc89SDoug Rabson 		}
27227a0bc89SDoug Rabson 	}
27327a0bc89SDoug Rabson 	if (closest) {
27427a0bc89SDoug Rabson 		*frcnp = closest->fc_frcn;
27527a0bc89SDoug Rabson 		*fsrcnp = closest->fc_fsrcn;
27627a0bc89SDoug Rabson 	}
27727a0bc89SDoug Rabson }
27827a0bc89SDoug Rabson 
27927a0bc89SDoug Rabson /*
2809287dbaaSEd Maste  * Purge the FAT cache in denode dep of all entries relating to file
28127a0bc89SDoug Rabson  * relative cluster frcn and beyond.
28227a0bc89SDoug Rabson  */
283952a6212SJordan K. Hubbard void
28410c9700fSEd Maste fc_purge(struct denode *dep, u_int frcn)
28527a0bc89SDoug Rabson {
28627a0bc89SDoug Rabson 	int i;
28727a0bc89SDoug Rabson 	struct fatcache *fcp;
28827a0bc89SDoug Rabson 
289ef6a2be3SKonstantin Belousov 	ASSERT_VOP_ELOCKED(DETOV(dep), "fc_purge");
290ef6a2be3SKonstantin Belousov 
29127a0bc89SDoug Rabson 	fcp = dep->de_fc;
29227a0bc89SDoug Rabson 	for (i = 0; i < FC_SIZE; i++, fcp++) {
29327a0bc89SDoug Rabson 		if (fcp->fc_frcn >= frcn)
29427a0bc89SDoug Rabson 			fcp->fc_frcn = FCE_EMPTY;
29527a0bc89SDoug Rabson 	}
29627a0bc89SDoug Rabson }
29727a0bc89SDoug Rabson 
29827a0bc89SDoug Rabson /*
2999287dbaaSEd Maste  * Update the FAT.
3009287dbaaSEd Maste  * If mirroring the FAT, update all copies, with the first copy as last.
3019287dbaaSEd Maste  * Else update only the current FAT (ignoring the others).
30227a0bc89SDoug Rabson  *
30327a0bc89SDoug Rabson  * pmp	 - msdosfsmount structure for filesystem to update
3049287dbaaSEd Maste  * bp	 - addr of modified FAT block
3059287dbaaSEd Maste  * fatbn - block number relative to begin of filesystem of the modified FAT block.
30627a0bc89SDoug Rabson  */
307a98ca469SPoul-Henning Kamp static void
30810c9700fSEd Maste updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
30927a0bc89SDoug Rabson {
31027a0bc89SDoug Rabson 	struct buf *bpn;
31179fb7dd1SKonstantin Belousov 	int cleanfat, i;
31227a0bc89SDoug Rabson 
31327a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
314952a6212SJordan K. Hubbard 	printf("updatefats(pmp %p, bp %p, fatbn %lu)\n", pmp, bp, fatbn);
31527a0bc89SDoug Rabson #endif
31627a0bc89SDoug Rabson 
317952a6212SJordan K. Hubbard 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
318952a6212SJordan K. Hubbard 		/*
3199287dbaaSEd Maste 		 * Now copy the block(s) of the modified FAT to the other copies of
3209287dbaaSEd Maste 		 * the FAT and write them out.  This is faster than reading in the
3219287dbaaSEd Maste 		 * other FATs and then writing them back out.  This could tie up
3229287dbaaSEd Maste 		 * the FAT for quite a while. Preventing others from accessing it.
3239287dbaaSEd Maste 		 * To prevent us from going after the FAT quite so much we use
3249287dbaaSEd Maste 		 * delayed writes, unless they specified "synchronous" when the
32527a0bc89SDoug Rabson 		 * filesystem was mounted.  If synch is asked for then use
32627a0bc89SDoug Rabson 		 * bwrite()'s and really slow things down.
32727a0bc89SDoug Rabson 		 */
32879fb7dd1SKonstantin Belousov 		if (fatbn != pmp->pm_fatblk || FAT12(pmp))
32979fb7dd1SKonstantin Belousov 			cleanfat = 0;
33079fb7dd1SKonstantin Belousov 		else if (FAT16(pmp))
33179fb7dd1SKonstantin Belousov 			cleanfat = 16;
33279fb7dd1SKonstantin Belousov 		else
33379fb7dd1SKonstantin Belousov 			cleanfat = 32;
33427a0bc89SDoug Rabson 		for (i = 1; i < pmp->pm_FATs; i++) {
33527a0bc89SDoug Rabson 			fatbn += pmp->pm_FATsecs;
33627a0bc89SDoug Rabson 			/* getblk() never fails */
3377261f5f6SJeff Roberson 			bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount,
3387261f5f6SJeff Roberson 			    0, 0, 0);
3396a1c2e1fSEd Maste 			memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
34079fb7dd1SKonstantin Belousov 			/* Force the clean bit on in the other copies. */
34179fb7dd1SKonstantin Belousov 			if (cleanfat == 16)
34223c53312SEd Maste 				((uint8_t *)bpn->b_data)[3] |= 0x80;
34379fb7dd1SKonstantin Belousov 			else if (cleanfat == 32)
34423c53312SEd Maste 				((uint8_t *)bpn->b_data)[7] |= 0x08;
34511fca81cSKonstantin Belousov 			if (pmp->pm_mountp->mnt_flag & MNT_SYNCHRONOUS)
34627a0bc89SDoug Rabson 				bwrite(bpn);
34727a0bc89SDoug Rabson 			else
34827a0bc89SDoug Rabson 				bdwrite(bpn);
34927a0bc89SDoug Rabson 		}
350952a6212SJordan K. Hubbard 	}
351952a6212SJordan K. Hubbard 
35227a0bc89SDoug Rabson 	/*
3539287dbaaSEd Maste 	 * Write out the first (or current) FAT last.
35427a0bc89SDoug Rabson 	 */
35511fca81cSKonstantin Belousov 	if (pmp->pm_mountp->mnt_flag & MNT_SYNCHRONOUS)
35627a0bc89SDoug Rabson 		bwrite(bp);
35727a0bc89SDoug Rabson 	else
35827a0bc89SDoug Rabson 		bdwrite(bp);
35927a0bc89SDoug Rabson }
36027a0bc89SDoug Rabson 
36127a0bc89SDoug Rabson /*
3629287dbaaSEd Maste  * Updating entries in 12 bit FATs is a pain in the butt.
36327a0bc89SDoug Rabson  *
36427a0bc89SDoug Rabson  * The following picture shows where nibbles go when moving from a 12 bit
36527a0bc89SDoug Rabson  * cluster number into the appropriate bytes in the FAT.
36627a0bc89SDoug Rabson  *
36727a0bc89SDoug Rabson  *	byte m        byte m+1      byte m+2
36827a0bc89SDoug Rabson  *	+----+----+   +----+----+   +----+----+
36927a0bc89SDoug Rabson  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
37027a0bc89SDoug Rabson  *	+----+----+   +----+----+   +----+----+
37127a0bc89SDoug Rabson  *
37227a0bc89SDoug Rabson  *	+----+----+----+   +----+----+----+
37327a0bc89SDoug Rabson  *	|  3    0    1 |   |  4    5    2 |
37427a0bc89SDoug Rabson  *	+----+----+----+   +----+----+----+
37527a0bc89SDoug Rabson  *	cluster n  	   cluster n+1
37627a0bc89SDoug Rabson  *
37727a0bc89SDoug Rabson  * Where n is even. m = n + (n >> 2)
37827a0bc89SDoug Rabson  *
37927a0bc89SDoug Rabson  */
380c1087c13SBruce Evans static __inline void
38110c9700fSEd Maste usemap_alloc(struct msdosfsmount *pmp, u_long cn)
38227a0bc89SDoug Rabson {
383952a6212SJordan K. Hubbard 
3846be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
385eb739c7cSKonstantin Belousov 
386b05088aeSKonstantin Belousov 	KASSERT(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
387b05088aeSKonstantin Belousov 	    pmp->pm_maxcluster));
388420d65d9SKonstantin Belousov 	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
389420d65d9SKonstantin Belousov 	    ("usemap_alloc on ro msdosfs mount"));
39053fcc6c9SKonstantin Belousov 	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] &
39153fcc6c9SKonstantin Belousov 	    (1U << (cn % N_INUSEBITS))) == 0,
39253fcc6c9SKonstantin Belousov 	    ("Allocating used sector %ld %ld %x", cn, cn % N_INUSEBITS,
393eb739c7cSKonstantin Belousov 	    (unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
394c820acbfSPedro F. Giffuni 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
395eb739c7cSKonstantin Belousov 	KASSERT(pmp->pm_freeclustercount > 0, ("usemap_alloc: too little"));
39627a0bc89SDoug Rabson 	pmp->pm_freeclustercount--;
397bb7ca822SKonstantin Belousov 	pmp->pm_flags |= MSDOSFS_FSIMOD;
39827a0bc89SDoug Rabson }
39927a0bc89SDoug Rabson 
4002c9a1c22SKonstantin Belousov static int
40110c9700fSEd Maste usemap_free(struct msdosfsmount *pmp, u_long cn)
40227a0bc89SDoug Rabson {
403952a6212SJordan K. Hubbard 
4046be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
405b05088aeSKonstantin Belousov 
406b05088aeSKonstantin Belousov 	KASSERT(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
407b05088aeSKonstantin Belousov 	    pmp->pm_maxcluster));
408420d65d9SKonstantin Belousov 	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
409420d65d9SKonstantin Belousov 	    ("usemap_free on ro msdosfs mount"));
4102c9a1c22SKonstantin Belousov 	if ((pmp->pm_inusemap[cn / N_INUSEBITS] &
4112c9a1c22SKonstantin Belousov 	    (1U << (cn % N_INUSEBITS))) == 0) {
4122c9a1c22SKonstantin Belousov 		printf("%s: Freeing unused sector %ld %ld %x\n",
4132c9a1c22SKonstantin Belousov 		    pmp->pm_mountp->mnt_stat.f_mntonname, cn, cn % N_INUSEBITS,
4142c9a1c22SKonstantin Belousov 		    (unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]);
415*41e85eeaSKonstantin Belousov 		msdosfs_integrity_error(pmp);
4162c9a1c22SKonstantin Belousov 		return (EINTEGRITY);
4172c9a1c22SKonstantin Belousov 	}
41827a0bc89SDoug Rabson 	pmp->pm_freeclustercount++;
419bb7ca822SKonstantin Belousov 	pmp->pm_flags |= MSDOSFS_FSIMOD;
420c820acbfSPedro F. Giffuni 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1U << (cn % N_INUSEBITS));
4212c9a1c22SKonstantin Belousov 	return (0);
42227a0bc89SDoug Rabson }
42327a0bc89SDoug Rabson 
42465990b68SKonstantin Belousov void
42565990b68SKonstantin Belousov clusterfree(struct msdosfsmount *pmp, u_long cluster)
42627a0bc89SDoug Rabson {
42727a0bc89SDoug Rabson 	int error;
42827a0bc89SDoug Rabson 	u_long oldcn;
42927a0bc89SDoug Rabson 
43027a0bc89SDoug Rabson 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
43165990b68SKonstantin Belousov 	if (error != 0)
43265990b68SKonstantin Belousov 		return;
43327a0bc89SDoug Rabson 	/*
43427a0bc89SDoug Rabson 	 * If the cluster was successfully marked free, then update
43527a0bc89SDoug Rabson 	 * the count of free clusters, and turn off the "allocated"
43627a0bc89SDoug Rabson 	 * bit in the "in use" cluster bit map.
43727a0bc89SDoug Rabson 	 */
4386be1a4ccSKonstantin Belousov 	MSDOSFS_LOCK_MP(pmp);
4392c9a1c22SKonstantin Belousov 	error = usemap_free(pmp, cluster);
4406be1a4ccSKonstantin Belousov 	MSDOSFS_UNLOCK_MP(pmp);
44127a0bc89SDoug Rabson }
44227a0bc89SDoug Rabson 
44327a0bc89SDoug Rabson /*
4449287dbaaSEd Maste  * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
44527a0bc89SDoug Rabson  *
4469287dbaaSEd Maste  * function	- whether to get or set a FAT entry
44727a0bc89SDoug Rabson  * pmp		- address of the msdosfsmount structure for the filesystem
4489287dbaaSEd Maste  *		  whose FAT is to be manipulated.
44927a0bc89SDoug Rabson  * cn		- which cluster is of interest
45027a0bc89SDoug Rabson  * oldcontents	- address of a word that is to receive the contents of the
45127a0bc89SDoug Rabson  *		  cluster'th entry if this is a get function
45227a0bc89SDoug Rabson  * newcontents	- the new value to be written into the cluster'th element of
4539287dbaaSEd Maste  *		  the FAT if this is a set function.
45427a0bc89SDoug Rabson  *
4559287dbaaSEd Maste  * This function can also be used to free a cluster by setting the FAT entry
45627a0bc89SDoug Rabson  * for a cluster to 0.
45727a0bc89SDoug Rabson  *
4589287dbaaSEd Maste  * All copies of the FAT are updated if this is a set function. NOTE: If
45927a0bc89SDoug Rabson  * fatentry() marks a cluster as free it does not update the inusemap in
46027a0bc89SDoug Rabson  * the msdosfsmount structure. This is left to the caller.
46127a0bc89SDoug Rabson  */
46227a0bc89SDoug Rabson int
4634882501bSEd Maste fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents,
4644882501bSEd Maste     u_long newcontents)
46527a0bc89SDoug Rabson {
46627a0bc89SDoug Rabson 	int error;
46727a0bc89SDoug Rabson 	u_long readcn;
46827a0bc89SDoug Rabson 	u_long bn, bo, bsize, byteoffset;
46927a0bc89SDoug Rabson 	struct buf *bp;
47027a0bc89SDoug Rabson 
471952a6212SJordan K. Hubbard #ifdef	MSDOSFS_DEBUG
472952a6212SJordan K. Hubbard 	printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
473952a6212SJordan K. Hubbard 	    function, pmp, cn, oldcontents, newcontents);
474952a6212SJordan K. Hubbard #endif
47527a0bc89SDoug Rabson 
47627a0bc89SDoug Rabson #ifdef DIAGNOSTIC
47727a0bc89SDoug Rabson 	/*
47827a0bc89SDoug Rabson 	 * Be sure they asked us to do something.
47927a0bc89SDoug Rabson 	 */
48027a0bc89SDoug Rabson 	if ((function & (FAT_SET | FAT_GET)) == 0) {
48154cf9198SKonstantin Belousov #ifdef MSDOSFS_DEBUG
48227a0bc89SDoug Rabson 		printf("fatentry(): function code doesn't specify get or set\n");
48354cf9198SKonstantin Belousov #endif
484952a6212SJordan K. Hubbard 		return (EINVAL);
48527a0bc89SDoug Rabson 	}
48627a0bc89SDoug Rabson 
48727a0bc89SDoug Rabson 	/*
48827a0bc89SDoug Rabson 	 * If they asked us to return a cluster number but didn't tell us
48927a0bc89SDoug Rabson 	 * where to put it, give them an error.
49027a0bc89SDoug Rabson 	 */
49127a0bc89SDoug Rabson 	if ((function & FAT_GET) && oldcontents == NULL) {
49254cf9198SKonstantin Belousov #ifdef MSDOSFS_DEBUG
49327a0bc89SDoug Rabson 		printf("fatentry(): get function with no place to put result\n");
49454cf9198SKonstantin Belousov #endif
495952a6212SJordan K. Hubbard 		return (EINVAL);
49627a0bc89SDoug Rabson 	}
49727a0bc89SDoug Rabson #endif
49827a0bc89SDoug Rabson 
49927a0bc89SDoug Rabson 	/*
50027a0bc89SDoug Rabson 	 * Be sure the requested cluster is in the filesystem.
50127a0bc89SDoug Rabson 	 */
50227a0bc89SDoug Rabson 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
503952a6212SJordan K. Hubbard 		return (EINVAL);
50427a0bc89SDoug Rabson 
50527a0bc89SDoug Rabson 	byteoffset = FATOFS(pmp, cn);
50627a0bc89SDoug Rabson 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
507c3c6d51eSPoul-Henning Kamp 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
508952a6212SJordan K. Hubbard 	if (error) {
509952a6212SJordan K. Hubbard 		return (error);
510952a6212SJordan K. Hubbard 	}
51127a0bc89SDoug Rabson 
51227a0bc89SDoug Rabson 	if (function & FAT_GET) {
513952a6212SJordan K. Hubbard 		if (FAT32(pmp))
514b257feb2SEd Maste 			readcn = getulong(bp->b_data + bo);
515952a6212SJordan K. Hubbard 		else
516b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
517952a6212SJordan K. Hubbard 		if (FAT12(pmp) & (cn & 1))
51827a0bc89SDoug Rabson 			readcn >>= 4;
519952a6212SJordan K. Hubbard 		readcn &= pmp->pm_fatmask;
5209287dbaaSEd Maste 		/* map reserved FAT entries to same values for all FATs */
521952a6212SJordan K. Hubbard 		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
522952a6212SJordan K. Hubbard 			readcn |= ~pmp->pm_fatmask;
52327a0bc89SDoug Rabson 		*oldcontents = readcn;
52427a0bc89SDoug Rabson 	}
52527a0bc89SDoug Rabson 	if (function & FAT_SET) {
526952a6212SJordan K. Hubbard 		switch (pmp->pm_fatmask) {
527952a6212SJordan K. Hubbard 		case FAT12_MASK:
528b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
52927a0bc89SDoug Rabson 			if (cn & 1) {
53027a0bc89SDoug Rabson 				readcn &= 0x000f;
53127a0bc89SDoug Rabson 				readcn |= newcontents << 4;
53227a0bc89SDoug Rabson 			} else {
53327a0bc89SDoug Rabson 				readcn &= 0xf000;
53427a0bc89SDoug Rabson 				readcn |= newcontents & 0xfff;
53527a0bc89SDoug Rabson 			}
536b257feb2SEd Maste 			putushort(bp->b_data + bo, readcn);
537952a6212SJordan K. Hubbard 			break;
538952a6212SJordan K. Hubbard 		case FAT16_MASK:
539b257feb2SEd Maste 			putushort(bp->b_data + bo, newcontents);
540952a6212SJordan K. Hubbard 			break;
541952a6212SJordan K. Hubbard 		case FAT32_MASK:
542952a6212SJordan K. Hubbard 			/*
543952a6212SJordan K. Hubbard 			 * According to spec we have to retain the
5449287dbaaSEd Maste 			 * high order bits of the FAT entry.
545952a6212SJordan K. Hubbard 			 */
546b257feb2SEd Maste 			readcn = getulong(bp->b_data + bo);
547952a6212SJordan K. Hubbard 			readcn &= ~FAT32_MASK;
548952a6212SJordan K. Hubbard 			readcn |= newcontents & FAT32_MASK;
549b257feb2SEd Maste 			putulong(bp->b_data + bo, readcn);
550952a6212SJordan K. Hubbard 			break;
551952a6212SJordan K. Hubbard 		}
55227a0bc89SDoug Rabson 		updatefats(pmp, bp, bn);
55327a0bc89SDoug Rabson 		bp = NULL;
55427a0bc89SDoug Rabson 		pmp->pm_fmod = 1;
55527a0bc89SDoug Rabson 	}
55627a0bc89SDoug Rabson 	if (bp)
55727a0bc89SDoug Rabson 		brelse(bp);
558952a6212SJordan K. Hubbard 	return (0);
55927a0bc89SDoug Rabson }
56027a0bc89SDoug Rabson 
56127a0bc89SDoug Rabson /*
56227a0bc89SDoug Rabson  * Update a contiguous cluster chain
56327a0bc89SDoug Rabson  *
56427a0bc89SDoug Rabson  * pmp	    - mount point
56527a0bc89SDoug Rabson  * start    - first cluster of chain
56627a0bc89SDoug Rabson  * count    - number of clusters in chain
5679287dbaaSEd Maste  * fillwith - what to write into FAT entry of last cluster
56827a0bc89SDoug Rabson  */
56927a0bc89SDoug Rabson static int
57010c9700fSEd Maste fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
57127a0bc89SDoug Rabson {
57227a0bc89SDoug Rabson 	int error;
57327a0bc89SDoug Rabson 	u_long bn, bo, bsize, byteoffset, readcn, newc;
57427a0bc89SDoug Rabson 	struct buf *bp;
57527a0bc89SDoug Rabson 
57627a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
577952a6212SJordan K. Hubbard 	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
57827a0bc89SDoug Rabson 	    pmp, start, count, fillwith);
57927a0bc89SDoug Rabson #endif
58027a0bc89SDoug Rabson 	/*
58127a0bc89SDoug Rabson 	 * Be sure the clusters are in the filesystem.
58227a0bc89SDoug Rabson 	 */
58327a0bc89SDoug Rabson 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
584952a6212SJordan K. Hubbard 		return (EINVAL);
58527a0bc89SDoug Rabson 
58627a0bc89SDoug Rabson 	while (count > 0) {
58727a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, start);
58827a0bc89SDoug Rabson 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
589c3c6d51eSPoul-Henning Kamp 		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
590952a6212SJordan K. Hubbard 		if (error) {
591952a6212SJordan K. Hubbard 			return (error);
592952a6212SJordan K. Hubbard 		}
59327a0bc89SDoug Rabson 		while (count > 0) {
59427a0bc89SDoug Rabson 			start++;
59527a0bc89SDoug Rabson 			newc = --count > 0 ? start : fillwith;
596952a6212SJordan K. Hubbard 			switch (pmp->pm_fatmask) {
597952a6212SJordan K. Hubbard 			case FAT12_MASK:
598b257feb2SEd Maste 				readcn = getushort(bp->b_data + bo);
59927a0bc89SDoug Rabson 				if (start & 1) {
60027a0bc89SDoug Rabson 					readcn &= 0xf000;
60127a0bc89SDoug Rabson 					readcn |= newc & 0xfff;
60227a0bc89SDoug Rabson 				} else {
60327a0bc89SDoug Rabson 					readcn &= 0x000f;
60427a0bc89SDoug Rabson 					readcn |= newc << 4;
60527a0bc89SDoug Rabson 				}
606b257feb2SEd Maste 				putushort(bp->b_data + bo, readcn);
60727a0bc89SDoug Rabson 				bo++;
60827a0bc89SDoug Rabson 				if (!(start & 1))
60927a0bc89SDoug Rabson 					bo++;
610952a6212SJordan K. Hubbard 				break;
611952a6212SJordan K. Hubbard 			case FAT16_MASK:
612b257feb2SEd Maste 				putushort(bp->b_data + bo, newc);
61327a0bc89SDoug Rabson 				bo += 2;
614952a6212SJordan K. Hubbard 				break;
615952a6212SJordan K. Hubbard 			case FAT32_MASK:
616b257feb2SEd Maste 				readcn = getulong(bp->b_data + bo);
617952a6212SJordan K. Hubbard 				readcn &= ~pmp->pm_fatmask;
618952a6212SJordan K. Hubbard 				readcn |= newc & pmp->pm_fatmask;
619b257feb2SEd Maste 				putulong(bp->b_data + bo, readcn);
620952a6212SJordan K. Hubbard 				bo += 4;
621952a6212SJordan K. Hubbard 				break;
62227a0bc89SDoug Rabson 			}
62327a0bc89SDoug Rabson 			if (bo >= bsize)
62427a0bc89SDoug Rabson 				break;
62527a0bc89SDoug Rabson 		}
62627a0bc89SDoug Rabson 		updatefats(pmp, bp, bn);
62727a0bc89SDoug Rabson 	}
62827a0bc89SDoug Rabson 	pmp->pm_fmod = 1;
629952a6212SJordan K. Hubbard 	return (0);
63027a0bc89SDoug Rabson }
63127a0bc89SDoug Rabson 
63227a0bc89SDoug Rabson /*
63327a0bc89SDoug Rabson  * Check the length of a free cluster chain starting at start.
63427a0bc89SDoug Rabson  *
63527a0bc89SDoug Rabson  * pmp	 - mount point
63627a0bc89SDoug Rabson  * start - start of chain
63727a0bc89SDoug Rabson  * count - maximum interesting length
63827a0bc89SDoug Rabson  */
6397fefffeeSPoul-Henning Kamp static int
64010c9700fSEd Maste chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
64127a0bc89SDoug Rabson {
64227a0bc89SDoug Rabson 	u_long idx, max_idx;
64327a0bc89SDoug Rabson 	u_int map;
64427a0bc89SDoug Rabson 	u_long len;
64527a0bc89SDoug Rabson 
6466be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
6476be1a4ccSKonstantin Belousov 
648b05088aeSKonstantin Belousov 	if (start > pmp->pm_maxcluster)
649b05088aeSKonstantin Belousov 		return (0);
65027a0bc89SDoug Rabson 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
65127a0bc89SDoug Rabson 	idx = start / N_INUSEBITS;
65227a0bc89SDoug Rabson 	start %= N_INUSEBITS;
65327a0bc89SDoug Rabson 	map = pmp->pm_inusemap[idx];
65453fcc6c9SKonstantin Belousov 	map &= ~((1U << start) - 1);
65527a0bc89SDoug Rabson 	if (map) {
65627a0bc89SDoug Rabson 		len = ffs(map) - 1 - start;
657b05088aeSKonstantin Belousov 		len = MIN(len, count);
658b05088aeSKonstantin Belousov 		if (start + len > pmp->pm_maxcluster)
659b05088aeSKonstantin Belousov 			len = pmp->pm_maxcluster - start + 1;
660b05088aeSKonstantin Belousov 		return (len);
66127a0bc89SDoug Rabson 	}
66227a0bc89SDoug Rabson 	len = N_INUSEBITS - start;
663b05088aeSKonstantin Belousov 	if (len >= count) {
664b05088aeSKonstantin Belousov 		len = count;
665b05088aeSKonstantin Belousov 		if (start + len > pmp->pm_maxcluster)
666b05088aeSKonstantin Belousov 			len = pmp->pm_maxcluster - start + 1;
667b05088aeSKonstantin Belousov 		return (len);
668b05088aeSKonstantin Belousov 	}
66927a0bc89SDoug Rabson 	while (++idx <= max_idx) {
67027a0bc89SDoug Rabson 		if (len >= count)
67127a0bc89SDoug Rabson 			break;
672c3c6d51eSPoul-Henning Kamp 		map = pmp->pm_inusemap[idx];
673c3c6d51eSPoul-Henning Kamp 		if (map) {
67427a0bc89SDoug Rabson 			len += ffs(map) - 1;
67527a0bc89SDoug Rabson 			break;
67627a0bc89SDoug Rabson 		}
67727a0bc89SDoug Rabson 		len += N_INUSEBITS;
67827a0bc89SDoug Rabson 	}
679b05088aeSKonstantin Belousov 	len = MIN(len, count);
680b05088aeSKonstantin Belousov 	if (start + len > pmp->pm_maxcluster)
681b05088aeSKonstantin Belousov 		len = pmp->pm_maxcluster - start + 1;
682b05088aeSKonstantin Belousov 	return (len);
68327a0bc89SDoug Rabson }
68427a0bc89SDoug Rabson 
68527a0bc89SDoug Rabson /*
68627a0bc89SDoug Rabson  * Allocate contigous free clusters.
68727a0bc89SDoug Rabson  *
68827a0bc89SDoug Rabson  * pmp	      - mount point.
68927a0bc89SDoug Rabson  * start      - start of cluster chain.
69027a0bc89SDoug Rabson  * count      - number of clusters to allocate.
6919287dbaaSEd Maste  * fillwith   - put this value into the FAT entry for the
69227a0bc89SDoug Rabson  *		last allocated cluster.
69327a0bc89SDoug Rabson  * retcluster - put the first allocated cluster's number here.
69427a0bc89SDoug Rabson  * got	      - how many clusters were actually allocated.
69527a0bc89SDoug Rabson  */
6967fefffeeSPoul-Henning Kamp static int
69710c9700fSEd Maste chainalloc(struct msdosfsmount *pmp, u_long start, u_long count,
69810c9700fSEd Maste     u_long fillwith, u_long *retcluster, u_long *got)
69927a0bc89SDoug Rabson {
70027a0bc89SDoug Rabson 	int error;
701952a6212SJordan K. Hubbard 	u_long cl, n;
702952a6212SJordan K. Hubbard 
7036be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
704420d65d9SKonstantin Belousov 	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
705420d65d9SKonstantin Belousov 	    ("chainalloc on ro msdosfs mount"));
7066be1a4ccSKonstantin Belousov 
707952a6212SJordan K. Hubbard 	for (cl = start, n = count; n-- > 0;)
708952a6212SJordan K. Hubbard 		usemap_alloc(pmp, cl++);
709bb7ca822SKonstantin Belousov 	pmp->pm_nxtfree = start + count;
710bb7ca822SKonstantin Belousov 	if (pmp->pm_nxtfree > pmp->pm_maxcluster)
711bb7ca822SKonstantin Belousov 		pmp->pm_nxtfree = CLUST_FIRST;
712bb7ca822SKonstantin Belousov 	pmp->pm_flags |= MSDOSFS_FSIMOD;
71327a0bc89SDoug Rabson 	error = fatchain(pmp, start, count, fillwith);
71403b8a419SKonstantin Belousov 	if (error != 0) {
71503b8a419SKonstantin Belousov 		for (cl = start, n = count; n-- > 0;)
7162c9a1c22SKonstantin Belousov 			(void)usemap_free(pmp, cl++);
717952a6212SJordan K. Hubbard 		return (error);
71803b8a419SKonstantin Belousov 	}
71927a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
720952a6212SJordan K. Hubbard 	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
72127a0bc89SDoug Rabson 	    start, count);
72227a0bc89SDoug Rabson #endif
72327a0bc89SDoug Rabson 	if (retcluster)
72427a0bc89SDoug Rabson 		*retcluster = start;
72527a0bc89SDoug Rabson 	if (got)
72627a0bc89SDoug Rabson 		*got = count;
727952a6212SJordan K. Hubbard 	return (0);
72827a0bc89SDoug Rabson }
72927a0bc89SDoug Rabson 
73027a0bc89SDoug Rabson /*
73127a0bc89SDoug Rabson  * Allocate contiguous free clusters.
73227a0bc89SDoug Rabson  *
73327a0bc89SDoug Rabson  * pmp	      - mount point.
73427a0bc89SDoug Rabson  * start      - preferred start of cluster chain.
73527a0bc89SDoug Rabson  * count      - number of clusters requested.
7369287dbaaSEd Maste  * fillwith   - put this value into the FAT entry for the
73727a0bc89SDoug Rabson  *		last allocated cluster.
73827a0bc89SDoug Rabson  * retcluster - put the first allocated cluster's number here.
73927a0bc89SDoug Rabson  * got	      - how many clusters were actually allocated.
74027a0bc89SDoug Rabson  */
74127a0bc89SDoug Rabson int
7426be1a4ccSKonstantin Belousov clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
7436be1a4ccSKonstantin Belousov     u_long fillwith, u_long *retcluster, u_long *got)
7446be1a4ccSKonstantin Belousov {
7456be1a4ccSKonstantin Belousov 	int error;
7466be1a4ccSKonstantin Belousov 
7476be1a4ccSKonstantin Belousov 	MSDOSFS_LOCK_MP(pmp);
7486be1a4ccSKonstantin Belousov 	error = clusteralloc1(pmp, start, count, fillwith, retcluster, got);
7496be1a4ccSKonstantin Belousov 	MSDOSFS_UNLOCK_MP(pmp);
7506be1a4ccSKonstantin Belousov 	return (error);
7516be1a4ccSKonstantin Belousov }
7526be1a4ccSKonstantin Belousov 
7536be1a4ccSKonstantin Belousov static int
7546be1a4ccSKonstantin Belousov clusteralloc1(struct msdosfsmount *pmp, u_long start, u_long count,
7556be1a4ccSKonstantin Belousov     u_long fillwith, u_long *retcluster, u_long *got)
75627a0bc89SDoug Rabson {
75727a0bc89SDoug Rabson 	u_long idx;
758952a6212SJordan K. Hubbard 	u_long len, newst, foundl, cn, l;
759952a6212SJordan K. Hubbard 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
76027a0bc89SDoug Rabson 	u_int map;
76127a0bc89SDoug Rabson 
7626be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
7636be1a4ccSKonstantin Belousov 
76427a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
765952a6212SJordan K. Hubbard 	printf("clusteralloc(): find %lu clusters\n", count);
76627a0bc89SDoug Rabson #endif
76727a0bc89SDoug Rabson 	if (start) {
76827a0bc89SDoug Rabson 		if ((len = chainlength(pmp, start, count)) >= count)
769952a6212SJordan K. Hubbard 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
7707cd5051bSPoul-Henning Kamp 	} else
77127a0bc89SDoug Rabson 		len = 0;
77227a0bc89SDoug Rabson 
7738e55bfafSBruce Evans 	newst = pmp->pm_nxtfree;
77427a0bc89SDoug Rabson 	foundl = 0;
77527a0bc89SDoug Rabson 
77627a0bc89SDoug Rabson 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
77727a0bc89SDoug Rabson 		idx = cn / N_INUSEBITS;
77827a0bc89SDoug Rabson 		map = pmp->pm_inusemap[idx];
779c820acbfSPedro F. Giffuni 		map |= (1U << (cn % N_INUSEBITS)) - 1;
780f33d62b2SKonstantin Belousov 		if (map != FULL_RUN) {
781f33d62b2SKonstantin Belousov 			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
78227a0bc89SDoug Rabson 			if ((l = chainlength(pmp, cn, count)) >= count)
783952a6212SJordan K. Hubbard 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
78427a0bc89SDoug Rabson 			if (l > foundl) {
78527a0bc89SDoug Rabson 				foundcn = cn;
78627a0bc89SDoug Rabson 				foundl = l;
78727a0bc89SDoug Rabson 			}
78827a0bc89SDoug Rabson 			cn += l + 1;
78927a0bc89SDoug Rabson 			continue;
79027a0bc89SDoug Rabson 		}
79127a0bc89SDoug Rabson 		cn += N_INUSEBITS - cn % N_INUSEBITS;
79227a0bc89SDoug Rabson 	}
79327a0bc89SDoug Rabson 	for (cn = 0; cn < newst;) {
79427a0bc89SDoug Rabson 		idx = cn / N_INUSEBITS;
79527a0bc89SDoug Rabson 		map = pmp->pm_inusemap[idx];
796c820acbfSPedro F. Giffuni 		map |= (1U << (cn % N_INUSEBITS)) - 1;
797f33d62b2SKonstantin Belousov 		if (map != FULL_RUN) {
798f33d62b2SKonstantin Belousov 			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
79927a0bc89SDoug Rabson 			if ((l = chainlength(pmp, cn, count)) >= count)
800952a6212SJordan K. Hubbard 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
80127a0bc89SDoug Rabson 			if (l > foundl) {
80227a0bc89SDoug Rabson 				foundcn = cn;
80327a0bc89SDoug Rabson 				foundl = l;
80427a0bc89SDoug Rabson 			}
80527a0bc89SDoug Rabson 			cn += l + 1;
80627a0bc89SDoug Rabson 			continue;
80727a0bc89SDoug Rabson 		}
80827a0bc89SDoug Rabson 		cn += N_INUSEBITS - cn % N_INUSEBITS;
80927a0bc89SDoug Rabson 	}
81027a0bc89SDoug Rabson 
81127a0bc89SDoug Rabson 	if (!foundl)
812952a6212SJordan K. Hubbard 		return (ENOSPC);
81327a0bc89SDoug Rabson 
81427a0bc89SDoug Rabson 	if (len)
815952a6212SJordan K. Hubbard 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
81627a0bc89SDoug Rabson 	else
817952a6212SJordan K. Hubbard 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
81827a0bc89SDoug Rabson }
81927a0bc89SDoug Rabson 
82027a0bc89SDoug Rabson /*
82127a0bc89SDoug Rabson  * Free a chain of clusters.
82227a0bc89SDoug Rabson  *
82327a0bc89SDoug Rabson  * pmp		- address of the msdosfs mount structure for the filesystem
82427a0bc89SDoug Rabson  *		  containing the cluster chain to be freed.
82527a0bc89SDoug Rabson  * startcluster - number of the 1st cluster in the chain of clusters to be
82627a0bc89SDoug Rabson  *		  freed.
82727a0bc89SDoug Rabson  */
82827a0bc89SDoug Rabson int
82910c9700fSEd Maste freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
83027a0bc89SDoug Rabson {
831952a6212SJordan K. Hubbard 	int error;
83227a0bc89SDoug Rabson 	struct buf *bp = NULL;
83327a0bc89SDoug Rabson 	u_long bn, bo, bsize, byteoffset;
83427a0bc89SDoug Rabson 	u_long readcn, lbn = -1;
83527a0bc89SDoug Rabson 
8366be1a4ccSKonstantin Belousov 	MSDOSFS_LOCK_MP(pmp);
83727a0bc89SDoug Rabson 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
83827a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, cluster);
83927a0bc89SDoug Rabson 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
84027a0bc89SDoug Rabson 		if (lbn != bn) {
84127a0bc89SDoug Rabson 			if (bp)
84224d4540cSBruce Evans 				updatefats(pmp, bp, lbn);
843c3c6d51eSPoul-Henning Kamp 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
844952a6212SJordan K. Hubbard 			if (error) {
8456be1a4ccSKonstantin Belousov 				MSDOSFS_UNLOCK_MP(pmp);
846952a6212SJordan K. Hubbard 				return (error);
847952a6212SJordan K. Hubbard 			}
84827a0bc89SDoug Rabson 			lbn = bn;
84927a0bc89SDoug Rabson 		}
8502c9a1c22SKonstantin Belousov 		error = usemap_free(pmp, cluster);
8512c9a1c22SKonstantin Belousov 		if (error != 0) {
8522c9a1c22SKonstantin Belousov 			updatefats(pmp, bp, lbn);
8532c9a1c22SKonstantin Belousov 			MSDOSFS_UNLOCK_MP(pmp);
8542c9a1c22SKonstantin Belousov 			return (error);
8552c9a1c22SKonstantin Belousov 		}
856952a6212SJordan K. Hubbard 		switch (pmp->pm_fatmask) {
857952a6212SJordan K. Hubbard 		case FAT12_MASK:
858b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
85927a0bc89SDoug Rabson 			if (cluster & 1) {
86027a0bc89SDoug Rabson 				cluster = readcn >> 4;
86127a0bc89SDoug Rabson 				readcn &= 0x000f;
86227a0bc89SDoug Rabson 				readcn |= MSDOSFSFREE << 4;
86327a0bc89SDoug Rabson 			} else {
86427a0bc89SDoug Rabson 				cluster = readcn;
86527a0bc89SDoug Rabson 				readcn &= 0xf000;
86627a0bc89SDoug Rabson 				readcn |= MSDOSFSFREE & 0xfff;
86727a0bc89SDoug Rabson 			}
868b257feb2SEd Maste 			putushort(bp->b_data + bo, readcn);
869952a6212SJordan K. Hubbard 			break;
870952a6212SJordan K. Hubbard 		case FAT16_MASK:
871b257feb2SEd Maste 			cluster = getushort(bp->b_data + bo);
872b257feb2SEd Maste 			putushort(bp->b_data + bo, MSDOSFSFREE);
873952a6212SJordan K. Hubbard 			break;
874952a6212SJordan K. Hubbard 		case FAT32_MASK:
875b257feb2SEd Maste 			cluster = getulong(bp->b_data + bo);
876b257feb2SEd Maste 			putulong(bp->b_data + bo,
877952a6212SJordan K. Hubbard 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
878952a6212SJordan K. Hubbard 			break;
87927a0bc89SDoug Rabson 		}
880952a6212SJordan K. Hubbard 		cluster &= pmp->pm_fatmask;
881952a6212SJordan K. Hubbard 		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
882952a6212SJordan K. Hubbard 			cluster |= pmp->pm_fatmask;
88327a0bc89SDoug Rabson 	}
88427a0bc89SDoug Rabson 	if (bp)
88527a0bc89SDoug Rabson 		updatefats(pmp, bp, bn);
8866be1a4ccSKonstantin Belousov 	MSDOSFS_UNLOCK_MP(pmp);
887952a6212SJordan K. Hubbard 	return (0);
88827a0bc89SDoug Rabson }
88927a0bc89SDoug Rabson 
89027a0bc89SDoug Rabson /*
8919287dbaaSEd Maste  * Read in FAT blocks looking for free clusters. For every free cluster
89227a0bc89SDoug Rabson  * found turn off its corresponding bit in the pm_inusemap.
89327a0bc89SDoug Rabson  */
89427a0bc89SDoug Rabson int
89510c9700fSEd Maste fillinusemap(struct msdosfsmount *pmp)
89627a0bc89SDoug Rabson {
8974eeec01fSKonstantin Belousov 	struct buf *bp;
8984eeec01fSKonstantin Belousov 	u_long bn, bo, bsize, byteoffset, cn, readcn;
89927a0bc89SDoug Rabson 	int error;
90027a0bc89SDoug Rabson 
9016be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
9024eeec01fSKonstantin Belousov 	bp = NULL;
9036be1a4ccSKonstantin Belousov 
90427a0bc89SDoug Rabson 	/*
9059287dbaaSEd Maste 	 * Mark all clusters in use, we mark the free ones in the FAT scan
90627a0bc89SDoug Rabson 	 * loop further down.
90727a0bc89SDoug Rabson 	 */
90827a0bc89SDoug Rabson 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
909f33d62b2SKonstantin Belousov 		pmp->pm_inusemap[cn] = FULL_RUN;
91027a0bc89SDoug Rabson 
91127a0bc89SDoug Rabson 	/*
91227a0bc89SDoug Rabson 	 * Figure how many free clusters are in the filesystem by ripping
9139287dbaaSEd Maste 	 * through the FAT counting the number of entries whose content is
91427a0bc89SDoug Rabson 	 * zero.  These represent free clusters.
91527a0bc89SDoug Rabson 	 */
91627a0bc89SDoug Rabson 	pmp->pm_freeclustercount = 0;
917fbcbbe78SKonstantin Belousov 	for (cn = 0; cn <= pmp->pm_maxcluster; cn++) {
91827a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, cn);
91927a0bc89SDoug Rabson 		bo = byteoffset % pmp->pm_fatblocksize;
920fbcbbe78SKonstantin Belousov 		if (bo == 0) {
92127a0bc89SDoug Rabson 			/* Read new FAT block */
922fbcbbe78SKonstantin Belousov 			if (bp != NULL)
92327a0bc89SDoug Rabson 				brelse(bp);
92427a0bc89SDoug Rabson 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
92527a0bc89SDoug Rabson 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
926fbcbbe78SKonstantin Belousov 			if (error != 0)
927952a6212SJordan K. Hubbard 				return (error);
92827a0bc89SDoug Rabson 		}
929952a6212SJordan K. Hubbard 		if (FAT32(pmp))
930b257feb2SEd Maste 			readcn = getulong(bp->b_data + bo);
931952a6212SJordan K. Hubbard 		else
932b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
933952a6212SJordan K. Hubbard 		if (FAT12(pmp) && (cn & 1))
93427a0bc89SDoug Rabson 			readcn >>= 4;
935952a6212SJordan K. Hubbard 		readcn &= pmp->pm_fatmask;
93627a0bc89SDoug Rabson 
937fbcbbe78SKonstantin Belousov 		/*
938fbcbbe78SKonstantin Belousov 		 * Check if the FAT ID matches the BPB's media descriptor and
939fbcbbe78SKonstantin Belousov 		 * all other bits are set to 1.
940fbcbbe78SKonstantin Belousov 		 */
941fbcbbe78SKonstantin Belousov 		if (cn == 0 && readcn != ((pmp->pm_fatmask & 0xffffff00) |
942fbcbbe78SKonstantin Belousov 		    pmp->pm_bpb.bpbMedia)) {
943fbcbbe78SKonstantin Belousov #ifdef MSDOSFS_DEBUG
944fbcbbe78SKonstantin Belousov 			printf("mountmsdosfs(): Media descriptor in BPB"
945fbcbbe78SKonstantin Belousov 			    "does not match FAT ID\n");
946fbcbbe78SKonstantin Belousov #endif
947fbcbbe78SKonstantin Belousov 			brelse(bp);
948fbcbbe78SKonstantin Belousov 			return (EINVAL);
9492c9a1c22SKonstantin Belousov 		} else if (readcn == CLUST_FREE) {
9502c9a1c22SKonstantin Belousov 			error = usemap_free(pmp, cn);
9512c9a1c22SKonstantin Belousov 			if (error != 0) {
9522c9a1c22SKonstantin Belousov 				brelse(bp);
9532c9a1c22SKonstantin Belousov 				return (error);
9542c9a1c22SKonstantin Belousov 			}
9552c9a1c22SKonstantin Belousov 		}
95627a0bc89SDoug Rabson 	}
9573c8b687fSKonstantin Belousov 	if (bp != NULL)
95827a0bc89SDoug Rabson 		brelse(bp);
959b05088aeSKonstantin Belousov 
960b05088aeSKonstantin Belousov 	for (cn = pmp->pm_maxcluster + 1; cn < (pmp->pm_maxcluster +
961b05088aeSKonstantin Belousov 	    N_INUSEBITS) / N_INUSEBITS; cn++)
962c820acbfSPedro F. Giffuni 		pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
963b05088aeSKonstantin Belousov 
964952a6212SJordan K. Hubbard 	return (0);
96527a0bc89SDoug Rabson }
96627a0bc89SDoug Rabson 
96727a0bc89SDoug Rabson /*
96827a0bc89SDoug Rabson  * Allocate a new cluster and chain it onto the end of the file.
96927a0bc89SDoug Rabson  *
97027a0bc89SDoug Rabson  * dep	 - the file to extend
97127a0bc89SDoug Rabson  * count - number of clusters to allocate
97227a0bc89SDoug Rabson  * bpp	 - where to return the address of the buf header for the first new
97327a0bc89SDoug Rabson  *	   file block
97427a0bc89SDoug Rabson  * ncp	 - where to put cluster number of the first newly allocated cluster
97527a0bc89SDoug Rabson  *	   If this pointer is 0, do not return the cluster number.
97627a0bc89SDoug Rabson  * flags - see fat.h
97727a0bc89SDoug Rabson  *
97827a0bc89SDoug Rabson  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
97927a0bc89SDoug Rabson  * the de_flag field of the denode and it does not change the de_FileSize
98027a0bc89SDoug Rabson  * field.  This is left for the caller to do.
98127a0bc89SDoug Rabson  */
98227a0bc89SDoug Rabson int
98310c9700fSEd Maste extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp,
98410c9700fSEd Maste     int flags)
98527a0bc89SDoug Rabson {
986952a6212SJordan K. Hubbard 	int error;
98727a0bc89SDoug Rabson 	u_long frcn;
98827a0bc89SDoug Rabson 	u_long cn, got;
98927a0bc89SDoug Rabson 	struct msdosfsmount *pmp = dep->de_pmp;
99027a0bc89SDoug Rabson 	struct buf *bp;
9910d2af521SKirk McKusick 	daddr_t blkno;
99227a0bc89SDoug Rabson 
99327a0bc89SDoug Rabson 	/*
99427a0bc89SDoug Rabson 	 * Don't try to extend the root directory
99527a0bc89SDoug Rabson 	 */
996952a6212SJordan K. Hubbard 	if (dep->de_StartCluster == MSDOSFSROOT
997952a6212SJordan K. Hubbard 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
99854cf9198SKonstantin Belousov #ifdef MSDOSFS_DEBUG
99927a0bc89SDoug Rabson 		printf("extendfile(): attempt to extend root directory\n");
100054cf9198SKonstantin Belousov #endif
1001952a6212SJordan K. Hubbard 		return (ENOSPC);
100227a0bc89SDoug Rabson 	}
100327a0bc89SDoug Rabson 
100427a0bc89SDoug Rabson 	/*
100527a0bc89SDoug Rabson 	 * If the "file's last cluster" cache entry is empty, and the file
100627a0bc89SDoug Rabson 	 * is not empty, then fill the cache entry by calling pcbmap().
100727a0bc89SDoug Rabson 	 */
100827a0bc89SDoug Rabson 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
100927a0bc89SDoug Rabson 	    dep->de_StartCluster != 0) {
1010952a6212SJordan K. Hubbard 		error = pcbmap(dep, 0xffff, 0, &cn, 0);
101127a0bc89SDoug Rabson 		/* we expect it to return E2BIG */
101227a0bc89SDoug Rabson 		if (error != E2BIG)
1013952a6212SJordan K. Hubbard 			return (error);
101427a0bc89SDoug Rabson 	}
101527a0bc89SDoug Rabson 
1016ededffc0STom Rhodes 	dep->de_fc[FC_NEXTTOLASTFC].fc_frcn =
1017ededffc0STom Rhodes 	    dep->de_fc[FC_LASTFC].fc_frcn;
1018ededffc0STom Rhodes 	dep->de_fc[FC_NEXTTOLASTFC].fc_fsrcn =
1019ededffc0STom Rhodes 	    dep->de_fc[FC_LASTFC].fc_fsrcn;
102027a0bc89SDoug Rabson 	while (count > 0) {
102127a0bc89SDoug Rabson 		/*
1022952a6212SJordan K. Hubbard 		 * Allocate a new cluster chain and cat onto the end of the
10231f7d7cd7SEd Maste 		 * file.  If the file is empty we make de_StartCluster point
10241f7d7cd7SEd Maste 		 * to the new block.  Note that de_StartCluster being 0 is
10251f7d7cd7SEd Maste 		 * sufficient to be sure the file is empty since we exclude
10261f7d7cd7SEd Maste 		 * attempts to extend the root directory above, and the root
10271f7d7cd7SEd Maste 		 * dir is the only file with a startcluster of 0 that has
10281f7d7cd7SEd Maste 		 * blocks allocated (sort of).
102927a0bc89SDoug Rabson 		 */
103027a0bc89SDoug Rabson 		if (dep->de_StartCluster == 0)
103127a0bc89SDoug Rabson 			cn = 0;
103227a0bc89SDoug Rabson 		else
103327a0bc89SDoug Rabson 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1034c3c6d51eSPoul-Henning Kamp 		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1035c3c6d51eSPoul-Henning Kamp 		if (error)
1036952a6212SJordan K. Hubbard 			return (error);
103727a0bc89SDoug Rabson 
103827a0bc89SDoug Rabson 		count -= got;
103927a0bc89SDoug Rabson 
104027a0bc89SDoug Rabson 		/*
104127a0bc89SDoug Rabson 		 * Give them the filesystem relative cluster number if they want
104227a0bc89SDoug Rabson 		 * it.
104327a0bc89SDoug Rabson 		 */
104427a0bc89SDoug Rabson 		if (ncp) {
104527a0bc89SDoug Rabson 			*ncp = cn;
104627a0bc89SDoug Rabson 			ncp = NULL;
104727a0bc89SDoug Rabson 		}
104827a0bc89SDoug Rabson 
104927a0bc89SDoug Rabson 		if (dep->de_StartCluster == 0) {
105027a0bc89SDoug Rabson 			dep->de_StartCluster = cn;
105127a0bc89SDoug Rabson 			frcn = 0;
105227a0bc89SDoug Rabson 		} else {
1053952a6212SJordan K. Hubbard 			error = fatentry(FAT_SET, pmp,
1054952a6212SJordan K. Hubbard 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
105527a0bc89SDoug Rabson 					 0, cn);
105627a0bc89SDoug Rabson 			if (error) {
105765990b68SKonstantin Belousov 				clusterfree(pmp, cn);
1058952a6212SJordan K. Hubbard 				return (error);
105927a0bc89SDoug Rabson 			}
106027a0bc89SDoug Rabson 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
106127a0bc89SDoug Rabson 		}
106227a0bc89SDoug Rabson 
106327a0bc89SDoug Rabson 		/*
10649287dbaaSEd Maste 		 * Update the "last cluster of the file" entry in the
10659287dbaaSEd Maste 		 * denode's FAT cache.
106627a0bc89SDoug Rabson 		 */
106727a0bc89SDoug Rabson 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
106827a0bc89SDoug Rabson 
106927a0bc89SDoug Rabson 		if (flags & DE_CLEAR) {
107027a0bc89SDoug Rabson 			while (got-- > 0) {
107127a0bc89SDoug Rabson 				/*
107227a0bc89SDoug Rabson 				 * Get the buf header for the new block of the file.
107327a0bc89SDoug Rabson 				 */
107427a0bc89SDoug Rabson 				if (dep->de_Attributes & ATTR_DIRECTORY)
10757261f5f6SJeff Roberson 					bp = getblk(pmp->pm_devvp,
10767261f5f6SJeff Roberson 					    cntobn(pmp, cn++),
10777261f5f6SJeff Roberson 					    pmp->pm_bpcluster, 0, 0, 0);
107827a0bc89SDoug Rabson 				else {
10797261f5f6SJeff Roberson 					bp = getblk(DETOV(dep),
108067c7bbf3SKonstantin Belousov 					    frcn++,
10817261f5f6SJeff Roberson 					    pmp->pm_bpcluster, 0, 0, 0);
108227a0bc89SDoug Rabson 					/*
108327a0bc89SDoug Rabson 					 * Do the bmap now, as in msdosfs_write
108427a0bc89SDoug Rabson 					 */
1085952a6212SJordan K. Hubbard 					if (pcbmap(dep,
108667c7bbf3SKonstantin Belousov 					    bp->b_lblkno,
10870d2af521SKirk McKusick 					    &blkno, 0, 0))
108827a0bc89SDoug Rabson 						bp->b_blkno = -1;
108927a0bc89SDoug Rabson 					if (bp->b_blkno == -1)
109027a0bc89SDoug Rabson 						panic("extendfile: pcbmap");
10910d2af521SKirk McKusick 					else
10920d2af521SKirk McKusick 						bp->b_blkno = blkno;
109327a0bc89SDoug Rabson 				}
10944111ab70SKirk McKusick 				clrbuf(bp);
109527a0bc89SDoug Rabson 				if (bpp) {
109627a0bc89SDoug Rabson 					*bpp = bp;
109727a0bc89SDoug Rabson 					bpp = NULL;
1098997febb1SKonstantin Belousov 				} else {
1099952a6212SJordan K. Hubbard 					bdwrite(bp);
110027a0bc89SDoug Rabson 				}
1101997febb1SKonstantin Belousov 				if (vm_page_count_severe() ||
1102ae909414SKonstantin Belousov 				    buf_dirty_count_severe())
1103ae909414SKonstantin Belousov 					vn_fsync_buf(DETOV(dep), MNT_WAIT);
1104997febb1SKonstantin Belousov 			}
110527a0bc89SDoug Rabson 		}
110627a0bc89SDoug Rabson 	}
110727a0bc89SDoug Rabson 
1108952a6212SJordan K. Hubbard 	return (0);
110927a0bc89SDoug Rabson }
1110cede1f56STom Rhodes 
1111392dbea3SBruce Evans /*-
1112392dbea3SBruce Evans  * Routine to mark a FAT16 or FAT32 volume as "clean" or "dirty" by
1113392dbea3SBruce Evans  * manipulating the upper bit of the FAT entry for cluster 1.  Note that
1114392dbea3SBruce Evans  * this bit is not defined for FAT12 volumes, which are always assumed to
1115a26b949fSKonstantin Belousov  * be clean.
1116cede1f56STom Rhodes  *
1117392dbea3SBruce Evans  * The fatentry() routine only works on cluster numbers that a file could
1118392dbea3SBruce Evans  * occupy, so it won't manipulate the entry for cluster 1.  So we have to do
1119392dbea3SBruce Evans  * it here.  The code was stolen from fatentry() and tailored for cluster 1.
1120cede1f56STom Rhodes  *
1121cede1f56STom Rhodes  * Inputs:
1122cede1f56STom Rhodes  *	pmp	The MS-DOS volume to mark
1123392dbea3SBruce Evans  *	dirty	Non-zero if the volume should be marked dirty; zero if it
1124392dbea3SBruce Evans  *		should be marked clean
1125cede1f56STom Rhodes  *
1126cede1f56STom Rhodes  * Result:
1127cede1f56STom Rhodes  *	0	Success
1128cede1f56STom Rhodes  *	EROFS	Volume is read-only
1129cede1f56STom Rhodes  *	?	(other errors from called routines)
1130cede1f56STom Rhodes  */
1131392dbea3SBruce Evans int
1132aaa38524SConrad Meyer markvoldirty_upgrade(struct msdosfsmount *pmp, bool dirty, bool rw_upgrade)
1133cede1f56STom Rhodes {
1134cede1f56STom Rhodes 	struct buf *bp;
1135392dbea3SBruce Evans 	u_long bn, bo, bsize, byteoffset, fatval;
1136392dbea3SBruce Evans 	int error;
1137cede1f56STom Rhodes 
1138392dbea3SBruce Evans 	/*
1139392dbea3SBruce Evans 	 * FAT12 does not support a "clean" bit, so don't do anything for
1140392dbea3SBruce Evans 	 * FAT12.
1141392dbea3SBruce Evans 	 */
1142cede1f56STom Rhodes 	if (FAT12(pmp))
1143392dbea3SBruce Evans 		return (0);
1144cede1f56STom Rhodes 
1145aaa38524SConrad Meyer 	/*
1146aaa38524SConrad Meyer 	 * Can't change the bit on a read-only filesystem, except as part of
1147aaa38524SConrad Meyer 	 * ro->rw upgrade.
1148aaa38524SConrad Meyer 	 */
1149aaa38524SConrad Meyer 	if ((pmp->pm_flags & MSDOSFSMNT_RONLY) != 0 && !rw_upgrade)
1150392dbea3SBruce Evans 		return (EROFS);
1151cede1f56STom Rhodes 
1152392dbea3SBruce Evans 	/*
1153392dbea3SBruce Evans 	 * Fetch the block containing the FAT entry.  It is given by the
1154392dbea3SBruce Evans 	 * pseudo-cluster 1.
1155392dbea3SBruce Evans 	 */
1156392dbea3SBruce Evans 	byteoffset = FATOFS(pmp, 1);
1157cede1f56STom Rhodes 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
1158cede1f56STom Rhodes 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
1159f80cbeb2SConrad Meyer 	if (error)
1160cede1f56STom Rhodes 		return (error);
1161cede1f56STom Rhodes 
1162392dbea3SBruce Evans 	/*
1163392dbea3SBruce Evans 	 * Get the current value of the FAT entry and set/clear the relevant
1164392dbea3SBruce Evans 	 * bit.  Dirty means clear the "clean" bit; clean means set the
1165392dbea3SBruce Evans 	 * "clean" bit.
1166392dbea3SBruce Evans 	 */
1167cede1f56STom Rhodes 	if (FAT32(pmp)) {
1168392dbea3SBruce Evans 		/* FAT32 uses bit 27. */
1169cede1f56STom Rhodes 		fatval = getulong(&bp->b_data[bo]);
1170cede1f56STom Rhodes 		if (dirty)
1171392dbea3SBruce Evans 			fatval &= 0xF7FFFFFF;
1172cede1f56STom Rhodes 		else
1173392dbea3SBruce Evans 			fatval |= 0x08000000;
1174cede1f56STom Rhodes 		putulong(&bp->b_data[bo], fatval);
1175392dbea3SBruce Evans 	} else {
1176392dbea3SBruce Evans 		/* Must be FAT16; use bit 15. */
1177cede1f56STom Rhodes 		fatval = getushort(&bp->b_data[bo]);
1178cede1f56STom Rhodes 		if (dirty)
1179392dbea3SBruce Evans 			fatval &= 0x7FFF;
1180cede1f56STom Rhodes 		else
1181392dbea3SBruce Evans 			fatval |= 0x8000;
1182cede1f56STom Rhodes 		putushort(&bp->b_data[bo], fatval);
1183cede1f56STom Rhodes 	}
1184cede1f56STom Rhodes 
1185aaa38524SConrad Meyer 	/*
1186aaa38524SConrad Meyer 	 * The concern here is that a devvp may be readonly, without reporting
1187aaa38524SConrad Meyer 	 * itself as such through the usual channels.  In that case, we'd like
1188aaa38524SConrad Meyer 	 * it if attempting to mount msdosfs rw didn't panic the system.
1189aaa38524SConrad Meyer 	 *
1190aaa38524SConrad Meyer 	 * markvoldirty is invoked as the first write on backing devvps when
1191aaa38524SConrad Meyer 	 * either msdosfs is mounted for the first time, or a ro mount is
1192aaa38524SConrad Meyer 	 * upgraded to rw.
1193aaa38524SConrad Meyer 	 *
1194aaa38524SConrad Meyer 	 * In either event, if a write error occurs dirtying the volume:
1195aaa38524SConrad Meyer 	 *   - No user data has been permitted to be written to cache yet.
1196aaa38524SConrad Meyer 	 *   - We can abort the high-level operation (mount, or ro->rw) safely.
1197aaa38524SConrad Meyer 	 *   - We don't derive any benefit from leaving a zombie dirty buf in
1198aaa38524SConrad Meyer 	 *   the cache that can not be cleaned or evicted.
1199aaa38524SConrad Meyer 	 *
1200aaa38524SConrad Meyer 	 * So, mark B_INVALONERR to have bwrite() -> brelse() detect that
1201aaa38524SConrad Meyer 	 * condition and force-invalidate our write to the block if it occurs.
1202aaa38524SConrad Meyer 	 *
1203aaa38524SConrad Meyer 	 * PR 210316 provides more context on the discovery and diagnosis of
1204aaa38524SConrad Meyer 	 * the problem, as well as earlier attempts to solve it.
1205aaa38524SConrad Meyer 	 */
1206aaa38524SConrad Meyer 	bp->b_flags |= B_INVALONERR;
1207aaa38524SConrad Meyer 
1208392dbea3SBruce Evans 	/* Write out the modified FAT block synchronously. */
1209392dbea3SBruce Evans 	return (bwrite(bp));
1210cede1f56STom Rhodes }
1211