xref: /freebsd/sys/fs/msdosfs/msdosfs_fat.c (revision 0085afdceb17cb7d4e41f9073299f688372c6a0f)
1952a6212SJordan K. Hubbard /*	$NetBSD: msdosfs_fat.c,v 1.28 1997/11/17 15:36:49 ws Exp $	*/
227a0bc89SDoug Rabson 
327a0bc89SDoug Rabson /*-
4d63027b6SPedro F. Giffuni  * SPDX-License-Identifier: BSD-4-Clause
5d63027b6SPedro F. Giffuni  *
6952a6212SJordan K. Hubbard  * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
7952a6212SJordan K. Hubbard  * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
827a0bc89SDoug Rabson  * All rights reserved.
927a0bc89SDoug Rabson  * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
1027a0bc89SDoug Rabson  *
1127a0bc89SDoug Rabson  * Redistribution and use in source and binary forms, with or without
1227a0bc89SDoug Rabson  * modification, are permitted provided that the following conditions
1327a0bc89SDoug Rabson  * are met:
1427a0bc89SDoug Rabson  * 1. Redistributions of source code must retain the above copyright
1527a0bc89SDoug Rabson  *    notice, this list of conditions and the following disclaimer.
1627a0bc89SDoug Rabson  * 2. Redistributions in binary form must reproduce the above copyright
1727a0bc89SDoug Rabson  *    notice, this list of conditions and the following disclaimer in the
1827a0bc89SDoug Rabson  *    documentation and/or other materials provided with the distribution.
1927a0bc89SDoug Rabson  * 3. All advertising materials mentioning features or use of this software
2027a0bc89SDoug Rabson  *    must display the following acknowledgement:
2127a0bc89SDoug Rabson  *	This product includes software developed by TooLs GmbH.
2227a0bc89SDoug Rabson  * 4. The name of TooLs GmbH may not be used to endorse or promote products
2327a0bc89SDoug Rabson  *    derived from this software without specific prior written permission.
2427a0bc89SDoug Rabson  *
2527a0bc89SDoug Rabson  * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
2627a0bc89SDoug Rabson  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
2727a0bc89SDoug Rabson  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2827a0bc89SDoug Rabson  * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2927a0bc89SDoug Rabson  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
3027a0bc89SDoug Rabson  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
3127a0bc89SDoug Rabson  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
3227a0bc89SDoug Rabson  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
3327a0bc89SDoug Rabson  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
3427a0bc89SDoug Rabson  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3527a0bc89SDoug Rabson  */
36d167cf6fSWarner Losh /*-
3727a0bc89SDoug Rabson  * Written by Paul Popelka (paulp@uts.amdahl.com)
3827a0bc89SDoug Rabson  *
3927a0bc89SDoug Rabson  * You can do anything you want with this software, just don't say you wrote
4027a0bc89SDoug Rabson  * it, and don't remove this notice.
4127a0bc89SDoug Rabson  *
4227a0bc89SDoug Rabson  * This software is provided "as is".
4327a0bc89SDoug Rabson  *
4427a0bc89SDoug Rabson  * The author supplies this software to be publicly redistributed on the
4527a0bc89SDoug Rabson  * understanding that the author is not responsible for the correct
4627a0bc89SDoug Rabson  * functioning of this software in any circumstances and is not liable for
4727a0bc89SDoug Rabson  * any damages caused by this software.
4827a0bc89SDoug Rabson  *
4927a0bc89SDoug Rabson  * October 1992
5027a0bc89SDoug Rabson  */
5127a0bc89SDoug Rabson 
5227a0bc89SDoug Rabson #include <sys/param.h>
5327a0bc89SDoug Rabson #include <sys/systm.h>
5427a0bc89SDoug Rabson #include <sys/buf.h>
555696c6e0SBruce Evans #include <sys/mount.h>
56997febb1SKonstantin Belousov #include <sys/vmmeter.h>
575696c6e0SBruce Evans #include <sys/vnode.h>
5827a0bc89SDoug Rabson 
591166fb51SRuslan Ermilov #include <fs/msdosfs/bpb.h>
601166fb51SRuslan Ermilov #include <fs/msdosfs/direntry.h>
611166fb51SRuslan Ermilov #include <fs/msdosfs/denode.h>
621166fb51SRuslan Ermilov #include <fs/msdosfs/fat.h>
635696c6e0SBruce Evans #include <fs/msdosfs/msdosfsmount.h>
6427a0bc89SDoug Rabson 
65f33d62b2SKonstantin Belousov #define	FULL_RUN	((u_int)0xffffffff)
66f33d62b2SKonstantin Belousov 
6711caded3SAlfred Perlstein static int	chainalloc(struct msdosfsmount *pmp, u_long start,
68b76d0b32SBruce Evans 		    u_long count, u_long fillwith, u_long *retcluster,
69b76d0b32SBruce Evans 		    u_long *got);
7011caded3SAlfred Perlstein static int	chainlength(struct msdosfsmount *pmp, u_long start,
7111caded3SAlfred Perlstein 		    u_long count);
72b76d0b32SBruce Evans static void	fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp,
73b76d0b32SBruce Evans 		    u_long *sizep, u_long *bop);
74b76d0b32SBruce Evans static int	fatchain(struct msdosfsmount *pmp, u_long start, u_long count,
75b76d0b32SBruce Evans 		    u_long fillwith);
76b76d0b32SBruce Evans static void	fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp,
77b76d0b32SBruce Evans 		    u_long *fsrcnp);
7811caded3SAlfred Perlstein static void	updatefats(struct msdosfsmount *pmp, struct buf *bp,
7911caded3SAlfred Perlstein 		    u_long fatbn);
80c1087c13SBruce Evans static __inline void
8111caded3SAlfred Perlstein 		usemap_alloc(struct msdosfsmount *pmp, u_long cn);
822c9a1c22SKonstantin Belousov static int	usemap_free(struct msdosfsmount *pmp, u_long cn);
836be1a4ccSKonstantin Belousov static int	clusteralloc1(struct msdosfsmount *pmp, u_long start,
846be1a4ccSKonstantin Belousov 		    u_long count, u_long fillwith, u_long *retcluster,
856be1a4ccSKonstantin Belousov 		    u_long *got);
8658c27bcfSBruce Evans 
8727a0bc89SDoug Rabson static void
fatblock(struct msdosfsmount * pmp,u_long ofs,u_long * bnp,u_long * sizep,u_long * bop)8810c9700fSEd Maste fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep,
8910c9700fSEd Maste     u_long *bop)
9027a0bc89SDoug Rabson {
910728695cSStefan Eßer 	u_long bn, size, fatblocksec;
9227a0bc89SDoug Rabson 
930728695cSStefan Eßer 	fatblocksec = pmp->pm_fatblocksec;
940728695cSStefan Eßer 	if (FAT12(pmp) && fatblocksec % 3 != 0) {
950728695cSStefan Eßer 		fatblocksec *= 3;
960728695cSStefan Eßer 		if (fatblocksec % 6 == 0)
970728695cSStefan Eßer 			fatblocksec /= 2;
980728695cSStefan Eßer 	}
9927a0bc89SDoug Rabson 	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
100*0085afdcSKonstantin Belousov 	size = roundup(ulmin(fatblocksec, pmp->pm_FATsecs - bn) * DEV_BSIZE,
1010728695cSStefan Eßer 	    pmp->pm_BlkPerSec * DEV_BSIZE);
102952a6212SJordan K. Hubbard 	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
103952a6212SJordan K. Hubbard 
10427a0bc89SDoug Rabson 	if (bnp)
10527a0bc89SDoug Rabson 		*bnp = bn;
10627a0bc89SDoug Rabson 	if (sizep)
10727a0bc89SDoug Rabson 		*sizep = size;
10827a0bc89SDoug Rabson 	if (bop)
10927a0bc89SDoug Rabson 		*bop = ofs % pmp->pm_fatblocksize;
11027a0bc89SDoug Rabson }
11127a0bc89SDoug Rabson 
11227a0bc89SDoug Rabson /*
11327a0bc89SDoug Rabson  * Map the logical cluster number of a file into a physical disk sector
11427a0bc89SDoug Rabson  * that is filesystem relative.
11527a0bc89SDoug Rabson  *
11627a0bc89SDoug Rabson  * dep	  - address of denode representing the file of interest
11727a0bc89SDoug Rabson  * findcn - file relative cluster whose filesystem relative cluster number
11827a0bc89SDoug Rabson  *	    and/or block number are/is to be found
11927a0bc89SDoug Rabson  * bnp	  - address of where to place the filesystem relative block number.
12027a0bc89SDoug Rabson  *	    If this pointer is null then don't return this quantity.
12127a0bc89SDoug Rabson  * cnp	  - address of where to place the filesystem relative cluster number.
12227a0bc89SDoug Rabson  *	    If this pointer is null then don't return this quantity.
1234882501bSEd Maste  * sp     - pointer to returned block size
12427a0bc89SDoug Rabson  *
12527a0bc89SDoug Rabson  * NOTE: Either bnp or cnp must be non-null.
12627a0bc89SDoug Rabson  * This function has one side effect.  If the requested file relative cluster
12727a0bc89SDoug Rabson  * is beyond the end of file, then the actual number of clusters in the file
12827a0bc89SDoug Rabson  * is returned in *cnp.  This is useful for determining how long a directory is.
12927a0bc89SDoug Rabson  *  If cnp is null, nothing is returned.
13027a0bc89SDoug Rabson  */
13127a0bc89SDoug Rabson int
pcbmap(struct denode * dep,u_long findcn,daddr_t * bnp,u_long * cnp,int * sp)13210c9700fSEd Maste pcbmap(struct denode *dep, u_long findcn, daddr_t *bnp, u_long *cnp, int *sp)
13327a0bc89SDoug Rabson {
13427a0bc89SDoug Rabson 	int error;
13527a0bc89SDoug Rabson 	u_long i;
13627a0bc89SDoug Rabson 	u_long cn;
137952a6212SJordan K. Hubbard 	u_long prevcn = 0; /* XXX: prevcn could be used unititialized */
13827a0bc89SDoug Rabson 	u_long byteoffset;
13927a0bc89SDoug Rabson 	u_long bn;
14027a0bc89SDoug Rabson 	u_long bo;
14127a0bc89SDoug Rabson 	struct buf *bp = NULL;
14227a0bc89SDoug Rabson 	u_long bp_bn = -1;
14327a0bc89SDoug Rabson 	struct msdosfsmount *pmp = dep->de_pmp;
14427a0bc89SDoug Rabson 	u_long bsize;
14527a0bc89SDoug Rabson 
146ef6a2be3SKonstantin Belousov 	KASSERT(bnp != NULL || cnp != NULL || sp != NULL,
147ef6a2be3SKonstantin Belousov 	    ("pcbmap: extra call"));
148ef6a2be3SKonstantin Belousov 	ASSERT_VOP_ELOCKED(DETOV(dep), "pcbmap");
14927a0bc89SDoug Rabson 
15027a0bc89SDoug Rabson 	cn = dep->de_StartCluster;
15127a0bc89SDoug Rabson 	/*
15227a0bc89SDoug Rabson 	 * The "file" that makes up the root directory is contiguous,
15327a0bc89SDoug Rabson 	 * permanently allocated, of fixed size, and is not made up of
15427a0bc89SDoug Rabson 	 * clusters.  If the cluster number is beyond the end of the root
15527a0bc89SDoug Rabson 	 * directory, then return the number of clusters in the file.
15627a0bc89SDoug Rabson 	 */
15727a0bc89SDoug Rabson 	if (cn == MSDOSFSROOT) {
15827a0bc89SDoug Rabson 		if (dep->de_Attributes & ATTR_DIRECTORY) {
159952a6212SJordan K. Hubbard 			if (de_cn2off(pmp, findcn) >= dep->de_FileSize) {
16027a0bc89SDoug Rabson 				if (cnp)
161952a6212SJordan K. Hubbard 					*cnp = de_bn2cn(pmp, pmp->pm_rootdirsize);
162952a6212SJordan K. Hubbard 				return (E2BIG);
16327a0bc89SDoug Rabson 			}
16427a0bc89SDoug Rabson 			if (bnp)
165952a6212SJordan K. Hubbard 				*bnp = pmp->pm_rootdirblk + de_cn2bn(pmp, findcn);
16627a0bc89SDoug Rabson 			if (cnp)
16727a0bc89SDoug Rabson 				*cnp = MSDOSFSROOT;
168952a6212SJordan K. Hubbard 			if (sp)
169952a6212SJordan K. Hubbard 				*sp = min(pmp->pm_bpcluster,
170952a6212SJordan K. Hubbard 				    dep->de_FileSize - de_cn2off(pmp, findcn));
171952a6212SJordan K. Hubbard 			return (0);
17227a0bc89SDoug Rabson 		} else {		/* just an empty file */
17327a0bc89SDoug Rabson 			if (cnp)
17427a0bc89SDoug Rabson 				*cnp = 0;
175952a6212SJordan K. Hubbard 			return (E2BIG);
17627a0bc89SDoug Rabson 		}
17727a0bc89SDoug Rabson 	}
17827a0bc89SDoug Rabson 
17927a0bc89SDoug Rabson 	/*
180952a6212SJordan K. Hubbard 	 * All other files do I/O in cluster sized blocks
181952a6212SJordan K. Hubbard 	 */
182952a6212SJordan K. Hubbard 	if (sp)
183952a6212SJordan K. Hubbard 		*sp = pmp->pm_bpcluster;
184952a6212SJordan K. Hubbard 
185952a6212SJordan K. Hubbard 	/*
1869287dbaaSEd Maste 	 * Rummage around in the FAT cache, maybe we can avoid tromping
1879287dbaaSEd Maste 	 * through every FAT entry for the file. And, keep track of how far
18827a0bc89SDoug Rabson 	 * off the cache was from where we wanted to be.
18927a0bc89SDoug Rabson 	 */
19027a0bc89SDoug Rabson 	i = 0;
19127a0bc89SDoug Rabson 	fc_lookup(dep, findcn, &i, &cn);
19227a0bc89SDoug Rabson 
19327a0bc89SDoug Rabson 	/*
19427a0bc89SDoug Rabson 	 * Handle all other files or directories the normal way.
19527a0bc89SDoug Rabson 	 */
19627a0bc89SDoug Rabson 	for (; i < findcn; i++) {
197952a6212SJordan K. Hubbard 		/*
198952a6212SJordan K. Hubbard 		 * Stop with all reserved clusters, not just with EOF.
199952a6212SJordan K. Hubbard 		 */
200952a6212SJordan K. Hubbard 		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
20127a0bc89SDoug Rabson 			goto hiteof;
20227a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, cn);
20327a0bc89SDoug Rabson 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
20427a0bc89SDoug Rabson 		if (bn != bp_bn) {
20527a0bc89SDoug Rabson 			if (bp)
20627a0bc89SDoug Rabson 				brelse(bp);
20727a0bc89SDoug Rabson 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
208952a6212SJordan K. Hubbard 			if (error) {
209952a6212SJordan K. Hubbard 				return (error);
210952a6212SJordan K. Hubbard 			}
21127a0bc89SDoug Rabson 			bp_bn = bn;
21227a0bc89SDoug Rabson 		}
21327a0bc89SDoug Rabson 		prevcn = cn;
214d23af19aSTim J. Robbins 		if (bo >= bsize) {
215d23af19aSTim J. Robbins 			if (bp)
216d23af19aSTim J. Robbins 				brelse(bp);
217d23af19aSTim J. Robbins 			return (EIO);
218d23af19aSTim J. Robbins 		}
219952a6212SJordan K. Hubbard 		if (FAT32(pmp))
220b257feb2SEd Maste 			cn = getulong(bp->b_data + bo);
221952a6212SJordan K. Hubbard 		else
222b257feb2SEd Maste 			cn = getushort(bp->b_data + bo);
223952a6212SJordan K. Hubbard 		if (FAT12(pmp) && (prevcn & 1))
22427a0bc89SDoug Rabson 			cn >>= 4;
225952a6212SJordan K. Hubbard 		cn &= pmp->pm_fatmask;
226952a6212SJordan K. Hubbard 
22727a0bc89SDoug Rabson 		/*
228952a6212SJordan K. Hubbard 		 * Force the special cluster numbers
229952a6212SJordan K. Hubbard 		 * to be the same for all cluster sizes
230952a6212SJordan K. Hubbard 		 * to let the rest of msdosfs handle
231952a6212SJordan K. Hubbard 		 * all cases the same.
23227a0bc89SDoug Rabson 		 */
233952a6212SJordan K. Hubbard 		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
234952a6212SJordan K. Hubbard 			cn |= ~pmp->pm_fatmask;
23527a0bc89SDoug Rabson 	}
23627a0bc89SDoug Rabson 
237952a6212SJordan K. Hubbard 	if (!MSDOSFSEOF(pmp, cn)) {
23827a0bc89SDoug Rabson 		if (bp)
23927a0bc89SDoug Rabson 			brelse(bp);
24027a0bc89SDoug Rabson 		if (bnp)
24127a0bc89SDoug Rabson 			*bnp = cntobn(pmp, cn);
24227a0bc89SDoug Rabson 		if (cnp)
24327a0bc89SDoug Rabson 			*cnp = cn;
24427a0bc89SDoug Rabson 		fc_setcache(dep, FC_LASTMAP, i, cn);
245952a6212SJordan K. Hubbard 		return (0);
24627a0bc89SDoug Rabson 	}
24727a0bc89SDoug Rabson 
24827a0bc89SDoug Rabson hiteof:;
24927a0bc89SDoug Rabson 	if (cnp)
25027a0bc89SDoug Rabson 		*cnp = i;
25127a0bc89SDoug Rabson 	if (bp)
25227a0bc89SDoug Rabson 		brelse(bp);
2539287dbaaSEd Maste 	/* update last file cluster entry in the FAT cache */
25427a0bc89SDoug Rabson 	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
255952a6212SJordan K. Hubbard 	return (E2BIG);
25627a0bc89SDoug Rabson }
25727a0bc89SDoug Rabson 
25827a0bc89SDoug Rabson /*
2599287dbaaSEd Maste  * Find the closest entry in the FAT cache to the cluster we are looking
26027a0bc89SDoug Rabson  * for.
26127a0bc89SDoug Rabson  */
2627fefffeeSPoul-Henning Kamp static void
fc_lookup(struct denode * dep,u_long findcn,u_long * frcnp,u_long * fsrcnp)26310c9700fSEd Maste fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
26427a0bc89SDoug Rabson {
26527a0bc89SDoug Rabson 	int i;
26627a0bc89SDoug Rabson 	u_long cn;
2670d3e502fSPedro F. Giffuni 	struct fatcache *closest = NULL;
26827a0bc89SDoug Rabson 
269ef6a2be3SKonstantin Belousov 	ASSERT_VOP_LOCKED(DETOV(dep), "fc_lookup");
270ef6a2be3SKonstantin Belousov 
27127a0bc89SDoug Rabson 	for (i = 0; i < FC_SIZE; i++) {
27227a0bc89SDoug Rabson 		cn = dep->de_fc[i].fc_frcn;
27327a0bc89SDoug Rabson 		if (cn != FCE_EMPTY && cn <= findcn) {
2740d3e502fSPedro F. Giffuni 			if (closest == NULL || cn > closest->fc_frcn)
27527a0bc89SDoug Rabson 				closest = &dep->de_fc[i];
27627a0bc89SDoug Rabson 		}
27727a0bc89SDoug Rabson 	}
27827a0bc89SDoug Rabson 	if (closest) {
27927a0bc89SDoug Rabson 		*frcnp = closest->fc_frcn;
28027a0bc89SDoug Rabson 		*fsrcnp = closest->fc_fsrcn;
28127a0bc89SDoug Rabson 	}
28227a0bc89SDoug Rabson }
28327a0bc89SDoug Rabson 
28427a0bc89SDoug Rabson /*
2859287dbaaSEd Maste  * Purge the FAT cache in denode dep of all entries relating to file
28627a0bc89SDoug Rabson  * relative cluster frcn and beyond.
28727a0bc89SDoug Rabson  */
288952a6212SJordan K. Hubbard void
fc_purge(struct denode * dep,u_int frcn)28910c9700fSEd Maste fc_purge(struct denode *dep, u_int frcn)
29027a0bc89SDoug Rabson {
29127a0bc89SDoug Rabson 	int i;
29227a0bc89SDoug Rabson 	struct fatcache *fcp;
29327a0bc89SDoug Rabson 
294ef6a2be3SKonstantin Belousov 	ASSERT_VOP_ELOCKED(DETOV(dep), "fc_purge");
295ef6a2be3SKonstantin Belousov 
29627a0bc89SDoug Rabson 	fcp = dep->de_fc;
29727a0bc89SDoug Rabson 	for (i = 0; i < FC_SIZE; i++, fcp++) {
29827a0bc89SDoug Rabson 		if (fcp->fc_frcn >= frcn)
29927a0bc89SDoug Rabson 			fcp->fc_frcn = FCE_EMPTY;
30027a0bc89SDoug Rabson 	}
30127a0bc89SDoug Rabson }
30227a0bc89SDoug Rabson 
30327a0bc89SDoug Rabson /*
3049287dbaaSEd Maste  * Update the FAT.
3059287dbaaSEd Maste  * If mirroring the FAT, update all copies, with the first copy as last.
3069287dbaaSEd Maste  * Else update only the current FAT (ignoring the others).
30727a0bc89SDoug Rabson  *
30827a0bc89SDoug Rabson  * pmp	 - msdosfsmount structure for filesystem to update
3099287dbaaSEd Maste  * bp	 - addr of modified FAT block
3109287dbaaSEd Maste  * fatbn - block number relative to begin of filesystem of the modified FAT block.
31127a0bc89SDoug Rabson  */
312a98ca469SPoul-Henning Kamp static void
updatefats(struct msdosfsmount * pmp,struct buf * bp,u_long fatbn)31310c9700fSEd Maste updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
31427a0bc89SDoug Rabson {
31527a0bc89SDoug Rabson 	struct buf *bpn;
31679fb7dd1SKonstantin Belousov 	int cleanfat, i;
31727a0bc89SDoug Rabson 
31827a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
319952a6212SJordan K. Hubbard 	printf("updatefats(pmp %p, bp %p, fatbn %lu)\n", pmp, bp, fatbn);
32027a0bc89SDoug Rabson #endif
32127a0bc89SDoug Rabson 
322952a6212SJordan K. Hubbard 	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
323952a6212SJordan K. Hubbard 		/*
3249287dbaaSEd Maste 		 * Now copy the block(s) of the modified FAT to the other copies of
3259287dbaaSEd Maste 		 * the FAT and write them out.  This is faster than reading in the
3269287dbaaSEd Maste 		 * other FATs and then writing them back out.  This could tie up
3279287dbaaSEd Maste 		 * the FAT for quite a while. Preventing others from accessing it.
3289287dbaaSEd Maste 		 * To prevent us from going after the FAT quite so much we use
3299287dbaaSEd Maste 		 * delayed writes, unless they specified "synchronous" when the
33027a0bc89SDoug Rabson 		 * filesystem was mounted.  If synch is asked for then use
33127a0bc89SDoug Rabson 		 * bwrite()'s and really slow things down.
33227a0bc89SDoug Rabson 		 */
33379fb7dd1SKonstantin Belousov 		if (fatbn != pmp->pm_fatblk || FAT12(pmp))
33479fb7dd1SKonstantin Belousov 			cleanfat = 0;
33579fb7dd1SKonstantin Belousov 		else if (FAT16(pmp))
33679fb7dd1SKonstantin Belousov 			cleanfat = 16;
33779fb7dd1SKonstantin Belousov 		else
33879fb7dd1SKonstantin Belousov 			cleanfat = 32;
33927a0bc89SDoug Rabson 		for (i = 1; i < pmp->pm_FATs; i++) {
34027a0bc89SDoug Rabson 			fatbn += pmp->pm_FATsecs;
34127a0bc89SDoug Rabson 			/* getblk() never fails */
3427261f5f6SJeff Roberson 			bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount,
3437261f5f6SJeff Roberson 			    0, 0, 0);
3446a1c2e1fSEd Maste 			memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
34579fb7dd1SKonstantin Belousov 			/* Force the clean bit on in the other copies. */
34679fb7dd1SKonstantin Belousov 			if (cleanfat == 16)
34723c53312SEd Maste 				((uint8_t *)bpn->b_data)[3] |= 0x80;
34879fb7dd1SKonstantin Belousov 			else if (cleanfat == 32)
34923c53312SEd Maste 				((uint8_t *)bpn->b_data)[7] |= 0x08;
35011fca81cSKonstantin Belousov 			if (pmp->pm_mountp->mnt_flag & MNT_SYNCHRONOUS)
35127a0bc89SDoug Rabson 				bwrite(bpn);
35227a0bc89SDoug Rabson 			else
35327a0bc89SDoug Rabson 				bdwrite(bpn);
35427a0bc89SDoug Rabson 		}
355952a6212SJordan K. Hubbard 	}
356952a6212SJordan K. Hubbard 
35727a0bc89SDoug Rabson 	/*
3589287dbaaSEd Maste 	 * Write out the first (or current) FAT last.
35927a0bc89SDoug Rabson 	 */
36011fca81cSKonstantin Belousov 	if (pmp->pm_mountp->mnt_flag & MNT_SYNCHRONOUS)
36127a0bc89SDoug Rabson 		bwrite(bp);
36227a0bc89SDoug Rabson 	else
36327a0bc89SDoug Rabson 		bdwrite(bp);
36427a0bc89SDoug Rabson }
36527a0bc89SDoug Rabson 
36627a0bc89SDoug Rabson /*
3679287dbaaSEd Maste  * Updating entries in 12 bit FATs is a pain in the butt.
36827a0bc89SDoug Rabson  *
36927a0bc89SDoug Rabson  * The following picture shows where nibbles go when moving from a 12 bit
37027a0bc89SDoug Rabson  * cluster number into the appropriate bytes in the FAT.
37127a0bc89SDoug Rabson  *
37227a0bc89SDoug Rabson  *	byte m        byte m+1      byte m+2
37327a0bc89SDoug Rabson  *	+----+----+   +----+----+   +----+----+
37427a0bc89SDoug Rabson  *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
37527a0bc89SDoug Rabson  *	+----+----+   +----+----+   +----+----+
37627a0bc89SDoug Rabson  *
37727a0bc89SDoug Rabson  *	+----+----+----+   +----+----+----+
37827a0bc89SDoug Rabson  *	|  3    0    1 |   |  4    5    2 |
37927a0bc89SDoug Rabson  *	+----+----+----+   +----+----+----+
38027a0bc89SDoug Rabson  *	cluster n  	   cluster n+1
38127a0bc89SDoug Rabson  *
38227a0bc89SDoug Rabson  * Where n is even. m = n + (n >> 2)
38327a0bc89SDoug Rabson  *
38427a0bc89SDoug Rabson  */
385c1087c13SBruce Evans static __inline void
usemap_alloc(struct msdosfsmount * pmp,u_long cn)38610c9700fSEd Maste usemap_alloc(struct msdosfsmount *pmp, u_long cn)
38727a0bc89SDoug Rabson {
388952a6212SJordan K. Hubbard 
3896be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
390eb739c7cSKonstantin Belousov 
391b05088aeSKonstantin Belousov 	KASSERT(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
392b05088aeSKonstantin Belousov 	    pmp->pm_maxcluster));
393420d65d9SKonstantin Belousov 	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
394420d65d9SKonstantin Belousov 	    ("usemap_alloc on ro msdosfs mount"));
39553fcc6c9SKonstantin Belousov 	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] &
39653fcc6c9SKonstantin Belousov 	    (1U << (cn % N_INUSEBITS))) == 0,
39753fcc6c9SKonstantin Belousov 	    ("Allocating used sector %ld %ld %x", cn, cn % N_INUSEBITS,
398eb739c7cSKonstantin Belousov 	    (unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
399c820acbfSPedro F. Giffuni 	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
400eb739c7cSKonstantin Belousov 	KASSERT(pmp->pm_freeclustercount > 0, ("usemap_alloc: too little"));
40127a0bc89SDoug Rabson 	pmp->pm_freeclustercount--;
402bb7ca822SKonstantin Belousov 	pmp->pm_flags |= MSDOSFS_FSIMOD;
40327a0bc89SDoug Rabson }
40427a0bc89SDoug Rabson 
4052c9a1c22SKonstantin Belousov static int
usemap_free(struct msdosfsmount * pmp,u_long cn)40610c9700fSEd Maste usemap_free(struct msdosfsmount *pmp, u_long cn)
40727a0bc89SDoug Rabson {
408952a6212SJordan K. Hubbard 
4096be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
410b05088aeSKonstantin Belousov 
411b05088aeSKonstantin Belousov 	KASSERT(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
412b05088aeSKonstantin Belousov 	    pmp->pm_maxcluster));
413420d65d9SKonstantin Belousov 	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
414420d65d9SKonstantin Belousov 	    ("usemap_free on ro msdosfs mount"));
4152c9a1c22SKonstantin Belousov 	if ((pmp->pm_inusemap[cn / N_INUSEBITS] &
4162c9a1c22SKonstantin Belousov 	    (1U << (cn % N_INUSEBITS))) == 0) {
4172c9a1c22SKonstantin Belousov 		printf("%s: Freeing unused sector %ld %ld %x\n",
4182c9a1c22SKonstantin Belousov 		    pmp->pm_mountp->mnt_stat.f_mntonname, cn, cn % N_INUSEBITS,
4192c9a1c22SKonstantin Belousov 		    (unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]);
42041e85eeaSKonstantin Belousov 		msdosfs_integrity_error(pmp);
4212c9a1c22SKonstantin Belousov 		return (EINTEGRITY);
4222c9a1c22SKonstantin Belousov 	}
42327a0bc89SDoug Rabson 	pmp->pm_freeclustercount++;
424bb7ca822SKonstantin Belousov 	pmp->pm_flags |= MSDOSFS_FSIMOD;
425c820acbfSPedro F. Giffuni 	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1U << (cn % N_INUSEBITS));
4262c9a1c22SKonstantin Belousov 	return (0);
42727a0bc89SDoug Rabson }
42827a0bc89SDoug Rabson 
42965990b68SKonstantin Belousov void
clusterfree(struct msdosfsmount * pmp,u_long cluster)43065990b68SKonstantin Belousov clusterfree(struct msdosfsmount *pmp, u_long cluster)
43127a0bc89SDoug Rabson {
43227a0bc89SDoug Rabson 	int error;
43327a0bc89SDoug Rabson 	u_long oldcn;
43427a0bc89SDoug Rabson 
43527a0bc89SDoug Rabson 	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
43665990b68SKonstantin Belousov 	if (error != 0)
43765990b68SKonstantin Belousov 		return;
43827a0bc89SDoug Rabson 	/*
43927a0bc89SDoug Rabson 	 * If the cluster was successfully marked free, then update
44027a0bc89SDoug Rabson 	 * the count of free clusters, and turn off the "allocated"
44127a0bc89SDoug Rabson 	 * bit in the "in use" cluster bit map.
44227a0bc89SDoug Rabson 	 */
4436be1a4ccSKonstantin Belousov 	MSDOSFS_LOCK_MP(pmp);
4442c9a1c22SKonstantin Belousov 	error = usemap_free(pmp, cluster);
4456be1a4ccSKonstantin Belousov 	MSDOSFS_UNLOCK_MP(pmp);
44627a0bc89SDoug Rabson }
44727a0bc89SDoug Rabson 
44827a0bc89SDoug Rabson /*
4499287dbaaSEd Maste  * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
45027a0bc89SDoug Rabson  *
4519287dbaaSEd Maste  * function	- whether to get or set a FAT entry
45227a0bc89SDoug Rabson  * pmp		- address of the msdosfsmount structure for the filesystem
4539287dbaaSEd Maste  *		  whose FAT is to be manipulated.
45427a0bc89SDoug Rabson  * cn		- which cluster is of interest
45527a0bc89SDoug Rabson  * oldcontents	- address of a word that is to receive the contents of the
45627a0bc89SDoug Rabson  *		  cluster'th entry if this is a get function
45727a0bc89SDoug Rabson  * newcontents	- the new value to be written into the cluster'th element of
4589287dbaaSEd Maste  *		  the FAT if this is a set function.
45927a0bc89SDoug Rabson  *
4609287dbaaSEd Maste  * This function can also be used to free a cluster by setting the FAT entry
46127a0bc89SDoug Rabson  * for a cluster to 0.
46227a0bc89SDoug Rabson  *
4639287dbaaSEd Maste  * All copies of the FAT are updated if this is a set function. NOTE: If
46427a0bc89SDoug Rabson  * fatentry() marks a cluster as free it does not update the inusemap in
46527a0bc89SDoug Rabson  * the msdosfsmount structure. This is left to the caller.
46627a0bc89SDoug Rabson  */
46727a0bc89SDoug Rabson int
fatentry(int function,struct msdosfsmount * pmp,u_long cn,u_long * oldcontents,u_long newcontents)4684882501bSEd Maste fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents,
4694882501bSEd Maste     u_long newcontents)
47027a0bc89SDoug Rabson {
47127a0bc89SDoug Rabson 	int error;
47227a0bc89SDoug Rabson 	u_long readcn;
47327a0bc89SDoug Rabson 	u_long bn, bo, bsize, byteoffset;
47427a0bc89SDoug Rabson 	struct buf *bp;
47527a0bc89SDoug Rabson 
476952a6212SJordan K. Hubbard #ifdef	MSDOSFS_DEBUG
477952a6212SJordan K. Hubbard 	printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
478952a6212SJordan K. Hubbard 	    function, pmp, cn, oldcontents, newcontents);
479952a6212SJordan K. Hubbard #endif
48027a0bc89SDoug Rabson 
48127a0bc89SDoug Rabson #ifdef DIAGNOSTIC
48227a0bc89SDoug Rabson 	/*
48327a0bc89SDoug Rabson 	 * Be sure they asked us to do something.
48427a0bc89SDoug Rabson 	 */
48527a0bc89SDoug Rabson 	if ((function & (FAT_SET | FAT_GET)) == 0) {
48654cf9198SKonstantin Belousov #ifdef MSDOSFS_DEBUG
48727a0bc89SDoug Rabson 		printf("fatentry(): function code doesn't specify get or set\n");
48854cf9198SKonstantin Belousov #endif
489952a6212SJordan K. Hubbard 		return (EINVAL);
49027a0bc89SDoug Rabson 	}
49127a0bc89SDoug Rabson 
49227a0bc89SDoug Rabson 	/*
49327a0bc89SDoug Rabson 	 * If they asked us to return a cluster number but didn't tell us
49427a0bc89SDoug Rabson 	 * where to put it, give them an error.
49527a0bc89SDoug Rabson 	 */
49627a0bc89SDoug Rabson 	if ((function & FAT_GET) && oldcontents == NULL) {
49754cf9198SKonstantin Belousov #ifdef MSDOSFS_DEBUG
49827a0bc89SDoug Rabson 		printf("fatentry(): get function with no place to put result\n");
49954cf9198SKonstantin Belousov #endif
500952a6212SJordan K. Hubbard 		return (EINVAL);
50127a0bc89SDoug Rabson 	}
50227a0bc89SDoug Rabson #endif
50327a0bc89SDoug Rabson 
50427a0bc89SDoug Rabson 	/*
50527a0bc89SDoug Rabson 	 * Be sure the requested cluster is in the filesystem.
50627a0bc89SDoug Rabson 	 */
50727a0bc89SDoug Rabson 	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
508952a6212SJordan K. Hubbard 		return (EINVAL);
50927a0bc89SDoug Rabson 
51027a0bc89SDoug Rabson 	byteoffset = FATOFS(pmp, cn);
51127a0bc89SDoug Rabson 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
512c3c6d51eSPoul-Henning Kamp 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
513952a6212SJordan K. Hubbard 	if (error) {
514952a6212SJordan K. Hubbard 		return (error);
515952a6212SJordan K. Hubbard 	}
51627a0bc89SDoug Rabson 
51727a0bc89SDoug Rabson 	if (function & FAT_GET) {
518952a6212SJordan K. Hubbard 		if (FAT32(pmp))
519b257feb2SEd Maste 			readcn = getulong(bp->b_data + bo);
520952a6212SJordan K. Hubbard 		else
521b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
522952a6212SJordan K. Hubbard 		if (FAT12(pmp) & (cn & 1))
52327a0bc89SDoug Rabson 			readcn >>= 4;
524952a6212SJordan K. Hubbard 		readcn &= pmp->pm_fatmask;
5259287dbaaSEd Maste 		/* map reserved FAT entries to same values for all FATs */
526952a6212SJordan K. Hubbard 		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
527952a6212SJordan K. Hubbard 			readcn |= ~pmp->pm_fatmask;
52827a0bc89SDoug Rabson 		*oldcontents = readcn;
52927a0bc89SDoug Rabson 	}
53027a0bc89SDoug Rabson 	if (function & FAT_SET) {
531952a6212SJordan K. Hubbard 		switch (pmp->pm_fatmask) {
532952a6212SJordan K. Hubbard 		case FAT12_MASK:
533b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
53427a0bc89SDoug Rabson 			if (cn & 1) {
53527a0bc89SDoug Rabson 				readcn &= 0x000f;
53627a0bc89SDoug Rabson 				readcn |= newcontents << 4;
53727a0bc89SDoug Rabson 			} else {
53827a0bc89SDoug Rabson 				readcn &= 0xf000;
53927a0bc89SDoug Rabson 				readcn |= newcontents & 0xfff;
54027a0bc89SDoug Rabson 			}
541b257feb2SEd Maste 			putushort(bp->b_data + bo, readcn);
542952a6212SJordan K. Hubbard 			break;
543952a6212SJordan K. Hubbard 		case FAT16_MASK:
544b257feb2SEd Maste 			putushort(bp->b_data + bo, newcontents);
545952a6212SJordan K. Hubbard 			break;
546952a6212SJordan K. Hubbard 		case FAT32_MASK:
547952a6212SJordan K. Hubbard 			/*
548952a6212SJordan K. Hubbard 			 * According to spec we have to retain the
5499287dbaaSEd Maste 			 * high order bits of the FAT entry.
550952a6212SJordan K. Hubbard 			 */
551b257feb2SEd Maste 			readcn = getulong(bp->b_data + bo);
552952a6212SJordan K. Hubbard 			readcn &= ~FAT32_MASK;
553952a6212SJordan K. Hubbard 			readcn |= newcontents & FAT32_MASK;
554b257feb2SEd Maste 			putulong(bp->b_data + bo, readcn);
555952a6212SJordan K. Hubbard 			break;
556952a6212SJordan K. Hubbard 		}
55727a0bc89SDoug Rabson 		updatefats(pmp, bp, bn);
55827a0bc89SDoug Rabson 		bp = NULL;
55927a0bc89SDoug Rabson 		pmp->pm_fmod = 1;
56027a0bc89SDoug Rabson 	}
56127a0bc89SDoug Rabson 	if (bp)
56227a0bc89SDoug Rabson 		brelse(bp);
563952a6212SJordan K. Hubbard 	return (0);
56427a0bc89SDoug Rabson }
56527a0bc89SDoug Rabson 
56627a0bc89SDoug Rabson /*
56727a0bc89SDoug Rabson  * Update a contiguous cluster chain
56827a0bc89SDoug Rabson  *
56927a0bc89SDoug Rabson  * pmp	    - mount point
57027a0bc89SDoug Rabson  * start    - first cluster of chain
57127a0bc89SDoug Rabson  * count    - number of clusters in chain
5729287dbaaSEd Maste  * fillwith - what to write into FAT entry of last cluster
57327a0bc89SDoug Rabson  */
57427a0bc89SDoug Rabson static int
fatchain(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith)57510c9700fSEd Maste fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
57627a0bc89SDoug Rabson {
57727a0bc89SDoug Rabson 	int error;
57827a0bc89SDoug Rabson 	u_long bn, bo, bsize, byteoffset, readcn, newc;
57927a0bc89SDoug Rabson 	struct buf *bp;
58027a0bc89SDoug Rabson 
58127a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
582952a6212SJordan K. Hubbard 	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
58327a0bc89SDoug Rabson 	    pmp, start, count, fillwith);
58427a0bc89SDoug Rabson #endif
58527a0bc89SDoug Rabson 	/*
58627a0bc89SDoug Rabson 	 * Be sure the clusters are in the filesystem.
58727a0bc89SDoug Rabson 	 */
58827a0bc89SDoug Rabson 	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
589952a6212SJordan K. Hubbard 		return (EINVAL);
59027a0bc89SDoug Rabson 
59127a0bc89SDoug Rabson 	while (count > 0) {
59227a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, start);
59327a0bc89SDoug Rabson 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
594c3c6d51eSPoul-Henning Kamp 		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
595952a6212SJordan K. Hubbard 		if (error) {
596952a6212SJordan K. Hubbard 			return (error);
597952a6212SJordan K. Hubbard 		}
59827a0bc89SDoug Rabson 		while (count > 0) {
59927a0bc89SDoug Rabson 			start++;
60027a0bc89SDoug Rabson 			newc = --count > 0 ? start : fillwith;
601952a6212SJordan K. Hubbard 			switch (pmp->pm_fatmask) {
602952a6212SJordan K. Hubbard 			case FAT12_MASK:
603b257feb2SEd Maste 				readcn = getushort(bp->b_data + bo);
60427a0bc89SDoug Rabson 				if (start & 1) {
60527a0bc89SDoug Rabson 					readcn &= 0xf000;
60627a0bc89SDoug Rabson 					readcn |= newc & 0xfff;
60727a0bc89SDoug Rabson 				} else {
60827a0bc89SDoug Rabson 					readcn &= 0x000f;
60927a0bc89SDoug Rabson 					readcn |= newc << 4;
61027a0bc89SDoug Rabson 				}
611b257feb2SEd Maste 				putushort(bp->b_data + bo, readcn);
61227a0bc89SDoug Rabson 				bo++;
61327a0bc89SDoug Rabson 				if (!(start & 1))
61427a0bc89SDoug Rabson 					bo++;
615952a6212SJordan K. Hubbard 				break;
616952a6212SJordan K. Hubbard 			case FAT16_MASK:
617b257feb2SEd Maste 				putushort(bp->b_data + bo, newc);
61827a0bc89SDoug Rabson 				bo += 2;
619952a6212SJordan K. Hubbard 				break;
620952a6212SJordan K. Hubbard 			case FAT32_MASK:
621b257feb2SEd Maste 				readcn = getulong(bp->b_data + bo);
622952a6212SJordan K. Hubbard 				readcn &= ~pmp->pm_fatmask;
623952a6212SJordan K. Hubbard 				readcn |= newc & pmp->pm_fatmask;
624b257feb2SEd Maste 				putulong(bp->b_data + bo, readcn);
625952a6212SJordan K. Hubbard 				bo += 4;
626952a6212SJordan K. Hubbard 				break;
62727a0bc89SDoug Rabson 			}
62827a0bc89SDoug Rabson 			if (bo >= bsize)
62927a0bc89SDoug Rabson 				break;
63027a0bc89SDoug Rabson 		}
63127a0bc89SDoug Rabson 		updatefats(pmp, bp, bn);
63227a0bc89SDoug Rabson 	}
63327a0bc89SDoug Rabson 	pmp->pm_fmod = 1;
634952a6212SJordan K. Hubbard 	return (0);
63527a0bc89SDoug Rabson }
63627a0bc89SDoug Rabson 
63727a0bc89SDoug Rabson /*
63827a0bc89SDoug Rabson  * Check the length of a free cluster chain starting at start.
63927a0bc89SDoug Rabson  *
64027a0bc89SDoug Rabson  * pmp	 - mount point
64127a0bc89SDoug Rabson  * start - start of chain
64227a0bc89SDoug Rabson  * count - maximum interesting length
64327a0bc89SDoug Rabson  */
6447fefffeeSPoul-Henning Kamp static int
chainlength(struct msdosfsmount * pmp,u_long start,u_long count)64510c9700fSEd Maste chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
64627a0bc89SDoug Rabson {
64727a0bc89SDoug Rabson 	u_long idx, max_idx;
64827a0bc89SDoug Rabson 	u_int map;
64927a0bc89SDoug Rabson 	u_long len;
65027a0bc89SDoug Rabson 
6516be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
6526be1a4ccSKonstantin Belousov 
653b05088aeSKonstantin Belousov 	if (start > pmp->pm_maxcluster)
654b05088aeSKonstantin Belousov 		return (0);
65527a0bc89SDoug Rabson 	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
65627a0bc89SDoug Rabson 	idx = start / N_INUSEBITS;
65727a0bc89SDoug Rabson 	start %= N_INUSEBITS;
65827a0bc89SDoug Rabson 	map = pmp->pm_inusemap[idx];
65953fcc6c9SKonstantin Belousov 	map &= ~((1U << start) - 1);
66027a0bc89SDoug Rabson 	if (map) {
66127a0bc89SDoug Rabson 		len = ffs(map) - 1 - start;
662b05088aeSKonstantin Belousov 		len = MIN(len, count);
663b05088aeSKonstantin Belousov 		if (start + len > pmp->pm_maxcluster)
664b05088aeSKonstantin Belousov 			len = pmp->pm_maxcluster - start + 1;
665b05088aeSKonstantin Belousov 		return (len);
66627a0bc89SDoug Rabson 	}
66727a0bc89SDoug Rabson 	len = N_INUSEBITS - start;
668b05088aeSKonstantin Belousov 	if (len >= count) {
669b05088aeSKonstantin Belousov 		len = count;
670b05088aeSKonstantin Belousov 		if (start + len > pmp->pm_maxcluster)
671b05088aeSKonstantin Belousov 			len = pmp->pm_maxcluster - start + 1;
672b05088aeSKonstantin Belousov 		return (len);
673b05088aeSKonstantin Belousov 	}
67427a0bc89SDoug Rabson 	while (++idx <= max_idx) {
67527a0bc89SDoug Rabson 		if (len >= count)
67627a0bc89SDoug Rabson 			break;
677c3c6d51eSPoul-Henning Kamp 		map = pmp->pm_inusemap[idx];
678c3c6d51eSPoul-Henning Kamp 		if (map) {
67927a0bc89SDoug Rabson 			len += ffs(map) - 1;
68027a0bc89SDoug Rabson 			break;
68127a0bc89SDoug Rabson 		}
68227a0bc89SDoug Rabson 		len += N_INUSEBITS;
68327a0bc89SDoug Rabson 	}
684b05088aeSKonstantin Belousov 	len = MIN(len, count);
685b05088aeSKonstantin Belousov 	if (start + len > pmp->pm_maxcluster)
686b05088aeSKonstantin Belousov 		len = pmp->pm_maxcluster - start + 1;
687b05088aeSKonstantin Belousov 	return (len);
68827a0bc89SDoug Rabson }
68927a0bc89SDoug Rabson 
69027a0bc89SDoug Rabson /*
69127a0bc89SDoug Rabson  * Allocate contigous free clusters.
69227a0bc89SDoug Rabson  *
69327a0bc89SDoug Rabson  * pmp	      - mount point.
69427a0bc89SDoug Rabson  * start      - start of cluster chain.
69527a0bc89SDoug Rabson  * count      - number of clusters to allocate.
6969287dbaaSEd Maste  * fillwith   - put this value into the FAT entry for the
69727a0bc89SDoug Rabson  *		last allocated cluster.
69827a0bc89SDoug Rabson  * retcluster - put the first allocated cluster's number here.
69927a0bc89SDoug Rabson  * got	      - how many clusters were actually allocated.
70027a0bc89SDoug Rabson  */
7017fefffeeSPoul-Henning Kamp static int
chainalloc(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith,u_long * retcluster,u_long * got)70210c9700fSEd Maste chainalloc(struct msdosfsmount *pmp, u_long start, u_long count,
70310c9700fSEd Maste     u_long fillwith, u_long *retcluster, u_long *got)
70427a0bc89SDoug Rabson {
70527a0bc89SDoug Rabson 	int error;
706952a6212SJordan K. Hubbard 	u_long cl, n;
707952a6212SJordan K. Hubbard 
7086be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
709420d65d9SKonstantin Belousov 	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
710420d65d9SKonstantin Belousov 	    ("chainalloc on ro msdosfs mount"));
7116be1a4ccSKonstantin Belousov 
712952a6212SJordan K. Hubbard 	for (cl = start, n = count; n-- > 0;)
713952a6212SJordan K. Hubbard 		usemap_alloc(pmp, cl++);
714bb7ca822SKonstantin Belousov 	pmp->pm_nxtfree = start + count;
715bb7ca822SKonstantin Belousov 	if (pmp->pm_nxtfree > pmp->pm_maxcluster)
716bb7ca822SKonstantin Belousov 		pmp->pm_nxtfree = CLUST_FIRST;
717bb7ca822SKonstantin Belousov 	pmp->pm_flags |= MSDOSFS_FSIMOD;
71827a0bc89SDoug Rabson 	error = fatchain(pmp, start, count, fillwith);
71903b8a419SKonstantin Belousov 	if (error != 0) {
72003b8a419SKonstantin Belousov 		for (cl = start, n = count; n-- > 0;)
7212c9a1c22SKonstantin Belousov 			(void)usemap_free(pmp, cl++);
722952a6212SJordan K. Hubbard 		return (error);
72303b8a419SKonstantin Belousov 	}
72427a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
725952a6212SJordan K. Hubbard 	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
72627a0bc89SDoug Rabson 	    start, count);
72727a0bc89SDoug Rabson #endif
72827a0bc89SDoug Rabson 	if (retcluster)
72927a0bc89SDoug Rabson 		*retcluster = start;
73027a0bc89SDoug Rabson 	if (got)
73127a0bc89SDoug Rabson 		*got = count;
732952a6212SJordan K. Hubbard 	return (0);
73327a0bc89SDoug Rabson }
73427a0bc89SDoug Rabson 
73527a0bc89SDoug Rabson /*
73627a0bc89SDoug Rabson  * Allocate contiguous free clusters.
73727a0bc89SDoug Rabson  *
73827a0bc89SDoug Rabson  * pmp	      - mount point.
73927a0bc89SDoug Rabson  * start      - preferred start of cluster chain.
74027a0bc89SDoug Rabson  * count      - number of clusters requested.
7419287dbaaSEd Maste  * fillwith   - put this value into the FAT entry for the
74227a0bc89SDoug Rabson  *		last allocated cluster.
74327a0bc89SDoug Rabson  * retcluster - put the first allocated cluster's number here.
74427a0bc89SDoug Rabson  * got	      - how many clusters were actually allocated.
74527a0bc89SDoug Rabson  */
74627a0bc89SDoug Rabson int
clusteralloc(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith,u_long * retcluster,u_long * got)7476be1a4ccSKonstantin Belousov clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
7486be1a4ccSKonstantin Belousov     u_long fillwith, u_long *retcluster, u_long *got)
7496be1a4ccSKonstantin Belousov {
7506be1a4ccSKonstantin Belousov 	int error;
7516be1a4ccSKonstantin Belousov 
7526be1a4ccSKonstantin Belousov 	MSDOSFS_LOCK_MP(pmp);
7536be1a4ccSKonstantin Belousov 	error = clusteralloc1(pmp, start, count, fillwith, retcluster, got);
7546be1a4ccSKonstantin Belousov 	MSDOSFS_UNLOCK_MP(pmp);
7556be1a4ccSKonstantin Belousov 	return (error);
7566be1a4ccSKonstantin Belousov }
7576be1a4ccSKonstantin Belousov 
7586be1a4ccSKonstantin Belousov static int
clusteralloc1(struct msdosfsmount * pmp,u_long start,u_long count,u_long fillwith,u_long * retcluster,u_long * got)7596be1a4ccSKonstantin Belousov clusteralloc1(struct msdosfsmount *pmp, u_long start, u_long count,
7606be1a4ccSKonstantin Belousov     u_long fillwith, u_long *retcluster, u_long *got)
76127a0bc89SDoug Rabson {
76227a0bc89SDoug Rabson 	u_long idx;
763952a6212SJordan K. Hubbard 	u_long len, newst, foundl, cn, l;
764952a6212SJordan K. Hubbard 	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
76527a0bc89SDoug Rabson 	u_int map;
76627a0bc89SDoug Rabson 
7676be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
7686be1a4ccSKonstantin Belousov 
76927a0bc89SDoug Rabson #ifdef MSDOSFS_DEBUG
770952a6212SJordan K. Hubbard 	printf("clusteralloc(): find %lu clusters\n", count);
77127a0bc89SDoug Rabson #endif
77227a0bc89SDoug Rabson 	if (start) {
77327a0bc89SDoug Rabson 		if ((len = chainlength(pmp, start, count)) >= count)
774952a6212SJordan K. Hubbard 			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
7757cd5051bSPoul-Henning Kamp 	} else
77627a0bc89SDoug Rabson 		len = 0;
77727a0bc89SDoug Rabson 
7788e55bfafSBruce Evans 	newst = pmp->pm_nxtfree;
77927a0bc89SDoug Rabson 	foundl = 0;
78027a0bc89SDoug Rabson 
78127a0bc89SDoug Rabson 	for (cn = newst; cn <= pmp->pm_maxcluster;) {
78227a0bc89SDoug Rabson 		idx = cn / N_INUSEBITS;
78327a0bc89SDoug Rabson 		map = pmp->pm_inusemap[idx];
784c820acbfSPedro F. Giffuni 		map |= (1U << (cn % N_INUSEBITS)) - 1;
785f33d62b2SKonstantin Belousov 		if (map != FULL_RUN) {
786f33d62b2SKonstantin Belousov 			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
78727a0bc89SDoug Rabson 			if ((l = chainlength(pmp, cn, count)) >= count)
788952a6212SJordan K. Hubbard 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
78927a0bc89SDoug Rabson 			if (l > foundl) {
79027a0bc89SDoug Rabson 				foundcn = cn;
79127a0bc89SDoug Rabson 				foundl = l;
79227a0bc89SDoug Rabson 			}
79327a0bc89SDoug Rabson 			cn += l + 1;
79427a0bc89SDoug Rabson 			continue;
79527a0bc89SDoug Rabson 		}
79627a0bc89SDoug Rabson 		cn += N_INUSEBITS - cn % N_INUSEBITS;
79727a0bc89SDoug Rabson 	}
79827a0bc89SDoug Rabson 	for (cn = 0; cn < newst;) {
79927a0bc89SDoug Rabson 		idx = cn / N_INUSEBITS;
80027a0bc89SDoug Rabson 		map = pmp->pm_inusemap[idx];
801c820acbfSPedro F. Giffuni 		map |= (1U << (cn % N_INUSEBITS)) - 1;
802f33d62b2SKonstantin Belousov 		if (map != FULL_RUN) {
803f33d62b2SKonstantin Belousov 			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
80427a0bc89SDoug Rabson 			if ((l = chainlength(pmp, cn, count)) >= count)
805952a6212SJordan K. Hubbard 				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
80627a0bc89SDoug Rabson 			if (l > foundl) {
80727a0bc89SDoug Rabson 				foundcn = cn;
80827a0bc89SDoug Rabson 				foundl = l;
80927a0bc89SDoug Rabson 			}
81027a0bc89SDoug Rabson 			cn += l + 1;
81127a0bc89SDoug Rabson 			continue;
81227a0bc89SDoug Rabson 		}
81327a0bc89SDoug Rabson 		cn += N_INUSEBITS - cn % N_INUSEBITS;
81427a0bc89SDoug Rabson 	}
81527a0bc89SDoug Rabson 
81627a0bc89SDoug Rabson 	if (!foundl)
817952a6212SJordan K. Hubbard 		return (ENOSPC);
81827a0bc89SDoug Rabson 
81927a0bc89SDoug Rabson 	if (len)
820952a6212SJordan K. Hubbard 		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
82127a0bc89SDoug Rabson 	else
822952a6212SJordan K. Hubbard 		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
82327a0bc89SDoug Rabson }
82427a0bc89SDoug Rabson 
82527a0bc89SDoug Rabson /*
82627a0bc89SDoug Rabson  * Free a chain of clusters.
82727a0bc89SDoug Rabson  *
82827a0bc89SDoug Rabson  * pmp		- address of the msdosfs mount structure for the filesystem
82927a0bc89SDoug Rabson  *		  containing the cluster chain to be freed.
83027a0bc89SDoug Rabson  * startcluster - number of the 1st cluster in the chain of clusters to be
83127a0bc89SDoug Rabson  *		  freed.
83227a0bc89SDoug Rabson  */
83327a0bc89SDoug Rabson int
freeclusterchain(struct msdosfsmount * pmp,u_long cluster)83410c9700fSEd Maste freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
83527a0bc89SDoug Rabson {
836952a6212SJordan K. Hubbard 	int error;
83727a0bc89SDoug Rabson 	struct buf *bp = NULL;
83827a0bc89SDoug Rabson 	u_long bn, bo, bsize, byteoffset;
83927a0bc89SDoug Rabson 	u_long readcn, lbn = -1;
84027a0bc89SDoug Rabson 
8416be1a4ccSKonstantin Belousov 	MSDOSFS_LOCK_MP(pmp);
84227a0bc89SDoug Rabson 	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
84327a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, cluster);
84427a0bc89SDoug Rabson 		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
84527a0bc89SDoug Rabson 		if (lbn != bn) {
84627a0bc89SDoug Rabson 			if (bp)
84724d4540cSBruce Evans 				updatefats(pmp, bp, lbn);
848c3c6d51eSPoul-Henning Kamp 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
849952a6212SJordan K. Hubbard 			if (error) {
8506be1a4ccSKonstantin Belousov 				MSDOSFS_UNLOCK_MP(pmp);
851952a6212SJordan K. Hubbard 				return (error);
852952a6212SJordan K. Hubbard 			}
85327a0bc89SDoug Rabson 			lbn = bn;
85427a0bc89SDoug Rabson 		}
8552c9a1c22SKonstantin Belousov 		error = usemap_free(pmp, cluster);
8562c9a1c22SKonstantin Belousov 		if (error != 0) {
8572c9a1c22SKonstantin Belousov 			updatefats(pmp, bp, lbn);
8582c9a1c22SKonstantin Belousov 			MSDOSFS_UNLOCK_MP(pmp);
8592c9a1c22SKonstantin Belousov 			return (error);
8602c9a1c22SKonstantin Belousov 		}
861952a6212SJordan K. Hubbard 		switch (pmp->pm_fatmask) {
862952a6212SJordan K. Hubbard 		case FAT12_MASK:
863b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
86427a0bc89SDoug Rabson 			if (cluster & 1) {
86527a0bc89SDoug Rabson 				cluster = readcn >> 4;
86627a0bc89SDoug Rabson 				readcn &= 0x000f;
86727a0bc89SDoug Rabson 				readcn |= MSDOSFSFREE << 4;
86827a0bc89SDoug Rabson 			} else {
86927a0bc89SDoug Rabson 				cluster = readcn;
87027a0bc89SDoug Rabson 				readcn &= 0xf000;
87127a0bc89SDoug Rabson 				readcn |= MSDOSFSFREE & 0xfff;
87227a0bc89SDoug Rabson 			}
873b257feb2SEd Maste 			putushort(bp->b_data + bo, readcn);
874952a6212SJordan K. Hubbard 			break;
875952a6212SJordan K. Hubbard 		case FAT16_MASK:
876b257feb2SEd Maste 			cluster = getushort(bp->b_data + bo);
877b257feb2SEd Maste 			putushort(bp->b_data + bo, MSDOSFSFREE);
878952a6212SJordan K. Hubbard 			break;
879952a6212SJordan K. Hubbard 		case FAT32_MASK:
880b257feb2SEd Maste 			cluster = getulong(bp->b_data + bo);
881b257feb2SEd Maste 			putulong(bp->b_data + bo,
882952a6212SJordan K. Hubbard 				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
883952a6212SJordan K. Hubbard 			break;
88427a0bc89SDoug Rabson 		}
885952a6212SJordan K. Hubbard 		cluster &= pmp->pm_fatmask;
886952a6212SJordan K. Hubbard 		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
887952a6212SJordan K. Hubbard 			cluster |= pmp->pm_fatmask;
88827a0bc89SDoug Rabson 	}
88927a0bc89SDoug Rabson 	if (bp)
89027a0bc89SDoug Rabson 		updatefats(pmp, bp, bn);
8916be1a4ccSKonstantin Belousov 	MSDOSFS_UNLOCK_MP(pmp);
892952a6212SJordan K. Hubbard 	return (0);
89327a0bc89SDoug Rabson }
89427a0bc89SDoug Rabson 
89527a0bc89SDoug Rabson /*
8969287dbaaSEd Maste  * Read in FAT blocks looking for free clusters. For every free cluster
89727a0bc89SDoug Rabson  * found turn off its corresponding bit in the pm_inusemap.
89827a0bc89SDoug Rabson  */
89927a0bc89SDoug Rabson int
fillinusemap(struct msdosfsmount * pmp)90010c9700fSEd Maste fillinusemap(struct msdosfsmount *pmp)
90127a0bc89SDoug Rabson {
9024eeec01fSKonstantin Belousov 	struct buf *bp;
9034eeec01fSKonstantin Belousov 	u_long bn, bo, bsize, byteoffset, cn, readcn;
90427a0bc89SDoug Rabson 	int error;
90527a0bc89SDoug Rabson 
9066be1a4ccSKonstantin Belousov 	MSDOSFS_ASSERT_MP_LOCKED(pmp);
9074eeec01fSKonstantin Belousov 	bp = NULL;
9086be1a4ccSKonstantin Belousov 
90927a0bc89SDoug Rabson 	/*
9109287dbaaSEd Maste 	 * Mark all clusters in use, we mark the free ones in the FAT scan
91127a0bc89SDoug Rabson 	 * loop further down.
91227a0bc89SDoug Rabson 	 */
91327a0bc89SDoug Rabson 	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
914f33d62b2SKonstantin Belousov 		pmp->pm_inusemap[cn] = FULL_RUN;
91527a0bc89SDoug Rabson 
91627a0bc89SDoug Rabson 	/*
91727a0bc89SDoug Rabson 	 * Figure how many free clusters are in the filesystem by ripping
9189287dbaaSEd Maste 	 * through the FAT counting the number of entries whose content is
91927a0bc89SDoug Rabson 	 * zero.  These represent free clusters.
92027a0bc89SDoug Rabson 	 */
92127a0bc89SDoug Rabson 	pmp->pm_freeclustercount = 0;
922fbcbbe78SKonstantin Belousov 	for (cn = 0; cn <= pmp->pm_maxcluster; cn++) {
92327a0bc89SDoug Rabson 		byteoffset = FATOFS(pmp, cn);
92427a0bc89SDoug Rabson 		bo = byteoffset % pmp->pm_fatblocksize;
925fbcbbe78SKonstantin Belousov 		if (bo == 0) {
92627a0bc89SDoug Rabson 			/* Read new FAT block */
927fbcbbe78SKonstantin Belousov 			if (bp != NULL)
92827a0bc89SDoug Rabson 				brelse(bp);
92927a0bc89SDoug Rabson 			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
93027a0bc89SDoug Rabson 			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
931fbcbbe78SKonstantin Belousov 			if (error != 0)
932952a6212SJordan K. Hubbard 				return (error);
93327a0bc89SDoug Rabson 		}
934952a6212SJordan K. Hubbard 		if (FAT32(pmp))
935b257feb2SEd Maste 			readcn = getulong(bp->b_data + bo);
936952a6212SJordan K. Hubbard 		else
937b257feb2SEd Maste 			readcn = getushort(bp->b_data + bo);
938952a6212SJordan K. Hubbard 		if (FAT12(pmp) && (cn & 1))
93927a0bc89SDoug Rabson 			readcn >>= 4;
940952a6212SJordan K. Hubbard 		readcn &= pmp->pm_fatmask;
94127a0bc89SDoug Rabson 
942fbcbbe78SKonstantin Belousov 		/*
943fbcbbe78SKonstantin Belousov 		 * Check if the FAT ID matches the BPB's media descriptor and
944fbcbbe78SKonstantin Belousov 		 * all other bits are set to 1.
945fbcbbe78SKonstantin Belousov 		 */
946fbcbbe78SKonstantin Belousov 		if (cn == 0 && readcn != ((pmp->pm_fatmask & 0xffffff00) |
947fbcbbe78SKonstantin Belousov 		    pmp->pm_bpb.bpbMedia)) {
948fbcbbe78SKonstantin Belousov #ifdef MSDOSFS_DEBUG
949fbcbbe78SKonstantin Belousov 			printf("mountmsdosfs(): Media descriptor in BPB"
950fbcbbe78SKonstantin Belousov 			    "does not match FAT ID\n");
951fbcbbe78SKonstantin Belousov #endif
952fbcbbe78SKonstantin Belousov 			brelse(bp);
953fbcbbe78SKonstantin Belousov 			return (EINVAL);
9542c9a1c22SKonstantin Belousov 		} else if (readcn == CLUST_FREE) {
9552c9a1c22SKonstantin Belousov 			error = usemap_free(pmp, cn);
9562c9a1c22SKonstantin Belousov 			if (error != 0) {
9572c9a1c22SKonstantin Belousov 				brelse(bp);
9582c9a1c22SKonstantin Belousov 				return (error);
9592c9a1c22SKonstantin Belousov 			}
9602c9a1c22SKonstantin Belousov 		}
96127a0bc89SDoug Rabson 	}
9623c8b687fSKonstantin Belousov 	if (bp != NULL)
96327a0bc89SDoug Rabson 		brelse(bp);
964b05088aeSKonstantin Belousov 
965b05088aeSKonstantin Belousov 	for (cn = pmp->pm_maxcluster + 1; cn < (pmp->pm_maxcluster +
966b05088aeSKonstantin Belousov 	    N_INUSEBITS) / N_INUSEBITS; cn++)
967c820acbfSPedro F. Giffuni 		pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
968b05088aeSKonstantin Belousov 
969952a6212SJordan K. Hubbard 	return (0);
97027a0bc89SDoug Rabson }
97127a0bc89SDoug Rabson 
97227a0bc89SDoug Rabson /*
97327a0bc89SDoug Rabson  * Allocate a new cluster and chain it onto the end of the file.
97427a0bc89SDoug Rabson  *
97527a0bc89SDoug Rabson  * dep	 - the file to extend
97627a0bc89SDoug Rabson  * count - number of clusters to allocate
97727a0bc89SDoug Rabson  * bpp	 - where to return the address of the buf header for the first new
97827a0bc89SDoug Rabson  *	   file block
97927a0bc89SDoug Rabson  * ncp	 - where to put cluster number of the first newly allocated cluster
98027a0bc89SDoug Rabson  *	   If this pointer is 0, do not return the cluster number.
98127a0bc89SDoug Rabson  * flags - see fat.h
98227a0bc89SDoug Rabson  *
98327a0bc89SDoug Rabson  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
98427a0bc89SDoug Rabson  * the de_flag field of the denode and it does not change the de_FileSize
98527a0bc89SDoug Rabson  * field.  This is left for the caller to do.
98627a0bc89SDoug Rabson  */
98727a0bc89SDoug Rabson int
extendfile(struct denode * dep,u_long count,struct buf ** bpp,u_long * ncp,int flags)98810c9700fSEd Maste extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp,
98910c9700fSEd Maste     int flags)
99027a0bc89SDoug Rabson {
991952a6212SJordan K. Hubbard 	int error;
99227a0bc89SDoug Rabson 	u_long frcn;
99327a0bc89SDoug Rabson 	u_long cn, got;
99427a0bc89SDoug Rabson 	struct msdosfsmount *pmp = dep->de_pmp;
99527a0bc89SDoug Rabson 	struct buf *bp;
9960d2af521SKirk McKusick 	daddr_t blkno;
99727a0bc89SDoug Rabson 
99827a0bc89SDoug Rabson 	/*
99927a0bc89SDoug Rabson 	 * Don't try to extend the root directory
100027a0bc89SDoug Rabson 	 */
1001952a6212SJordan K. Hubbard 	if (dep->de_StartCluster == MSDOSFSROOT
1002952a6212SJordan K. Hubbard 	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
100354cf9198SKonstantin Belousov #ifdef MSDOSFS_DEBUG
100427a0bc89SDoug Rabson 		printf("extendfile(): attempt to extend root directory\n");
100554cf9198SKonstantin Belousov #endif
1006952a6212SJordan K. Hubbard 		return (ENOSPC);
100727a0bc89SDoug Rabson 	}
100827a0bc89SDoug Rabson 
100927a0bc89SDoug Rabson 	/*
101027a0bc89SDoug Rabson 	 * If the "file's last cluster" cache entry is empty, and the file
101127a0bc89SDoug Rabson 	 * is not empty, then fill the cache entry by calling pcbmap().
101227a0bc89SDoug Rabson 	 */
101327a0bc89SDoug Rabson 	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
101427a0bc89SDoug Rabson 	    dep->de_StartCluster != 0) {
1015952a6212SJordan K. Hubbard 		error = pcbmap(dep, 0xffff, 0, &cn, 0);
101627a0bc89SDoug Rabson 		/* we expect it to return E2BIG */
101727a0bc89SDoug Rabson 		if (error != E2BIG)
1018952a6212SJordan K. Hubbard 			return (error);
101927a0bc89SDoug Rabson 	}
102027a0bc89SDoug Rabson 
1021ededffc0STom Rhodes 	dep->de_fc[FC_NEXTTOLASTFC].fc_frcn =
1022ededffc0STom Rhodes 	    dep->de_fc[FC_LASTFC].fc_frcn;
1023ededffc0STom Rhodes 	dep->de_fc[FC_NEXTTOLASTFC].fc_fsrcn =
1024ededffc0STom Rhodes 	    dep->de_fc[FC_LASTFC].fc_fsrcn;
102527a0bc89SDoug Rabson 	while (count > 0) {
102627a0bc89SDoug Rabson 		/*
1027952a6212SJordan K. Hubbard 		 * Allocate a new cluster chain and cat onto the end of the
10281f7d7cd7SEd Maste 		 * file.  If the file is empty we make de_StartCluster point
10291f7d7cd7SEd Maste 		 * to the new block.  Note that de_StartCluster being 0 is
10301f7d7cd7SEd Maste 		 * sufficient to be sure the file is empty since we exclude
10311f7d7cd7SEd Maste 		 * attempts to extend the root directory above, and the root
10321f7d7cd7SEd Maste 		 * dir is the only file with a startcluster of 0 that has
10331f7d7cd7SEd Maste 		 * blocks allocated (sort of).
103427a0bc89SDoug Rabson 		 */
103527a0bc89SDoug Rabson 		if (dep->de_StartCluster == 0)
103627a0bc89SDoug Rabson 			cn = 0;
103727a0bc89SDoug Rabson 		else
103827a0bc89SDoug Rabson 			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1039c3c6d51eSPoul-Henning Kamp 		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1040c3c6d51eSPoul-Henning Kamp 		if (error)
1041952a6212SJordan K. Hubbard 			return (error);
104227a0bc89SDoug Rabson 
104327a0bc89SDoug Rabson 		count -= got;
104427a0bc89SDoug Rabson 
104527a0bc89SDoug Rabson 		/*
104627a0bc89SDoug Rabson 		 * Give them the filesystem relative cluster number if they want
104727a0bc89SDoug Rabson 		 * it.
104827a0bc89SDoug Rabson 		 */
104927a0bc89SDoug Rabson 		if (ncp) {
105027a0bc89SDoug Rabson 			*ncp = cn;
105127a0bc89SDoug Rabson 			ncp = NULL;
105227a0bc89SDoug Rabson 		}
105327a0bc89SDoug Rabson 
105427a0bc89SDoug Rabson 		if (dep->de_StartCluster == 0) {
105527a0bc89SDoug Rabson 			dep->de_StartCluster = cn;
105627a0bc89SDoug Rabson 			frcn = 0;
105727a0bc89SDoug Rabson 		} else {
1058952a6212SJordan K. Hubbard 			error = fatentry(FAT_SET, pmp,
1059952a6212SJordan K. Hubbard 					 dep->de_fc[FC_LASTFC].fc_fsrcn,
106027a0bc89SDoug Rabson 					 0, cn);
106127a0bc89SDoug Rabson 			if (error) {
106265990b68SKonstantin Belousov 				clusterfree(pmp, cn);
1063952a6212SJordan K. Hubbard 				return (error);
106427a0bc89SDoug Rabson 			}
106527a0bc89SDoug Rabson 			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
106627a0bc89SDoug Rabson 		}
106727a0bc89SDoug Rabson 
106827a0bc89SDoug Rabson 		/*
10699287dbaaSEd Maste 		 * Update the "last cluster of the file" entry in the
10709287dbaaSEd Maste 		 * denode's FAT cache.
107127a0bc89SDoug Rabson 		 */
107227a0bc89SDoug Rabson 		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
107327a0bc89SDoug Rabson 
107427a0bc89SDoug Rabson 		if (flags & DE_CLEAR) {
107527a0bc89SDoug Rabson 			while (got-- > 0) {
107627a0bc89SDoug Rabson 				/*
107727a0bc89SDoug Rabson 				 * Get the buf header for the new block of the file.
107827a0bc89SDoug Rabson 				 */
107927a0bc89SDoug Rabson 				if (dep->de_Attributes & ATTR_DIRECTORY)
10807261f5f6SJeff Roberson 					bp = getblk(pmp->pm_devvp,
10817261f5f6SJeff Roberson 					    cntobn(pmp, cn++),
10827261f5f6SJeff Roberson 					    pmp->pm_bpcluster, 0, 0, 0);
108327a0bc89SDoug Rabson 				else {
10847261f5f6SJeff Roberson 					bp = getblk(DETOV(dep),
108567c7bbf3SKonstantin Belousov 					    frcn++,
10867261f5f6SJeff Roberson 					    pmp->pm_bpcluster, 0, 0, 0);
108727a0bc89SDoug Rabson 					/*
108827a0bc89SDoug Rabson 					 * Do the bmap now, as in msdosfs_write
108927a0bc89SDoug Rabson 					 */
1090952a6212SJordan K. Hubbard 					if (pcbmap(dep,
109167c7bbf3SKonstantin Belousov 					    bp->b_lblkno,
10920d2af521SKirk McKusick 					    &blkno, 0, 0))
109327a0bc89SDoug Rabson 						bp->b_blkno = -1;
109427a0bc89SDoug Rabson 					if (bp->b_blkno == -1)
109527a0bc89SDoug Rabson 						panic("extendfile: pcbmap");
10960d2af521SKirk McKusick 					else
10970d2af521SKirk McKusick 						bp->b_blkno = blkno;
109827a0bc89SDoug Rabson 				}
10994111ab70SKirk McKusick 				clrbuf(bp);
110027a0bc89SDoug Rabson 				if (bpp) {
110127a0bc89SDoug Rabson 					*bpp = bp;
110227a0bc89SDoug Rabson 					bpp = NULL;
1103997febb1SKonstantin Belousov 				} else {
1104952a6212SJordan K. Hubbard 					bdwrite(bp);
110527a0bc89SDoug Rabson 				}
1106997febb1SKonstantin Belousov 				if (vm_page_count_severe() ||
1107ae909414SKonstantin Belousov 				    buf_dirty_count_severe())
1108ae909414SKonstantin Belousov 					vn_fsync_buf(DETOV(dep), MNT_WAIT);
1109997febb1SKonstantin Belousov 			}
111027a0bc89SDoug Rabson 		}
111127a0bc89SDoug Rabson 	}
111227a0bc89SDoug Rabson 
1113952a6212SJordan K. Hubbard 	return (0);
111427a0bc89SDoug Rabson }
1115cede1f56STom Rhodes 
1116392dbea3SBruce Evans /*-
1117392dbea3SBruce Evans  * Routine to mark a FAT16 or FAT32 volume as "clean" or "dirty" by
1118392dbea3SBruce Evans  * manipulating the upper bit of the FAT entry for cluster 1.  Note that
1119392dbea3SBruce Evans  * this bit is not defined for FAT12 volumes, which are always assumed to
1120a26b949fSKonstantin Belousov  * be clean.
1121cede1f56STom Rhodes  *
1122392dbea3SBruce Evans  * The fatentry() routine only works on cluster numbers that a file could
1123392dbea3SBruce Evans  * occupy, so it won't manipulate the entry for cluster 1.  So we have to do
1124392dbea3SBruce Evans  * it here.  The code was stolen from fatentry() and tailored for cluster 1.
1125cede1f56STom Rhodes  *
1126cede1f56STom Rhodes  * Inputs:
1127cede1f56STom Rhodes  *	pmp	The MS-DOS volume to mark
1128392dbea3SBruce Evans  *	dirty	Non-zero if the volume should be marked dirty; zero if it
1129392dbea3SBruce Evans  *		should be marked clean
1130cede1f56STom Rhodes  *
1131cede1f56STom Rhodes  * Result:
1132cede1f56STom Rhodes  *	0	Success
1133cede1f56STom Rhodes  *	EROFS	Volume is read-only
1134cede1f56STom Rhodes  *	?	(other errors from called routines)
1135cede1f56STom Rhodes  */
1136392dbea3SBruce Evans int
markvoldirty_upgrade(struct msdosfsmount * pmp,bool dirty,bool rw_upgrade)1137aaa38524SConrad Meyer markvoldirty_upgrade(struct msdosfsmount *pmp, bool dirty, bool rw_upgrade)
1138cede1f56STom Rhodes {
1139cede1f56STom Rhodes 	struct buf *bp;
1140392dbea3SBruce Evans 	u_long bn, bo, bsize, byteoffset, fatval;
1141392dbea3SBruce Evans 	int error;
1142cede1f56STom Rhodes 
1143392dbea3SBruce Evans 	/*
1144392dbea3SBruce Evans 	 * FAT12 does not support a "clean" bit, so don't do anything for
1145392dbea3SBruce Evans 	 * FAT12.
1146392dbea3SBruce Evans 	 */
1147cede1f56STom Rhodes 	if (FAT12(pmp))
1148392dbea3SBruce Evans 		return (0);
1149cede1f56STom Rhodes 
1150aaa38524SConrad Meyer 	/*
1151aaa38524SConrad Meyer 	 * Can't change the bit on a read-only filesystem, except as part of
1152aaa38524SConrad Meyer 	 * ro->rw upgrade.
1153aaa38524SConrad Meyer 	 */
1154aaa38524SConrad Meyer 	if ((pmp->pm_flags & MSDOSFSMNT_RONLY) != 0 && !rw_upgrade)
1155392dbea3SBruce Evans 		return (EROFS);
1156cede1f56STom Rhodes 
1157392dbea3SBruce Evans 	/*
1158392dbea3SBruce Evans 	 * Fetch the block containing the FAT entry.  It is given by the
1159392dbea3SBruce Evans 	 * pseudo-cluster 1.
1160392dbea3SBruce Evans 	 */
1161392dbea3SBruce Evans 	byteoffset = FATOFS(pmp, 1);
1162cede1f56STom Rhodes 	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
1163cede1f56STom Rhodes 	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
1164f80cbeb2SConrad Meyer 	if (error)
1165cede1f56STom Rhodes 		return (error);
1166cede1f56STom Rhodes 
1167392dbea3SBruce Evans 	/*
1168392dbea3SBruce Evans 	 * Get the current value of the FAT entry and set/clear the relevant
1169392dbea3SBruce Evans 	 * bit.  Dirty means clear the "clean" bit; clean means set the
1170392dbea3SBruce Evans 	 * "clean" bit.
1171392dbea3SBruce Evans 	 */
1172cede1f56STom Rhodes 	if (FAT32(pmp)) {
1173392dbea3SBruce Evans 		/* FAT32 uses bit 27. */
1174cede1f56STom Rhodes 		fatval = getulong(&bp->b_data[bo]);
1175cede1f56STom Rhodes 		if (dirty)
1176392dbea3SBruce Evans 			fatval &= 0xF7FFFFFF;
1177cede1f56STom Rhodes 		else
1178392dbea3SBruce Evans 			fatval |= 0x08000000;
1179cede1f56STom Rhodes 		putulong(&bp->b_data[bo], fatval);
1180392dbea3SBruce Evans 	} else {
1181392dbea3SBruce Evans 		/* Must be FAT16; use bit 15. */
1182cede1f56STom Rhodes 		fatval = getushort(&bp->b_data[bo]);
1183cede1f56STom Rhodes 		if (dirty)
1184392dbea3SBruce Evans 			fatval &= 0x7FFF;
1185cede1f56STom Rhodes 		else
1186392dbea3SBruce Evans 			fatval |= 0x8000;
1187cede1f56STom Rhodes 		putushort(&bp->b_data[bo], fatval);
1188cede1f56STom Rhodes 	}
1189cede1f56STom Rhodes 
1190aaa38524SConrad Meyer 	/*
1191aaa38524SConrad Meyer 	 * The concern here is that a devvp may be readonly, without reporting
1192aaa38524SConrad Meyer 	 * itself as such through the usual channels.  In that case, we'd like
1193aaa38524SConrad Meyer 	 * it if attempting to mount msdosfs rw didn't panic the system.
1194aaa38524SConrad Meyer 	 *
1195aaa38524SConrad Meyer 	 * markvoldirty is invoked as the first write on backing devvps when
1196aaa38524SConrad Meyer 	 * either msdosfs is mounted for the first time, or a ro mount is
1197aaa38524SConrad Meyer 	 * upgraded to rw.
1198aaa38524SConrad Meyer 	 *
1199aaa38524SConrad Meyer 	 * In either event, if a write error occurs dirtying the volume:
1200aaa38524SConrad Meyer 	 *   - No user data has been permitted to be written to cache yet.
1201aaa38524SConrad Meyer 	 *   - We can abort the high-level operation (mount, or ro->rw) safely.
1202aaa38524SConrad Meyer 	 *   - We don't derive any benefit from leaving a zombie dirty buf in
1203aaa38524SConrad Meyer 	 *   the cache that can not be cleaned or evicted.
1204aaa38524SConrad Meyer 	 *
1205aaa38524SConrad Meyer 	 * So, mark B_INVALONERR to have bwrite() -> brelse() detect that
1206aaa38524SConrad Meyer 	 * condition and force-invalidate our write to the block if it occurs.
1207aaa38524SConrad Meyer 	 *
1208aaa38524SConrad Meyer 	 * PR 210316 provides more context on the discovery and diagnosis of
1209aaa38524SConrad Meyer 	 * the problem, as well as earlier attempts to solve it.
1210aaa38524SConrad Meyer 	 */
1211aaa38524SConrad Meyer 	bp->b_flags |= B_INVALONERR;
1212aaa38524SConrad Meyer 
1213392dbea3SBruce Evans 	/* Write out the modified FAT block synchronously. */
1214392dbea3SBruce Evans 	return (bwrite(bp));
1215cede1f56STom Rhodes }
1216