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