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