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