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