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