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