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