]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/msdosfs/msdosfs_fat.c
This commit was generated by cvs2svn to compensate for changes in r171825,
[FreeBSD/FreeBSD.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                 u_long cn = pmp->pm_nxtfree;
357
358                 if (pmp->pm_freeclustercount
359                     && (pmp->pm_inusemap[cn / N_INUSEBITS]
360                         & (1 << (cn % N_INUSEBITS)))) {
361                         /*
362                          * The cluster indicated in FSInfo isn't free
363                          * any longer.  Got get a new free one.
364                          */
365                         for (cn = 0; cn < pmp->pm_maxcluster; cn += N_INUSEBITS)
366                                 if (pmp->pm_inusemap[cn / N_INUSEBITS] != (u_int)-1)
367                                         break;
368                         pmp->pm_nxtfree = cn
369                                 + ffs(pmp->pm_inusemap[cn / N_INUSEBITS]
370                                       ^ (u_int)-1) - 1;
371                 }
372                 if (bread(pmp->pm_devvp, pmp->pm_fsinfo, pmp->pm_BytesPerSec,
373                     NOCRED, &bpn) != 0) {
374                         /*
375                          * Ignore the error, but turn off FSInfo update for the future.
376                          */
377                         pmp->pm_fsinfo = 0;
378                         brelse(bpn);
379                 } else {
380                         struct fsinfo *fp = (struct fsinfo *)bpn->b_data;
381
382                         putulong(fp->fsinfree, pmp->pm_freeclustercount);
383                         putulong(fp->fsinxtfree, pmp->pm_nxtfree);
384                         if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
385                                 bwrite(bpn);
386                         else
387                                 bdwrite(bpn);
388                 }
389         }
390
391         if (pmp->pm_flags & MSDOSFS_FATMIRROR) {
392                 /*
393                  * Now copy the block(s) of the modified fat to the other copies of
394                  * the fat and write them out.  This is faster than reading in the
395                  * other fats and then writing them back out.  This could tie up
396                  * the fat for quite a while. Preventing others from accessing it.
397                  * To prevent us from going after the fat quite so much we use
398                  * delayed writes, unless they specfied "synchronous" when the
399                  * filesystem was mounted.  If synch is asked for then use
400                  * bwrite()'s and really slow things down.
401                  */
402                 for (i = 1; i < pmp->pm_FATs; i++) {
403                         fatbn += pmp->pm_FATsecs;
404                         /* getblk() never fails */
405                         bpn = getblk(pmp->pm_devvp, fatbn, bp->b_bcount,
406                             0, 0, 0);
407                         bcopy(bp->b_data, bpn->b_data, bp->b_bcount);
408                         if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
409                                 bwrite(bpn);
410                         else
411                                 bdwrite(bpn);
412                 }
413         }
414
415         /*
416          * Write out the first (or current) fat last.
417          */
418         if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
419                 bwrite(bp);
420         else
421                 bdwrite(bp);
422         /*
423          * Maybe update fsinfo sector here?
424          */
425 }
426
427 /*
428  * Updating entries in 12 bit fats is a pain in the butt.
429  *
430  * The following picture shows where nibbles go when moving from a 12 bit
431  * cluster number into the appropriate bytes in the FAT.
432  *
433  *      byte m        byte m+1      byte m+2
434  *      +----+----+   +----+----+   +----+----+
435  *      |  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
436  *      +----+----+   +----+----+   +----+----+
437  *
438  *      +----+----+----+   +----+----+----+
439  *      |  3    0    1 |   |  4    5    2 |
440  *      +----+----+----+   +----+----+----+
441  *      cluster n          cluster n+1
442  *
443  * Where n is even. m = n + (n >> 2)
444  *
445  */
446 static __inline void
447 usemap_alloc(pmp, cn)
448         struct msdosfsmount *pmp;
449         u_long cn;
450 {
451
452         pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
453         pmp->pm_freeclustercount--;
454 }
455
456 static __inline void
457 usemap_free(pmp, cn)
458         struct msdosfsmount *pmp;
459         u_long cn;
460 {
461
462         pmp->pm_freeclustercount++;
463         pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
464 }
465
466 int
467 clusterfree(pmp, cluster, oldcnp)
468         struct msdosfsmount *pmp;
469         u_long cluster;
470         u_long *oldcnp;
471 {
472         int error;
473         u_long oldcn;
474
475         usemap_free(pmp, cluster);
476         error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
477         if (error) {
478                 usemap_alloc(pmp, cluster);
479                 return (error);
480         }
481         /*
482          * If the cluster was successfully marked free, then update
483          * the count of free clusters, and turn off the "allocated"
484          * bit in the "in use" cluster bit map.
485          */
486         if (oldcnp)
487                 *oldcnp = oldcn;
488         return (0);
489 }
490
491 /*
492  * Get or Set or 'Get and Set' the cluster'th entry in the fat.
493  *
494  * function     - whether to get or set a fat entry
495  * pmp          - address of the msdosfsmount structure for the filesystem
496  *                whose fat is to be manipulated.
497  * cn           - which cluster is of interest
498  * oldcontents  - address of a word that is to receive the contents of the
499  *                cluster'th entry if this is a get function
500  * newcontents  - the new value to be written into the cluster'th element of
501  *                the fat if this is a set function.
502  *
503  * This function can also be used to free a cluster by setting the fat entry
504  * for a cluster to 0.
505  *
506  * All copies of the fat are updated if this is a set function. NOTE: If
507  * fatentry() marks a cluster as free it does not update the inusemap in
508  * the msdosfsmount structure. This is left to the caller.
509  */
510 int
511 fatentry(function, pmp, cn, oldcontents, newcontents)
512         int function;
513         struct msdosfsmount *pmp;
514         u_long cn;
515         u_long *oldcontents;
516         u_long newcontents;
517 {
518         int error;
519         u_long readcn;
520         u_long bn, bo, bsize, byteoffset;
521         struct buf *bp;
522
523 #ifdef  MSDOSFS_DEBUG
524         printf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
525             function, pmp, cn, oldcontents, newcontents);
526 #endif
527
528 #ifdef DIAGNOSTIC
529         /*
530          * Be sure they asked us to do something.
531          */
532         if ((function & (FAT_SET | FAT_GET)) == 0) {
533                 printf("fatentry(): function code doesn't specify get or set\n");
534                 return (EINVAL);
535         }
536
537         /*
538          * If they asked us to return a cluster number but didn't tell us
539          * where to put it, give them an error.
540          */
541         if ((function & FAT_GET) && oldcontents == NULL) {
542                 printf("fatentry(): get function with no place to put result\n");
543                 return (EINVAL);
544         }
545 #endif
546
547         /*
548          * Be sure the requested cluster is in the filesystem.
549          */
550         if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
551                 return (EINVAL);
552
553         byteoffset = FATOFS(pmp, cn);
554         fatblock(pmp, byteoffset, &bn, &bsize, &bo);
555         error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
556         if (error) {
557                 brelse(bp);
558                 return (error);
559         }
560
561         if (function & FAT_GET) {
562                 if (FAT32(pmp))
563                         readcn = getulong(&bp->b_data[bo]);
564                 else
565                         readcn = getushort(&bp->b_data[bo]);
566                 if (FAT12(pmp) & (cn & 1))
567                         readcn >>= 4;
568                 readcn &= pmp->pm_fatmask;
569                 /* map reserved fat entries to same values for all fats */
570                 if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
571                         readcn |= ~pmp->pm_fatmask;
572                 *oldcontents = readcn;
573         }
574         if (function & FAT_SET) {
575                 switch (pmp->pm_fatmask) {
576                 case FAT12_MASK:
577                         readcn = getushort(&bp->b_data[bo]);
578                         if (cn & 1) {
579                                 readcn &= 0x000f;
580                                 readcn |= newcontents << 4;
581                         } else {
582                                 readcn &= 0xf000;
583                                 readcn |= newcontents & 0xfff;
584                         }
585                         putushort(&bp->b_data[bo], readcn);
586                         break;
587                 case FAT16_MASK:
588                         putushort(&bp->b_data[bo], newcontents);
589                         break;
590                 case FAT32_MASK:
591                         /*
592                          * According to spec we have to retain the
593                          * high order bits of the fat entry.
594                          */
595                         readcn = getulong(&bp->b_data[bo]);
596                         readcn &= ~FAT32_MASK;
597                         readcn |= newcontents & FAT32_MASK;
598                         putulong(&bp->b_data[bo], readcn);
599                         break;
600                 }
601                 updatefats(pmp, bp, bn);
602                 bp = NULL;
603                 pmp->pm_fmod = 1;
604         }
605         if (bp)
606                 brelse(bp);
607         return (0);
608 }
609
610 /*
611  * Update a contiguous cluster chain
612  *
613  * pmp      - mount point
614  * start    - first cluster of chain
615  * count    - number of clusters in chain
616  * fillwith - what to write into fat entry of last cluster
617  */
618 static int
619 fatchain(pmp, start, count, fillwith)
620         struct msdosfsmount *pmp;
621         u_long start;
622         u_long count;
623         u_long fillwith;
624 {
625         int error;
626         u_long bn, bo, bsize, byteoffset, readcn, newc;
627         struct buf *bp;
628
629 #ifdef MSDOSFS_DEBUG
630         printf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
631             pmp, start, count, fillwith);
632 #endif
633         /*
634          * Be sure the clusters are in the filesystem.
635          */
636         if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
637                 return (EINVAL);
638
639         while (count > 0) {
640                 byteoffset = FATOFS(pmp, start);
641                 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
642                 error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
643                 if (error) {
644                         brelse(bp);
645                         return (error);
646                 }
647                 while (count > 0) {
648                         start++;
649                         newc = --count > 0 ? start : fillwith;
650                         switch (pmp->pm_fatmask) {
651                         case FAT12_MASK:
652                                 readcn = getushort(&bp->b_data[bo]);
653                                 if (start & 1) {
654                                         readcn &= 0xf000;
655                                         readcn |= newc & 0xfff;
656                                 } else {
657                                         readcn &= 0x000f;
658                                         readcn |= newc << 4;
659                                 }
660                                 putushort(&bp->b_data[bo], readcn);
661                                 bo++;
662                                 if (!(start & 1))
663                                         bo++;
664                                 break;
665                         case FAT16_MASK:
666                                 putushort(&bp->b_data[bo], newc);
667                                 bo += 2;
668                                 break;
669                         case FAT32_MASK:
670                                 readcn = getulong(&bp->b_data[bo]);
671                                 readcn &= ~pmp->pm_fatmask;
672                                 readcn |= newc & pmp->pm_fatmask;
673                                 putulong(&bp->b_data[bo], readcn);
674                                 bo += 4;
675                                 break;
676                         }
677                         if (bo >= bsize)
678                                 break;
679                 }
680                 updatefats(pmp, bp, bn);
681         }
682         pmp->pm_fmod = 1;
683         return (0);
684 }
685
686 /*
687  * Check the length of a free cluster chain starting at start.
688  *
689  * pmp   - mount point
690  * start - start of chain
691  * count - maximum interesting length
692  */
693 static int
694 chainlength(pmp, start, count)
695         struct msdosfsmount *pmp;
696         u_long start;
697         u_long count;
698 {
699         u_long idx, max_idx;
700         u_int map;
701         u_long len;
702
703         max_idx = pmp->pm_maxcluster / N_INUSEBITS;
704         idx = start / N_INUSEBITS;
705         start %= N_INUSEBITS;
706         map = pmp->pm_inusemap[idx];
707         map &= ~((1 << start) - 1);
708         if (map) {
709                 len = ffs(map) - 1 - start;
710                 return (len > count ? count : len);
711         }
712         len = N_INUSEBITS - start;
713         if (len >= count)
714                 return (count);
715         while (++idx <= max_idx) {
716                 if (len >= count)
717                         break;
718                 map = pmp->pm_inusemap[idx];
719                 if (map) {
720                         len += ffs(map) - 1;
721                         break;
722                 }
723                 len += N_INUSEBITS;
724         }
725         return (len > count ? count : len);
726 }
727
728 /*
729  * Allocate contigous free clusters.
730  *
731  * pmp        - mount point.
732  * start      - start of cluster chain.
733  * count      - number of clusters to allocate.
734  * fillwith   - put this value into the fat entry for the
735  *              last allocated cluster.
736  * retcluster - put the first allocated cluster's number here.
737  * got        - how many clusters were actually allocated.
738  */
739 static int
740 chainalloc(pmp, start, count, fillwith, retcluster, got)
741         struct msdosfsmount *pmp;
742         u_long start;
743         u_long count;
744         u_long fillwith;
745         u_long *retcluster;
746         u_long *got;
747 {
748         int error;
749         u_long cl, n;
750
751         for (cl = start, n = count; n-- > 0;)
752                 usemap_alloc(pmp, cl++);
753
754         error = fatchain(pmp, start, count, fillwith);
755         if (error != 0)
756                 return (error);
757 #ifdef MSDOSFS_DEBUG
758         printf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
759             start, count);
760 #endif
761         if (retcluster)
762                 *retcluster = start;
763         if (got)
764                 *got = count;
765         pmp->pm_nxtfree = start + count;
766         if (pmp->pm_nxtfree > pmp->pm_maxcluster)
767                 pmp->pm_nxtfree = CLUST_FIRST;
768         return (0);
769 }
770
771 /*
772  * Allocate contiguous free clusters.
773  *
774  * pmp        - mount point.
775  * start      - preferred start of cluster chain.
776  * count      - number of clusters requested.
777  * fillwith   - put this value into the fat entry for the
778  *              last allocated cluster.
779  * retcluster - put the first allocated cluster's number here.
780  * got        - how many clusters were actually allocated.
781  */
782 int
783 clusteralloc(pmp, start, count, fillwith, retcluster, got)
784         struct msdosfsmount *pmp;
785         u_long start;
786         u_long count;
787         u_long fillwith;
788         u_long *retcluster;
789         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_int map;
795
796 #ifdef MSDOSFS_DEBUG
797         printf("clusteralloc(): find %lu clusters\n", count);
798 #endif
799         if (start) {
800                 if ((len = chainlength(pmp, start, count)) >= count)
801                         return (chainalloc(pmp, start, count, fillwith, retcluster, got));
802         } else
803                 len = 0;
804
805         newst = pmp->pm_nxtfree;
806         foundl = 0;
807
808         for (cn = newst; cn <= pmp->pm_maxcluster;) {
809                 idx = cn / N_INUSEBITS;
810                 map = pmp->pm_inusemap[idx];
811                 map |= (1 << (cn % N_INUSEBITS)) - 1;
812                 if (map != (u_int)-1) {
813                         cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
814                         if ((l = chainlength(pmp, cn, count)) >= count)
815                                 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
816                         if (l > foundl) {
817                                 foundcn = cn;
818                                 foundl = l;
819                         }
820                         cn += l + 1;
821                         continue;
822                 }
823                 cn += N_INUSEBITS - cn % N_INUSEBITS;
824         }
825         for (cn = 0; cn < newst;) {
826                 idx = cn / N_INUSEBITS;
827                 map = pmp->pm_inusemap[idx];
828                 map |= (1 << (cn % N_INUSEBITS)) - 1;
829                 if (map != (u_int)-1) {
830                         cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
831                         if ((l = chainlength(pmp, cn, count)) >= count)
832                                 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
833                         if (l > foundl) {
834                                 foundcn = cn;
835                                 foundl = l;
836                         }
837                         cn += l + 1;
838                         continue;
839                 }
840                 cn += N_INUSEBITS - cn % N_INUSEBITS;
841         }
842
843         if (!foundl)
844                 return (ENOSPC);
845
846         if (len)
847                 return (chainalloc(pmp, start, len, fillwith, retcluster, got));
848         else
849                 return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
850 }
851
852
853 /*
854  * Free a chain of clusters.
855  *
856  * pmp          - address of the msdosfs mount structure for the filesystem
857  *                containing the cluster chain to be freed.
858  * startcluster - number of the 1st cluster in the chain of clusters to be
859  *                freed.
860  */
861 int
862 freeclusterchain(pmp, cluster)
863         struct msdosfsmount *pmp;
864         u_long cluster;
865 {
866         int error;
867         struct buf *bp = NULL;
868         u_long bn, bo, bsize, byteoffset;
869         u_long readcn, lbn = -1;
870
871         while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
872                 byteoffset = FATOFS(pmp, cluster);
873                 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
874                 if (lbn != bn) {
875                         if (bp)
876                                 updatefats(pmp, bp, lbn);
877                         error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
878                         if (error) {
879                                 brelse(bp);
880                                 return (error);
881                         }
882                         lbn = bn;
883                 }
884                 usemap_free(pmp, cluster);
885                 switch (pmp->pm_fatmask) {
886                 case FAT12_MASK:
887                         readcn = getushort(&bp->b_data[bo]);
888                         if (cluster & 1) {
889                                 cluster = readcn >> 4;
890                                 readcn &= 0x000f;
891                                 readcn |= MSDOSFSFREE << 4;
892                         } else {
893                                 cluster = readcn;
894                                 readcn &= 0xf000;
895                                 readcn |= MSDOSFSFREE & 0xfff;
896                         }
897                         putushort(&bp->b_data[bo], readcn);
898                         break;
899                 case FAT16_MASK:
900                         cluster = getushort(&bp->b_data[bo]);
901                         putushort(&bp->b_data[bo], MSDOSFSFREE);
902                         break;
903                 case FAT32_MASK:
904                         cluster = getulong(&bp->b_data[bo]);
905                         putulong(&bp->b_data[bo],
906                                  (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
907                         break;
908                 }
909                 cluster &= pmp->pm_fatmask;
910                 if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
911                         cluster |= pmp->pm_fatmask;
912         }
913         if (bp)
914                 updatefats(pmp, bp, bn);
915         return (0);
916 }
917
918 /*
919  * Read in fat blocks looking for free clusters. For every free cluster
920  * found turn off its corresponding bit in the pm_inusemap.
921  */
922 int
923 fillinusemap(pmp)
924         struct msdosfsmount *pmp;
925 {
926         struct buf *bp = NULL;
927         u_long cn, readcn;
928         int error;
929         u_long bn, bo, bsize, byteoffset;
930
931         /*
932          * Mark all clusters in use, we mark the free ones in the fat scan
933          * loop further down.
934          */
935         for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
936                 pmp->pm_inusemap[cn] = (u_int)-1;
937
938         /*
939          * Figure how many free clusters are in the filesystem by ripping
940          * through the fat counting the number of entries whose content is
941          * zero.  These represent free clusters.
942          */
943         pmp->pm_freeclustercount = 0;
944         for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
945                 byteoffset = FATOFS(pmp, cn);
946                 bo = byteoffset % pmp->pm_fatblocksize;
947                 if (!bo || !bp) {
948                         /* Read new FAT block */
949                         if (bp)
950                                 brelse(bp);
951                         fatblock(pmp, byteoffset, &bn, &bsize, NULL);
952                         error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
953                         if (error) {
954                                 brelse(bp);
955                                 return (error);
956                         }
957                 }
958                 if (FAT32(pmp))
959                         readcn = getulong(&bp->b_data[bo]);
960                 else
961                         readcn = getushort(&bp->b_data[bo]);
962                 if (FAT12(pmp) && (cn & 1))
963                         readcn >>= 4;
964                 readcn &= pmp->pm_fatmask;
965
966                 if (readcn == 0)
967                         usemap_free(pmp, cn);
968         }
969         brelse(bp);
970         return (0);
971 }
972
973 /*
974  * Allocate a new cluster and chain it onto the end of the file.
975  *
976  * dep   - the file to extend
977  * count - number of clusters to allocate
978  * bpp   - where to return the address of the buf header for the first new
979  *         file block
980  * ncp   - where to put cluster number of the first newly allocated cluster
981  *         If this pointer is 0, do not return the cluster number.
982  * flags - see fat.h
983  *
984  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
985  * the de_flag field of the denode and it does not change the de_FileSize
986  * field.  This is left for the caller to do.
987  */
988 int
989 extendfile(dep, count, bpp, ncp, flags)
990         struct denode *dep;
991         u_long count;
992         struct buf **bpp;
993         u_long *ncp;
994         int flags;
995 {
996         int error;
997         u_long frcn;
998         u_long cn, got;
999         struct msdosfsmount *pmp = dep->de_pmp;
1000         struct buf *bp;
1001         daddr_t blkno;
1002
1003         /*
1004          * Don't try to extend the root directory
1005          */
1006         if (dep->de_StartCluster == MSDOSFSROOT
1007             && (dep->de_Attributes & ATTR_DIRECTORY)) {
1008                 printf("extendfile(): attempt to extend root directory\n");
1009                 return (ENOSPC);
1010         }
1011
1012         /*
1013          * If the "file's last cluster" cache entry is empty, and the file
1014          * is not empty, then fill the cache entry by calling pcbmap().
1015          */
1016         fc_fileextends++;
1017         if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
1018             dep->de_StartCluster != 0) {
1019                 fc_lfcempty++;
1020                 error = pcbmap(dep, 0xffff, 0, &cn, 0);
1021                 /* we expect it to return E2BIG */
1022                 if (error != E2BIG)
1023                         return (error);
1024         }
1025
1026         fc_last_to_nexttolast(dep);
1027         while (count > 0) {
1028                 /*
1029                  * Allocate a new cluster chain and cat onto the end of the
1030                  * file.  * If the file is empty we make de_StartCluster point
1031                  * to the new block.  Note that de_StartCluster being 0 is
1032                  * sufficient to be sure the file is empty since we exclude
1033                  * attempts to extend the root directory above, and the root
1034                  * dir is the only file with a startcluster of 0 that has
1035                  * blocks allocated (sort of).
1036                  */
1037                 if (dep->de_StartCluster == 0)
1038                         cn = 0;
1039                 else
1040                         cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
1041                 error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
1042                 if (error)
1043                         return (error);
1044
1045                 count -= got;
1046
1047                 /*
1048                  * Give them the filesystem relative cluster number if they want
1049                  * it.
1050                  */
1051                 if (ncp) {
1052                         *ncp = cn;
1053                         ncp = NULL;
1054                 }
1055
1056                 if (dep->de_StartCluster == 0) {
1057                         dep->de_StartCluster = cn;
1058                         frcn = 0;
1059                 } else {
1060                         error = fatentry(FAT_SET, pmp,
1061                                          dep->de_fc[FC_LASTFC].fc_fsrcn,
1062                                          0, cn);
1063                         if (error) {
1064                                 clusterfree(pmp, cn, NULL);
1065                                 return (error);
1066                         }
1067                         frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1068                 }
1069
1070                 /*
1071                  * Update the "last cluster of the file" entry in the denode's fat
1072                  * cache.
1073                  */
1074                 fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1075
1076                 if (flags & DE_CLEAR) {
1077                         while (got-- > 0) {
1078                                 /*
1079                                  * Get the buf header for the new block of the file.
1080                                  */
1081                                 if (dep->de_Attributes & ATTR_DIRECTORY)
1082                                         bp = getblk(pmp->pm_devvp,
1083                                             cntobn(pmp, cn++),
1084                                             pmp->pm_bpcluster, 0, 0, 0);
1085                                 else {
1086                                         bp = getblk(DETOV(dep),
1087                                             de_cn2bn(pmp, frcn++),
1088                                             pmp->pm_bpcluster, 0, 0, 0);
1089                                         /*
1090                                          * Do the bmap now, as in msdosfs_write
1091                                          */
1092                                         if (pcbmap(dep,
1093                                             de_bn2cn(pmp, bp->b_lblkno),
1094                                             &blkno, 0, 0))
1095                                                 bp->b_blkno = -1;
1096                                         if (bp->b_blkno == -1)
1097                                                 panic("extendfile: pcbmap");
1098                                         else
1099                                                 bp->b_blkno = blkno;
1100                                 }
1101                                 vfs_bio_clrbuf(bp);
1102                                 if (bpp) {
1103                                         *bpp = bp;
1104                                         bpp = NULL;
1105                                 } else
1106                                         bdwrite(bp);
1107                         }
1108                 }
1109         }
1110
1111         return (0);
1112 }
1113
1114 /*-
1115  * Routine to mark a FAT16 or FAT32 volume as "clean" or "dirty" by
1116  * manipulating the upper bit of the FAT entry for cluster 1.  Note that
1117  * this bit is not defined for FAT12 volumes, which are always assumed to
1118  * be dirty.
1119  *
1120  * The fatentry() routine only works on cluster numbers that a file could
1121  * occupy, so it won't manipulate the entry for cluster 1.  So we have to do
1122  * it here.  The code was stolen from fatentry() and tailored for cluster 1.
1123  *
1124  * Inputs:
1125  *      pmp     The MS-DOS volume to mark
1126  *      dirty   Non-zero if the volume should be marked dirty; zero if it
1127  *              should be marked clean
1128  *
1129  * Result:
1130  *      0       Success
1131  *      EROFS   Volume is read-only
1132  *      ?       (other errors from called routines)
1133  */
1134 int
1135 markvoldirty(struct msdosfsmount *pmp, int dirty)
1136 {
1137         struct buf *bp;
1138         u_long bn, bo, bsize, byteoffset, fatval;
1139         int error;
1140
1141         /*
1142          * FAT12 does not support a "clean" bit, so don't do anything for
1143          * FAT12.
1144          */
1145         if (FAT12(pmp))
1146                 return (0);
1147
1148         /* Can't change the bit on a read-only filesystem. */
1149         if (pmp->pm_flags & MSDOSFSMNT_RONLY)
1150                 return (EROFS);
1151
1152         /*
1153          * Fetch the block containing the FAT entry.  It is given by the
1154          * pseudo-cluster 1.
1155          */
1156         byteoffset = FATOFS(pmp, 1);
1157         fatblock(pmp, byteoffset, &bn, &bsize, &bo);
1158         error = bread(pmp->pm_devvp, bn, bsize, NOCRED, &bp);
1159         if (error) {
1160                 brelse(bp);
1161                 return (error);
1162         }
1163
1164         /*
1165          * Get the current value of the FAT entry and set/clear the relevant
1166          * bit.  Dirty means clear the "clean" bit; clean means set the
1167          * "clean" bit.
1168          */
1169         if (FAT32(pmp)) {
1170                 /* FAT32 uses bit 27. */
1171                 fatval = getulong(&bp->b_data[bo]);
1172                 if (dirty)
1173                         fatval &= 0xF7FFFFFF;
1174                 else
1175                         fatval |= 0x08000000;
1176                 putulong(&bp->b_data[bo], fatval);
1177         } else {
1178                 /* Must be FAT16; use bit 15. */
1179                 fatval = getushort(&bp->b_data[bo]);
1180                 if (dirty)
1181                         fatval &= 0x7FFF;
1182                 else
1183                         fatval |= 0x8000;
1184                 putushort(&bp->b_data[bo], fatval);
1185         }
1186
1187         /* Write out the modified FAT block synchronously. */
1188         return (bwrite(bp));
1189 }