Rename printf -> kprintf in sys/ and add some defines where necessary
[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.11 2006/12/23 00:41:29 swildner 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, de_bntodoff(pmp, 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 = xcntobn(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         kprintf("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, de_bntodoff(pmp, 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, de_bntodoff(pmp, fatbn),
387                                      bp->b_bcount, 0, 0);
388                         bcopy(bp->b_data, bpn->b_data, bp->b_bcount);
389                         if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
390                                 bwrite(bpn);
391                         else
392                                 bdwrite(bpn);
393                 }
394         }
395
396         /*
397          * Write out the first (or current) fat last.
398          */
399         if (pmp->pm_flags & MSDOSFSMNT_WAITONFAT)
400                 bwrite(bp);
401         else
402                 bdwrite(bp);
403         /*
404          * Maybe update fsinfo sector here?
405          */
406 }
407
408 /*
409  * Updating entries in 12 bit fats is a pain in the butt.
410  *
411  * The following picture shows where nibbles go when moving from a 12 bit
412  * cluster number into the appropriate bytes in the FAT.
413  *
414  *      byte m        byte m+1      byte m+2
415  *      +----+----+   +----+----+   +----+----+
416  *      |  0    1 |   |  2    3 |   |  4    5 |   FAT bytes
417  *      +----+----+   +----+----+   +----+----+
418  *
419  *      +----+----+----+   +----+----+----+
420  *      |  3    0    1 |   |  4    5    2 |
421  *      +----+----+----+   +----+----+----+
422  *      cluster n          cluster n+1
423  *
424  * Where n is even. m = n + (n >> 2)
425  *
426  */
427 static __inline void
428 usemap_alloc(struct msdosfsmount *pmp, u_long cn)
429 {
430
431         pmp->pm_inusemap[cn / N_INUSEBITS] |= 1 << (cn % N_INUSEBITS);
432         pmp->pm_freeclustercount--;
433 }
434
435 static __inline void
436 usemap_free(struct msdosfsmount *pmp, u_long cn)
437 {
438
439         pmp->pm_freeclustercount++;
440         pmp->pm_inusemap[cn / N_INUSEBITS] &= ~(1 << (cn % N_INUSEBITS));
441 }
442
443 int
444 clusterfree(struct msdosfsmount *pmp, u_long cluster, u_long *oldcnp)
445 {
446         int error;
447         u_long oldcn;
448
449         usemap_free(pmp, cluster);
450         error = fatentry(FAT_GET_AND_SET, pmp, cluster, &oldcn, MSDOSFSFREE);
451         if (error) {
452                 usemap_alloc(pmp, cluster);
453                 return (error);
454         }
455         /*
456          * If the cluster was successfully marked free, then update
457          * the count of free clusters, and turn off the "allocated"
458          * bit in the "in use" cluster bit map.
459          */
460         if (oldcnp)
461                 *oldcnp = oldcn;
462         return (0);
463 }
464
465 /*
466  * Get or Set or 'Get and Set' the cluster'th entry in the fat.
467  *
468  * function     - whether to get or set a fat entry
469  * pmp          - address of the msdosfsmount structure for the filesystem
470  *                whose fat is to be manipulated.
471  * cn           - which cluster is of interest
472  * oldcontents  - address of a word that is to receive the contents of the
473  *                cluster'th entry if this is a get function
474  * newcontents  - the new value to be written into the cluster'th element of
475  *                the fat if this is a set function.
476  *
477  * This function can also be used to free a cluster by setting the fat entry
478  * for a cluster to 0.
479  *
480  * All copies of the fat are updated if this is a set function. NOTE: If
481  * fatentry() marks a cluster as free it does not update the inusemap in
482  * the msdosfsmount structure. This is left to the caller.
483  */
484 int
485 fatentry(int function, struct msdosfsmount *pmp, u_long cn, u_long *oldcontents,
486          u_long newcontents)
487 {
488         int error;
489         u_long readcn;
490         u_long bn, bo, bsize, byteoffset;
491         struct buf *bp;
492
493 #ifdef  MSDOSFS_DEBUG
494         kprintf("fatentry(func %d, pmp %p, clust %lu, oldcon %p, newcon %lx)\n",
495              function, pmp, cn, oldcontents, newcontents);
496 #endif
497
498 #ifdef DIAGNOSTIC
499         /*
500          * Be sure they asked us to do something.
501          */
502         if ((function & (FAT_SET | FAT_GET)) == 0) {
503                 kprintf("fatentry(): function code doesn't specify get or set\n");
504                 return (EINVAL);
505         }
506
507         /*
508          * If they asked us to return a cluster number but didn't tell us
509          * where to put it, give them an error.
510          */
511         if ((function & FAT_GET) && oldcontents == NULL) {
512                 kprintf("fatentry(): get function with no place to put result\n");
513                 return (EINVAL);
514         }
515 #endif
516
517         /*
518          * Be sure the requested cluster is in the filesystem.
519          */
520         if (cn < CLUST_FIRST || cn > pmp->pm_maxcluster)
521                 return (EINVAL);
522
523         byteoffset = FATOFS(pmp, cn);
524         fatblock(pmp, byteoffset, &bn, &bsize, &bo);
525         error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
526         if (error) {
527                 brelse(bp);
528                 return (error);
529         }
530
531         if (function & FAT_GET) {
532                 if (FAT32(pmp))
533                         readcn = getulong(&bp->b_data[bo]);
534                 else
535                         readcn = getushort(&bp->b_data[bo]);
536                 if (FAT12(pmp) & (cn & 1))
537                         readcn >>= 4;
538                 readcn &= pmp->pm_fatmask;
539                 /* map reserved fat entries to same values for all fats */
540                 if ((readcn | ~pmp->pm_fatmask) >= CLUST_RSRVD)
541                         readcn |= ~pmp->pm_fatmask;
542                 *oldcontents = readcn;
543         }
544         if (function & FAT_SET) {
545                 switch (pmp->pm_fatmask) {
546                 case FAT12_MASK:
547                         readcn = getushort(&bp->b_data[bo]);
548                         if (cn & 1) {
549                                 readcn &= 0x000f;
550                                 readcn |= newcontents << 4;
551                         } else {
552                                 readcn &= 0xf000;
553                                 readcn |= newcontents & 0xfff;
554                         }
555                         putushort(&bp->b_data[bo], readcn);
556                         break;
557                 case FAT16_MASK:
558                         putushort(&bp->b_data[bo], newcontents);
559                         break;
560                 case FAT32_MASK:
561                         /*
562                          * According to spec we have to retain the
563                          * high order bits of the fat entry.
564                          */
565                         readcn = getulong(&bp->b_data[bo]);
566                         readcn &= ~FAT32_MASK;
567                         readcn |= newcontents & FAT32_MASK;
568                         putulong(&bp->b_data[bo], readcn);
569                         break;
570                 }
571                 updatefats(pmp, bp, bn);
572                 bp = NULL;
573                 pmp->pm_fmod = 1;
574         }
575         if (bp)
576                 brelse(bp);
577         return (0);
578 }
579
580 /*
581  * Update a contiguous cluster chain
582  *
583  * pmp      - mount point
584  * start    - first cluster of chain
585  * count    - number of clusters in chain
586  * fillwith - what to write into fat entry of last cluster
587  */
588 static int
589 fatchain(struct msdosfsmount *pmp, u_long start, u_long count, u_long fillwith)
590 {
591         int error;
592         u_long bn, bo, bsize, byteoffset, readcn, newc;
593         struct buf *bp;
594
595 #ifdef MSDOSFS_DEBUG
596         kprintf("fatchain(pmp %p, start %lu, count %lu, fillwith %lx)\n",
597             pmp, start, count, fillwith);
598 #endif
599         /*
600          * Be sure the clusters are in the filesystem.
601          */
602         if (start < CLUST_FIRST || start + count - 1 > pmp->pm_maxcluster)
603                 return (EINVAL);
604
605         while (count > 0) {
606                 byteoffset = FATOFS(pmp, start);
607                 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
608                 error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
609                 if (error) {
610                         brelse(bp);
611                         return (error);
612                 }
613                 while (count > 0) {
614                         start++;
615                         newc = --count > 0 ? start : fillwith;
616                         switch (pmp->pm_fatmask) {
617                         case FAT12_MASK:
618                                 readcn = getushort(&bp->b_data[bo]);
619                                 if (start & 1) {
620                                         readcn &= 0xf000;
621                                         readcn |= newc & 0xfff;
622                                 } else {
623                                         readcn &= 0x000f;
624                                         readcn |= newc << 4;
625                                 }
626                                 putushort(&bp->b_data[bo], readcn);
627                                 bo++;
628                                 if (!(start & 1))
629                                         bo++;
630                                 break;
631                         case FAT16_MASK:
632                                 putushort(&bp->b_data[bo], newc);
633                                 bo += 2;
634                                 break;
635                         case FAT32_MASK:
636                                 readcn = getulong(&bp->b_data[bo]);
637                                 readcn &= ~pmp->pm_fatmask;
638                                 readcn |= newc & pmp->pm_fatmask;
639                                 putulong(&bp->b_data[bo], readcn);
640                                 bo += 4;
641                                 break;
642                         }
643                         if (bo >= bsize)
644                                 break;
645                 }
646                 updatefats(pmp, bp, bn);
647         }
648         pmp->pm_fmod = 1;
649         return (0);
650 }
651
652 /*
653  * Check the length of a free cluster chain starting at start.
654  *
655  * pmp   - mount point
656  * start - start of chain
657  * count - maximum interesting length
658  */
659 static int
660 chainlength(struct msdosfsmount *pmp, u_long start, u_long count)
661 {
662         u_long idx, max_idx;
663         u_int map;
664         u_long len;
665
666         max_idx = pmp->pm_maxcluster / N_INUSEBITS;
667         idx = start / N_INUSEBITS;
668         start %= N_INUSEBITS;
669         map = pmp->pm_inusemap[idx];
670         map &= ~((1 << start) - 1);
671         if (map) {
672                 len = ffs(map) - 1 - start;
673                 return (len > count ? count : len);
674         }
675         len = N_INUSEBITS - start;
676         if (len >= count)
677                 return (count);
678         while (++idx <= max_idx) {
679                 if (len >= count)
680                         break;
681                 map = pmp->pm_inusemap[idx];
682                 if (map) {
683                         len +=  ffs(map) - 1;
684                         break;
685                 }
686                 len += N_INUSEBITS;
687         }
688         return (len > count ? count : len);
689 }
690
691 /*
692  * Allocate contigous free clusters.
693  *
694  * pmp        - mount point.
695  * start      - start of cluster chain.
696  * count      - number of clusters to allocate.
697  * fillwith   - put this value into the fat entry for the
698  *              last allocated cluster.
699  * retcluster - put the first allocated cluster's number here.
700  * got        - how many clusters were actually allocated.
701  */
702 static int
703 chainalloc(struct msdosfsmount *pmp, u_long start, u_long count,
704            u_long fillwith, u_long *retcluster, u_long *got)
705 {
706         int error;
707         u_long cl, n;
708
709         for (cl = start, n = count; n-- > 0;)
710                 usemap_alloc(pmp, cl++);
711
712         error = fatchain(pmp, start, count, fillwith);
713         if (error != 0)
714                 return (error);
715 #ifdef MSDOSFS_DEBUG
716         kprintf("clusteralloc(): allocated cluster chain at %lu (%lu clusters)\n",
717             start, count);
718 #endif
719         if (retcluster)
720                 *retcluster = start;
721         if (got)
722                 *got = count;
723         return (0);
724 }
725
726 /*
727  * Allocate contiguous free clusters.
728  *
729  * pmp        - mount point.
730  * start      - preferred start of cluster chain.
731  * count      - number of clusters requested.
732  * fillwith   - put this value into the fat entry for the
733  *              last allocated cluster.
734  * retcluster - put the first allocated cluster's number here.
735  * got        - how many clusters were actually allocated.
736  */
737 int
738 clusteralloc(struct msdosfsmount *pmp, u_long start, u_long count,
739              u_long fillwith, u_long *retcluster, u_long *got)
740 {
741         u_long idx;
742         u_long len, newst, foundl, cn, l;
743         u_long foundcn = 0; /* XXX: foundcn could be used unititialized */
744         u_int map;
745
746 #ifdef MSDOSFS_DEBUG
747         kprintf("clusteralloc(): find %lu clusters\n",count);
748 #endif
749         if (start) {
750                 if ((len = chainlength(pmp, start, count)) >= count)
751                         return (chainalloc(pmp, start, count, fillwith, retcluster, got));
752         } else 
753                 len = 0;
754
755         /*
756          * Start at a (pseudo) random place to maximize cluster runs
757          * under multiple writers.
758          */
759         newst = krandom() % (pmp->pm_maxcluster + 1);
760         foundl = 0;
761
762         for (cn = newst; cn <= pmp->pm_maxcluster;) {
763                 idx = cn / N_INUSEBITS;
764                 map = pmp->pm_inusemap[idx];
765                 map |= (1 << (cn % N_INUSEBITS)) - 1;
766                 if (map != (u_int)-1) {
767                         cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
768                         if ((l = chainlength(pmp, cn, count)) >= count)
769                                 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
770                         if (l > foundl) {
771                                 foundcn = cn;
772                                 foundl = l;
773                         }
774                         cn += l + 1;
775                         continue;
776                 }
777                 cn += N_INUSEBITS - cn % N_INUSEBITS;
778         }
779         for (cn = 0; cn < newst;) {
780                 idx = cn / N_INUSEBITS;
781                 map = pmp->pm_inusemap[idx];
782                 map |= (1 << (cn % N_INUSEBITS)) - 1;
783                 if (map != (u_int)-1) {
784                         cn = idx * N_INUSEBITS + ffs(map^(u_int)-1) - 1;
785                         if ((l = chainlength(pmp, cn, count)) >= count)
786                                 return (chainalloc(pmp, cn, count, fillwith, retcluster, got));
787                         if (l > foundl) {
788                                 foundcn = cn;
789                                 foundl = l;
790                         }
791                         cn += l + 1;
792                         continue;
793                 }
794                 cn += N_INUSEBITS - cn % N_INUSEBITS;
795         }
796
797         if (!foundl)
798                 return (ENOSPC);
799
800         if (len)
801                 return (chainalloc(pmp, start, len, fillwith, retcluster, got));
802         else
803                 return (chainalloc(pmp, foundcn, foundl, fillwith, retcluster, got));
804 }
805
806
807 /*
808  * Free a chain of clusters.
809  *
810  * pmp          - address of the msdosfs mount structure for the filesystem
811  *                containing the cluster chain to be freed.
812  * startcluster - number of the 1st cluster in the chain of clusters to be
813  *                freed.
814  */
815 int
816 freeclusterchain(struct msdosfsmount *pmp, u_long cluster)
817 {
818         int error;
819         struct buf *bp = NULL;
820         u_long bn, bo, bsize, byteoffset;
821         u_long readcn, lbn = -1;
822
823         while (cluster >= CLUST_FIRST && cluster <= pmp->pm_maxcluster) {
824                 byteoffset = FATOFS(pmp, cluster);
825                 fatblock(pmp, byteoffset, &bn, &bsize, &bo);
826                 if (lbn != bn) {
827                         if (bp)
828                                 updatefats(pmp, bp, lbn);
829                         error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
830                         if (error) {
831                                 brelse(bp);
832                                 return (error);
833                         }
834                         lbn = bn;
835                 }
836                 usemap_free(pmp, cluster);
837                 switch (pmp->pm_fatmask) {
838                 case FAT12_MASK:
839                         readcn = getushort(&bp->b_data[bo]);
840                         if (cluster & 1) {
841                                 cluster = readcn >> 4;
842                                 readcn &= 0x000f;
843                                 readcn |= MSDOSFSFREE << 4;
844                         } else {
845                                 cluster = readcn;
846                                 readcn &= 0xf000;
847                                 readcn |= MSDOSFSFREE & 0xfff;
848                         }
849                         putushort(&bp->b_data[bo], readcn);
850                         break;
851                 case FAT16_MASK:
852                         cluster = getushort(&bp->b_data[bo]);
853                         putushort(&bp->b_data[bo], MSDOSFSFREE);
854                         break;
855                 case FAT32_MASK:
856                         cluster = getulong(&bp->b_data[bo]);
857                         putulong(&bp->b_data[bo],
858                                  (MSDOSFSFREE & FAT32_MASK) | (cluster & ~FAT32_MASK));
859                         break;
860                 }
861                 cluster &= pmp->pm_fatmask;
862                 if ((cluster | ~pmp->pm_fatmask) >= CLUST_RSRVD)
863                         cluster |= pmp->pm_fatmask;
864         }
865         if (bp)
866                 updatefats(pmp, bp, bn);
867         return (0);
868 }
869
870 /*
871  * Read in fat blocks looking for free clusters. For every free cluster
872  * found turn off its corresponding bit in the pm_inusemap.
873  */
874 int
875 fillinusemap(struct msdosfsmount *pmp)
876 {
877         struct buf *bp = NULL;
878         u_long cn, readcn;
879         int error;
880         u_long bn, bo, bsize, byteoffset;
881
882         /*
883          * Mark all clusters in use, we mark the free ones in the fat scan
884          * loop further down.
885          */
886         for (cn = 0; cn < (pmp->pm_maxcluster + N_INUSEBITS) / N_INUSEBITS; cn++)
887                 pmp->pm_inusemap[cn] = (u_int)-1;
888
889         /*
890          * Figure how many free clusters are in the filesystem by ripping
891          * through the fat counting the number of entries whose content is
892          * zero.  These represent free clusters.
893          */
894         pmp->pm_freeclustercount = 0;
895         for (cn = CLUST_FIRST; cn <= pmp->pm_maxcluster; cn++) {
896                 byteoffset = FATOFS(pmp, cn);
897                 bo = byteoffset % pmp->pm_fatblocksize;
898                 if (!bo || !bp) {
899                         /* Read new FAT block */
900                         if (bp)
901                                 brelse(bp);
902                         fatblock(pmp, byteoffset, &bn, &bsize, NULL);
903                         error = bread(pmp->pm_devvp, de_bntodoff(pmp, bn), bsize, &bp);
904                         if (error) {
905                                 brelse(bp);
906                                 return (error);
907                         }
908                 }
909                 if (FAT32(pmp))
910                         readcn = getulong(&bp->b_data[bo]);
911                 else
912                         readcn = getushort(&bp->b_data[bo]);
913                 if (FAT12(pmp) && (cn & 1))
914                         readcn >>= 4;
915                 readcn &= pmp->pm_fatmask;
916
917                 if (readcn == 0)
918                         usemap_free(pmp, cn);
919         }
920         brelse(bp);
921         return (0);
922 }
923
924 /*
925  * Allocate a new cluster and chain it onto the end of the file.
926  *
927  * dep   - the file to extend
928  * count - number of clusters to allocate
929  * bpp   - where to return the address of the buf header for the first new
930  *         file block
931  * ncp   - where to put cluster number of the first newly allocated cluster
932  *         If this pointer is 0, do not return the cluster number.
933  * flags - see fat.h
934  *
935  * NOTE: This function is not responsible for turning on the DE_UPDATE bit of
936  * the de_flag field of the denode and it does not change the de_FileSize
937  * field.  This is left for the caller to do.
938  */
939 int
940 extendfile(struct denode *dep, u_long count, struct buf **bpp, u_long *ncp,
941            int flags)
942 {
943         int error;
944         u_long frcn;
945         u_long cn, got;
946         struct msdosfsmount *pmp = dep->de_pmp;
947         struct buf *bp;
948
949         /*
950          * Don't try to extend the root directory
951          */
952         if (dep->de_StartCluster == MSDOSFSROOT
953             && (dep->de_Attributes & ATTR_DIRECTORY)) {
954                 kprintf("extendfile(): attempt to extend root directory\n");
955                 return (ENOSPC);
956         }
957
958         /*
959          * If the "file's last cluster" cache entry is empty, and the file
960          * is not empty, then fill the cache entry by calling pcbmap().
961          */
962         fc_fileextends++;
963         if (dep->de_fc[FC_LASTFC].fc_frcn == FCE_EMPTY &&
964             dep->de_StartCluster != 0) {
965                 fc_lfcempty++;
966                 error = pcbmap(dep, 0xffff, NULL, &cn, NULL);
967                 /* we expect it to return E2BIG */
968                 if (error != E2BIG)
969                         return (error);
970         }
971
972         while (count > 0) {
973                 /*
974                  * Allocate a new cluster chain and cat onto the end of the
975                  * file.  * If the file is empty we make de_StartCluster point
976                  * to the new block.  Note that de_StartCluster being 0 is
977                  * sufficient to be sure the file is empty since we exclude
978                  * attempts to extend the root directory above, and the root
979                  * dir is the only file with a startcluster of 0 that has
980                  * blocks allocated (sort of).
981                  */
982                 if (dep->de_StartCluster == 0)
983                         cn = 0;
984                 else
985                         cn = dep->de_fc[FC_LASTFC].fc_fsrcn + 1;
986                 error = clusteralloc(pmp, cn, count, CLUST_EOFE, &cn, &got);
987                 if (error)
988                         return (error);
989
990                 count -= got;
991
992                 /*
993                  * Give them the filesystem relative cluster number if they want
994                  * it.
995                  */
996                 if (ncp) {
997                         *ncp = cn;
998                         ncp = NULL;
999                 }
1000
1001                 if (dep->de_StartCluster == 0) {
1002                         dep->de_StartCluster = cn;
1003                         frcn = 0;
1004                 } else {
1005                         error = fatentry(FAT_SET, pmp,
1006                                          dep->de_fc[FC_LASTFC].fc_fsrcn,
1007                                          0, cn);
1008                         if (error) {
1009                                 clusterfree(pmp, cn, NULL);
1010                                 return (error);
1011                         }
1012                         frcn = dep->de_fc[FC_LASTFC].fc_frcn + 1;
1013                 }
1014
1015                 /*
1016                  * Update the "last cluster of the file" entry in the
1017                  * denode's fat cache.
1018                  */
1019                 fc_setcache(dep, FC_LASTFC, frcn + got - 1, cn + got - 1);
1020
1021                 if (flags & DE_CLEAR) {
1022                         while (got-- > 0) {
1023                                 /*
1024                                  * Get the buf header for the new block of the file.
1025                                  */
1026                                 if (dep->de_Attributes & ATTR_DIRECTORY) {
1027                                         bp = getblk(pmp->pm_devvp,
1028                                                     xcntodoff(pmp, cn),
1029                                                     pmp->pm_bpcluster, 0, 0);
1030                                         ++cn;
1031                                 } else {
1032                                         daddr_t dblkno;
1033
1034                                         bp = getblk(DETOV(dep),
1035                                                     de_cn2doff(pmp, frcn),
1036                                                     pmp->pm_bpcluster, 0, 0);
1037                                         ++frcn;
1038                                         /*
1039                                          * Do the bmap now, as in msdosfs_write
1040                                          */
1041                                         if (pcbmap(dep,
1042                                             de_bn2cn(pmp, de_off2bn(pmp, bp->b_bio1.bio_offset)),
1043                                             &dblkno, NULL, NULL)) {
1044                                                 bp->b_bio2.bio_offset = NOOFFSET;
1045                                         } else {
1046                                                 bp->b_bio2.bio_offset = de_bntodoff(pmp, dblkno);
1047                                         }
1048                                         if (bp->b_bio2.bio_offset == NOOFFSET)
1049                                                 panic("extendfile: pcbmap");
1050                                 }
1051                                 clrbuf(bp);
1052                                 if (bpp) {
1053                                         *bpp = bp;
1054                                         bpp = NULL;
1055                                 } else
1056                                         bdwrite(bp);
1057                         }
1058                 }
1059         }
1060
1061         return (0);
1062 }