1/* $FreeBSD$ */
2/*	$NetBSD: msdosfs_fat.c,v 1.28 1997/11/17 15:36:49 ws Exp $	*/
3
4/*-
5 * SPDX-License-Identifier: BSD-4-Clause
6 *
7 * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
8 * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
9 * All rights reserved.
10 * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 *    notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 *    notice, this list of conditions and the following disclaimer in the
19 *    documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 *    must display the following acknowledgement:
22 *	This product includes software developed by TooLs GmbH.
23 * 4. The name of TooLs GmbH may not be used to endorse or promote products
24 *    derived from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
27 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29 * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
30 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
32 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
33 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
34 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
35 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 */
37/*-
38 * Written by Paul Popelka (paulp@uts.amdahl.com)
39 *
40 * You can do anything you want with this software, just don't say you wrote
41 * it, and don't remove this notice.
42 *
43 * This software is provided "as is".
44 *
45 * The author supplies this software to be publicly redistributed on the
46 * understanding that the author is not responsible for the correct
47 * functioning of this software in any circumstances and is not liable for
48 * any damages caused by this software.
49 *
50 * October 1992
51 */
52
53#include <sys/param.h>
54#include <sys/systm.h>
55#include <sys/buf.h>
56#include <sys/mount.h>
57#include <sys/vmmeter.h>
58#include <sys/vnode.h>
59
60#include <fs/msdosfs/bpb.h>
61#include <fs/msdosfs/direntry.h>
62#include <fs/msdosfs/denode.h>
63#include <fs/msdosfs/fat.h>
64#include <fs/msdosfs/msdosfsmount.h>
65
66#define	FULL_RUN	((u_int)0xffffffff)
67
68static int	chainalloc(struct msdosfsmount *pmp, u_long start,
69		    u_long count, u_long fillwith, u_long *retcluster,
70		    u_long *got);
71static int	chainlength(struct msdosfsmount *pmp, u_long start,
72		    u_long count);
73static void	fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp,
74		    u_long *sizep, u_long *bop);
75static int	fatchain(struct msdosfsmount *pmp, u_long start, u_long count,
76		    u_long fillwith);
77static void	fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp,
78		    u_long *fsrcnp);
79static void	updatefats(struct msdosfsmount *pmp, struct buf *bp,
80		    u_long fatbn);
81static __inline void
82		usemap_alloc(struct msdosfsmount *pmp, u_long cn);
83static __inline void
84		usemap_free(struct msdosfsmount *pmp, u_long cn);
85static int	clusteralloc1(struct msdosfsmount *pmp, u_long start,
86		    u_long count, u_long fillwith, u_long *retcluster,
87		    u_long *got);
88
89static void
90fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep,
91    u_long *bop)
92{
93	u_long bn, size;
94
95	bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
96	size = min(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
97	    * DEV_BSIZE;
98	bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
99
100	if (bnp)
101		*bnp = bn;
102	if (sizep)
103		*sizep = size;
104	if (bop)
105		*bop = ofs % pmp->pm_fatblocksize;
106}
107
108/*
109 * Map the logical cluster number of a file into a physical disk sector
110 * that is filesystem relative.
111 *
112 * dep	  - address of denode representing the file of interest
113 * findcn - file relative cluster whose filesystem relative cluster number
114 *	    and/or block number are/is to be found
115 * bnp	  - address of where to place the filesystem relative block number.
116 *	    If this pointer is null then don't return this quantity.
117 * cnp	  - address of where to place the filesystem relative cluster number.
118 *	    If this pointer is null then don't return this quantity.
119 * sp     - pointer to returned block size
120 *
121 * NOTE: Either bnp or cnp must be non-null.
122 * This function has one side effect.  If the requested file relative cluster
123 * is beyond the end of file, then the actual number of clusters in the file
124 * is returned in *cnp.  This is useful for determining how long a directory is.
125 *  If cnp is null, nothing is returned.
126 */
127int
128pcbmap(struct denode *dep, u_long findcn, daddr_t *bnp, u_long *cnp, int *sp)
129{
130	int error;
131	u_long i;
132	u_long cn;
133	u_long prevcn = 0; /* XXX: prevcn could be used unititialized */
134	u_long byteoffset;
135	u_long bn;
136	u_long bo;
137	struct buf *bp = NULL;
138	u_long bp_bn = -1;
139	struct msdosfsmount *pmp = dep->de_pmp;
140	u_long bsize;
141
142	KASSERT(bnp != NULL || cnp != NULL || sp != NULL,
143	    ("pcbmap: extra call"));
144	ASSERT_VOP_ELOCKED(DETOV(dep), "pcbmap");
145
146	cn = dep->de_StartCluster;
147	/*
148	 * The "file" that makes up the root directory is contiguous,
149	 * permanently allocated, of fixed size, and is not made up of
150	 * clusters.  If the cluster number is beyond the end of the root
151	 * directory, then return the number of clusters in the file.
152	 */
153	if (cn == MSDOSFSROOT) {
154		if (dep->de_Attributes & ATTR_DIRECTORY) {
155			if (de_cn2off(pmp, findcn) >= dep->de_FileSize) {
156				if (cnp)
157					*cnp = de_bn2cn(pmp, pmp->pm_rootdirsize);
158				return (E2BIG);
159			}
160			if (bnp)
161				*bnp = pmp->pm_rootdirblk + de_cn2bn(pmp, findcn);
162			if (cnp)
163				*cnp = MSDOSFSROOT;
164			if (sp)
165				*sp = min(pmp->pm_bpcluster,
166				    dep->de_FileSize - de_cn2off(pmp, findcn));
167			return (0);
168		} else {		/* just an empty file */
169			if (cnp)
170				*cnp = 0;
171			return (E2BIG);
172		}
173	}
174
175	/*
176	 * All other files do I/O in cluster sized blocks
177	 */
178	if (sp)
179		*sp = pmp->pm_bpcluster;
180
181	/*
182	 * Rummage around in the FAT cache, maybe we can avoid tromping
183	 * through every FAT entry for the file. And, keep track of how far
184	 * off the cache was from where we wanted to be.
185	 */
186	i = 0;
187	fc_lookup(dep, findcn, &i, &cn);
188
189	/*
190	 * Handle all other files or directories the normal way.
191	 */
192	for (; i < findcn; i++) {
193		/*
194		 * Stop with all reserved clusters, not just with EOF.
195		 */
196		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
197			goto hiteof;
198		byteoffset = FATOFS(pmp, cn);
199		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
200		if (bn != bp_bn) {
201			if (bp)
202				brelse(bp);
203			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
204			if (error) {
205				brelse(bp);
206				return (error);
207			}
208			bp_bn = bn;
209		}
210		prevcn = cn;
211		if (bo >= bsize) {
212			if (bp)
213				brelse(bp);
214			return (EIO);
215		}
216		if (FAT32(pmp))
217			cn = getulong(bp->b_data + bo);
218		else
219			cn = getushort(bp->b_data + bo);
220		if (FAT12(pmp) && (prevcn & 1))
221			cn >>= 4;
222		cn &= pmp->pm_fatmask;
223
224		/*
225		 * Force the special cluster numbers
226		 * to be the same for all cluster sizes
227		 * to let the rest of msdosfs handle
228		 * all cases the same.
229		 */
230		if ((cn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
231			cn |= ~pmp->pm_fatmask;
232	}
233
234	if (!MSDOSFSEOF(pmp, cn)) {
235		if (bp)
236			brelse(bp);
237		if (bnp)
238			*bnp = cntobn(pmp, cn);
239		if (cnp)
240			*cnp = cn;
241		fc_setcache(dep, FC_LASTMAP, i, cn);
242		return (0);
243	}
244
245hiteof:;
246	if (cnp)
247		*cnp = i;
248	if (bp)
249		brelse(bp);
250	/* update last file cluster entry in the FAT cache */
251	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
252	return (E2BIG);
253}
254
255/*
256 * Find the closest entry in the FAT cache to the cluster we are looking
257 * for.
258 */
259static void
260fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
261{
262	int i;
263	u_long cn;
264	struct fatcache *closest = NULL;
265
266	ASSERT_VOP_LOCKED(DETOV(dep), "fc_lookup");
267
268	for (i = 0; i < FC_SIZE; i++) {
269		cn = dep->de_fc[i].fc_frcn;
270		if (cn != FCE_EMPTY && cn <= findcn) {
271			if (closest == NULL || cn > closest->fc_frcn)
272				closest = &dep->de_fc[i];
273		}
274	}
275	if (closest) {
276		*frcnp = closest->fc_frcn;
277		*fsrcnp = closest->fc_fsrcn;
278	}
279}
280
281/*
282 * Purge the FAT cache in denode dep of all entries relating to file
283 * relative cluster frcn and beyond.
284 */
285void
286fc_purge(struct denode *dep, u_int frcn)
287{
288	int i;
289	struct fatcache *fcp;
290
291	ASSERT_VOP_ELOCKED(DETOV(dep), "fc_purge");
292
293	fcp = dep->de_fc;
294	for (i = 0; i < FC_SIZE; i++, fcp++) {
295		if (fcp->fc_frcn >= frcn)
296			fcp->fc_frcn = FCE_EMPTY;
297	}
298}
299
300/*
301 * Update the FAT.
302 * If mirroring the FAT, update all copies, with the first copy as last.
303 * Else update only the current FAT (ignoring the others).
304 *
305 * pmp	 - msdosfsmount structure for filesystem to update
306 * bp	 - addr of modified FAT block
307 * fatbn - block number relative to begin of filesystem of the modified FAT block.
308 */
309static void
310updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
311{
312	struct buf *bpn;
313	int cleanfat, i;
314
315#ifdef MSDOSFS_DEBUG
316	printf("updatefats(pmp %p, bp %p, fatbn %lu)\n", pmp, bp, fatbn);
317#endif
318
319	if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
320		/*
321		 * Now copy the block(s) of the modified FAT to the other copies of
322		 * the FAT and write them out.  This is faster than reading in the
323		 * other FATs and then writing them back out.  This could tie up
324		 * the FAT for quite a while. Preventing others from accessing it.
325		 * To prevent us from going after the FAT quite so much we use
326		 * delayed writes, unless they specified "synchronous" when the
327		 * filesystem was mounted.  If synch is asked for then use
328		 * bwrite()'s and really slow things down.
329		 */
330		if (fatbn != pmp->pm_fatblk || FAT12(pmp))
331			cleanfat = 0;
332		else if (FAT16(pmp))
333			cleanfat = 16;
334		else
335			cleanfat = 32;
336		for (i = 1; i < pmp->pm_FATs; i++) {
337			fatbn += pmp->pm_FATsecs;
338			/* getblk() never fails */
339			bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount,
340			    0, 0, 0);
341			memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
342			/* Force the clean bit on in the other copies. */
343			if (cleanfat == 16)
344				((uint8_t *)bpn->b_data)[3] |= 0x80;
345			else if (cleanfat == 32)
346				((uint8_t *)bpn->b_data)[7] |= 0x08;
347			if (pmp->pm_mountp->mnt_flag & MNT_SYNCHRONOUS)
348				bwrite(bpn);
349			else
350				bdwrite(bpn);
351		}
352	}
353
354	/*
355	 * Write out the first (or current) FAT last.
356	 */
357	if (pmp->pm_mountp->mnt_flag & MNT_SYNCHRONOUS)
358		bwrite(bp);
359	else
360		bdwrite(bp);
361}
362
363/*
364 * Updating entries in 12 bit FATs is a pain in the butt.
365 *
366 * The following picture shows where nibbles go when moving from a 12 bit
367 * cluster number into the appropriate bytes in the FAT.
368 *
369 *	byte m        byte m+1      byte m+2
370 *	+----+----+   +----+----+   +----+----+
371 *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
372 *	+----+----+   +----+----+   +----+----+
373 *
374 *	+----+----+----+   +----+----+----+
375 *	|  3    0    1 |   |  4    5    2 |
376 *	+----+----+----+   +----+----+----+
377 *	cluster n  	   cluster n+1
378 *
379 * Where n is even. m = n + (n >> 2)
380 *
381 */
382static __inline void
383usemap_alloc(struct msdosfsmount *pmp, u_long cn)
384{
385
386	MSDOSFS_ASSERT_MP_LOCKED(pmp);
387
388	KASSERT(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
389	    pmp->pm_maxcluster));
390	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
391	    ("usemap_alloc on ro msdosfs mount"));
392	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] &
393	    (1U << (cn % N_INUSEBITS))) == 0,
394	    ("Allocating used sector %ld %ld %x", cn, cn % N_INUSEBITS,
395	    (unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
396	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
397	KASSERT(pmp->pm_freeclustercount > 0, ("usemap_alloc: too little"));
398	pmp->pm_freeclustercount--;
399	pmp->pm_flags |= MSDOSFS_FSIMOD;
400}
401
402static __inline void
403usemap_free(struct msdosfsmount *pmp, u_long cn)
404{
405
406	MSDOSFS_ASSERT_MP_LOCKED(pmp);
407
408	KASSERT(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
409	    pmp->pm_maxcluster));
410	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
411	    ("usemap_free on ro msdosfs mount"));
412	pmp->pm_freeclustercount++;
413	pmp->pm_flags |= MSDOSFS_FSIMOD;
414	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] &
415	    (1U << (cn % N_INUSEBITS))) != 0,
416	    ("Freeing unused sector %ld %ld %x", cn, cn % N_INUSEBITS,
417	    (unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
418	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1U << (cn % N_INUSEBITS));
419}
420
421int
422clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
423{
424	int error;
425	u_long oldcn;
426
427	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
428	if (error)
429		return (error);
430	/*
431	 * If the cluster was successfully marked free, then update
432	 * the count of free clusters, and turn off the "allocated"
433	 * bit in the "in use" cluster bit map.
434	 */
435	MSDOSFS_LOCK_MP(pmp);
436	usemap_free(pmp, cluster);
437	MSDOSFS_UNLOCK_MP(pmp);
438	if (oldcnp)
439		*oldcnp = oldcn;
440	return (0);
441}
442
443/*
444 * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
445 *
446 * function	- whether to get or set a FAT entry
447 * pmp		- address of the msdosfsmount structure for the filesystem
448 *		  whose FAT is to be manipulated.
449 * cn		- which cluster is of interest
450 * oldcontents	- address of a word that is to receive the contents of the
451 *		  cluster'th entry if this is a get function
452 * newcontents	- the new value to be written into the cluster'th element of
453 *		  the FAT if this is a set function.
454 *
455 * This function can also be used to free a cluster by setting the FAT entry
456 * for a cluster to 0.
457 *
458 * All copies of the FAT are updated if this is a set function. NOTE: If
459 * fatentry() marks a cluster as free it does not update the inusemap in
460 * the msdosfsmount structure. This is left to the caller.
461 */
462int
463fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents,
464    u_long newcontents)
465{
466	int error;
467	u_long readcn;
468	u_long bn, bo, bsize, byteoffset;
469	struct buf *bp;
470
471#ifdef	MSDOSFS_DEBUG
472	printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
473	    function, pmp, cn, oldcontents, newcontents);
474#endif
475
476#ifdef DIAGNOSTIC
477	/*
478	 * Be sure they asked us to do something.
479	 */
480	if ((function & (FAT_SET | FAT_GET)) == 0) {
481#ifdef MSDOSFS_DEBUG
482		printf("fatentry(): function code doesn't specify get or set\n");
483#endif
484		return (EINVAL);
485	}
486
487	/*
488	 * If they asked us to return a cluster number but didn't tell us
489	 * where to put it, give them an error.
490	 */
491	if ((function & FAT_GET) && oldcontents == NULL) {
492#ifdef MSDOSFS_DEBUG
493		printf("fatentry(): get function with no place to put result\n");
494#endif
495		return (EINVAL);
496	}
497#endif
498
499	/*
500	 * Be sure the requested cluster is in the filesystem.
501	 */
502	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
503		return (EINVAL);
504
505	byteoffset = FATOFS(pmp, cn);
506	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
507	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
508	if (error) {
509		brelse(bp);
510		return (error);
511	}
512
513	if (function & FAT_GET) {
514		if (FAT32(pmp))
515			readcn = getulong(bp->b_data + bo);
516		else
517			readcn = getushort(bp->b_data + bo);
518		if (FAT12(pmp) & (cn & 1))
519			readcn >>= 4;
520		readcn &= pmp->pm_fatmask;
521		/* map reserved FAT entries to same values for all FATs */
522		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
523			readcn |= ~pmp->pm_fatmask;
524		*oldcontents = readcn;
525	}
526	if (function & FAT_SET) {
527		switch (pmp->pm_fatmask) {
528		case FAT12_MASK:
529			readcn = getushort(bp->b_data + bo);
530			if (cn & 1) {
531				readcn &= 0x000f;
532				readcn |= newcontents << 4;
533			} else {
534				readcn &= 0xf000;
535				readcn |= newcontents & 0xfff;
536			}
537			putushort(bp->b_data + bo, readcn);
538			break;
539		case FAT16_MASK:
540			putushort(bp->b_data + bo, newcontents);
541			break;
542		case FAT32_MASK:
543			/*
544			 * According to spec we have to retain the
545			 * high order bits of the FAT entry.
546			 */
547			readcn = getulong(bp->b_data + bo);
548			readcn &= ~FAT32_MASK;
549			readcn |= newcontents & FAT32_MASK;
550			putulong(bp->b_data + bo, readcn);
551			break;
552		}
553		updatefats(pmp, bp, bn);
554		bp = NULL;
555		pmp->pm_fmod = 1;
556	}
557	if (bp)
558		brelse(bp);
559	return (0);
560}
561
562/*
563 * Update a contiguous cluster chain
564 *
565 * pmp	    - mount point
566 * start    - first cluster of chain
567 * count    - number of clusters in chain
568 * fillwith - what to write into FAT entry of last cluster
569 */
570static int
571fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
572{
573	int error;
574	u_long bn, bo, bsize, byteoffset, readcn, newc;
575	struct buf *bp;
576
577#ifdef MSDOSFS_DEBUG
578	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
579	    pmp, start, count, fillwith);
580#endif
581	/*
582	 * Be sure the clusters are in the filesystem.
583	 */
584	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
585		return (EINVAL);
586
587	while (count > 0) {
588		byteoffset = FATOFS(pmp, start);
589		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
590		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
591		if (error) {
592			brelse(bp);
593			return (error);
594		}
595		while (count > 0) {
596			start++;
597			newc = --count > 0 ? start : fillwith;
598			switch (pmp->pm_fatmask) {
599			case FAT12_MASK:
600				readcn = getushort(bp->b_data + bo);
601				if (start & 1) {
602					readcn &= 0xf000;
603					readcn |= newc & 0xfff;
604				} else {
605					readcn &= 0x000f;
606					readcn |= newc << 4;
607				}
608				putushort(bp->b_data + bo, readcn);
609				bo++;
610				if (!(start & 1))
611					bo++;
612				break;
613			case FAT16_MASK:
614				putushort(bp->b_data + bo, newc);
615				bo += 2;
616				break;
617			case FAT32_MASK:
618				readcn = getulong(bp->b_data + bo);
619				readcn &= ~pmp->pm_fatmask;
620				readcn |= newc & pmp->pm_fatmask;
621				putulong(bp->b_data + bo, readcn);
622				bo += 4;
623				break;
624			}
625			if (bo >= bsize)
626				break;
627		}
628		updatefats(pmp, bp, bn);
629	}
630	pmp->pm_fmod = 1;
631	return (0);
632}
633
634/*
635 * Check the length of a free cluster chain starting at start.
636 *
637 * pmp	 - mount point
638 * start - start of chain
639 * count - maximum interesting length
640 */
641static int
642chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
643{
644	u_long idx, max_idx;
645	u_int map;
646	u_long len;
647
648	MSDOSFS_ASSERT_MP_LOCKED(pmp);
649
650	if (start > pmp->pm_maxcluster)
651		return (0);
652	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
653	idx = start / N_INUSEBITS;
654	start %= N_INUSEBITS;
655	map = pmp->pm_inusemap[idx];
656	map &= ~((1U << start) - 1);
657	if (map) {
658		len = ffs(map) - 1 - start;
659		len = MIN(len, count);
660		if (start + len > pmp->pm_maxcluster)
661			len = pmp->pm_maxcluster - start + 1;
662		return (len);
663	}
664	len = N_INUSEBITS - start;
665	if (len >= count) {
666		len = count;
667		if (start + len > pmp->pm_maxcluster)
668			len = pmp->pm_maxcluster - start + 1;
669		return (len);
670	}
671	while (++idx <= max_idx) {
672		if (len >= count)
673			break;
674		map = pmp->pm_inusemap[idx];
675		if (map) {
676			len += ffs(map) - 1;
677			break;
678		}
679		len += N_INUSEBITS;
680	}
681	len = MIN(len, count);
682	if (start + len > pmp->pm_maxcluster)
683		len = pmp->pm_maxcluster - start + 1;
684	return (len);
685}
686
687/*
688 * Allocate contigous free clusters.
689 *
690 * pmp	      - mount point.
691 * start      - start of cluster chain.
692 * count      - number of clusters to allocate.
693 * fillwith   - put this value into the FAT entry for the
694 *		last allocated cluster.
695 * retcluster - put the first allocated cluster's number here.
696 * got	      - how many clusters were actually allocated.
697 */
698static int
699chainalloc(struct msdosfsmount *pmp, u_long start, u_long count,
700    u_long fillwith, u_long *retcluster, u_long *got)
701{
702	int error;
703	u_long cl, n;
704
705	MSDOSFS_ASSERT_MP_LOCKED(pmp);
706	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
707	    ("chainalloc on ro msdosfs mount"));
708
709	for (cl = start, n = count; n-- > 0;)
710		usemap_alloc(pmp, cl++);
711	pmp->pm_nxtfree = start + count;
712	if (pmp->pm_nxtfree > pmp->pm_maxcluster)
713		pmp->pm_nxtfree = CLUST_FIRST;
714	pmp->pm_flags |= MSDOSFS_FSIMOD;
715	error = fatchain(pmp, start, count, fillwith);
716	if (error != 0) {
717		for (cl = start, n = count; n-- > 0;)
718			usemap_free(pmp, cl++);
719		return (error);
720	}
721#ifdef MSDOSFS_DEBUG
722	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
723	    start, count);
724#endif
725	if (retcluster)
726		*retcluster = start;
727	if (got)
728		*got = count;
729	return (0);
730}
731
732/*
733 * Allocate contiguous free clusters.
734 *
735 * pmp	      - mount point.
736 * start      - preferred start of cluster chain.
737 * count      - number of clusters requested.
738 * fillwith   - put this value into the FAT entry for the
739 *		last allocated cluster.
740 * retcluster - put the first allocated cluster's number here.
741 * got	      - how many clusters were actually allocated.
742 */
743int
744clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
745    u_long fillwith, u_long *retcluster, u_long *got)
746{
747	int error;
748
749	MSDOSFS_LOCK_MP(pmp);
750	error = clusteralloc1(pmp, start, count, fillwith, retcluster, got);
751	MSDOSFS_UNLOCK_MP(pmp);
752	return (error);
753}
754
755static int
756clusteralloc1(struct msdosfsmount *pmp, u_long start, u_long count,
757    u_long fillwith, u_long *retcluster, u_long *got)
758{
759	u_long idx;
760	u_long len, newst, foundl, cn, l;
761	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
762	u_int map;
763
764	MSDOSFS_ASSERT_MP_LOCKED(pmp);
765
766#ifdef MSDOSFS_DEBUG
767	printf("clusteralloc(): find %lu clusters\n", count);
768#endif
769	if (start) {
770		if ((len = chainlength(pmp, start, count)) >= count)
771			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
772	} else
773		len = 0;
774
775	newst = pmp->pm_nxtfree;
776	foundl = 0;
777
778	for (cn = newst; cn <= pmp->pm_maxcluster;) {
779		idx = cn / N_INUSEBITS;
780		map = pmp->pm_inusemap[idx];
781		map |= (1U << (cn % N_INUSEBITS)) - 1;
782		if (map != FULL_RUN) {
783			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
784			if ((l = chainlength(pmp, cn, count)) >= count)
785				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
786			if (l > foundl) {
787				foundcn = cn;
788				foundl = l;
789			}
790			cn += l + 1;
791			continue;
792		}
793		cn += N_INUSEBITS - cn % N_INUSEBITS;
794	}
795	for (cn = 0; cn < newst;) {
796		idx = cn / N_INUSEBITS;
797		map = pmp->pm_inusemap[idx];
798		map |= (1U << (cn % N_INUSEBITS)) - 1;
799		if (map != FULL_RUN) {
800			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
801			if ((l = chainlength(pmp, cn, count)) >= count)
802				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
803			if (l > foundl) {
804				foundcn = cn;
805				foundl = l;
806			}
807			cn += l + 1;
808			continue;
809		}
810		cn += N_INUSEBITS - cn % N_INUSEBITS;
811	}
812
813	if (!foundl)
814		return (ENOSPC);
815
816	if (len)
817		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
818	else
819		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
820}
821
822
823/*
824 * Free a chain of clusters.
825 *
826 * pmp		- address of the msdosfs mount structure for the filesystem
827 *		  containing the cluster chain to be freed.
828 * startcluster - number of the 1st cluster in the chain of clusters to be
829 *		  freed.
830 */
831int
832freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
833{
834	int error;
835	struct buf *bp = NULL;
836	u_long bn, bo, bsize, byteoffset;
837	u_long readcn, lbn = -1;
838
839	MSDOSFS_LOCK_MP(pmp);
840	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
841		byteoffset = FATOFS(pmp, cluster);
842		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
843		if (lbn != bn) {
844			if (bp)
845				updatefats(pmp, bp, lbn);
846			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
847			if (error) {
848				brelse(bp);
849				MSDOSFS_UNLOCK_MP(pmp);
850				return (error);
851			}
852			lbn = bn;
853		}
854		usemap_free(pmp, cluster);
855		switch (pmp->pm_fatmask) {
856		case FAT12_MASK:
857			readcn = getushort(bp->b_data + bo);
858			if (cluster & 1) {
859				cluster = readcn >> 4;
860				readcn &= 0x000f;
861				readcn |= MSDOSFSFREE << 4;
862			} else {
863				cluster = readcn;
864				readcn &= 0xf000;
865				readcn |= MSDOSFSFREE & 0xfff;
866			}
867			putushort(bp->b_data + bo, readcn);
868			break;
869		case FAT16_MASK:
870			cluster = getushort(bp->b_data + bo);
871			putushort(bp->b_data + bo, MSDOSFSFREE);
872			break;
873		case FAT32_MASK:
874			cluster = getulong(bp->b_data + bo);
875			putulong(bp->b_data + bo,
876				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
877			break;
878		}
879		cluster &= pmp->pm_fatmask;
880		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
881			cluster |= pmp->pm_fatmask;
882	}
883	if (bp)
884		updatefats(pmp, bp, bn);
885	MSDOSFS_UNLOCK_MP(pmp);
886	return (0);
887}
888
889/*
890 * Read in FAT blocks looking for free clusters. For every free cluster
891 * found turn off its corresponding bit in the pm_inusemap.
892 */
893int
894fillinusemap(struct msdosfsmount *pmp)
895{
896	struct buf *bp;
897	u_long bn, bo, bsize, byteoffset, cn, readcn;
898	int error;
899
900	MSDOSFS_ASSERT_MP_LOCKED(pmp);
901	bp = NULL;
902
903	/*
904	 * Mark all clusters in use, we mark the free ones in the FAT scan
905	 * loop further down.
906	 */
907	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
908		pmp->pm_inusemap[cn] = FULL_RUN;
909
910	/*
911	 * Figure how many free clusters are in the filesystem by ripping
912	 * through the FAT counting the number of entries whose content is
913	 * zero.  These represent free clusters.
914	 */
915	pmp->pm_freeclustercount = 0;
916	for (cn = 0; cn <= pmp->pm_maxcluster; cn++) {
917		byteoffset = FATOFS(pmp, cn);
918		bo = byteoffset % pmp->pm_fatblocksize;
919		if (bo == 0) {
920			/* Read new FAT block */
921			if (bp != NULL)
922				brelse(bp);
923			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
924			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
925			if (error != 0)
926				return (error);
927		}
928		if (FAT32(pmp))
929			readcn = getulong(bp->b_data + bo);
930		else
931			readcn = getushort(bp->b_data + bo);
932		if (FAT12(pmp) && (cn & 1))
933			readcn >>= 4;
934		readcn &= pmp->pm_fatmask;
935
936		/*
937		 * Check if the FAT ID matches the BPB's media descriptor and
938		 * all other bits are set to 1.
939		 */
940		if (cn == 0 && readcn != ((pmp->pm_fatmask & 0xffffff00) |
941		    pmp->pm_bpb.bpbMedia)) {
942#ifdef MSDOSFS_DEBUG
943			printf("mountmsdosfs(): Media descriptor in BPB"
944			    "does not match FAT ID\n");
945#endif
946			brelse(bp);
947			return (EINVAL);
948		} else if (readcn == CLUST_FREE)
949			usemap_free(pmp, cn);
950	}
951	if (bp != NULL)
952		brelse(bp);
953
954	for (cn = pmp->pm_maxcluster + 1; cn < (pmp->pm_maxcluster +
955	    N_INUSEBITS) / N_INUSEBITS; cn++)
956		pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
957
958	return (0);
959}
960
961/*
962 * Allocate a new cluster and chain it onto the end of the file.
963 *
964 * dep	 - the file to extend
965 * count - number of clusters to allocate
966 * bpp	 - where to return the address of the buf header for the first new
967 *	   file block
968 * ncp	 - where to put cluster number of the first newly allocated cluster
969 *	   If this pointer is 0, do not return the cluster number.
970 * flags - see fat.h
971 *
972 * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
973 * the de_flag field of the denode and it does not change the de_FileSize
974 * field.  This is left for the caller to do.
975 */
976int
977extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp,
978    int flags)
979{
980	int error;
981	u_long frcn;
982	u_long cn, got;
983	struct msdosfsmount *pmp = dep->de_pmp;
984	struct buf *bp;
985	daddr_t blkno;
986
987	/*
988	 * Don't try to extend the root directory
989	 */
990	if (dep->de_StartCluster == MSDOSFSROOT
991	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
992#ifdef MSDOSFS_DEBUG
993		printf("extendfile(): attempt to extend root directory\n");
994#endif
995		return (ENOSPC);
996	}
997
998	/*
999	 * If the "file's last cluster" cache entry is empty, and the file
1000	 * is not empty, then fill the cache entry by calling pcbmap().
1001	 */
1002	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
1003	    dep->de_StartCluster != 0) {
1004		error = pcbmap(dep, 0xffff, 0, &cn, 0);
1005		/* we expect it to return E2BIG */
1006		if (error != E2BIG)
1007			return (error);
1008	}
1009
1010	dep->de_fc[FC_NEXTTOLASTFC].fc_frcn =
1011	    dep->de_fc[FC_LASTFC].fc_frcn;
1012	dep->de_fc[FC_NEXTTOLASTFC].fc_fsrcn =
1013	    dep->de_fc[FC_LASTFC].fc_fsrcn;
1014	while (count > 0) {
1015		/*
1016		 * Allocate a new cluster chain and cat onto the end of the
1017		 * file.  If the file is empty we make de_StartCluster point
1018		 * to the new block.  Note that de_StartCluster being 0 is
1019		 * sufficient to be sure the file is empty since we exclude
1020		 * attempts to extend the root directory above, and the root
1021		 * dir is the only file with a startcluster of 0 that has
1022		 * blocks allocated (sort of).
1023		 */
1024		if (dep->de_StartCluster == 0)
1025			cn = 0;
1026		else
1027			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1028		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1029		if (error)
1030			return (error);
1031
1032		count -= got;
1033
1034		/*
1035		 * Give them the filesystem relative cluster number if they want
1036		 * it.
1037		 */
1038		if (ncp) {
1039			*ncp = cn;
1040			ncp = NULL;
1041		}
1042
1043		if (dep->de_StartCluster == 0) {
1044			dep->de_StartCluster = cn;
1045			frcn = 0;
1046		} else {
1047			error = fatentry(FAT_SET, pmp,
1048					 dep->de_fc[FC_LASTFC].fc_fsrcn,
1049					 0, cn);
1050			if (error) {
1051				clusterfree(pmp, cn, NULL);
1052				return (error);
1053			}
1054			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1055		}
1056
1057		/*
1058		 * Update the "last cluster of the file" entry in the
1059		 * denode's FAT cache.
1060		 */
1061		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1062
1063		if (flags & DE_CLEAR) {
1064			while (got-- > 0) {
1065				/*
1066				 * Get the buf header for the new block of the file.
1067				 */
1068				if (dep->de_Attributes & ATTR_DIRECTORY)
1069					bp = getblk(pmp->pm_devvp,
1070					    cntobn(pmp, cn++),
1071					    pmp->pm_bpcluster, 0, 0, 0);
1072				else {
1073					bp = getblk(DETOV(dep),
1074					    frcn++,
1075					    pmp->pm_bpcluster, 0, 0, 0);
1076					/*
1077					 * Do the bmap now, as in msdosfs_write
1078					 */
1079					if (pcbmap(dep,
1080					    bp->b_lblkno,
1081					    &blkno, 0, 0))
1082						bp->b_blkno = -1;
1083					if (bp->b_blkno == -1)
1084						panic("extendfile: pcbmap");
1085					else
1086						bp->b_blkno = blkno;
1087				}
1088				clrbuf(bp);
1089				if (bpp) {
1090					*bpp = bp;
1091					bpp = NULL;
1092				} else {
1093					bdwrite(bp);
1094				}
1095				if (vm_page_count_severe() ||
1096				    buf_dirty_count_severe())
1097					vn_fsync_buf(DETOV(dep), MNT_WAIT);
1098			}
1099		}
1100	}
1101
1102	return (0);
1103}
1104
1105/*-
1106 * Routine to mark a FAT16 or FAT32 volume as "clean" or "dirty" by
1107 * manipulating the upper bit of the FAT entry for cluster 1.  Note that
1108 * this bit is not defined for FAT12 volumes, which are always assumed to
1109 * be clean.
1110 *
1111 * The fatentry() routine only works on cluster numbers that a file could
1112 * occupy, so it won't manipulate the entry for cluster 1.  So we have to do
1113 * it here.  The code was stolen from fatentry() and tailored for cluster 1.
1114 *
1115 * Inputs:
1116 *	pmp	The MS-DOS volume to mark
1117 *	dirty	Non-zero if the volume should be marked dirty; zero if it
1118 *		should be marked clean
1119 *
1120 * Result:
1121 *	0	Success
1122 *	EROFS	Volume is read-only
1123 *	?	(other errors from called routines)
1124 */
1125int
1126markvoldirty(struct msdosfsmount *pmp, int dirty)
1127{
1128	struct buf *bp;
1129	u_long bn, bo, bsize, byteoffset, fatval;
1130	int error;
1131
1132	/*
1133	 * FAT12 does not support a "clean" bit, so don't do anything for
1134	 * FAT12.
1135	 */
1136	if (FAT12(pmp))
1137		return (0);
1138
1139	/* Can't change the bit on a read-only filesystem. */
1140	if (pmp->pm_flags & MSDOSFSMNT_RONLY)
1141		return (EROFS);
1142
1143	/*
1144	 * Fetch the block containing the FAT entry.  It is given by the
1145	 * pseudo-cluster 1.
1146	 */
1147	byteoffset = FATOFS(pmp, 1);
1148	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
1149	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
1150	if (error) {
1151		brelse(bp);
1152		return (error);
1153	}
1154
1155	/*
1156	 * Get the current value of the FAT entry and set/clear the relevant
1157	 * bit.  Dirty means clear the "clean" bit; clean means set the
1158	 * "clean" bit.
1159	 */
1160	if (FAT32(pmp)) {
1161		/* FAT32 uses bit 27. */
1162		fatval = getulong(&bp->b_data[bo]);
1163		if (dirty)
1164			fatval &= 0xF7FFFFFF;
1165		else
1166			fatval |= 0x08000000;
1167		putulong(&bp->b_data[bo], fatval);
1168	} else {
1169		/* Must be FAT16; use bit 15. */
1170		fatval = getushort(&bp->b_data[bo]);
1171		if (dirty)
1172			fatval &= 0x7FFF;
1173		else
1174			fatval |= 0x8000;
1175		putushort(&bp->b_data[bo], fatval);
1176	}
1177
1178	/* Write out the modified FAT block synchronously. */
1179	return (bwrite(bp));
1180}
1181