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