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