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