msdosfs_fat.c revision 338180
1/* $FreeBSD: stable/10/sys/fs/msdosfs/msdosfs_fat.c 338180 2018-08-22 04:21:25Z pfg $ */
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(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
405	    pmp->pm_maxcluster));
406	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
407	    ("usemap_alloc on ro msdosfs mount"));
408	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] & (1 << (cn % N_INUSEBITS)))
409	    == 0, ("Allocating used sector %ld %ld %x", cn, cn % N_INUSEBITS,
410		(unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
411	pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
412	KASSERT(pmp->pm_freeclustercount > 0, ("usemap_alloc: too little"));
413	pmp->pm_freeclustercount--;
414	pmp->pm_flags |= MSDOSFS_FSIMOD;
415}
416
417static __inline void
418usemap_free(pmp, cn)
419	struct msdosfsmount *pmp;
420	u_long cn;
421{
422
423	MSDOSFS_ASSERT_MP_LOCKED(pmp);
424
425	KASSERT(cn <= pmp->pm_maxcluster, ("cn too large %lu %lu", cn,
426	    pmp->pm_maxcluster));
427	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
428	    ("usemap_free on ro msdosfs mount"));
429	pmp->pm_freeclustercount++;
430	pmp->pm_flags |= MSDOSFS_FSIMOD;
431	KASSERT((pmp->pm_inusemap[cn / N_INUSEBITS] & (1 << (cn % N_INUSEBITS)))
432	    != 0, ("Freeing unused sector %ld %ld %x", cn, cn % N_INUSEBITS,
433		(unsigned)pmp->pm_inusemap[cn / N_INUSEBITS]));
434	pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1U << (cn % N_INUSEBITS));
435}
436
437int
438clusterfree(pmp, cluster, oldcnp)
439	struct msdosfsmount *pmp;
440	u_long cluster;
441	u_long *oldcnp;
442{
443	int error;
444	u_long oldcn;
445
446	error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
447	if (error)
448		return (error);
449	/*
450	 * If the cluster was successfully marked free, then update
451	 * the count of free clusters, and turn off the "allocated"
452	 * bit in the "in use" cluster bit map.
453	 */
454	MSDOSFS_LOCK_MP(pmp);
455	usemap_free(pmp, cluster);
456	MSDOSFS_UNLOCK_MP(pmp);
457	if (oldcnp)
458		*oldcnp = oldcn;
459	return (0);
460}
461
462/*
463 * Get or Set or 'Get and Set' the cluster'th entry in the fat.
464 *
465 * function	- whether to get or set a fat entry
466 * pmp		- address of the msdosfsmount structure for the filesystem
467 *		  whose fat is to be manipulated.
468 * cn		- which cluster is of interest
469 * oldcontents	- address of a word that is to receive the contents of the
470 *		  cluster'th entry if this is a get function
471 * newcontents	- the new value to be written into the cluster'th element of
472 *		  the fat if this is a set function.
473 *
474 * This function can also be used to free a cluster by setting the fat entry
475 * for a cluster to 0.
476 *
477 * All copies of the fat are updated if this is a set function. NOTE: If
478 * fatentry() marks a cluster as free it does not update the inusemap in
479 * the msdosfsmount structure. This is left to the caller.
480 */
481int
482fatentry(function, pmp, cn, oldcontents, newcontents)
483	int function;
484	struct msdosfsmount *pmp;
485	u_long cn;
486	u_long *oldcontents;
487	u_long newcontents;
488{
489	int error;
490	u_long readcn;
491	u_long bn, bo, bsize, byteoffset;
492	struct buf *bp;
493
494#ifdef	MSDOSFS_DEBUG
495	printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
496	    function, pmp, cn, oldcontents, newcontents);
497#endif
498
499#ifdef DIAGNOSTIC
500	/*
501	 * Be sure they asked us to do something.
502	 */
503	if ((function & (FAT_SET | FAT_GET)) == 0) {
504#ifdef MSDOSFS_DEBUG
505		printf("fatentry(): function code doesn't specify get or set\n");
506#endif
507		return (EINVAL);
508	}
509
510	/*
511	 * If they asked us to return a cluster number but didn't tell us
512	 * where to put it, give them an error.
513	 */
514	if ((function & FAT_GET) && oldcontents == NULL) {
515#ifdef MSDOSFS_DEBUG
516		printf("fatentry(): get function with no place to put result\n");
517#endif
518		return (EINVAL);
519	}
520#endif
521
522	/*
523	 * Be sure the requested cluster is in the filesystem.
524	 */
525	if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
526		return (EINVAL);
527
528	byteoffset = FATOFS(pmp, cn);
529	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
530	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
531	if (error) {
532		brelse(bp);
533		return (error);
534	}
535
536	if (function & FAT_GET) {
537		if (FAT32(pmp))
538			readcn = getulong(&bp->b_data[bo]);
539		else
540			readcn = getushort(&bp->b_data[bo]);
541		if (FAT12(pmp) & (cn & 1))
542			readcn >>= 4;
543		readcn &= pmp->pm_fatmask;
544		/* map reserved fat entries to same values for all fats */
545		if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
546			readcn |= ~pmp->pm_fatmask;
547		*oldcontents = readcn;
548	}
549	if (function & FAT_SET) {
550		switch (pmp->pm_fatmask) {
551		case FAT12_MASK:
552			readcn = getushort(&bp->b_data[bo]);
553			if (cn & 1) {
554				readcn &= 0x000f;
555				readcn |= newcontents << 4;
556			} else {
557				readcn &= 0xf000;
558				readcn |= newcontents & 0xfff;
559			}
560			putushort(&bp->b_data[bo], readcn);
561			break;
562		case FAT16_MASK:
563			putushort(&bp->b_data[bo], newcontents);
564			break;
565		case FAT32_MASK:
566			/*
567			 * According to spec we have to retain the
568			 * high order bits of the fat entry.
569			 */
570			readcn = getulong(&bp->b_data[bo]);
571			readcn &= ~FAT32_MASK;
572			readcn |= newcontents & FAT32_MASK;
573			putulong(&bp->b_data[bo], readcn);
574			break;
575		}
576		updatefats(pmp, bp, bn);
577		bp = NULL;
578		pmp->pm_fmod = 1;
579	}
580	if (bp)
581		brelse(bp);
582	return (0);
583}
584
585/*
586 * Update a contiguous cluster chain
587 *
588 * pmp	    - mount point
589 * start    - first cluster of chain
590 * count    - number of clusters in chain
591 * fillwith - what to write into fat entry of last cluster
592 */
593static int
594fatchain(pmp, start, count, fillwith)
595	struct msdosfsmount *pmp;
596	u_long start;
597	u_long count;
598	u_long fillwith;
599{
600	int error;
601	u_long bn, bo, bsize, byteoffset, readcn, newc;
602	struct buf *bp;
603
604#ifdef MSDOSFS_DEBUG
605	printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
606	    pmp, start, count, fillwith);
607#endif
608	/*
609	 * Be sure the clusters are in the filesystem.
610	 */
611	if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
612		return (EINVAL);
613
614	while (count > 0) {
615		byteoffset = FATOFS(pmp, start);
616		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
617		error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
618		if (error) {
619			brelse(bp);
620			return (error);
621		}
622		while (count > 0) {
623			start++;
624			newc = --count > 0 ? start : fillwith;
625			switch (pmp->pm_fatmask) {
626			case FAT12_MASK:
627				readcn = getushort(&bp->b_data[bo]);
628				if (start & 1) {
629					readcn &= 0xf000;
630					readcn |= newc & 0xfff;
631				} else {
632					readcn &= 0x000f;
633					readcn |= newc << 4;
634				}
635				putushort(&bp->b_data[bo], readcn);
636				bo++;
637				if (!(start & 1))
638					bo++;
639				break;
640			case FAT16_MASK:
641				putushort(&bp->b_data[bo], newc);
642				bo += 2;
643				break;
644			case FAT32_MASK:
645				readcn = getulong(&bp->b_data[bo]);
646				readcn &= ~pmp->pm_fatmask;
647				readcn |= newc & pmp->pm_fatmask;
648				putulong(&bp->b_data[bo], readcn);
649				bo += 4;
650				break;
651			}
652			if (bo >= bsize)
653				break;
654		}
655		updatefats(pmp, bp, bn);
656	}
657	pmp->pm_fmod = 1;
658	return (0);
659}
660
661/*
662 * Check the length of a free cluster chain starting at start.
663 *
664 * pmp	 - mount point
665 * start - start of chain
666 * count - maximum interesting length
667 */
668static int
669chainlength(pmp, start, count)
670	struct msdosfsmount *pmp;
671	u_long start;
672	u_long count;
673{
674	u_long idx, max_idx;
675	u_int map;
676	u_long len;
677
678	MSDOSFS_ASSERT_MP_LOCKED(pmp);
679
680	if (start > pmp->pm_maxcluster)
681		return (0);
682	max_idx = pmp->pm_maxcluster / N_INUSEBITS;
683	idx = start / N_INUSEBITS;
684	start %= N_INUSEBITS;
685	map = pmp->pm_inusemap[idx];
686	map &= ~((1 << start) - 1);
687	if (map) {
688		len = ffs(map) - 1 - start;
689		len = MIN(len, count);
690		if (start + len > pmp->pm_maxcluster)
691			len = pmp->pm_maxcluster - start + 1;
692		return (len);
693	}
694	len = N_INUSEBITS - start;
695	if (len >= count) {
696		len = count;
697		if (start + len > pmp->pm_maxcluster)
698			len = pmp->pm_maxcluster - start + 1;
699		return (len);
700	}
701	while (++idx <= max_idx) {
702		if (len >= count)
703			break;
704		map = pmp->pm_inusemap[idx];
705		if (map) {
706			len += ffs(map) - 1;
707			break;
708		}
709		len += N_INUSEBITS;
710	}
711	len = MIN(len, count);
712	if (start + len > pmp->pm_maxcluster)
713		len = pmp->pm_maxcluster - start + 1;
714	return (len);
715}
716
717/*
718 * Allocate contigous free clusters.
719 *
720 * pmp	      - mount point.
721 * start      - start of cluster chain.
722 * count      - number of clusters to allocate.
723 * fillwith   - put this value into the fat entry for the
724 *		last allocated cluster.
725 * retcluster - put the first allocated cluster's number here.
726 * got	      - how many clusters were actually allocated.
727 */
728static int
729chainalloc(pmp, start, count, fillwith, retcluster, got)
730	struct msdosfsmount *pmp;
731	u_long start;
732	u_long count;
733	u_long fillwith;
734	u_long *retcluster;
735	u_long *got;
736{
737	int error;
738	u_long cl, n;
739
740	MSDOSFS_ASSERT_MP_LOCKED(pmp);
741	KASSERT((pmp->pm_flags & MSDOSFSMNT_RONLY) == 0,
742	    ("chainalloc on ro msdosfs mount"));
743
744	for (cl = start, n = count; n-- > 0;)
745		usemap_alloc(pmp, cl++);
746	pmp->pm_nxtfree = start + count;
747	if (pmp->pm_nxtfree > pmp->pm_maxcluster)
748		pmp->pm_nxtfree = CLUST_FIRST;
749	pmp->pm_flags |= MSDOSFS_FSIMOD;
750	error = fatchain(pmp, start, count, fillwith);
751	if (error != 0) {
752		for (cl = start, n = count; n-- > 0;)
753			usemap_free(pmp, cl++);
754		return (error);
755	}
756#ifdef MSDOSFS_DEBUG
757	printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
758	    start, count);
759#endif
760	if (retcluster)
761		*retcluster = start;
762	if (got)
763		*got = count;
764	return (0);
765}
766
767/*
768 * Allocate contiguous free clusters.
769 *
770 * pmp	      - mount point.
771 * start      - preferred start of cluster chain.
772 * count      - number of clusters requested.
773 * fillwith   - put this value into the fat entry for the
774 *		last allocated cluster.
775 * retcluster - put the first allocated cluster's number here.
776 * got	      - how many clusters were actually allocated.
777 */
778int
779clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
780    u_long fillwith, u_long *retcluster, u_long *got)
781{
782	int error;
783
784	MSDOSFS_LOCK_MP(pmp);
785	error = clusteralloc1(pmp, start, count, fillwith, retcluster, got);
786	MSDOSFS_UNLOCK_MP(pmp);
787	return (error);
788}
789
790static int
791clusteralloc1(struct msdosfsmount *pmp, u_long start, u_long count,
792    u_long fillwith, u_long *retcluster, u_long *got)
793{
794	u_long idx;
795	u_long len, newst, foundl, cn, l;
796	u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
797	u_int map;
798
799	MSDOSFS_ASSERT_MP_LOCKED(pmp);
800
801#ifdef MSDOSFS_DEBUG
802	printf("clusteralloc(): find %lu clusters\n", count);
803#endif
804	if (start) {
805		if ((len = chainlength(pmp, start, count)) >= count)
806			return (chainalloc(pmp, start, count, fillwith, retcluster, got));
807	} else
808		len = 0;
809
810	newst = pmp->pm_nxtfree;
811	foundl = 0;
812
813	for (cn = newst; cn <= pmp->pm_maxcluster;) {
814		idx = cn / N_INUSEBITS;
815		map = pmp->pm_inusemap[idx];
816		map |= (1U << (cn % N_INUSEBITS)) - 1;
817		if (map != FULL_RUN) {
818			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
819			if ((l = chainlength(pmp, cn, count)) >= count)
820				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
821			if (l > foundl) {
822				foundcn = cn;
823				foundl = l;
824			}
825			cn += l + 1;
826			continue;
827		}
828		cn += N_INUSEBITS - cn % N_INUSEBITS;
829	}
830	for (cn = 0; cn < newst;) {
831		idx = cn / N_INUSEBITS;
832		map = pmp->pm_inusemap[idx];
833		map |= (1U << (cn % N_INUSEBITS)) - 1;
834		if (map != FULL_RUN) {
835			cn = idx * N_INUSEBITS + ffs(map ^ FULL_RUN) - 1;
836			if ((l = chainlength(pmp, cn, count)) >= count)
837				return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
838			if (l > foundl) {
839				foundcn = cn;
840				foundl = l;
841			}
842			cn += l + 1;
843			continue;
844		}
845		cn += N_INUSEBITS - cn % N_INUSEBITS;
846	}
847
848	if (!foundl)
849		return (ENOSPC);
850
851	if (len)
852		return (chainalloc(pmp, start, len, fillwith, retcluster, got));
853	else
854		return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
855}
856
857
858/*
859 * Free a chain of clusters.
860 *
861 * pmp		- address of the msdosfs mount structure for the filesystem
862 *		  containing the cluster chain to be freed.
863 * startcluster - number of the 1st cluster in the chain of clusters to be
864 *		  freed.
865 */
866int
867freeclusterchain(pmp, cluster)
868	struct msdosfsmount *pmp;
869	u_long cluster;
870{
871	int error;
872	struct buf *bp = NULL;
873	u_long bn, bo, bsize, byteoffset;
874	u_long readcn, lbn = -1;
875
876	MSDOSFS_LOCK_MP(pmp);
877	while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
878		byteoffset = FATOFS(pmp, cluster);
879		fatblock(pmp, byteoffset, &bn, &bsize, &bo);
880		if (lbn != bn) {
881			if (bp)
882				updatefats(pmp, bp, lbn);
883			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
884			if (error) {
885				brelse(bp);
886				MSDOSFS_UNLOCK_MP(pmp);
887				return (error);
888			}
889			lbn = bn;
890		}
891		usemap_free(pmp, cluster);
892		switch (pmp->pm_fatmask) {
893		case FAT12_MASK:
894			readcn = getushort(&bp->b_data[bo]);
895			if (cluster & 1) {
896				cluster = readcn >> 4;
897				readcn &= 0x000f;
898				readcn |= MSDOSFSFREE << 4;
899			} else {
900				cluster = readcn;
901				readcn &= 0xf000;
902				readcn |= MSDOSFSFREE & 0xfff;
903			}
904			putushort(&bp->b_data[bo], readcn);
905			break;
906		case FAT16_MASK:
907			cluster = getushort(&bp->b_data[bo]);
908			putushort(&bp->b_data[bo], MSDOSFSFREE);
909			break;
910		case FAT32_MASK:
911			cluster = getulong(&bp->b_data[bo]);
912			putulong(&bp->b_data[bo],
913				 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
914			break;
915		}
916		cluster &= pmp->pm_fatmask;
917		if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
918			cluster |= pmp->pm_fatmask;
919	}
920	if (bp)
921		updatefats(pmp, bp, bn);
922	MSDOSFS_UNLOCK_MP(pmp);
923	return (0);
924}
925
926/*
927 * Read in fat blocks looking for free clusters. For every free cluster
928 * found turn off its corresponding bit in the pm_inusemap.
929 */
930int
931fillinusemap(pmp)
932	struct msdosfsmount *pmp;
933{
934	struct buf *bp = NULL;
935	u_long cn, readcn;
936	int error;
937	u_long bn, bo, bsize, byteoffset;
938
939	MSDOSFS_ASSERT_MP_LOCKED(pmp);
940
941	/*
942	 * Mark all clusters in use, we mark the free ones in the fat scan
943	 * loop further down.
944	 */
945	for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
946		pmp->pm_inusemap[cn] = FULL_RUN;
947
948	/*
949	 * Figure how many free clusters are in the filesystem by ripping
950	 * through the fat counting the number of entries whose content is
951	 * zero.  These represent free clusters.
952	 */
953	pmp->pm_freeclustercount = 0;
954	for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
955		byteoffset = FATOFS(pmp, cn);
956		bo = byteoffset % pmp->pm_fatblocksize;
957		if (!bo || !bp) {
958			/* Read new FAT block */
959			if (bp)
960				brelse(bp);
961			fatblock(pmp, byteoffset, &bn, &bsize, NULL);
962			error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
963			if (error) {
964				brelse(bp);
965				return (error);
966			}
967		}
968		if (FAT32(pmp))
969			readcn = getulong(&bp->b_data[bo]);
970		else
971			readcn = getushort(&bp->b_data[bo]);
972		if (FAT12(pmp) && (cn & 1))
973			readcn >>= 4;
974		readcn &= pmp->pm_fatmask;
975
976		if (readcn == CLUST_FREE)
977			usemap_free(pmp, cn);
978	}
979	if (bp != NULL)
980		brelse(bp);
981
982	for (cn = pmp->pm_maxcluster + 1; cn < (pmp->pm_maxcluster +
983	    N_INUSEBITS) / N_INUSEBITS; cn++)
984		pmp->pm_inusemap[cn / N_INUSEBITS] |= 1U << (cn % N_INUSEBITS);
985
986	return (0);
987}
988
989/*
990 * Allocate a new cluster and chain it onto the end of the file.
991 *
992 * dep	 - the file to extend
993 * count - number of clusters to allocate
994 * bpp	 - where to return the address of the buf header for the first new
995 *	   file block
996 * ncp	 - where to put cluster number of the first newly allocated cluster
997 *	   If this pointer is 0, do not return the cluster number.
998 * flags - see fat.h
999 *
1000 * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
1001 * the de_flag field of the denode and it does not change the de_FileSize
1002 * field.  This is left for the caller to do.
1003 */
1004int
1005extendfile(dep, count, bpp, ncp, flags)
1006	struct denode *dep;
1007	u_long count;
1008	struct buf **bpp;
1009	u_long *ncp;
1010	int flags;
1011{
1012	int error;
1013	u_long frcn;
1014	u_long cn, got;
1015	struct msdosfsmount *pmp = dep->de_pmp;
1016	struct buf *bp;
1017	daddr_t blkno;
1018
1019	/*
1020	 * Don't try to extend the root directory
1021	 */
1022	if (dep->de_StartCluster == MSDOSFSROOT
1023	    && (dep->de_Attributes & ATTR_DIRECTORY)) {
1024#ifdef MSDOSFS_DEBUG
1025		printf("extendfile(): attempt to extend root directory\n");
1026#endif
1027		return (ENOSPC);
1028	}
1029
1030	/*
1031	 * If the "file's last cluster" cache entry is empty, and the file
1032	 * is not empty, then fill the cache entry by calling pcbmap().
1033	 */
1034	if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
1035	    dep->de_StartCluster != 0) {
1036		error = pcbmap(dep, 0xffff, 0, &cn, 0);
1037		/* we expect it to return E2BIG */
1038		if (error != E2BIG)
1039			return (error);
1040	}
1041
1042	dep->de_fc[FC_NEXTTOLASTFC].fc_frcn =
1043	    dep->de_fc[FC_LASTFC].fc_frcn;
1044	dep->de_fc[FC_NEXTTOLASTFC].fc_fsrcn =
1045	    dep->de_fc[FC_LASTFC].fc_fsrcn;
1046	while (count > 0) {
1047		/*
1048		 * Allocate a new cluster chain and cat onto the end of the
1049		 * file.
1050		 * If the file is empty we make de_StartCluster point
1051		 * to the new block.  Note that de_StartCluster being
1052		 * 0 is sufficient to be sure the file is empty since
1053		 * we exclude attempts to extend the root directory
1054		 * above, and the root dir is the only file with a
1055		 * startcluster of 0 that has blocks allocated (sort
1056		 * of).
1057		 */
1058		if (dep->de_StartCluster == 0)
1059			cn = 0;
1060		else
1061			cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1062		error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1063		if (error)
1064			return (error);
1065
1066		count -= got;
1067
1068		/*
1069		 * Give them the filesystem relative cluster number if they want
1070		 * it.
1071		 */
1072		if (ncp) {
1073			*ncp = cn;
1074			ncp = NULL;
1075		}
1076
1077		if (dep->de_StartCluster == 0) {
1078			dep->de_StartCluster = cn;
1079			frcn = 0;
1080		} else {
1081			error = fatentry(FAT_SET, pmp,
1082					 dep->de_fc[FC_LASTFC].fc_fsrcn,
1083					 0, cn);
1084			if (error) {
1085				clusterfree(pmp, cn, NULL);
1086				return (error);
1087			}
1088			frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1089		}
1090
1091		/*
1092		 * Update the "last cluster of the file" entry in the denode's fat
1093		 * cache.
1094		 */
1095		fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1096
1097		if (flags & DE_CLEAR) {
1098			while (got-- > 0) {
1099				/*
1100				 * Get the buf header for the new block of the file.
1101				 */
1102				if (dep->de_Attributes & ATTR_DIRECTORY)
1103					bp = getblk(pmp->pm_devvp,
1104					    cntobn(pmp, cn++),
1105					    pmp->pm_bpcluster, 0, 0, 0);
1106				else {
1107					bp = getblk(DETOV(dep),
1108					    frcn++,
1109					    pmp->pm_bpcluster, 0, 0, 0);
1110					/*
1111					 * Do the bmap now, as in msdosfs_write
1112					 */
1113					if (pcbmap(dep,
1114					    bp->b_lblkno,
1115					    &blkno, 0, 0))
1116						bp->b_blkno = -1;
1117					if (bp->b_blkno == -1)
1118						panic("extendfile: pcbmap");
1119					else
1120						bp->b_blkno = blkno;
1121				}
1122				vfs_bio_clrbuf(bp);
1123				if (bpp) {
1124					*bpp = bp;
1125					bpp = NULL;
1126				} else
1127					bdwrite(bp);
1128			}
1129		}
1130	}
1131
1132	return (0);
1133}
1134
1135/*-
1136 * Routine to mark a FAT16 or FAT32 volume as "clean" or "dirty" by
1137 * manipulating the upper bit of the FAT entry for cluster 1.  Note that
1138 * this bit is not defined for FAT12 volumes, which are always assumed to
1139 * be clean.
1140 *
1141 * The fatentry() routine only works on cluster numbers that a file could
1142 * occupy, so it won't manipulate the entry for cluster 1.  So we have to do
1143 * it here.  The code was stolen from fatentry() and tailored for cluster 1.
1144 *
1145 * Inputs:
1146 *	pmp	The MS-DOS volume to mark
1147 *	dirty	Non-zero if the volume should be marked dirty; zero if it
1148 *		should be marked clean
1149 *
1150 * Result:
1151 *	0	Success
1152 *	EROFS	Volume is read-only
1153 *	?	(other errors from called routines)
1154 */
1155int
1156markvoldirty(struct msdosfsmount *pmp, int dirty)
1157{
1158	struct buf *bp;
1159	u_long bn, bo, bsize, byteoffset, fatval;
1160	int error;
1161
1162	/*
1163	 * FAT12 does not support a "clean" bit, so don't do anything for
1164	 * FAT12.
1165	 */
1166	if (FAT12(pmp))
1167		return (0);
1168
1169	/* Can't change the bit on a read-only filesystem. */
1170	if (pmp->pm_flags & MSDOSFSMNT_RONLY)
1171		return (EROFS);
1172
1173	/*
1174	 * Fetch the block containing the FAT entry.  It is given by the
1175	 * pseudo-cluster 1.
1176	 */
1177	byteoffset = FATOFS(pmp, 1);
1178	fatblock(pmp, byteoffset, &bn, &bsize, &bo);
1179	error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
1180	if (error) {
1181		brelse(bp);
1182		return (error);
1183	}
1184
1185	/*
1186	 * Get the current value of the FAT entry and set/clear the relevant
1187	 * bit.  Dirty means clear the "clean" bit; clean means set the
1188	 * "clean" bit.
1189	 */
1190	if (FAT32(pmp)) {
1191		/* FAT32 uses bit 27. */
1192		fatval = getulong(&bp->b_data[bo]);
1193		if (dirty)
1194			fatval &= 0xF7FFFFFF;
1195		else
1196			fatval |= 0x08000000;
1197		putulong(&bp->b_data[bo], fatval);
1198	} else {
1199		/* Must be FAT16; use bit 15. */
1200		fatval = getushort(&bp->b_data[bo]);
1201		if (dirty)
1202			fatval &= 0x7FFF;
1203		else
1204			fatval |= 0x8000;
1205		putushort(&bp->b_data[bo], fatval);
1206	}
1207
1208	/* Write out the modified FAT block synchronously. */
1209	return (bwrite(bp));
1210}
1211