msdosfs_fat.c revision 1.19.12.3 1 /* $NetBSD: msdosfs_fat.c,v 1.19.12.3 2013/01/23 00:06:19 yamt Exp $ */
2
3 /*-
4 * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
5 * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
6 * All rights reserved.
7 * Original code by Paul Popelka (paulp (at) uts.amdahl.com) (see below).
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by TooLs GmbH.
20 * 4. The name of TooLs GmbH may not be used to endorse or promote products
21 * derived from this software without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
24 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26 * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
27 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
28 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
29 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
30 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
31 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 */
34 /*
35 * Written by Paul Popelka (paulp (at) uts.amdahl.com)
36 *
37 * You can do anything you want with this software, just don't say you wrote
38 * it, and don't remove this notice.
39 *
40 * This software is provided "as is".
41 *
42 * The author supplies this software to be publicly redistributed on the
43 * understanding that the author is not responsible for the correct
44 * functioning of this software in any circumstances and is not liable for
45 * any damages caused by this software.
46 *
47 * October 1992
48 */
49
50 #include <sys/cdefs.h>
51 __KERNEL_RCSID(0, "$NetBSD: msdosfs_fat.c,v 1.19.12.3 2013/01/23 00:06:19 yamt Exp $");
52
53 /*
54 * kernel include files.
55 */
56 #include <sys/param.h>
57 #include <sys/systm.h>
58 #include <sys/buf.h>
59 #include <sys/file.h>
60 #include <sys/namei.h>
61 #include <sys/mount.h> /* to define statvfs structure */
62 #include <sys/vnode.h> /* to define vattr structure */
63 #include <sys/errno.h>
64 #include <sys/dirent.h>
65 #include <sys/kauth.h>
66
67 /*
68 * msdosfs include files.
69 */
70 #include <fs/msdosfs/bpb.h>
71 #include <fs/msdosfs/msdosfsmount.h>
72 #include <fs/msdosfs/direntry.h>
73 #include <fs/msdosfs/denode.h>
74 #include <fs/msdosfs/fat.h>
75
76 /*
77 * Fat cache stats.
78 */
79 int fc_fileextends; /* # of file extends */
80 int fc_lfcempty; /* # of time last file cluster cache entry
81 * was empty */
82 int fc_bmapcalls; /* # of times pcbmap was called */
83
84 #define LMMAX 20
85 int fc_lmdistance[LMMAX]; /* counters for how far off the last
86 * cluster mapped entry was. */
87 int fc_largedistance; /* off by more than LMMAX */
88 int fc_wherefrom, fc_whereto, fc_lastclust;
89 int pm_fatblocksize;
90
91 #ifdef MSDOSFS_DEBUG
92 void print_fat_stats(void);
93
94 void
95 print_fat_stats(void)
96 {
97 int i;
98
99 printf("fc_fileextends=%d fc_lfcempty=%d fc_bmapcalls=%d "
100 "fc_largedistance=%d [%d->%d=%d] fc_lastclust=%d pm_fatblocksize=%d\n",
101 fc_fileextends, fc_lfcempty, fc_bmapcalls, fc_largedistance,
102 fc_wherefrom, fc_whereto, fc_whereto-fc_wherefrom,
103 fc_lastclust, pm_fatblocksize);
104
105 fc_fileextends = fc_lfcempty = fc_bmapcalls = 0;
106 fc_wherefrom = fc_whereto = fc_lastclust = 0;
107
108 for (i = 0; i < LMMAX; i++) {
109 printf("%d:%d ", i, fc_lmdistance[i]);
110 fc_lmdistance[i] = 0;
111 }
112
113 printf("\n");
114 }
115 #endif
116
117 static void fatblock(struct msdosfsmount *, u_long, u_long *, u_long *,
118 u_long *);
119 void updatefats(struct msdosfsmount *, struct buf *, u_long);
120 static inline void usemap_free(struct msdosfsmount *, u_long);
121 static inline void usemap_alloc(struct msdosfsmount *, u_long);
122 static int fatchain(struct msdosfsmount *, u_long, u_long, u_long);
123 int chainlength(struct msdosfsmount *, u_long, u_long);
124 int chainalloc(struct msdosfsmount *, u_long, u_long, u_long, u_long *,
125 u_long *);
126
127 static void
128 fatblock(struct msdosfsmount *pmp, u_long ofs, u_long *bnp, u_long *sizep, u_long *bop)
129 {
130 u_long bn, size;
131
132 bn = ofs / pmp->pm_fatblocksize * pmp->pm_fatblocksec;
133 size = min(pmp->pm_fatblocksec, pmp->pm_FATsecs - bn)
134 * pmp->pm_BytesPerSec;
135 bn += pmp->pm_fatblk + pmp->pm_curfat * pmp->pm_FATsecs;
136
137 if (bnp)
138 *bnp = bn;
139 if (sizep)
140 *sizep = size;
141 if (bop)
142 *bop = ofs % pmp->pm_fatblocksize;
143
144 pm_fatblocksize = pmp->pm_fatblocksize;
145 }
146
147 /*
148 * Map the logical cluster number of a file into a physical disk sector
149 * that is filesystem relative.
150 *
151 * dep - address of denode representing the file of interest
152 * findcn - file relative cluster whose filesystem relative cluster number
153 * and/or block number are/is to be found
154 * bnp - address of where to place the file system relative block number.
155 * If this pointer is null then don't return this quantity.
156 * cnp - address of where to place the file system relative cluster number.
157 * If this pointer is null then don't return this quantity.
158 *
159 * NOTE: Either bnp or cnp must be non-null.
160 * This function has one side effect. If the requested file relative cluster
161 * is beyond the end of file, then the actual number of clusters in the file
162 * is returned in *cnp. This is useful for determining how long a directory is.
163 * If cnp is null, nothing is returned.
164 */
165 int
166 pcbmap(struct denode *dep, u_long findcn, daddr_t *bnp, u_long *cnp, int *sp)
167 /* findcn: file relative cluster to get */
168 /* bnp: returned filesys rel sector number */
169 /* cnp: returned cluster number */
170 /* sp: returned block size */
171 {
172 int error;
173 u_long i;
174 u_long cn;
175 u_long prevcn = 0; /* XXX: prevcn could be used unititialized */
176 u_long byteoffset;
177 u_long bn;
178 u_long bo;
179 struct buf *bp = NULL;
180 u_long bp_bn = -1;
181 struct msdosfsmount *pmp = dep->de_pmp;
182 u_long bsize;
183
184 fc_bmapcalls++;
185
186 /*
187 * If they don't give us someplace to return a value then don't
188 * bother doing anything.
189 */
190 if (bnp == NULL && cnp == NULL && sp == NULL)
191 return (0);
192
193 cn = dep->de_StartCluster;
194 /*
195 * The "file" that makes up the root directory is contiguous,
196 * permanently allocated, of fixed size, and is not made up of
197 * clusters. If the cluster number is beyond the end of the root
198 * directory, then return the number of clusters in the file.
199 */
200 if (cn == MSDOSFSROOT) {
201 if (dep->de_Attributes & ATTR_DIRECTORY) {
202 if (de_cn2off(pmp, findcn) >= dep->de_FileSize) {
203 if (cnp)
204 *cnp = de_bn2cn(pmp, pmp->pm_rootdirsize);
205 return (E2BIG);
206 }
207 if (bnp)
208 *bnp = pmp->pm_rootdirblk + de_cn2bn(pmp, findcn);
209 if (cnp)
210 *cnp = MSDOSFSROOT;
211 if (sp)
212 *sp = min(pmp->pm_bpcluster,
213 dep->de_FileSize - de_cn2off(pmp, findcn));
214 return (0);
215 } else { /* just an empty file */
216 if (cnp)
217 *cnp = 0;
218 return (E2BIG);
219 }
220 }
221
222 /*
223 * All other files do I/O in cluster sized blocks
224 */
225 if (sp)
226 *sp = pmp->pm_bpcluster;
227
228 /*
229 * Rummage around in the FAT cache, maybe we can avoid tromping
230 * thru every FAT entry for the file. And, keep track of how far
231 * off the cache was from where we wanted to be.
232 */
233 i = 0;
234 fc_lookup(dep, findcn, &i, &cn);
235 if ((bn = findcn - i) >= LMMAX) {
236 fc_largedistance++;
237 fc_wherefrom = i;
238 fc_whereto = findcn;
239 fc_lastclust = dep->de_fc[FC_LASTFC].fc_frcn;
240 } else
241 fc_lmdistance[bn]++;
242
243 /*
244 * Handle all other files or directories the normal way.
245 */
246 for (; i < findcn; i++) {
247 /*
248 * Stop with all reserved clusters, not just with EOF.
249 */
250 if (cn >= (CLUST_RSRVD & pmp->pm_fatmask))
251 goto hiteof;
252 byteoffset = FATOFS(pmp, cn);
253 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
254 if (bn != bp_bn) {
255 if (bp)
256 brelse(bp, 0);
257 error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
258 NOCRED, 0, &bp);
259 if (error) {
260 return (error);
261 }
262 bp_bn = bn;
263 }
264 prevcn = cn;
265 if (bo >= bsize) {
266 if (bp)
267 brelse(bp, 0);
268 return (EIO);
269 }
270 KASSERT(bp != NULL);
271 if (FAT32(pmp))
272 cn = getulong((char *)bp->b_data + bo);
273 else
274 cn = getushort((char *)bp->b_data + bo);
275 if (FAT12(pmp) && (prevcn & 1))
276 cn >>= 4;
277 cn &= pmp->pm_fatmask;
278 }
279
280 if (!MSDOSFSEOF(cn, pmp->pm_fatmask)) {
281 if (bp)
282 brelse(bp, 0);
283 if (bnp)
284 *bnp = cntobn(pmp, cn);
285 if (cnp)
286 *cnp = cn;
287 fc_setcache(dep, FC_LASTMAP, i, cn);
288 return (0);
289 }
290
291 hiteof:;
292 if (cnp)
293 *cnp = i;
294 if (bp)
295 brelse(bp, 0);
296 /* update last file cluster entry in the FAT cache */
297 fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
298 return (E2BIG);
299 }
300
301 /*
302 * Find the closest entry in the FAT cache to the cluster we are looking
303 * for.
304 */
305 void
306 fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
307 {
308 int i;
309 u_long cn;
310 struct fatcache *closest = 0;
311
312 for (i = 0; i < FC_SIZE; i++) {
313 cn = dep->de_fc[i].fc_frcn;
314 if (cn != FCE_EMPTY && cn <= findcn) {
315 if (closest == 0 || cn > closest->fc_frcn)
316 closest = &dep->de_fc[i];
317 }
318 }
319 if (closest) {
320 *frcnp = closest->fc_frcn;
321 *fsrcnp = closest->fc_fsrcn;
322 }
323 }
324
325 /*
326 * Purge the FAT cache in denode dep of all entries relating to file
327 * relative cluster frcn and beyond.
328 */
329 void
330 fc_purge(struct denode *dep, u_int frcn)
331 {
332 int i;
333 struct fatcache *fcp;
334
335 fcp = dep->de_fc;
336 for (i = 0; i < FC_SIZE; i++, fcp++) {
337 if (fcp->fc_frcn >= frcn)
338 fcp->fc_frcn = FCE_EMPTY;
339 }
340 }
341
342 /*
343 * Update the FAT.
344 * If mirroring the FAT, update all copies, with the first copy as last.
345 * Else update only the current FAT (ignoring the others).
346 *
347 * pmp - msdosfsmount structure for filesystem to update
348 * bp - addr of modified FAT block
349 * fatbn - block number relative to begin of filesystem of the modified FAT block.
350 */
351 void
352 updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
353 {
354 int i;
355 struct buf *bpn;
356
357 #ifdef MSDOSFS_DEBUG
358 printf("updatefats(pmp %p, bp %p, fatbn %lu)\n",
359 pmp, bp, fatbn);
360 #endif
361
362 /*
363 * If we have an FSInfo block, update it.
364 */
365 if (pmp->pm_fsinfo) {
366 u_long cn = pmp->pm_nxtfree;
367
368 if (pmp->pm_freeclustercount
369 && (pmp->pm_inusemap[cn / N_INUSEBITS]
370 & (1 << (cn % N_INUSEBITS)))) {
371 /*
372 * The cluster indicated in FSInfo isn't free
373 * any longer. Got get a new free one.
374 */
375 for (cn = 0; cn < pmp->pm_maxcluster; cn++)
376 if (pmp->pm_inusemap[cn / N_INUSEBITS] != (u_int)-1)
377 break;
378 pmp->pm_nxtfree = cn
379 + ffs(pmp->pm_inusemap[cn / N_INUSEBITS]
380 ^ (u_int)-1) - 1;
381 }
382 /*
383 * XXX If the fsinfo block is stored on media with
384 * 2KB or larger sectors, is the fsinfo structure
385 * padded at the end or in the middle?
386 */
387 if (bread(pmp->pm_devvp, de_bn2kb(pmp, pmp->pm_fsinfo),
388 pmp->pm_BytesPerSec, NOCRED, B_MODIFY, &bpn) != 0) {
389 /*
390 * Ignore the error, but turn off FSInfo update for the future.
391 */
392 pmp->pm_fsinfo = 0;
393 } else {
394 struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
395
396 putulong(fp->fsinfree, pmp->pm_freeclustercount);
397 putulong(fp->fsinxtfree, pmp->pm_nxtfree);
398 if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
399 bwrite(bpn);
400 else
401 bdwrite(bpn);
402 }
403 }
404
405 if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
406 /*
407 * Now copy the block(s) of the modified FAT to the other copies of
408 * the FAT and write them out. This is faster than reading in the
409 * other FATs and then writing them back out. This could tie up
410 * the FAT for quite a while. Preventing others from accessing it.
411 * To prevent us from going after the FAT quite so much we use
412 * delayed writes, unless they specified "synchronous" when the
413 * filesystem was mounted. If synch is asked for then use
414 * bwrite()'s and really slow things down.
415 */
416 for (i = 1; i < pmp->pm_FATs; i++) {
417 fatbn += pmp->pm_FATsecs;
418 /* getblk() never fails */
419 bpn = getblk(pmp->pm_devvp, de_bn2kb(pmp, fatbn),
420 bp->b_bcount, 0, 0);
421 memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
422 if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
423 bwrite(bpn);
424 else
425 bdwrite(bpn);
426 }
427 }
428
429 /*
430 * Write out the first (or current) FAT last.
431 */
432 if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
433 bwrite(bp);
434 else
435 bdwrite(bp);
436 /*
437 * Maybe update fsinfo sector here?
438 */
439 }
440
441 /*
442 * Updating entries in 12 bit FATs is a pain in the butt.
443 *
444 * The following picture shows where nibbles go when moving from a 12 bit
445 * cluster number into the appropriate bytes in the FAT.
446 *
447 * byte m byte m+1 byte m+2
448 * +----+----+ +----+----+ +----+----+
449 * | 0 1 | | 2 3 | | 4 5 | FAT bytes
450 * +----+----+ +----+----+ +----+----+
451 *
452 * +----+----+----+ +----+----+----+
453 * | 3 0 1 | | 4 5 2 |
454 * +----+----+----+ +----+----+----+
455 * cluster n cluster n+1
456 *
457 * Where n is even. m = n + (n >> 2)
458 *
459 */
460 static inline void
461 usemap_alloc(struct msdosfsmount *pmp, u_long cn)
462 {
463
464 pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
465 pmp->pm_freeclustercount--;
466 }
467
468 static inline void
469 usemap_free(struct msdosfsmount *pmp, u_long cn)
470 {
471
472 pmp->pm_freeclustercount++;
473 pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
474 }
475
476 int
477 clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
478 {
479 int error;
480 u_long oldcn;
481
482 usemap_free(pmp, cluster);
483 error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
484 if (error) {
485 usemap_alloc(pmp, cluster);
486 return (error);
487 }
488 /*
489 * If the cluster was successfully marked free, then update
490 * the count of free clusters, and turn off the "allocated"
491 * bit in the "in use" cluster bit map.
492 */
493 if (oldcnp)
494 *oldcnp = oldcn;
495 return (0);
496 }
497
498 /*
499 * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
500 *
501 * function - whether to get or set a fat entry
502 * pmp - address of the msdosfsmount structure for the filesystem
503 * whose FAT is to be manipulated.
504 * cn - which cluster is of interest
505 * oldcontents - address of a word that is to receive the contents of the
506 * cluster'th entry if this is a get function
507 * newcontents - the new value to be written into the cluster'th element of
508 * the FAT if this is a set function.
509 *
510 * This function can also be used to free a cluster by setting the FAT entry
511 * for a cluster to 0.
512 *
513 * All copies of the FAT are updated if this is a set function. NOTE: If
514 * fatentry() marks a cluster as free it does not update the inusemap in
515 * the msdosfsmount structure. This is left to the caller.
516 */
517 int
518 fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents, u_long newcontents)
519 {
520 int error;
521 u_long readcn;
522 u_long bn, bo, bsize, byteoffset;
523 struct buf *bp;
524
525 #ifdef MSDOSFS_DEBUG
526 printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
527 function, pmp, cn, oldcontents, newcontents);
528 #endif
529
530 #ifdef DIAGNOSTIC
531 /*
532 * Be sure they asked us to do something.
533 */
534 if ((function & (FAT_SET | FAT_GET)) == 0) {
535 printf("fatentry(): function code doesn't specify get or set\n");
536 return (EINVAL);
537 }
538
539 /*
540 * If they asked us to return a cluster number but didn't tell us
541 * where to put it, give them an error.
542 */
543 if ((function & FAT_GET) && oldcontents == NULL) {
544 printf("fatentry(): get function with no place to put result\n");
545 return (EINVAL);
546 }
547 #endif
548
549 /*
550 * Be sure the requested cluster is in the filesystem.
551 */
552 if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
553 return (EINVAL);
554
555 byteoffset = FATOFS(pmp, cn);
556 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
557 if ((error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize, NOCRED,
558 0, &bp)) != 0) {
559 return (error);
560 }
561
562 if (function & FAT_GET) {
563 if (FAT32(pmp))
564 readcn = getulong((char *)bp->b_data + bo);
565 else
566 readcn = getushort((char *)bp->b_data + bo);
567 if (FAT12(pmp) & (cn & 1))
568 readcn >>= 4;
569 readcn &= pmp->pm_fatmask;
570 *oldcontents = readcn;
571 }
572 if (function & FAT_SET) {
573 switch (pmp->pm_fatmask) {
574 case FAT12_MASK:
575 readcn = getushort((char *)bp->b_data + bo);
576 if (cn & 1) {
577 readcn &= 0x000f;
578 readcn |= newcontents << 4;
579 } else {
580 readcn &= 0xf000;
581 readcn |= newcontents & 0xfff;
582 }
583 putushort((char *)bp->b_data + bo, readcn);
584 break;
585 case FAT16_MASK:
586 putushort((char *)bp->b_data + bo, newcontents);
587 break;
588 case FAT32_MASK:
589 /*
590 * According to spec we have to retain the
591 * high order bits of the FAT entry.
592 */
593 readcn = getulong((char *)bp->b_data + bo);
594 readcn &= ~FAT32_MASK;
595 readcn |= newcontents & FAT32_MASK;
596 putulong((char *)bp->b_data + bo, readcn);
597 break;
598 }
599 updatefats(pmp, bp, bn);
600 bp = NULL;
601 pmp->pm_fmod = 1;
602 }
603 if (bp)
604 brelse(bp, 0);
605 return (0);
606 }
607
608 /*
609 * Update a contiguous cluster chain
610 *
611 * pmp - mount point
612 * start - first cluster of chain
613 * count - number of clusters in chain
614 * fillwith - what to write into FAT entry of last cluster
615 */
616 static int
617 fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
618 {
619 int error;
620 u_long bn, bo, bsize, byteoffset, readcn, newc;
621 struct buf *bp;
622
623 #ifdef MSDOSFS_DEBUG
624 printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
625 pmp, start, count, fillwith);
626 #endif
627 /*
628 * Be sure the clusters are in the filesystem.
629 */
630 if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
631 return (EINVAL);
632
633 while (count > 0) {
634 byteoffset = FATOFS(pmp, start);
635 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
636 error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize, NOCRED,
637 B_MODIFY, &bp);
638 if (error) {
639 return (error);
640 }
641 while (count > 0) {
642 start++;
643 newc = --count > 0 ? start : fillwith;
644 switch (pmp->pm_fatmask) {
645 case FAT12_MASK:
646 readcn = getushort((char *)bp->b_data + bo);
647 if (start & 1) {
648 readcn &= 0xf000;
649 readcn |= newc & 0xfff;
650 } else {
651 readcn &= 0x000f;
652 readcn |= newc << 4;
653 }
654 putushort((char *)bp->b_data + bo, readcn);
655 bo++;
656 if (!(start & 1))
657 bo++;
658 break;
659 case FAT16_MASK:
660 putushort((char *)bp->b_data + bo, newc);
661 bo += 2;
662 break;
663 case FAT32_MASK:
664 readcn = getulong((char *)bp->b_data + bo);
665 readcn &= ~pmp->pm_fatmask;
666 readcn |= newc & pmp->pm_fatmask;
667 putulong((char *)bp->b_data + bo, readcn);
668 bo += 4;
669 break;
670 }
671 if (bo >= bsize)
672 break;
673 }
674 updatefats(pmp, bp, bn);
675 }
676 pmp->pm_fmod = 1;
677 return (0);
678 }
679
680 /*
681 * Check the length of a free cluster chain starting at start.
682 *
683 * pmp - mount point
684 * start - start of chain
685 * count - maximum interesting length
686 */
687 int
688 chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
689 {
690 u_long idx, max_idx;
691 u_int map;
692 u_long len;
693
694 max_idx = pmp->pm_maxcluster / N_INUSEBITS;
695 idx = start / N_INUSEBITS;
696 start %= N_INUSEBITS;
697 map = pmp->pm_inusemap[idx];
698 map &= ~((1 << start) - 1);
699 if (map) {
700 len = ffs(map) - 1 - start;
701 return (len > count ? count : len);
702 }
703 len = N_INUSEBITS - start;
704 if (len >= count)
705 return (count);
706 while (++idx <= max_idx) {
707 if (len >= count)
708 break;
709 if ((map = pmp->pm_inusemap[idx]) != 0) {
710 len += ffs(map) - 1;
711 break;
712 }
713 len += N_INUSEBITS;
714 }
715 return (len > count ? count : len);
716 }
717
718 /*
719 * Allocate contigous free clusters.
720 *
721 * pmp - mount point.
722 * start - start of cluster chain.
723 * count - number of clusters to allocate.
724 * fillwith - put this value into the FAT entry for the
725 * last allocated cluster.
726 * retcluster - put the first allocated cluster's number here.
727 * got - how many clusters were actually allocated.
728 */
729 int
730 chainalloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith, u_long *retcluster, u_long *got)
731 {
732 int error;
733 u_long cl, n;
734
735 for (cl = start, n = count; n-- > 0;)
736 usemap_alloc(pmp, cl++);
737 if ((error = fatchain(pmp, start, count, fillwith)) != 0)
738 return (error);
739 #ifdef MSDOSFS_DEBUG
740 printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
741 start, count);
742 #endif
743 if (retcluster)
744 *retcluster = start;
745 if (got)
746 *got = count;
747 return (0);
748 }
749
750 /*
751 * Allocate contiguous free clusters.
752 *
753 * pmp - mount point.
754 * start - preferred start of cluster chain.
755 * count - number of clusters requested.
756 * fillwith - put this value into the FAT entry for the
757 * last allocated cluster.
758 * retcluster - put the first allocated cluster's number here.
759 * got - how many clusters were actually allocated.
760 */
761 int
762 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long *retcluster, u_long *got)
763 {
764 u_long idx;
765 u_long len, newst, foundl, cn, l;
766 u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
767 u_long fillwith = CLUST_EOFE;
768 u_int map;
769
770 #ifdef MSDOSFS_DEBUG
771 printf("clusteralloc(): find %lu clusters\n",count);
772 #endif
773 if (start) {
774 if ((len = chainlength(pmp, start, count)) >= count)
775 return (chainalloc(pmp, start, count, fillwith, retcluster, got));
776 } else {
777 /*
778 * This is a new file, initialize start
779 */
780 struct timeval tv;
781
782 microtime(&tv);
783 start = (tv.tv_usec >> 10) | tv.tv_usec;
784 len = 0;
785 }
786
787 /*
788 * Start at a (pseudo) random place to maximize cluster runs
789 * under multiple writers.
790 */
791 newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1);
792 foundl = 0;
793
794 for (cn = newst; cn <= pmp->pm_maxcluster;) {
795 idx = cn / N_INUSEBITS;
796 map = pmp->pm_inusemap[idx];
797 map |= (1 << (cn % N_INUSEBITS)) - 1;
798 if (map != (u_int)-1) {
799 cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
800 if ((l = chainlength(pmp, cn, count)) >= count)
801 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
802 if (l > foundl) {
803 foundcn = cn;
804 foundl = l;
805 }
806 cn += l + 1;
807 continue;
808 }
809 cn += N_INUSEBITS - cn % N_INUSEBITS;
810 }
811 for (cn = 0; cn < newst;) {
812 idx = cn / N_INUSEBITS;
813 map = pmp->pm_inusemap[idx];
814 map |= (1 << (cn % N_INUSEBITS)) - 1;
815 if (map != (u_int)-1) {
816 cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
817 if ((l = chainlength(pmp, cn, count)) >= count)
818 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
819 if (l > foundl) {
820 foundcn = cn;
821 foundl = l;
822 }
823 cn += l + 1;
824 continue;
825 }
826 cn += N_INUSEBITS - cn % N_INUSEBITS;
827 }
828
829 if (!foundl)
830 return (ENOSPC);
831
832 if (len)
833 return (chainalloc(pmp, start, len, fillwith, retcluster, got));
834 else
835 return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
836 }
837
838
839 /*
840 * Free a chain of clusters.
841 *
842 * pmp - address of the msdosfs mount structure for the filesystem
843 * containing the cluster chain to be freed.
844 * startcluster - number of the 1st cluster in the chain of clusters to be
845 * freed.
846 */
847 int
848 freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
849 {
850 int error;
851 struct buf *bp = NULL;
852 u_long bn, bo, bsize, byteoffset;
853 u_long readcn, lbn = -1;
854
855 while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
856 byteoffset = FATOFS(pmp, cluster);
857 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
858 if (lbn != bn) {
859 if (bp)
860 updatefats(pmp, bp, lbn);
861 error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
862 NOCRED, B_MODIFY, &bp);
863 if (error) {
864 return (error);
865 }
866 lbn = bn;
867 }
868 usemap_free(pmp, cluster);
869 KASSERT(bp != NULL);
870 switch (pmp->pm_fatmask) {
871 case FAT12_MASK:
872 readcn = getushort((char *)bp->b_data + bo);
873 if (cluster & 1) {
874 cluster = readcn >> 4;
875 readcn &= 0x000f;
876 readcn |= MSDOSFSFREE << 4;
877 } else {
878 cluster = readcn;
879 readcn &= 0xf000;
880 readcn |= MSDOSFSFREE & 0xfff;
881 }
882 putushort((char *)bp->b_data + bo, readcn);
883 break;
884 case FAT16_MASK:
885 cluster = getushort((char *)bp->b_data + bo);
886 putushort((char *)bp->b_data + bo, MSDOSFSFREE);
887 break;
888 case FAT32_MASK:
889 cluster = getulong((char *)bp->b_data + bo);
890 putulong((char *)bp->b_data + bo,
891 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
892 break;
893 }
894 cluster &= pmp->pm_fatmask;
895 }
896 if (bp)
897 updatefats(pmp, bp, bn);
898 return (0);
899 }
900
901 /*
902 * Read in FAT blocks looking for free clusters. For every free cluster
903 * found turn off its corresponding bit in the pm_inusemap.
904 */
905 int
906 fillinusemap(struct msdosfsmount *pmp)
907 {
908 struct buf *bp = NULL;
909 u_long cn, readcn;
910 int error;
911 u_long bn, bo, bsize, byteoffset;
912
913 /*
914 * Mark all clusters in use, we mark the free ones in the FAT scan
915 * loop further down.
916 */
917 for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
918 pmp->pm_inusemap[cn] = (u_int)-1;
919
920 /*
921 * Figure how many free clusters are in the filesystem by ripping
922 * through the FAT counting the number of entries whose content is
923 * zero. These represent free clusters.
924 */
925 pmp->pm_freeclustercount = 0;
926 for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
927 byteoffset = FATOFS(pmp, cn);
928 bo = byteoffset % pmp->pm_fatblocksize;
929 if (!bo || !bp) {
930 /* Read new FAT block */
931 if (bp)
932 brelse(bp, 0);
933 fatblock(pmp, byteoffset, &bn, &bsize, NULL);
934 error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
935 NOCRED, 0, &bp);
936 if (error) {
937 return (error);
938 }
939 }
940 if (FAT32(pmp))
941 readcn = getulong((char *)bp->b_data + bo);
942 else
943 readcn = getushort((char *)bp->b_data + bo);
944 if (FAT12(pmp) && (cn & 1))
945 readcn >>= 4;
946 readcn &= pmp->pm_fatmask;
947
948 if (readcn == 0)
949 usemap_free(pmp, cn);
950 }
951 if (bp)
952 brelse(bp, 0);
953 return (0);
954 }
955
956 /*
957 * Allocate a new cluster and chain it onto the end of the file.
958 *
959 * dep - the file to extend
960 * count - number of clusters to allocate
961 * bpp - where to return the address of the buf header for the first new
962 * file block
963 * ncp - where to put cluster number of the first newly allocated cluster
964 * If this pointer is 0, do not return the cluster number.
965 * flags - see fat.h
966 *
967 * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
968 * the de_flag field of the denode and it does not change the de_FileSize
969 * field. This is left for the caller to do.
970 */
971
972 int
973 extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp, int flags)
974 {
975 int error;
976 u_long frcn = 0, cn, got;
977 struct msdosfsmount *pmp = dep->de_pmp;
978 struct buf *bp;
979
980 /*
981 * Don't try to extend the root directory
982 */
983 if (dep->de_StartCluster == MSDOSFSROOT
984 && (dep->de_Attributes & ATTR_DIRECTORY)) {
985 printf("extendfile(): attempt to extend root directory\n");
986 return (ENOSPC);
987 }
988
989 /*
990 * If the "file's last cluster" cache entry is empty, and the file
991 * is not empty, then fill the cache entry by calling pcbmap().
992 */
993 fc_fileextends++;
994 if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
995 dep->de_StartCluster != 0) {
996 fc_lfcempty++;
997 error = pcbmap(dep, CLUST_END, 0, &cn, 0);
998 /* we expect it to return E2BIG */
999 if (error != E2BIG)
1000 return (error);
1001 }
1002
1003 fc_last_to_nexttolast(dep);
1004
1005 while (count > 0) {
1006
1007 /*
1008 * Allocate a new cluster chain and cat onto the end of the
1009 * file. If the file is empty we make de_StartCluster point
1010 * to the new block. Note that de_StartCluster being 0 is
1011 * sufficient to be sure the file is empty since we exclude
1012 * attempts to extend the root directory above, and the root
1013 * dir is the only file with a startcluster of 0 that has
1014 * blocks allocated (sort of).
1015 */
1016
1017 if (dep->de_StartCluster == 0)
1018 cn = 0;
1019 else
1020 cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1021 error = clusteralloc(pmp, cn, count, &cn, &got);
1022 if (error)
1023 return (error);
1024
1025 count -= got;
1026
1027 /*
1028 * Give them the filesystem relative cluster number if they want
1029 * it.
1030 */
1031 if (ncp) {
1032 *ncp = cn;
1033 ncp = NULL;
1034 }
1035
1036 if (dep->de_StartCluster == 0) {
1037 dep->de_StartCluster = cn;
1038 frcn = 0;
1039 } else {
1040 error = fatentry(FAT_SET, pmp,
1041 dep->de_fc[FC_LASTFC].fc_fsrcn,
1042 0, cn);
1043 if (error) {
1044 clusterfree(pmp, cn, NULL);
1045 return (error);
1046 }
1047 frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1048 }
1049
1050 /*
1051 * Update the "last cluster of the file" entry in the
1052 * denode's FAT cache.
1053 */
1054
1055 fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1056 if ((flags & DE_CLEAR) &&
1057 (dep->de_Attributes & ATTR_DIRECTORY)) {
1058 while (got-- > 0) {
1059 bp = getblk(pmp->pm_devvp,
1060 de_bn2kb(pmp, cntobn(pmp, cn++)),
1061 pmp->pm_bpcluster, 0, 0);
1062 clrbuf(bp);
1063 if (bpp) {
1064 *bpp = bp;
1065 bpp = NULL;
1066 } else {
1067 bdwrite(bp);
1068 }
1069 }
1070 }
1071 }
1072
1073 return (0);
1074 }
1075