msdosfs_fat.c revision 1.22 1 /* $NetBSD: msdosfs_fat.c,v 1.22 2012/12/20 08:03:42 hannken 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.22 2012/12/20 08:03:42 hannken 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 bp = getblk(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
258 0, 0);
259 if (bp == NULL) {
260 /*
261 * getblk() above returns NULL only iff we are
262 * pagedaemon. See the implementation of getblk
263 * for detail.
264 */
265 return ENOMEM;
266 }
267 if (!ISSET(bp->b_oflags, (BO_DONE | BO_DELWRI))) {
268 SET(bp->b_flags, B_READ);
269 BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
270 VOP_STRATEGY(pmp->pm_devvp, bp);
271 curlwp->l_ru.ru_inblock++;
272 error = biowait(bp);
273 if (error) {
274 brelse(bp, 0);
275 return error;
276 }
277 }
278 bp_bn = bn;
279 }
280 prevcn = cn;
281 if (bo >= bsize) {
282 if (bp)
283 brelse(bp, 0);
284 return (EIO);
285 }
286 KASSERT(bp != NULL);
287 if (FAT32(pmp))
288 cn = getulong((char *)bp->b_data + bo);
289 else
290 cn = getushort((char *)bp->b_data + bo);
291 if (FAT12(pmp) && (prevcn & 1))
292 cn >>= 4;
293 cn &= pmp->pm_fatmask;
294 }
295
296 if (!MSDOSFSEOF(cn, pmp->pm_fatmask)) {
297 if (bp)
298 brelse(bp, 0);
299 if (bnp)
300 *bnp = cntobn(pmp, cn);
301 if (cnp)
302 *cnp = cn;
303 fc_setcache(dep, FC_LASTMAP, i, cn);
304 return (0);
305 }
306
307 hiteof:;
308 if (cnp)
309 *cnp = i;
310 if (bp)
311 brelse(bp, 0);
312 /* update last file cluster entry in the FAT cache */
313 fc_setcache(dep, FC_LASTFC, i - 1, prevcn);
314 return (E2BIG);
315 }
316
317 /*
318 * Find the closest entry in the FAT cache to the cluster we are looking
319 * for.
320 */
321 void
322 fc_lookup(struct denode *dep, u_long findcn, u_long *frcnp, u_long *fsrcnp)
323 {
324 int i;
325 u_long cn;
326 struct fatcache *closest = 0;
327
328 for (i = 0; i < FC_SIZE; i++) {
329 cn = dep->de_fc[i].fc_frcn;
330 if (cn != FCE_EMPTY && cn <= findcn) {
331 if (closest == 0 || cn > closest->fc_frcn)
332 closest = &dep->de_fc[i];
333 }
334 }
335 if (closest) {
336 *frcnp = closest->fc_frcn;
337 *fsrcnp = closest->fc_fsrcn;
338 }
339 }
340
341 /*
342 * Purge the FAT cache in denode dep of all entries relating to file
343 * relative cluster frcn and beyond.
344 */
345 void
346 fc_purge(struct denode *dep, u_int frcn)
347 {
348 int i;
349 struct fatcache *fcp;
350
351 fcp = dep->de_fc;
352 for (i = 0; i < FC_SIZE; i++, fcp++) {
353 if (fcp->fc_frcn >= frcn)
354 fcp->fc_frcn = FCE_EMPTY;
355 }
356 }
357
358 /*
359 * Update the FAT.
360 * If mirroring the FAT, update all copies, with the first copy as last.
361 * Else update only the current FAT (ignoring the others).
362 *
363 * pmp - msdosfsmount structure for filesystem to update
364 * bp - addr of modified FAT block
365 * fatbn - block number relative to begin of filesystem of the modified FAT block.
366 */
367 void
368 updatefats(struct msdosfsmount *pmp, struct buf *bp, u_long fatbn)
369 {
370 int i;
371 struct buf *bpn;
372
373 #ifdef MSDOSFS_DEBUG
374 printf("updatefats(pmp %p, bp %p, fatbn %lu)\n",
375 pmp, bp, fatbn);
376 #endif
377
378 /*
379 * If we have an FSInfo block, update it.
380 */
381 if (pmp->pm_fsinfo) {
382 u_long cn = pmp->pm_nxtfree;
383
384 if (pmp->pm_freeclustercount
385 && (pmp->pm_inusemap[cn / N_INUSEBITS]
386 & (1 << (cn % N_INUSEBITS)))) {
387 /*
388 * The cluster indicated in FSInfo isn't free
389 * any longer. Got get a new free one.
390 */
391 for (cn = 0; cn < pmp->pm_maxcluster; cn++)
392 if (pmp->pm_inusemap[cn / N_INUSEBITS] != (u_int)-1)
393 break;
394 pmp->pm_nxtfree = cn
395 + ffs(pmp->pm_inusemap[cn / N_INUSEBITS]
396 ^ (u_int)-1) - 1;
397 }
398 /*
399 * XXX If the fsinfo block is stored on media with
400 * 2KB or larger sectors, is the fsinfo structure
401 * padded at the end or in the middle?
402 */
403 if (bread(pmp->pm_devvp, de_bn2kb(pmp, pmp->pm_fsinfo),
404 pmp->pm_BytesPerSec, NOCRED, B_MODIFY, &bpn) != 0) {
405 /*
406 * Ignore the error, but turn off FSInfo update for the future.
407 */
408 pmp->pm_fsinfo = 0;
409 } else {
410 struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
411
412 putulong(fp->fsinfree, pmp->pm_freeclustercount);
413 putulong(fp->fsinxtfree, pmp->pm_nxtfree);
414 if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
415 bwrite(bpn);
416 else
417 bdwrite(bpn);
418 }
419 }
420
421 if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
422 /*
423 * Now copy the block(s) of the modified FAT to the other copies of
424 * the FAT and write them out. This is faster than reading in the
425 * other FATs and then writing them back out. This could tie up
426 * the FAT for quite a while. Preventing others from accessing it.
427 * To prevent us from going after the FAT quite so much we use
428 * delayed writes, unless they specified "synchronous" when the
429 * filesystem was mounted. If synch is asked for then use
430 * bwrite()'s and really slow things down.
431 */
432 for (i = 1; i < pmp->pm_FATs; i++) {
433 fatbn += pmp->pm_FATsecs;
434 /* getblk() never fails */
435 bpn = getblk(pmp->pm_devvp, de_bn2kb(pmp, fatbn),
436 bp->b_bcount, 0, 0);
437 memcpy(bpn->b_data, bp->b_data, bp->b_bcount);
438 if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
439 bwrite(bpn);
440 else
441 bdwrite(bpn);
442 }
443 }
444
445 /*
446 * Write out the first (or current) FAT last.
447 */
448 if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
449 bwrite(bp);
450 else
451 bdwrite(bp);
452 /*
453 * Maybe update fsinfo sector here?
454 */
455 }
456
457 /*
458 * Updating entries in 12 bit FATs is a pain in the butt.
459 *
460 * The following picture shows where nibbles go when moving from a 12 bit
461 * cluster number into the appropriate bytes in the FAT.
462 *
463 * byte m byte m+1 byte m+2
464 * +----+----+ +----+----+ +----+----+
465 * | 0 1 | | 2 3 | | 4 5 | FAT bytes
466 * +----+----+ +----+----+ +----+----+
467 *
468 * +----+----+----+ +----+----+----+
469 * | 3 0 1 | | 4 5 2 |
470 * +----+----+----+ +----+----+----+
471 * cluster n cluster n+1
472 *
473 * Where n is even. m = n + (n >> 2)
474 *
475 */
476 static inline void
477 usemap_alloc(struct msdosfsmount *pmp, u_long cn)
478 {
479
480 pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
481 pmp->pm_freeclustercount--;
482 }
483
484 static inline void
485 usemap_free(struct msdosfsmount *pmp, u_long cn)
486 {
487
488 pmp->pm_freeclustercount++;
489 pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
490 }
491
492 int
493 clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
494 {
495 int error;
496 u_long oldcn;
497
498 usemap_free(pmp, cluster);
499 error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
500 if (error) {
501 usemap_alloc(pmp, cluster);
502 return (error);
503 }
504 /*
505 * If the cluster was successfully marked free, then update
506 * the count of free clusters, and turn off the "allocated"
507 * bit in the "in use" cluster bit map.
508 */
509 if (oldcnp)
510 *oldcnp = oldcn;
511 return (0);
512 }
513
514 /*
515 * Get or Set or 'Get and Set' the cluster'th entry in the FAT.
516 *
517 * function - whether to get or set a fat entry
518 * pmp - address of the msdosfsmount structure for the filesystem
519 * whose FAT is to be manipulated.
520 * cn - which cluster is of interest
521 * oldcontents - address of a word that is to receive the contents of the
522 * cluster'th entry if this is a get function
523 * newcontents - the new value to be written into the cluster'th element of
524 * the FAT if this is a set function.
525 *
526 * This function can also be used to free a cluster by setting the FAT entry
527 * for a cluster to 0.
528 *
529 * All copies of the FAT are updated if this is a set function. NOTE: If
530 * fatentry() marks a cluster as free it does not update the inusemap in
531 * the msdosfsmount structure. This is left to the caller.
532 */
533 int
534 fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents, u_long newcontents)
535 {
536 int error;
537 u_long readcn;
538 u_long bn, bo, bsize, byteoffset;
539 struct buf *bp;
540
541 #ifdef MSDOSFS_DEBUG
542 printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
543 function, pmp, cn, oldcontents, newcontents);
544 #endif
545
546 #ifdef DIAGNOSTIC
547 /*
548 * Be sure they asked us to do something.
549 */
550 if ((function & (FAT_SET | FAT_GET)) == 0) {
551 printf("fatentry(): function code doesn't specify get or set\n");
552 return (EINVAL);
553 }
554
555 /*
556 * If they asked us to return a cluster number but didn't tell us
557 * where to put it, give them an error.
558 */
559 if ((function & FAT_GET) && oldcontents == NULL) {
560 printf("fatentry(): get function with no place to put result\n");
561 return (EINVAL);
562 }
563 #endif
564
565 /*
566 * Be sure the requested cluster is in the filesystem.
567 */
568 if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
569 return (EINVAL);
570
571 byteoffset = FATOFS(pmp, cn);
572 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
573 if ((error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize, NOCRED,
574 0, &bp)) != 0) {
575 return (error);
576 }
577
578 if (function & FAT_GET) {
579 if (FAT32(pmp))
580 readcn = getulong((char *)bp->b_data + bo);
581 else
582 readcn = getushort((char *)bp->b_data + bo);
583 if (FAT12(pmp) & (cn & 1))
584 readcn >>= 4;
585 readcn &= pmp->pm_fatmask;
586 *oldcontents = readcn;
587 }
588 if (function & FAT_SET) {
589 switch (pmp->pm_fatmask) {
590 case FAT12_MASK:
591 readcn = getushort((char *)bp->b_data + bo);
592 if (cn & 1) {
593 readcn &= 0x000f;
594 readcn |= newcontents << 4;
595 } else {
596 readcn &= 0xf000;
597 readcn |= newcontents & 0xfff;
598 }
599 putushort((char *)bp->b_data + bo, readcn);
600 break;
601 case FAT16_MASK:
602 putushort((char *)bp->b_data + bo, newcontents);
603 break;
604 case FAT32_MASK:
605 /*
606 * According to spec we have to retain the
607 * high order bits of the FAT entry.
608 */
609 readcn = getulong((char *)bp->b_data + bo);
610 readcn &= ~FAT32_MASK;
611 readcn |= newcontents & FAT32_MASK;
612 putulong((char *)bp->b_data + bo, readcn);
613 break;
614 }
615 updatefats(pmp, bp, bn);
616 bp = NULL;
617 pmp->pm_fmod = 1;
618 }
619 if (bp)
620 brelse(bp, 0);
621 return (0);
622 }
623
624 /*
625 * Update a contiguous cluster chain
626 *
627 * pmp - mount point
628 * start - first cluster of chain
629 * count - number of clusters in chain
630 * fillwith - what to write into FAT entry of last cluster
631 */
632 static int
633 fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
634 {
635 int error;
636 u_long bn, bo, bsize, byteoffset, readcn, newc;
637 struct buf *bp;
638
639 #ifdef MSDOSFS_DEBUG
640 printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
641 pmp, start, count, fillwith);
642 #endif
643 /*
644 * Be sure the clusters are in the filesystem.
645 */
646 if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
647 return (EINVAL);
648
649 while (count > 0) {
650 byteoffset = FATOFS(pmp, start);
651 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
652 error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize, NOCRED,
653 B_MODIFY, &bp);
654 if (error) {
655 return (error);
656 }
657 while (count > 0) {
658 start++;
659 newc = --count > 0 ? start : fillwith;
660 switch (pmp->pm_fatmask) {
661 case FAT12_MASK:
662 readcn = getushort((char *)bp->b_data + bo);
663 if (start & 1) {
664 readcn &= 0xf000;
665 readcn |= newc & 0xfff;
666 } else {
667 readcn &= 0x000f;
668 readcn |= newc << 4;
669 }
670 putushort((char *)bp->b_data + bo, readcn);
671 bo++;
672 if (!(start & 1))
673 bo++;
674 break;
675 case FAT16_MASK:
676 putushort((char *)bp->b_data + bo, newc);
677 bo += 2;
678 break;
679 case FAT32_MASK:
680 readcn = getulong((char *)bp->b_data + bo);
681 readcn &= ~pmp->pm_fatmask;
682 readcn |= newc & pmp->pm_fatmask;
683 putulong((char *)bp->b_data + bo, readcn);
684 bo += 4;
685 break;
686 }
687 if (bo >= bsize)
688 break;
689 }
690 updatefats(pmp, bp, bn);
691 }
692 pmp->pm_fmod = 1;
693 return (0);
694 }
695
696 /*
697 * Check the length of a free cluster chain starting at start.
698 *
699 * pmp - mount point
700 * start - start of chain
701 * count - maximum interesting length
702 */
703 int
704 chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
705 {
706 u_long idx, max_idx;
707 u_int map;
708 u_long len;
709
710 max_idx = pmp->pm_maxcluster / N_INUSEBITS;
711 idx = start / N_INUSEBITS;
712 start %= N_INUSEBITS;
713 map = pmp->pm_inusemap[idx];
714 map &= ~((1 << start) - 1);
715 if (map) {
716 len = ffs(map) - 1 - start;
717 return (len > count ? count : len);
718 }
719 len = N_INUSEBITS - start;
720 if (len >= count)
721 return (count);
722 while (++idx <= max_idx) {
723 if (len >= count)
724 break;
725 if ((map = pmp->pm_inusemap[idx]) != 0) {
726 len += ffs(map) - 1;
727 break;
728 }
729 len += N_INUSEBITS;
730 }
731 return (len > count ? count : len);
732 }
733
734 /*
735 * Allocate contigous free clusters.
736 *
737 * pmp - mount point.
738 * start - start of cluster chain.
739 * count - number of clusters to allocate.
740 * fillwith - put this value into the FAT entry for the
741 * last allocated cluster.
742 * retcluster - put the first allocated cluster's number here.
743 * got - how many clusters were actually allocated.
744 */
745 int
746 chainalloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith, u_long *retcluster, u_long *got)
747 {
748 int error;
749 u_long cl, n;
750
751 for (cl = start, n = count; n-- > 0;)
752 usemap_alloc(pmp, cl++);
753 if ((error = fatchain(pmp, start, count, fillwith)) != 0)
754 return (error);
755 #ifdef MSDOSFS_DEBUG
756 printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
757 start, count);
758 #endif
759 if (retcluster)
760 *retcluster = start;
761 if (got)
762 *got = count;
763 return (0);
764 }
765
766 /*
767 * Allocate contiguous free clusters.
768 *
769 * pmp - mount point.
770 * start - preferred start of cluster chain.
771 * count - number of clusters requested.
772 * fillwith - put this value into the FAT entry for the
773 * last allocated cluster.
774 * retcluster - put the first allocated cluster's number here.
775 * got - how many clusters were actually allocated.
776 */
777 int
778 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count, u_long *retcluster, u_long *got)
779 {
780 u_long idx;
781 u_long len, newst, foundl, cn, l;
782 u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
783 u_long fillwith = CLUST_EOFE;
784 u_int map;
785
786 #ifdef MSDOSFS_DEBUG
787 printf("clusteralloc(): find %lu clusters\n",count);
788 #endif
789 if (start) {
790 if ((len = chainlength(pmp, start, count)) >= count)
791 return (chainalloc(pmp, start, count, fillwith, retcluster, got));
792 } else {
793 /*
794 * This is a new file, initialize start
795 */
796 struct timeval tv;
797
798 microtime(&tv);
799 start = (tv.tv_usec >> 10) | tv.tv_usec;
800 len = 0;
801 }
802
803 /*
804 * Start at a (pseudo) random place to maximize cluster runs
805 * under multiple writers.
806 */
807 newst = (start * 1103515245 + 12345) % (pmp->pm_maxcluster + 1);
808 foundl = 0;
809
810 for (cn = newst; cn <= pmp->pm_maxcluster;) {
811 idx = cn / N_INUSEBITS;
812 map = pmp->pm_inusemap[idx];
813 map |= (1 << (cn % N_INUSEBITS)) - 1;
814 if (map != (u_int)-1) {
815 cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
816 if ((l = chainlength(pmp, cn, count)) >= count)
817 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
818 if (l > foundl) {
819 foundcn = cn;
820 foundl = l;
821 }
822 cn += l + 1;
823 continue;
824 }
825 cn += N_INUSEBITS - cn % N_INUSEBITS;
826 }
827 for (cn = 0; cn < newst;) {
828 idx = cn / N_INUSEBITS;
829 map = pmp->pm_inusemap[idx];
830 map |= (1 << (cn % N_INUSEBITS)) - 1;
831 if (map != (u_int)-1) {
832 cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
833 if ((l = chainlength(pmp, cn, count)) >= count)
834 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
835 if (l > foundl) {
836 foundcn = cn;
837 foundl = l;
838 }
839 cn += l + 1;
840 continue;
841 }
842 cn += N_INUSEBITS - cn % N_INUSEBITS;
843 }
844
845 if (!foundl)
846 return (ENOSPC);
847
848 if (len)
849 return (chainalloc(pmp, start, len, fillwith, retcluster, got));
850 else
851 return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
852 }
853
854
855 /*
856 * Free a chain of clusters.
857 *
858 * pmp - address of the msdosfs mount structure for the filesystem
859 * containing the cluster chain to be freed.
860 * startcluster - number of the 1st cluster in the chain of clusters to be
861 * freed.
862 */
863 int
864 freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
865 {
866 int error;
867 struct buf *bp = NULL;
868 u_long bn, bo, bsize, byteoffset;
869 u_long readcn, lbn = -1;
870
871 while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
872 byteoffset = FATOFS(pmp, cluster);
873 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
874 if (lbn != bn) {
875 if (bp)
876 updatefats(pmp, bp, lbn);
877 error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
878 NOCRED, B_MODIFY, &bp);
879 if (error) {
880 return (error);
881 }
882 lbn = bn;
883 }
884 usemap_free(pmp, cluster);
885 KASSERT(bp != NULL);
886 switch (pmp->pm_fatmask) {
887 case FAT12_MASK:
888 readcn = getushort((char *)bp->b_data + bo);
889 if (cluster & 1) {
890 cluster = readcn >> 4;
891 readcn &= 0x000f;
892 readcn |= MSDOSFSFREE << 4;
893 } else {
894 cluster = readcn;
895 readcn &= 0xf000;
896 readcn |= MSDOSFSFREE & 0xfff;
897 }
898 putushort((char *)bp->b_data + bo, readcn);
899 break;
900 case FAT16_MASK:
901 cluster = getushort((char *)bp->b_data + bo);
902 putushort((char *)bp->b_data + bo, MSDOSFSFREE);
903 break;
904 case FAT32_MASK:
905 cluster = getulong((char *)bp->b_data + bo);
906 putulong((char *)bp->b_data + bo,
907 (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
908 break;
909 }
910 cluster &= pmp->pm_fatmask;
911 }
912 if (bp)
913 updatefats(pmp, bp, bn);
914 return (0);
915 }
916
917 /*
918 * Read in FAT blocks looking for free clusters. For every free cluster
919 * found turn off its corresponding bit in the pm_inusemap.
920 */
921 int
922 fillinusemap(struct msdosfsmount *pmp)
923 {
924 struct buf *bp = NULL;
925 u_long cn, readcn;
926 int error;
927 u_long bn, bo, bsize, byteoffset;
928
929 /*
930 * Mark all clusters in use, we mark the free ones in the FAT scan
931 * loop further down.
932 */
933 for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
934 pmp->pm_inusemap[cn] = (u_int)-1;
935
936 /*
937 * Figure how many free clusters are in the filesystem by ripping
938 * through the FAT counting the number of entries whose content is
939 * zero. These represent free clusters.
940 */
941 pmp->pm_freeclustercount = 0;
942 for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
943 byteoffset = FATOFS(pmp, cn);
944 bo = byteoffset % pmp->pm_fatblocksize;
945 if (!bo || !bp) {
946 /* Read new FAT block */
947 if (bp)
948 brelse(bp, 0);
949 fatblock(pmp, byteoffset, &bn, &bsize, NULL);
950 error = bread(pmp->pm_devvp, de_bn2kb(pmp, bn), bsize,
951 NOCRED, 0, &bp);
952 if (error) {
953 return (error);
954 }
955 }
956 if (FAT32(pmp))
957 readcn = getulong((char *)bp->b_data + bo);
958 else
959 readcn = getushort((char *)bp->b_data + bo);
960 if (FAT12(pmp) && (cn & 1))
961 readcn >>= 4;
962 readcn &= pmp->pm_fatmask;
963
964 if (readcn == 0)
965 usemap_free(pmp, cn);
966 }
967 if (bp)
968 brelse(bp, 0);
969 return (0);
970 }
971
972 /*
973 * Allocate a new cluster and chain it onto the end of the file.
974 *
975 * dep - the file to extend
976 * count - number of clusters to allocate
977 * bpp - where to return the address of the buf header for the first new
978 * file block
979 * ncp - where to put cluster number of the first newly allocated cluster
980 * If this pointer is 0, do not return the cluster number.
981 * flags - see fat.h
982 *
983 * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
984 * the de_flag field of the denode and it does not change the de_FileSize
985 * field. This is left for the caller to do.
986 */
987
988 int
989 extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp, int flags)
990 {
991 int error;
992 u_long frcn = 0, cn, got;
993 struct msdosfsmount *pmp = dep->de_pmp;
994 struct buf *bp;
995
996 /*
997 * Don't try to extend the root directory
998 */
999 if (dep->de_StartCluster == MSDOSFSROOT
1000 && (dep->de_Attributes & ATTR_DIRECTORY)) {
1001 printf("extendfile(): attempt to extend root directory\n");
1002 return (ENOSPC);
1003 }
1004
1005 /*
1006 * If the "file's last cluster" cache entry is empty, and the file
1007 * is not empty, then fill the cache entry by calling pcbmap().
1008 */
1009 fc_fileextends++;
1010 if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
1011 dep->de_StartCluster != 0) {
1012 fc_lfcempty++;
1013 error = pcbmap(dep, CLUST_END, 0, &cn, 0);
1014 /* we expect it to return E2BIG */
1015 if (error != E2BIG)
1016 return (error);
1017 }
1018
1019 fc_last_to_nexttolast(dep);
1020
1021 while (count > 0) {
1022
1023 /*
1024 * Allocate a new cluster chain and cat onto the end of the
1025 * file. If the file is empty we make de_StartCluster point
1026 * to the new block. Note that de_StartCluster being 0 is
1027 * sufficient to be sure the file is empty since we exclude
1028 * attempts to extend the root directory above, and the root
1029 * dir is the only file with a startcluster of 0 that has
1030 * blocks allocated (sort of).
1031 */
1032
1033 if (dep->de_StartCluster == 0)
1034 cn = 0;
1035 else
1036 cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1037 error = clusteralloc(pmp, cn, count, &cn, &got);
1038 if (error)
1039 return (error);
1040
1041 count -= got;
1042
1043 /*
1044 * Give them the filesystem relative cluster number if they want
1045 * it.
1046 */
1047 if (ncp) {
1048 *ncp = cn;
1049 ncp = NULL;
1050 }
1051
1052 if (dep->de_StartCluster == 0) {
1053 dep->de_StartCluster = cn;
1054 frcn = 0;
1055 } else {
1056 error = fatentry(FAT_SET, pmp,
1057 dep->de_fc[FC_LASTFC].fc_fsrcn,
1058 0, cn);
1059 if (error) {
1060 clusterfree(pmp, cn, NULL);
1061 return (error);
1062 }
1063 frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1064 }
1065
1066 /*
1067 * Update the "last cluster of the file" entry in the
1068 * denode's FAT cache.
1069 */
1070
1071 fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1072 if ((flags & DE_CLEAR) &&
1073 (dep->de_Attributes & ATTR_DIRECTORY)) {
1074 while (got-- > 0) {
1075 bp = getblk(pmp->pm_devvp,
1076 de_bn2kb(pmp, cntobn(pmp, cn++)),
1077 pmp->pm_bpcluster, 0, 0);
1078 clrbuf(bp);
1079 if (bpp) {
1080 *bpp = bp;
1081 bpp = NULL;
1082 } else {
1083 bdwrite(bp);
1084 }
1085 }
1086 }
1087 }
1088
1089 return (0);
1090 }
1091