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