msdosfs_fat.c revision 33181
1/*	$Id: msdosfs_fat.c,v 1.15 1998/02/06 12:13:46 eivind Exp $ */
2/*	$NetBSD: msdosfs_fat.c,v 1.12 1994/08/21 18:44:04 ws Exp $	*/
3
4/*-
5 * Copyright (C) 1994 Wolfgang Solfrank.
6 * Copyright (C) 1994 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
82/* Byte offset in FAT on filesystem pmp, cluster cn */
83#define	FATOFS(pmp, cn)	(FAT12(pmp) ? (cn) * 3 / 2 : (cn) * 2)
84
85static int	chainalloc __P((struct msdosfsmount *pmp, u_long start,
86				u_long count, u_long fillwith,
87				u_long *retcluster, u_long *got));
88static int	chainlength __P((struct msdosfsmount *pmp, u_long start,
89				 u_long count));
90static void	fatblock __P((struct msdosfsmount *pmp, u_long ofs,
91			      u_long *bnp, u_long *sizep, u_long *bop));
92static int	fatchain __P((struct msdosfsmount *pmp, u_long start,
93			      u_long count, u_long fillwith));
94static void	fc_lookup __P((struct denode *dep, u_long findcn,
95			       u_long *frcnp, u_long *fsrcnp));
96static void	updatefats __P((struct msdosfsmount *pmp, struct buf *bp,
97				u_long fatbn));
98static void	usemap_alloc __P((struct msdosfsmount *pmp, u_long cn));
99static void	usemap_free __P((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	    * pmp->pm_BytesPerSec;
114	bn += pmp->pm_fatblk;
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)
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{
148	int error;
149	u_long i;
150	u_long cn;
151	u_long prevcn;
152	u_long byteoffset;
153	u_long bn;
154	u_long bo;
155	struct buf *bp = NULL;
156	u_long bp_bn = -1;
157	struct msdosfsmount *pmp = dep->de_pmp;
158	u_long bsize;
159	int fat12 = FAT12(pmp);	/* 12 bit fat	 */
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)
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 (findcn * pmp->pm_SectPerClust >= pmp->pm_rootdirsize) {
180				if (cnp)
181					*cnp = pmp->pm_rootdirsize / pmp->pm_SectPerClust;
182				return E2BIG;
183			}
184			if (bnp)
185				*bnp = pmp->pm_rootdirblk + (findcn * pmp->pm_SectPerClust);
186			if (cnp)
187				*cnp = MSDOSFSROOT;
188			return 0;
189		} else {		/* just an empty file */
190			if (cnp)
191				*cnp = 0;
192			return E2BIG;
193		}
194	}
195
196	/*
197	 * Rummage around in the fat cache, maybe we can avoid tromping
198	 * thru every fat entry for the file. And, keep track of how far
199	 * off the cache was from where we wanted to be.
200	 */
201	i = 0;
202	fc_lookup(dep, findcn, &i, &cn);
203	if ((bn = findcn - i) >= LMMAX)
204		fc_largedistance++;
205	else
206		fc_lmdistance[bn]++;
207
208	/*
209	 * Handle all other files or directories the normal way.
210	 */
211	prevcn = 0;
212	for (; i < findcn; i++) {
213		if (MSDOSFSEOF(cn))
214			goto hiteof;
215		byteoffset = FATOFS(pmp, cn);
216		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
217		if (bn != bp_bn) {
218			if (bp)
219				brelse(bp);
220			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
221			if (error)
222				return error;
223			bp_bn = bn;
224		}
225		prevcn = cn;
226		cn = getushort(&bp->b_data[bo]);
227		if (fat12) {
228			if (prevcn & 1)
229				cn >>= 4;
230			cn &= 0x0fff;
231			/*
232			 * Force the special cluster numbers in the range
233			 * 0x0ff0-0x0fff to be the same as for 16 bit
234			 * cluster numbers to let the rest of msdosfs think
235			 * it is always dealing with 16 bit fats.
236			 */
237			if ((cn & 0x0ff0) == 0x0ff0)
238				cn |= 0xf000;
239		}
240	}
241
242	if (!MSDOSFSEOF(cn)) {
243		if (bp)
244			brelse(bp);
245		if (bnp)
246			*bnp = cntobn(pmp, cn);
247		if (cnp)
248			*cnp = cn;
249		fc_setcache(dep, FC_LASTMAP, i, cn);
250		return 0;
251	}
252
253hiteof:;
254	if (cnp)
255		*cnp = i;
256	if (bp)
257		brelse(bp);
258	/* update last file cluster entry in the fat cache */
259	fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
260	return E2BIG;
261}
262
263/*
264 * Find the closest entry in the fat cache to the cluster we are looking
265 * for.
266 */
267static void
268fc_lookup(dep, findcn, frcnp, fsrcnp)
269	struct denode *dep;
270	u_long findcn;
271	u_long *frcnp;
272	u_long *fsrcnp;
273{
274	int i;
275	u_long cn;
276	struct fatcache *closest = 0;
277
278	for (i = 0; i < FC_SIZE; i++) {
279		cn = dep->de_fc[i].fc_frcn;
280		if (cn != FCE_EMPTY && cn <= findcn) {
281			if (closest == 0 || cn > closest->fc_frcn)
282				closest = &dep->de_fc[i];
283		}
284	}
285	if (closest) {
286		*frcnp = closest->fc_frcn;
287		*fsrcnp = closest->fc_fsrcn;
288	}
289}
290
291/*
292 * Purge the fat cache in denode dep of all entries relating to file
293 * relative cluster frcn and beyond.
294 */
295void fc_purge(dep, frcn)
296	struct denode *dep;
297	u_int frcn;
298{
299	int i;
300	struct fatcache *fcp;
301
302	fcp = dep->de_fc;
303	for (i = 0; i < FC_SIZE; i++, fcp++) {
304		if (fcp->fc_frcn >= frcn)
305			fcp->fc_frcn = FCE_EMPTY;
306	}
307}
308
309/*
310 * Update all copies of the fat. The first copy is updated last.
311 *
312 * pmp	 - msdosfsmount structure for filesystem to update
313 * bp	 - addr of modified fat block
314 * fatbn - block number relative to begin of filesystem of the modified fat block.
315 */
316static void
317updatefats(pmp, bp, fatbn)
318	struct msdosfsmount *pmp;
319	struct buf *bp;
320	u_long fatbn;
321{
322	int i;
323	struct buf *bpn;
324
325#ifdef MSDOSFS_DEBUG
326	printf("updatefats(pmp %p, bp %p, fatbn %ld)\n", pmp, bp, fatbn);
327#endif
328
329	/*
330	 * Now copy the block(s) of the modified fat to the other copies of
331	 * the fat and write them out.  This is faster than reading in the
332	 * other fats and then writing them back out.  This could tie up
333	 * the fat for quite a while. Preventing others from accessing it.
334	 * To prevent us from going after the fat quite so much we use
335	 * delayed writes, unless they specfied "synchronous" when the
336	 * filesystem was mounted.  If synch is asked for then use
337	 * bwrite()'s and really slow things down.
338	 */
339	for (i = 1; i < pmp->pm_FATs; i++) {
340		fatbn += pmp->pm_FATsecs;
341		/* getblk() never fails */
342		bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount, 0, 0);
343		bcopy(bp->b_data, bpn->b_data, bp->b_bcount);
344		if (pmp->pm_waitonfat)
345			bwrite(bpn);
346		else
347			bdwrite(bpn);
348	}
349	/*
350	 * Write out the first fat last.
351	 */
352	if (pmp->pm_waitonfat)
353		bwrite(bp);
354	else
355		bdwrite(bp);
356}
357
358/*
359 * Updating entries in 12 bit fats is a pain in the butt.
360 *
361 * The following picture shows where nibbles go when moving from a 12 bit
362 * cluster number into the appropriate bytes in the FAT.
363 *
364 *	byte m        byte m+1      byte m+2
365 *	+----+----+   +----+----+   +----+----+
366 *	|  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
367 *	+----+----+   +----+----+   +----+----+
368 *
369 *	+----+----+----+   +----+----+----+
370 *	|  3    0    1 |   |  4    5    2 |
371 *	+----+----+----+   +----+----+----+
372 *	cluster n  	   cluster n+1
373 *
374 * Where n is even. m = n + (n >> 2)
375 *
376 */
377static inline void
378usemap_alloc(pmp, cn)
379	struct msdosfsmount *pmp;
380	u_long cn;
381{
382	pmp->pm_inusemap[cn / N_INUSEBITS]
383			 |= 1 << (cn % N_INUSEBITS);
384	pmp->pm_freeclustercount--;
385}
386
387static inline void
388usemap_free(pmp, cn)
389	struct msdosfsmount *pmp;
390	u_long cn;
391{
392	pmp->pm_freeclustercount++;
393	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
394}
395
396int
397clusterfree(pmp, cluster, oldcnp)
398	struct msdosfsmount *pmp;
399	u_long cluster;
400	u_long *oldcnp;
401{
402	int error;
403	u_long oldcn;
404
405	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
406	if (error == 0) {
407		/*
408		 * If the cluster was successfully marked free, then update
409		 * the count of free clusters, and turn off the "allocated"
410		 * bit in the "in use" cluster bit map.
411		 */
412		usemap_free(pmp, cluster);
413		if (oldcnp)
414			*oldcnp = oldcn;
415	}
416	return error;
417}
418
419/*
420 * Get or Set or 'Get and Set' the cluster'th entry in the fat.
421 *
422 * function	- whether to get or set a fat entry
423 * pmp		- address of the msdosfsmount structure for the filesystem
424 *		  whose fat is to be manipulated.
425 * cn		- which cluster is of interest
426 * oldcontents	- address of a word that is to receive the contents of the
427 *		  cluster'th entry if this is a get function
428 * newcontents	- the new value to be written into the cluster'th element of
429 *		  the fat if this is a set function.
430 *
431 * This function can also be used to free a cluster by setting the fat entry
432 * for a cluster to 0.
433 *
434 * All copies of the fat are updated if this is a set function. NOTE: If
435 * fatentry() marks a cluster as free it does not update the inusemap in
436 * the msdosfsmount structure. This is left to the caller.
437 */
438int
439fatentry(function, pmp, cn, oldcontents, newcontents)
440	int function;
441	struct msdosfsmount *pmp;
442	u_long cn;
443	u_long *oldcontents;
444	u_long newcontents;
445{
446	int error;
447	u_long readcn;
448	u_long bn, bo, bsize, byteoffset;
449	struct buf *bp;
450
451	/*
452	 * printf("fatentry(func %d, pmp %08x, clust %d, oldcon %08x, newcon %d)\n",
453	 *	  function, pmp, cluster, oldcontents, newcontents);
454	 */
455
456#ifdef DIAGNOSTIC
457	/*
458	 * Be sure they asked us to do something.
459	 */
460	if ((function & (FAT_SET | FAT_GET)) == 0) {
461		printf("fatentry(): function code doesn't specify get or set\n");
462		return EINVAL;
463	}
464
465	/*
466	 * If they asked us to return a cluster number but didn't tell us
467	 * where to put it, give them an error.
468	 */
469	if ((function & FAT_GET) && oldcontents == NULL) {
470		printf("fatentry(): get function with no place to put result\n");
471		return EINVAL;
472	}
473#endif
474
475	/*
476	 * Be sure the requested cluster is in the filesystem.
477	 */
478	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
479		return EINVAL;
480
481	byteoffset = FATOFS(pmp, cn);
482	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
483	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
484	if (error)
485		return error;
486
487	if (function & FAT_GET) {
488		readcn = getushort(&bp->b_data[bo]);
489		if (FAT12(pmp)) {
490			if (cn & 1)
491				readcn >>= 4;
492			readcn &= 0x0fff;
493			/* map certain 12 bit fat entries to 16 bit */
494			if ((readcn & 0x0ff0) == 0x0ff0)
495				readcn |= 0xf000;
496		}
497		*oldcontents = readcn;
498	}
499	if (function & FAT_SET) {
500		if (FAT12(pmp)) {
501			readcn = getushort(&bp->b_data[bo]);
502			if (cn & 1) {
503				readcn &= 0x000f;
504				readcn |= newcontents << 4;
505			} else {
506				readcn &= 0xf000;
507				readcn |= newcontents & 0xfff;
508			}
509			putushort(&bp->b_data[bo], readcn);
510		} else
511			putushort(&bp->b_data[bo], newcontents);
512		updatefats(pmp, bp, bn);
513		bp = NULL;
514		pmp->pm_fmod = 1;
515	}
516	if (bp)
517		brelse(bp);
518	return 0;
519}
520
521/*
522 * Update a contiguous cluster chain
523 *
524 * pmp	    - mount point
525 * start    - first cluster of chain
526 * count    - number of clusters in chain
527 * fillwith - what to write into fat entry of last cluster
528 */
529static int
530fatchain(pmp, start, count, fillwith)
531	struct msdosfsmount *pmp;
532	u_long start;
533	u_long count;
534	u_long fillwith;
535{
536	int error;
537	u_long bn, bo, bsize, byteoffset, readcn, newc;
538	struct buf *bp;
539
540#ifdef MSDOSFS_DEBUG
541	printf("fatchain(pmp %p, start %ld, count %ld, fillwith %ld)\n",
542	       pmp, start, count, fillwith);
543#endif
544	/*
545	 * Be sure the clusters are in the filesystem.
546	 */
547	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
548		return EINVAL;
549
550	while (count > 0) {
551		byteoffset = FATOFS(pmp, start);
552		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
553		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
554		if (error)
555			return error;
556		while (count > 0) {
557			start++;
558			newc = --count > 0 ? start : fillwith;
559			if (FAT12(pmp)) {
560				readcn = getushort(&bp->b_data[bo]);
561				if (start & 1) {
562					readcn &= 0xf000;
563					readcn |= newc & 0xfff;
564				} else {
565					readcn &= 0x000f;
566					readcn |= newc << 4;
567				}
568				putushort(&bp->b_data[bo], readcn);
569				bo++;
570				if (!(start & 1))
571					bo++;
572			} else {
573				putushort(&bp->b_data[bo], newc);
574				bo += 2;
575			}
576			if (bo >= bsize)
577				break;
578		}
579		updatefats(pmp, bp, bn);
580	}
581	pmp->pm_fmod = 1;
582	return 0;
583}
584
585/*
586 * Check the length of a free cluster chain starting at start.
587 *
588 * pmp	 - mount point
589 * start - start of chain
590 * count - maximum interesting length
591 */
592static int
593chainlength(pmp, start, count)
594	struct msdosfsmount *pmp;
595	u_long start;
596	u_long count;
597{
598	u_long idx, max_idx;
599	u_int map;
600	u_long len;
601
602	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
603	idx = start / N_INUSEBITS;
604	start %= N_INUSEBITS;
605	map = pmp->pm_inusemap[idx];
606	map &= ~((1 << start) - 1);
607	if (map) {
608		len = ffs(map) - 1 - start;
609		return len > count ? count : len;
610	}
611	len = N_INUSEBITS - start;
612	if (len >= count)
613		return count;
614	while (++idx <= max_idx) {
615		if (len >= count)
616			break;
617		map = pmp->pm_inusemap[idx];
618		if (map) {
619			len +=  ffs(map) - 1;
620			break;
621		}
622		len += N_INUSEBITS;
623	}
624	return len > count ? count : len;
625}
626
627/*
628 * Allocate contigous free clusters.
629 *
630 * pmp	      - mount point.
631 * start      - start of cluster chain.
632 * count      - number of clusters to allocate.
633 * fillwith   - put this value into the fat entry for the
634 *		last allocated cluster.
635 * retcluster - put the first allocated cluster's number here.
636 * got	      - how many clusters were actually allocated.
637 */
638static int
639chainalloc(pmp, start, count, fillwith, retcluster, got)
640	struct msdosfsmount *pmp;
641	u_long start;
642	u_long count;
643	u_long fillwith;
644	u_long *retcluster;
645	u_long *got;
646{
647	int error;
648
649	error = fatchain(pmp, start, count, fillwith);
650	if (error == 0) {
651#ifdef MSDOSFS_DEBUG
652		printf("clusteralloc(): allocated cluster chain at %ld (%ld clusters)\n",
653		       start, count);
654#endif
655		if (retcluster)
656			*retcluster = start;
657		if (got)
658			*got = count;
659		while (count-- > 0)
660			usemap_alloc(pmp, start++);
661	}
662	return error;
663}
664
665/*
666 * Allocate contiguous free clusters.
667 *
668 * pmp	      - mount point.
669 * start      - preferred start of cluster chain.
670 * count      - number of clusters requested.
671 * fillwith   - put this value into the fat entry for the
672 *		last allocated cluster.
673 * retcluster - put the first allocated cluster's number here.
674 * got	      - how many clusters were actually allocated.
675 */
676int
677clusteralloc(pmp, start, count, fillwith, retcluster, got)
678	struct msdosfsmount *pmp;
679	u_long start;
680	u_long count;
681	u_long fillwith;
682	u_long *retcluster;
683	u_long *got;
684{
685	u_long idx;
686	u_long len, newst, foundcn, foundl, cn, l;
687	u_int map;
688
689#ifdef MSDOSFS_DEBUG
690	printf("clusteralloc(): find %d clusters\n",count);
691#endif
692	if (start) {
693		if ((len = chainlength(pmp, start, count)) >= count)
694			return chainalloc(pmp, start, count, fillwith, retcluster, got);
695	} else {
696		/*
697		 * This is a new file, initialize start
698		 */
699		struct timeval tv;
700
701		microtime(&tv);
702		start = (tv.tv_usec >> 10)|tv.tv_usec;
703		len = 0;
704	}
705
706	/*
707	 * Start at a (pseudo) random place to maximize cluster runs
708	 * under multiple writers.
709	 */
710	foundcn = newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1);
711	foundl = 0;
712
713	for (cn = newst; cn <= pmp->pm_maxcluster;) {
714		idx = cn / N_INUSEBITS;
715		map = pmp->pm_inusemap[idx];
716		map |= (1 << (cn % N_INUSEBITS)) - 1;
717		if (map != (u_int)-1) {
718			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
719			if ((l = chainlength(pmp, cn, count)) >= count)
720				return chainalloc(pmp, cn, count, fillwith, retcluster, got);
721			if (l > foundl) {
722				foundcn = cn;
723				foundl = l;
724			}
725			cn += l + 1;
726			continue;
727		}
728		cn += N_INUSEBITS - cn % N_INUSEBITS;
729	}
730	for (cn = 0; cn < newst;) {
731		idx = cn / N_INUSEBITS;
732		map = pmp->pm_inusemap[idx];
733		map |= (1 << (cn % N_INUSEBITS)) - 1;
734		if (map != (u_int)-1) {
735			cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
736			if ((l = chainlength(pmp, cn, count)) >= count)
737				return chainalloc(pmp, cn, count, fillwith, retcluster, got);
738			if (l > foundl) {
739				foundcn = cn;
740				foundl = l;
741			}
742			cn += l + 1;
743			continue;
744		}
745		cn += N_INUSEBITS - cn % N_INUSEBITS;
746	}
747
748	if (!foundl)
749		return ENOSPC;
750
751	if (len)
752		return chainalloc(pmp, start, len, fillwith, retcluster, got);
753	else
754		return chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got);
755}
756
757
758/*
759 * Free a chain of clusters.
760 *
761 * pmp		- address of the msdosfs mount structure for the filesystem
762 *		  containing the cluster chain to be freed.
763 * startcluster - number of the 1st cluster in the chain of clusters to be
764 *		  freed.
765 */
766int
767freeclusterchain(pmp, cluster)
768	struct msdosfsmount *pmp;
769	u_long cluster;
770{
771	int error = 0;
772	struct buf *bp = NULL;
773	u_long bn, bo, bsize, byteoffset;
774	u_long readcn, lbn = -1;
775
776	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
777		byteoffset = FATOFS(pmp, cluster);
778		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
779		if (lbn != bn) {
780			if (bp)
781				updatefats(pmp, bp, lbn);
782			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
783			if (error)
784				return error;
785			lbn = bn;
786		}
787		usemap_free(pmp, cluster);
788		readcn = getushort(&bp->b_data[bo]);
789		if (FAT12(pmp)) {
790			if (cluster & 1) {
791				cluster = readcn >> 4;
792				readcn &= 0x000f;
793				readcn |= MSDOSFSFREE << 4;
794			} else {
795				cluster = readcn;
796				readcn &= 0xf000;
797				readcn |= MSDOSFSFREE & 0xfff;
798			}
799			putushort(&bp->b_data[bo], readcn);
800			cluster &= 0x0fff;
801			if ((cluster&0x0ff0) == 0x0ff0)
802				cluster |= 0xf000;
803		} else {
804			cluster = readcn;
805			putushort(&bp->b_data[bo], MSDOSFSFREE);
806		}
807	}
808	if (bp)
809		updatefats(pmp, bp, bn);
810	return error;
811}
812
813/*
814 * Read in fat blocks looking for free clusters. For every free cluster
815 * found turn off its corresponding bit in the pm_inusemap.
816 */
817int
818fillinusemap(pmp)
819	struct msdosfsmount *pmp;
820{
821	struct buf *bp = NULL;
822	u_long cn, readcn;
823	int error;
824	int fat12 = FAT12(pmp);
825	u_long bn, bo, bsize, byteoffset;
826
827	/*
828	 * Mark all clusters in use, we mark the free ones in the fat scan
829	 * loop further down.
830	 */
831	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
832		pmp->pm_inusemap[cn] = (u_int)-1;
833
834	/*
835	 * Figure how many free clusters are in the filesystem by ripping
836	 * through the fat counting the number of entries whose content is
837	 * zero.  These represent free clusters.
838	 */
839	pmp->pm_freeclustercount = 0;
840	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
841		byteoffset = FATOFS(pmp, cn);
842		bo = byteoffset % pmp->pm_fatblocksize;
843		if (!bo || !bp) {
844			/* Read new FAT block */
845			if (bp)
846				brelse(bp);
847			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
848			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
849			if (error)
850				return error;
851		}
852		readcn = getushort(&bp->b_data[bo]);
853		if (fat12) {
854			if (cn & 1)
855				readcn >>= 4;
856			readcn &= 0x0fff;
857		}
858
859		if (readcn == 0)
860			usemap_free(pmp, cn);
861	}
862	brelse(bp);
863	return 0;
864}
865
866/*
867 * Allocate a new cluster and chain it onto the end of the file.
868 *
869 * dep	 - the file to extend
870 * count - number of clusters to allocate
871 * bpp	 - where to return the address of the buf header for the first new
872 *	   file block
873 * ncp	 - where to put cluster number of the first newly allocated cluster
874 *	   If this pointer is 0, do not return the cluster number.
875 * flags - see fat.h
876 *
877 * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
878 * the de_flag field of the denode and it does not change the de_FileSize
879 * field.  This is left for the caller to do.
880 */
881int
882extendfile(dep, count, bpp, ncp, flags)
883	struct denode *dep;
884	u_long count;
885	struct buf **bpp;
886	u_long *ncp;
887	int flags;
888{
889	int error = 0;
890	u_long frcn;
891	u_long cn, got;
892	struct msdosfsmount *pmp = dep->de_pmp;
893	struct buf *bp;
894
895	/*
896	 * Don't try to extend the root directory
897	 */
898	if (DETOV(dep)->v_flag & VROOT) {
899		printf("extendfile(): attempt to extend root directory\n");
900		return ENOSPC;
901	}
902
903	/*
904	 * If the "file's last cluster" cache entry is empty, and the file
905	 * is not empty, then fill the cache entry by calling pcbmap().
906	 */
907	fc_fileextends++;
908	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
909	    dep->de_StartCluster != 0) {
910		fc_lfcempty++;
911		error = pcbmap(dep, 0xffff, 0, &cn);
912		/* we expect it to return E2BIG */
913		if (error != E2BIG)
914			return error;
915		error = 0;
916	}
917
918	while (count > 0) {
919		/*
920		 * Allocate a new cluster chain and cat onto the end of the file.
921		 * If the file is empty we make de_StartCluster point to the new
922		 * block.  Note that de_StartCluster being 0 is sufficient to be
923		 * sure the file is empty since we exclude attempts to extend the
924		 * root directory above, and the root dir is the only file with a
925		 * startcluster of 0 that has blocks allocated (sort of).
926		 */
927		if (dep->de_StartCluster == 0)
928			cn = 0;
929		else
930			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
931		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
932		if (error)
933			return error;
934
935		count -= got;
936
937		/*
938		 * Give them the filesystem relative cluster number if they want
939		 * it.
940		 */
941		if (ncp) {
942			*ncp = cn;
943			ncp = NULL;
944		}
945
946		if (dep->de_StartCluster == 0) {
947			dep->de_StartCluster = cn;
948			frcn = 0;
949		} else {
950			error = fatentry(FAT_SET, pmp, dep->de_fc[FC_LASTFC].fc_fsrcn,
951					 0, cn);
952			if (error) {
953				clusterfree(pmp, cn, NULL);
954				return error;
955			}
956
957			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
958		}
959
960		/*
961		 * Update the "last cluster of the file" entry in the denode's fat
962		 * cache.
963		 */
964		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
965
966		if (flags & DE_CLEAR) {
967			while (got-- > 0) {
968				/*
969				 * Get the buf header for the new block of the file.
970				 */
971				if (dep->de_Attributes & ATTR_DIRECTORY)
972					bp = getblk(pmp->pm_devvp, cntobn(pmp, cn++),
973						    pmp->pm_bpcluster, 0, 0);
974				else {
975					bp = getblk(DETOV(dep), frcn++, pmp->pm_bpcluster, 0, 0);
976					/*
977					 * Do the bmap now, as in msdosfs_write
978					 */
979					if (pcbmap(dep, bp->b_lblkno, &bp->b_blkno, 0))
980						bp->b_blkno = -1;
981					if (bp->b_blkno == -1)
982						panic("extendfile: pcbmap");
983				}
984				clrbuf(bp);
985				if (bpp) {
986					*bpp = bp;
987					bpp = NULL;
988				} else {
989					bp->b_flags |= B_AGE;
990					bawrite(bp);
991				}
992			}
993		}
994	}
995
996	return 0;
997}
998