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