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