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