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