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