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