Home | History | Annotate | Line # | Download | only in fsck_lfs
      1 /* $NetBSD: lfs.c,v 1.76 2025/10/12 01:44:26 perseant Exp $ */
      2 /*-
      3  * Copyright (c) 2003 The NetBSD Foundation, Inc.
      4  * All rights reserved.
      5  *
      6  * This code is derived from software contributed to The NetBSD Foundation
      7  * by Konrad E. Schroder <perseant (at) hhhh.org>.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  *
     18  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     19  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     20  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     21  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     22  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     28  * POSSIBILITY OF SUCH DAMAGE.
     29  */
     30 /*
     31  * Copyright (c) 1989, 1991, 1993
     32  *	The Regents of the University of California.  All rights reserved.
     33  * (c) UNIX System Laboratories, Inc.
     34  * All or some portions of this file are derived from material licensed
     35  * to the University of California by American Telephone and Telegraph
     36  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     37  * the permission of UNIX System Laboratories, Inc.
     38  *
     39  * Redistribution and use in source and binary forms, with or without
     40  * modification, are permitted provided that the following conditions
     41  * are met:
     42  * 1. Redistributions of source code must retain the above copyright
     43  *    notice, this list of conditions and the following disclaimer.
     44  * 2. Redistributions in binary form must reproduce the above copyright
     45  *    notice, this list of conditions and the following disclaimer in the
     46  *    documentation and/or other materials provided with the distribution.
     47  * 3. Neither the name of the University nor the names of its contributors
     48  *    may be used to endorse or promote products derived from this software
     49  *    without specific prior written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     61  * SUCH DAMAGE.
     62  *
     63  *	@(#)ufs_bmap.c	8.8 (Berkeley) 8/11/95
     64  */
     65 
     66 
     67 #include <sys/types.h>
     68 #include <sys/param.h>
     69 #include <sys/time.h>
     70 #include <sys/buf.h>
     71 #include <sys/mount.h>
     72 
     73 #define vnode uvnode
     74 #include <ufs/lfs/lfs.h>
     75 #include <ufs/lfs/lfs_inode.h>
     76 #include <ufs/lfs/lfs_accessors.h>
     77 #undef vnode
     78 
     79 #include <assert.h>
     80 #include <err.h>
     81 #include <errno.h>
     82 #include <stdarg.h>
     83 #include <stdbool.h>
     84 #include <stdio.h>
     85 #include <stdlib.h>
     86 #include <string.h>
     87 #include <unistd.h>
     88 #include <util.h>
     89 
     90 #include "bufcache.h"
     91 #include "extern.h"
     92 #include "lfs_user.h"
     93 #include "segwrite.h"
     94 #include "kernelops.h"
     95 
     96 #define panic call_panic
     97 
     98 long dev_bsize = DEV_BSIZE;
     99 
    100 static int
    101 lfs_fragextend(struct uvnode *, int, int, daddr_t, struct ubuf **);
    102 
    103 int fsdirty = 0;
    104 void (*panic_func)(int, const char *, va_list) = my_vpanic;
    105 
    106 /*
    107  * LFS buffer and uvnode operations
    108  */
    109 
    110 int
    111 lfs_vop_strategy(struct ubuf * bp)
    112 {
    113 	int count;
    114 
    115 	if (bp->b_flags & B_READ) {
    116 		count = kops.ko_pread(bp->b_vp->v_fd, bp->b_data, bp->b_bcount,
    117 		    bp->b_blkno * dev_bsize);
    118 		if (count == bp->b_bcount)
    119 			bp->b_flags |= B_DONE;
    120 	} else {
    121 		count = kops.ko_pwrite(bp->b_vp->v_fd, bp->b_data, bp->b_bcount,
    122 		    bp->b_blkno * dev_bsize);
    123 		if (count == 0) {
    124 			perror("pwrite");
    125 			return -1;
    126 		}
    127 		bp->b_flags &= ~B_DELWRI;
    128 		reassignbuf(bp, bp->b_vp);
    129 	}
    130 	return 0;
    131 }
    132 
    133 int
    134 lfs_vop_bwrite(struct ubuf * bp)
    135 {
    136 	struct lfs *fs;
    137 
    138 	fs = bp->b_vp->v_fs;
    139 	if (!(bp->b_flags & B_DELWRI)) {
    140 		lfs_sb_subavail(fs, lfs_btofsb(fs, bp->b_bcount));
    141 	}
    142 	bp->b_flags |= B_DELWRI | B_LOCKED;
    143 	reassignbuf(bp, bp->b_vp);
    144 	brelse(bp, 0);
    145 	return 0;
    146 }
    147 
    148 /*
    149  * ulfs_bmaparray does the bmap conversion, and if requested returns the
    150  * array of logical blocks which must be traversed to get to a block.
    151  * Each entry contains the offset into that block that gets you to the
    152  * next block and the disk address of the block (if it is assigned).
    153  */
    154 int
    155 ulfs_bmaparray(struct lfs * fs, struct uvnode * vp, daddr_t bn, daddr_t * bnp, struct indir * ap, int *nump)
    156 {
    157 	struct inode *ip;
    158 	struct ubuf *bp;
    159 	struct indir a[ULFS_NIADDR + 1], *xap;
    160 	daddr_t daddr;
    161 	daddr_t metalbn;
    162 	int error, num;
    163 
    164 	ip = VTOI(vp);
    165 
    166 	if (bn >= 0 && bn < ULFS_NDADDR) {
    167 		if (nump != NULL)
    168 			*nump = 0;
    169 		*bnp = LFS_FSBTODB(fs, lfs_dino_getdb(fs, ip->i_din, bn));
    170 		if (*bnp == 0)
    171 			*bnp = -1;
    172 		return (0);
    173 	}
    174 	xap = ap == NULL ? a : ap;
    175 	if (!nump)
    176 		nump = &num;
    177 	if ((error = ulfs_getlbns(fs, vp, bn, xap, nump)) != 0)
    178 		return (error);
    179 
    180 	num = *nump;
    181 
    182 	/* Get disk address out of indirect block array */
    183 	daddr = lfs_dino_getib(fs, ip->i_din, xap->in_off);
    184 
    185 	for (bp = NULL, ++xap; --num; ++xap) {
    186 		/* Exit the loop if there is no disk address assigned yet and
    187 		 * the indirect block isn't in the cache, or if we were
    188 		 * looking for an indirect block and we've found it. */
    189 
    190 		metalbn = xap->in_lbn;
    191 		if ((daddr == 0 && !incore(vp, metalbn)) || metalbn == bn)
    192 			break;
    193 		/*
    194 		 * If we get here, we've either got the block in the cache
    195 		 * or we have a disk address for it, go fetch it.
    196 		 */
    197 		if (bp)
    198 			brelse(bp, 0);
    199 
    200 		xap->in_exists = 1;
    201 		bp = getblk(vp, metalbn, lfs_sb_getbsize(fs));
    202 
    203 		if (!(bp->b_flags & (B_DONE | B_DELWRI))) {
    204 			bp->b_blkno = LFS_FSBTODB(fs, daddr);
    205 			bp->b_flags |= B_READ;
    206 			VOP_STRATEGY(bp);
    207 		}
    208 		daddr = lfs_iblock_get(fs, bp->b_data, xap->in_off);
    209 	}
    210 	if (bp)
    211 		brelse(bp, 0);
    212 
    213 	daddr = LFS_FSBTODB(fs, daddr);
    214 	*bnp = daddr == 0 ? -1 : daddr;
    215 	return (0);
    216 }
    217 
    218 /*
    219  * Create an array of logical block number/offset pairs which represent the
    220  * path of indirect blocks required to access a data block.  The first "pair"
    221  * contains the logical block number of the appropriate single, double or
    222  * triple indirect block and the offset into the inode indirect block array.
    223  * Note, the logical block number of the inode single/double/triple indirect
    224  * block appears twice in the array, once with the offset into di_ib and
    225  * once with the offset into the page itself.
    226  */
    227 int
    228 ulfs_getlbns(struct lfs * fs, struct uvnode * vp, daddr_t bn, struct indir * ap, int *nump)
    229 {
    230 	daddr_t metalbn, realbn;
    231 	int64_t blockcnt;
    232 	int lbc;
    233 	int i, numlevels, off;
    234 	int lognindir, indir;
    235 
    236 	metalbn = 0;    /* XXXGCC -Wuninitialized [sh3] */
    237 
    238 	if (nump)
    239 		*nump = 0;
    240 	numlevels = 0;
    241 	realbn = bn;
    242 	if (bn < 0)
    243 		bn = -bn;
    244 
    245 	lognindir = -1;
    246 	for (indir = lfs_sb_getnindir(fs); indir; indir >>= 1)
    247 		++lognindir;
    248 
    249 	/* Determine the number of levels of indirection.  After this loop is
    250 	 * done, blockcnt indicates the number of data blocks possible at the
    251 	 * given level of indirection, and ULFS_NIADDR - i is the number of levels
    252 	 * of indirection needed to locate the requested block. */
    253 
    254 	bn -= ULFS_NDADDR;
    255 	for (lbc = 0, i = ULFS_NIADDR;; i--, bn -= blockcnt) {
    256 		if (i == 0)
    257 			return (EFBIG);
    258 
    259 		lbc += lognindir;
    260 		blockcnt = (int64_t) 1 << lbc;
    261 
    262 		if (bn < blockcnt)
    263 			break;
    264 	}
    265 
    266 	/* Calculate the address of the first meta-block. */
    267 	metalbn = -((realbn >= 0 ? realbn : -realbn) - bn + ULFS_NIADDR - i);
    268 
    269 	/* At each iteration, off is the offset into the bap array which is an
    270 	 * array of disk addresses at the current level of indirection. The
    271 	 * logical block number and the offset in that block are stored into
    272 	 * the argument array. */
    273 	ap->in_lbn = metalbn;
    274 	ap->in_off = off = ULFS_NIADDR - i;
    275 	ap->in_exists = 0;
    276 	ap++;
    277 	for (++numlevels; i <= ULFS_NIADDR; i++) {
    278 		/* If searching for a meta-data block, quit when found. */
    279 		if (metalbn == realbn)
    280 			break;
    281 
    282 		lbc -= lognindir;
    283 		/*blockcnt = (int64_t) 1 << lbc;*/
    284 		off = (bn >> lbc) & (lfs_sb_getnindir(fs) - 1);
    285 
    286 		++numlevels;
    287 		ap->in_lbn = metalbn;
    288 		ap->in_off = off;
    289 		ap->in_exists = 0;
    290 		++ap;
    291 
    292 		metalbn -= -1 + (off << lbc);
    293 	}
    294 	if (nump)
    295 		*nump = numlevels;
    296 	return (0);
    297 }
    298 
    299 int
    300 lfs_vop_bmap(struct uvnode * vp, daddr_t lbn, daddr_t * daddrp)
    301 {
    302 	return ulfs_bmaparray(vp->v_fs, vp, lbn, daddrp, NULL, NULL);
    303 }
    304 
    305 /* Search a block for a specific dinode. */
    306 union lfs_dinode *
    307 lfs_ifind(struct lfs *fs, ino_t ino, struct ubuf *bp)
    308 {
    309 	union lfs_dinode *ldip;
    310 	unsigned i, num;
    311 
    312 	num = LFS_INOPB(fs);
    313 
    314 	/*
    315 	 * Read the inode block backwards, since later versions of the
    316 	 * inode will supercede earlier ones.  Though it is unlikely, it is
    317 	 * possible that the same inode will appear in the same inode block.
    318 	 */
    319 	for (i = num; i-- > 0; ) {
    320 		ldip = DINO_IN_BLOCK(fs, bp->b_data, i);
    321 		if (lfs_dino_getinumber(fs, ldip) == ino)
    322 			return (ldip);
    323 	}
    324 	return NULL;
    325 }
    326 
    327 /*
    328  * lfs_raw_vget makes us a new vnode from the inode at the given disk address.
    329  * XXX it currently loses atime information.
    330  */
    331 struct uvnode *
    332 lfs_raw_vget(struct lfs * fs, ino_t ino, int fd, daddr_t daddr)
    333 {
    334 	struct uvnode *vp;
    335 	struct inode *ip;
    336 	union lfs_dinode *dip;
    337 	struct ubuf *bp;
    338 	int i, hash;
    339 
    340 	vp = ecalloc(1, sizeof(*vp));
    341 	vp->v_fd = fd;
    342 	vp->v_fs = fs;
    343 	vp->v_usecount = 0;
    344 	vp->v_strategy_op = lfs_vop_strategy;
    345 	vp->v_bwrite_op = lfs_vop_bwrite;
    346 	vp->v_bmap_op = lfs_vop_bmap;
    347 	LIST_INIT(&vp->v_cleanblkhd);
    348 	LIST_INIT(&vp->v_dirtyblkhd);
    349 
    350 	ip = ecalloc(1, sizeof(*ip));
    351 
    352 	ip->i_din = dip = ecalloc(1, sizeof(*dip));
    353 
    354 	/* Initialize the inode -- from lfs_vcreate. */
    355 	ip->inode_ext.lfs = ecalloc(1, sizeof(*ip->inode_ext.lfs));
    356 	vp->v_data = ip;
    357 	/* ip->i_vnode = vp; */
    358 	ip->i_lockf = 0;
    359 	ip->i_state = 0;
    360 
    361 	/* Load inode block and find inode */
    362 	if (daddr > 0) {
    363 		bread(fs->lfs_devvp, LFS_FSBTODB(fs, daddr), lfs_sb_getibsize(fs),
    364 		    0, &bp);
    365 		bp->b_flags |= B_AGE;
    366 		dip = lfs_ifind(fs, ino, bp);
    367 		if (dip == NULL) {
    368 			brelse(bp, 0);
    369 			free(ip->i_din);
    370 			free(ip->inode_ext.lfs);
    371 			free(ip);
    372 			free(vp);
    373 			return NULL;
    374 		}
    375 		lfs_copy_dinode(fs, ip->i_din, dip);
    376 		brelse(bp, 0);
    377 	}
    378 	ip->i_number = ino;
    379 	/* ip->i_devvp = fs->lfs_devvp; */
    380 	ip->i_lfs = fs;
    381 
    382 	ip->i_lfs_effnblks = lfs_dino_getblocks(fs, ip->i_din);
    383 	ip->i_lfs_osize = lfs_dino_getsize(fs, ip->i_din);
    384 #if 0
    385 	if (lfs_sb_getversion(fs) > 1) {
    386 		lfs_dino_setatime(fs, ip->i_din, ts.tv_sec);
    387 		lfs_dino_setatimensec(fs, ip->i_din, ts.tv_nsec);
    388 	}
    389 #endif
    390 
    391 	memset(ip->i_lfs_fragsize, 0, ULFS_NDADDR * sizeof(*ip->i_lfs_fragsize));
    392 	for (i = 0; i < ULFS_NDADDR; i++)
    393 		if (lfs_dino_getdb(fs, ip->i_din, i) != 0)
    394 			ip->i_lfs_fragsize[i] = lfs_blksize(fs, ip, i);
    395 
    396 	++nvnodes;
    397 	hash = ((int)(intptr_t)fs + ino) & (VNODE_HASH_MAX - 1);
    398 	LIST_INSERT_HEAD(&getvnodelist[hash], vp, v_getvnodes);
    399 	LIST_INSERT_HEAD(&vnodelist, vp, v_mntvnodes);
    400 
    401 	return vp;
    402 }
    403 
    404 static struct uvnode *
    405 lfs_vget(void *vfs, ino_t ino)
    406 {
    407 	struct lfs *fs = (struct lfs *)vfs;
    408 	daddr_t daddr;
    409 	struct ubuf *bp;
    410 	IFILE *ifp;
    411 
    412 	LFS_IENTRY(ifp, fs, ino, bp);
    413 	daddr = lfs_if_getdaddr(fs, ifp);
    414 	brelse(bp, 0);
    415 	if (daddr <= 0 || lfs_dtosn(fs, daddr) >= lfs_sb_getnseg(fs))
    416 		return NULL;
    417 	return lfs_raw_vget(fs, ino, fs->lfs_ivnode->v_fd, daddr);
    418 }
    419 
    420 /*
    421  * Check superblock magic number and checksum.
    422  * Sets lfs_is64 and lfs_dobyteswap.
    423  */
    424 static int
    425 check_sb(struct lfs *fs)
    426 {
    427 	u_int32_t checksum;
    428 	u_int32_t magic;
    429 
    430 	/* we can read the magic out of either the 32-bit or 64-bit dlfs */
    431 	magic = fs->lfs_dlfs_u.u_32.dlfs_magic;
    432 
    433 	switch (magic) {
    434 	    case LFS_MAGIC:
    435 		fs->lfs_is64 = false;
    436 		fs->lfs_dobyteswap = false;
    437 		break;
    438 	    case LFS_MAGIC_SWAPPED:
    439 		fs->lfs_is64 = false;
    440 		fs->lfs_dobyteswap = true;
    441 		break;
    442 	    case LFS64_MAGIC:
    443 		fs->lfs_is64 = true;
    444 		fs->lfs_dobyteswap = false;
    445 		break;
    446 	    case LFS64_MAGIC_SWAPPED:
    447 		fs->lfs_is64 = true;
    448 		fs->lfs_dobyteswap = true;
    449 		break;
    450 	    default:
    451 		printf("Superblock magic number (0x%lx) does not match "
    452 		       "any of the expected 0x%lx, 0x%lx, 0x%lx or 0x%lx\n",
    453 		       (unsigned long)magic,
    454 		       (unsigned long)LFS_MAGIC,
    455 		       (unsigned long)LFS_MAGIC_SWAPPED,
    456 		       (unsigned long)LFS64_MAGIC,
    457 		       (unsigned long)LFS64_MAGIC_SWAPPED);
    458 		return 1;
    459 	}
    460 
    461 	/* checksum */
    462 	checksum = lfs_sb_cksum(fs);
    463 	if (lfs_sb_getcksum(fs) != checksum) {
    464 		printf("Superblock checksum (%lx) does not match computed checksum (%lx)\n",
    465 		    (unsigned long) lfs_sb_getcksum(fs), (unsigned long) checksum);
    466 		return 1;
    467 	}
    468 	return 0;
    469 }
    470 
    471 /* Initialize LFS library; load superblocks and choose which to use. */
    472 struct lfs *
    473 lfs_init(int devfd, daddr_t sblkno, daddr_t idaddr, int dummy_read, int debug)
    474 {
    475 	struct uvnode *devvp;
    476 	struct ubuf *bp;
    477 	int tryalt;
    478 	struct lfs *fs, *altfs;
    479 
    480 	vfs_init();
    481 
    482 	devvp = ecalloc(1, sizeof(*devvp));
    483 	devvp->v_fs = NULL;
    484 	devvp->v_fd = devfd;
    485 	devvp->v_strategy_op = raw_vop_strategy;
    486 	devvp->v_bwrite_op = raw_vop_bwrite;
    487 	devvp->v_bmap_op = raw_vop_bmap;
    488 	LIST_INIT(&devvp->v_cleanblkhd);
    489 	LIST_INIT(&devvp->v_dirtyblkhd);
    490 
    491 	tryalt = 0;
    492 	if (dummy_read) {
    493 		if (sblkno == 0)
    494 			sblkno = LFS_LABELPAD / dev_bsize;
    495 		fs = ecalloc(1, sizeof(*fs));
    496 		fs->lfs_devvp = devvp;
    497 	} else {
    498 		if (sblkno == 0) {
    499 			sblkno = LFS_LABELPAD / dev_bsize;
    500 			tryalt = 1;
    501 		} else if (debug) {
    502 			printf("No -b flag given, not attempting to verify checkpoint\n");
    503 		}
    504 
    505 		dev_bsize = DEV_BSIZE;
    506 
    507 		(void)bread(devvp, sblkno, LFS_SBPAD, 0, &bp);
    508 		fs = ecalloc(1, sizeof(*fs));
    509 		__CTASSERT(sizeof(struct dlfs) == sizeof(struct dlfs64));
    510 		memcpy(&fs->lfs_dlfs_u, bp->b_data, sizeof(struct dlfs));
    511 		fs->lfs_devvp = devvp;
    512 		bp->b_flags |= B_INVAL;
    513 		brelse(bp, 0);
    514 
    515 		/*
    516 		 * Look at the magic number before validating the rest
    517 		 * of the superblock.  If the magic number is bad, too,
    518 		 * we don't know where to look for an alternate superblock
    519 		 * either; so bail out now.
    520 		 */
    521 		switch (fs->lfs_dlfs_u.u_32.dlfs_magic) {
    522 		case LFS_MAGIC:
    523 		case LFS_MAGIC_SWAPPED:
    524 			break;
    525 
    526 		case LFS64_MAGIC:
    527 		case LFS64_MAGIC_SWAPPED:
    528 			fs->lfs_is64 = true;
    529 			break;
    530 
    531 		default:
    532 			return NULL;
    533 		}
    534 
    535 
    536 		dev_bsize = lfs_sb_getfsize(fs) >> lfs_sb_getfsbtodb(fs);
    537 
    538 		if (tryalt) {
    539 			(void)bread(devvp, LFS_FSBTODB(fs, lfs_sb_getsboff(fs, 1)),
    540 		    	LFS_SBPAD, 0, &bp);
    541 			altfs = ecalloc(1, sizeof(*altfs));
    542 			memcpy(&altfs->lfs_dlfs_u, bp->b_data,
    543 			       sizeof(altfs->lfs_dlfs_u));
    544 			altfs->lfs_devvp = devvp;
    545 			bp->b_flags |= B_INVAL;
    546 			brelse(bp, 0);
    547 
    548 			if (check_sb(fs) || lfs_sb_getidaddr(fs) <= 0) {
    549 				if (debug)
    550 					printf("Primary superblock is no good, using first alternate\n");
    551 				free(fs);
    552 				fs = altfs;
    553 			} else {
    554 				/* If both superblocks check out, try verification */
    555 				if (check_sb(altfs)) {
    556 					if (debug)
    557 						printf("First alternate superblock is no good, using primary\n");
    558 					free(altfs);
    559 				} else {
    560 					if (lfs_verify(fs, altfs, devvp, debug) == fs) {
    561 						free(altfs);
    562 					} else {
    563 						free(fs);
    564 						fs = altfs;
    565 					}
    566 				}
    567 			}
    568 		}
    569 		if (check_sb(fs)) {
    570 			free(fs);
    571 			return NULL;
    572 		}
    573 	}
    574 
    575 	/* Compatibility */
    576 	if (lfs_sb_getversion(fs) < 2) {
    577 		lfs_sb_setsumsize(fs, LFS_V1_SUMMARY_SIZE);
    578 		lfs_sb_setibsize(fs, lfs_sb_getbsize(fs));
    579 		lfs_sb_sets0addr(fs, lfs_sb_getsboff(fs, 0));
    580 		lfs_sb_settstamp(fs, lfs_sb_getotstamp(fs));
    581 		lfs_sb_setfsbtodb(fs, 0);
    582 	}
    583 
    584 	if (!dummy_read) {
    585 		fs->lfs_suflags = emalloc(2 * sizeof(u_int32_t *));
    586 		fs->lfs_suflags[0] = emalloc(lfs_sb_getnseg(fs) * sizeof(u_int32_t));
    587 		fs->lfs_suflags[1] = emalloc(lfs_sb_getnseg(fs) * sizeof(u_int32_t));
    588 	}
    589 
    590 	if (idaddr == 0)
    591 		idaddr = lfs_sb_getidaddr(fs);
    592 	else
    593 		lfs_sb_setidaddr(fs, idaddr);
    594 	/* NB: If dummy_read!=0, idaddr==0 here so we get a fake inode. */
    595 	fs->lfs_ivnode = lfs_raw_vget(fs, LFS_IFILE_INUM,
    596 		devvp->v_fd, idaddr);
    597 	if (fs->lfs_ivnode == NULL)
    598 		return NULL;
    599 
    600 	register_vget((void *)fs, lfs_vget);
    601 
    602 	return fs;
    603 }
    604 
    605 /*
    606  * Check partial segment validity between fs->lfs_offset and the given goal.
    607  *
    608  * If goal == 0, just keep on going until the segments stop making sense,
    609  * and return the address of the last valid partial segment.
    610  *
    611  * If goal != 0, return the address of the first partial segment that failed,
    612  * or "goal" if we reached it without failure (the partial segment *at* goal
    613  * need not be valid).
    614  */
    615 daddr_t
    616 try_verify(struct lfs *osb, struct uvnode *devvp, daddr_t goal, int debug)
    617 {
    618 	daddr_t daddr, odaddr;
    619 	SEGSUM *sp;
    620 	int i, bc, hitclean;
    621 	struct ubuf *bp;
    622 	daddr_t nodirop_daddr;
    623 	u_int64_t serial;
    624 
    625 	bc = 0;
    626 	hitclean = 0;
    627 	odaddr = -1;
    628 	daddr = lfs_sb_getoffset(osb);
    629 	nodirop_daddr = daddr;
    630 	serial = lfs_sb_getserial(osb);
    631 	while (daddr != goal) {
    632 		/*
    633 		 * Don't mistakenly read a superblock, if there is one here.
    634 		 */
    635 		if (lfs_sntod(osb, lfs_dtosn(osb, daddr)) == daddr) {
    636 			if (daddr == lfs_sb_gets0addr(osb))
    637 				daddr += lfs_btofsb(osb, LFS_LABELPAD);
    638 			for (i = 0; i < LFS_MAXNUMSB; i++) {
    639 				/* XXX dholland 20150828 I think this is wrong */
    640 				if (lfs_sb_getsboff(osb, i) < daddr)
    641 					break;
    642 				if (lfs_sb_getsboff(osb, i) == daddr)
    643 					daddr += lfs_btofsb(osb, LFS_SBPAD);
    644 			}
    645 		}
    646 
    647 		/* Read in summary block */
    648 		bread(devvp, LFS_FSBTODB(osb, daddr), lfs_sb_getsumsize(osb),
    649 		    0, &bp);
    650 		sp = (SEGSUM *)bp->b_data;
    651 
    652 		/*
    653 		 * Check for a valid segment summary belonging to our fs.
    654 		 */
    655 		if (lfs_ss_getmagic(osb, sp) != SS_MAGIC ||
    656 		    lfs_ss_getident(osb, sp) != lfs_sb_getident(osb) ||
    657 		    lfs_ss_getserial(osb, sp) < serial ||	/* XXX strengthen this */
    658 		    lfs_ss_getsumsum(osb, sp) !=
    659 		            cksum((char *)sp + lfs_ss_getsumstart(osb),
    660 				  lfs_sb_getsumsize(osb) - lfs_ss_getsumstart(osb))) {
    661 			brelse(bp, 0);
    662 			if (debug) {
    663 				if (lfs_ss_getmagic(osb, sp) != SS_MAGIC)
    664 					pwarn("pseg at 0x%jx: "
    665 					      "wrong magic number\n",
    666 					      (uintmax_t)daddr);
    667 				else if (lfs_ss_getident(osb, sp) != lfs_sb_getident(osb))
    668 					pwarn("pseg at 0x%jx: "
    669 					      "expected ident %jx, got %jx\n",
    670 					      (uintmax_t)daddr,
    671 					      (uintmax_t)lfs_ss_getident(osb, sp),
    672 					      (uintmax_t)lfs_sb_getident(osb));
    673 				else if (lfs_ss_getserial(osb, sp) >= serial)
    674 					pwarn("pseg at 0x%jx: "
    675 					      "serial %d < %d\n",
    676 					      (uintmax_t)daddr,
    677 					      (int)lfs_ss_getserial(osb, sp), (int)serial);
    678 				else
    679 					pwarn("pseg at 0x%jx: "
    680 					      "summary checksum wrong\n",
    681 					      (uintmax_t)daddr);
    682 			}
    683 			break;
    684 		}
    685 		if (debug && lfs_ss_getserial(osb, sp) != serial)
    686 			pwarn("warning, serial=%d ss_serial=%d\n",
    687 				(int)serial, (int)lfs_ss_getserial(osb, sp));
    688 		++serial;
    689 		bc = check_summary(osb, sp, daddr, debug, devvp, NULL);
    690 		if (bc == 0) {
    691 			brelse(bp, 0);
    692 			break;
    693 		}
    694 		if (debug)
    695 			pwarn("summary good: 0x%jx/%d\n", (uintmax_t)daddr,
    696 			      (int)lfs_ss_getserial(osb, sp));
    697 		assert (bc > 0);
    698 		odaddr = daddr;
    699 		daddr += lfs_btofsb(osb, lfs_sb_getsumsize(osb) + bc);
    700 		if (lfs_dtosn(osb, odaddr) != lfs_dtosn(osb, daddr) ||
    701 		    lfs_dtosn(osb, daddr) != lfs_dtosn(osb, daddr +
    702 			lfs_btofsb(osb, lfs_sb_getsumsize(osb) + lfs_sb_getbsize(osb)) - 1)) {
    703 			daddr = lfs_ss_getnext(osb, sp);
    704 		}
    705 
    706 		/*
    707 		 * Check for the beginning and ending of a sequence of
    708 		 * dirops.  Writes from the cleaner never involve new
    709 		 * information, and are always checkpoints; so don't try
    710 		 * to roll forward through them.  Likewise, psegs written
    711 		 * by a previous roll-forward attempt are not interesting.
    712 		 */
    713 		if (lfs_ss_getflags(osb, sp) & (SS_CLEAN | SS_RFW))
    714 			hitclean = 1;
    715 		if (hitclean == 0 && (lfs_ss_getflags(osb, sp) & SS_CONT) == 0)
    716 			nodirop_daddr = daddr;
    717 
    718 		brelse(bp, 0);
    719 	}
    720 
    721 	if (goal == 0)
    722 		return nodirop_daddr;
    723 	else
    724 		return daddr;
    725 }
    726 
    727 /* Use try_verify to check whether the newer superblock is valid. */
    728 struct lfs *
    729 lfs_verify(struct lfs *sb0, struct lfs *sb1, struct uvnode *devvp, int debug)
    730 {
    731 	daddr_t daddr;
    732 	struct lfs *osb, *nsb;
    733 
    734 	/*
    735 	 * Verify the checkpoint of the newer superblock,
    736 	 * if the timestamp/serial number of the two superblocks is
    737 	 * different.
    738 	 */
    739 
    740 	osb = NULL;
    741 	if (debug)
    742 		pwarn("sb0 %ju, sb1 %ju",
    743 		      (uintmax_t) lfs_sb_getserial(sb0),
    744 		      (uintmax_t) lfs_sb_getserial(sb1));
    745 
    746 	if ((lfs_sb_getversion(sb0) == 1 &&
    747 		lfs_sb_getotstamp(sb0) != lfs_sb_getotstamp(sb1)) ||
    748 	    (lfs_sb_getversion(sb0) > 1 &&
    749 		lfs_sb_getserial(sb0) != lfs_sb_getserial(sb1))) {
    750 		if (lfs_sb_getversion(sb0) == 1) {
    751 			if (lfs_sb_getotstamp(sb0) > lfs_sb_getotstamp(sb1)) {
    752 				osb = sb1;
    753 				nsb = sb0;
    754 			} else {
    755 				osb = sb0;
    756 				nsb = sb1;
    757 			}
    758 		} else {
    759 			if (lfs_sb_getserial(sb0) > lfs_sb_getserial(sb1)) {
    760 				osb = sb1;
    761 				nsb = sb0;
    762 			} else {
    763 				osb = sb0;
    764 				nsb = sb1;
    765 			}
    766 		}
    767 		if (debug) {
    768 			printf("Attempting to verify newer checkpoint...");
    769 			fflush(stdout);
    770 		}
    771 		daddr = try_verify(osb, devvp, lfs_sb_getoffset(nsb), debug);
    772 
    773 		if (debug)
    774 			printf("done.\n");
    775 		if (daddr == lfs_sb_getoffset(nsb)) {
    776 			pwarn("** Newer checkpoint verified; recovered %jd seconds of data\n",
    777 			    (intmax_t)(lfs_sb_gettstamp(nsb) - lfs_sb_gettstamp(osb)));
    778 			sbdirty();
    779 		} else {
    780 			pwarn("** Newer checkpoint invalid; lost %jd seconds of data\n", (intmax_t)(lfs_sb_gettstamp(nsb) - lfs_sb_gettstamp(osb)));
    781 		}
    782 		return (daddr == lfs_sb_getoffset(nsb) ? nsb : osb);
    783 	}
    784 	/* Nothing to check */
    785 	return osb;
    786 }
    787 
    788 /* Verify a partial-segment summary; return the number of bytes on disk. */
    789 int
    790 check_summary(struct lfs *fs, SEGSUM *sp, daddr_t pseg_addr, int debug,
    791 	      struct uvnode *devvp, void (func(daddr_t, FINFO *)))
    792 {
    793 	FINFO *fp;
    794 	int bc;			/* Bytes in partial segment */
    795 	int nblocks;
    796 	daddr_t daddr;
    797 	IINFO *iibase, *iip;
    798 	struct ubuf *bp;
    799 	int i, j, k, datac, len;
    800 	lfs_checkword *datap;
    801 	u_int32_t ccksum;
    802 
    803 	/* We've already checked the sumsum, just do the data bounds and sum */
    804 
    805 	/* Count the blocks. */
    806 	nblocks = howmany(lfs_ss_getninos(fs, sp), LFS_INOPB(fs));
    807 	bc = nblocks << (lfs_sb_getversion(fs) > 1 ? lfs_sb_getffshift(fs) : lfs_sb_getbshift(fs));
    808 	assert(bc >= 0);
    809 
    810 	fp = SEGSUM_FINFOBASE(fs, sp);
    811 	for (i = 0; i < lfs_ss_getnfinfo(fs, sp); i++) {
    812 		nblocks += lfs_fi_getnblocks(fs, fp);
    813 		bc += lfs_fi_getlastlength(fs, fp) + ((lfs_fi_getnblocks(fs, fp) - 1)
    814 					   << lfs_sb_getbshift(fs));
    815 		assert(bc >= 0);
    816 		fp = NEXT_FINFO(fs, fp);
    817 		if (((char *)fp) - (char *)sp > lfs_sb_getsumsize(fs))
    818 			return 0;
    819 	}
    820 	datap = emalloc(nblocks * sizeof(*datap));
    821 	datac = 0;
    822 
    823 	iibase = SEGSUM_IINFOSTART(fs, sp);
    824 
    825 	iip = iibase;
    826 	daddr = pseg_addr + lfs_btofsb(fs, lfs_sb_getsumsize(fs));
    827 	fp = SEGSUM_FINFOBASE(fs, sp);
    828 	for (i = 0, j = 0;
    829 	     i < lfs_ss_getnfinfo(fs, sp) || j < howmany(lfs_ss_getninos(fs, sp), LFS_INOPB(fs)); i++) {
    830 		if (i >= lfs_ss_getnfinfo(fs, sp) && lfs_ii_getblock(fs, iip) != daddr) {
    831 			pwarn("Not enough inode blocks in pseg at 0x%jx: "
    832 			      "found %d, wanted %d\n",
    833 			      pseg_addr, j, howmany(lfs_ss_getninos(fs, sp),
    834 						    LFS_INOPB(fs)));
    835 			if (debug)
    836 				pwarn("iip=0x%jx, daddr=0x%jx\n",
    837 				    (uintmax_t)lfs_ii_getblock(fs, iip),
    838 				    (intmax_t)daddr);
    839 			break;
    840 		}
    841 		while (j < howmany(lfs_ss_getninos(fs, sp), LFS_INOPB(fs)) && lfs_ii_getblock(fs, iip) == daddr) {
    842 			bread(devvp, LFS_FSBTODB(fs, daddr), lfs_sb_getibsize(fs),
    843 			    0, &bp);
    844 			datap[datac++] = ((lfs_checkword *)bp->b_data)[0];
    845 			brelse(bp, 0);
    846 
    847 			++j;
    848 			daddr += lfs_btofsb(fs, lfs_sb_getibsize(fs));
    849 			iip = NEXTLOWER_IINFO(fs, iip);
    850 		}
    851 		if (i < lfs_ss_getnfinfo(fs, sp)) {
    852 			if (func)
    853 				func(daddr, fp);
    854 			for (k = 0; k < lfs_fi_getnblocks(fs, fp); k++) {
    855 				len = (k == lfs_fi_getnblocks(fs, fp) - 1 ?
    856 				       lfs_fi_getlastlength(fs, fp)
    857 				       : lfs_sb_getbsize(fs));
    858 				bread(devvp, LFS_FSBTODB(fs, daddr), len,
    859 				    0, &bp);
    860 				datap[datac++] = ((lfs_checkword *)bp->b_data)[0];
    861 				brelse(bp, 0);
    862 				daddr += lfs_btofsb(fs, len);
    863 			}
    864 			fp = NEXT_FINFO(fs, fp);
    865 		}
    866 	}
    867 
    868 	if (datac != nblocks) {
    869 		pwarn("Partial segment at 0x%jx expected %d blocks counted %d\n",
    870 		    (intmax_t)pseg_addr, nblocks, datac);
    871 	}
    872 	ccksum = cksum(datap, nblocks * sizeof(datap[0]));
    873 	/* Check the data checksum */
    874 	if (ccksum != lfs_ss_getdatasum(fs, sp)) {
    875 		pwarn("Partial segment at 0x%jx data checksum"
    876 		      " mismatch: given 0x%x, computed 0x%x\n",
    877 		      (uintmax_t)pseg_addr, lfs_ss_getdatasum(fs, sp), ccksum);
    878 		free(datap);
    879 		return 0;
    880 	}
    881 	free(datap);
    882 	assert(bc >= 0);
    883 	return bc;
    884 }
    885 
    886 /* print message and exit */
    887 void
    888 my_vpanic(int fatal, const char *fmt, va_list ap)
    889 {
    890         (void) vprintf(fmt, ap);
    891 	exit(8);
    892 }
    893 
    894 void
    895 call_panic(const char *fmt, ...)
    896 {
    897 	va_list ap;
    898 
    899 	va_start(ap, fmt);
    900         panic_func(1, fmt, ap);
    901 	va_end(ap);
    902 }
    903 
    904 /* Allocate a new inode. */
    905 struct uvnode *
    906 lfs_valloc(struct lfs *fs, ino_t ino)
    907 {
    908 	struct ubuf *bp, *cbp;
    909 	IFILE *ifp;
    910 	ino_t new_ino;
    911 	int error;
    912 	CLEANERINFO *cip;
    913 
    914 	/* Get the head of the freelist. */
    915 	LFS_GET_HEADFREE(fs, cip, cbp, &new_ino);
    916 
    917 	/*
    918 	 * Remove the inode from the free list and write the new start
    919 	 * of the free list into the superblock.
    920 	 */
    921 	LFS_IENTRY(ifp, fs, new_ino, bp);
    922 	if (lfs_if_getdaddr(fs, ifp) != LFS_UNUSED_DADDR)
    923 		panic("lfs_valloc: inuse inode %d on the free list", new_ino);
    924 	LFS_PUT_HEADFREE(fs, cip, cbp, lfs_if_getnextfree(fs, ifp));
    925 
    926 	brelse(bp, 0);
    927 
    928 	/* Extend IFILE so that the next lfs_valloc will succeed. */
    929 	if (lfs_sb_getfreehd(fs) == LFS_UNUSED_INUM) {
    930 		if ((error = extend_ifile(fs)) != 0) {
    931 			LFS_PUT_HEADFREE(fs, cip, cbp, new_ino);
    932 			return NULL;
    933 		}
    934 	}
    935 
    936 	/* Set superblock modified bit and increment file count. */
    937         sbdirty();
    938 	lfs_sb_addnfiles(fs, 1);
    939 
    940         return lfs_raw_vget(fs, ino, fs->lfs_devvp->v_fd, 0x0);
    941 }
    942 
    943 #ifdef IN_FSCK_LFS
    944 void reset_maxino(ino_t);
    945 #endif
    946 
    947 /*
    948  * Add a new block to the Ifile, to accommodate future file creations.
    949  */
    950 int
    951 extend_ifile(struct lfs *fs)
    952 {
    953 	struct uvnode *vp;
    954 	struct inode *ip;
    955 	IFILE64 *ifp64;
    956 	IFILE32 *ifp32;
    957 	IFILE_V1 *ifp_v1;
    958 	struct ubuf *bp, *cbp;
    959 	daddr_t i, blkno, max;
    960 	ino_t oldlast;
    961 	CLEANERINFO *cip;
    962 
    963 	vp = fs->lfs_ivnode;
    964 	ip = VTOI(vp);
    965 	blkno = lfs_lblkno(fs, lfs_dino_getsize(fs, ip->i_din));
    966 
    967 	lfs_balloc(vp, lfs_dino_getsize(fs, ip->i_din), lfs_sb_getbsize(fs), &bp);
    968 	lfs_dino_setsize(fs, ip->i_din,
    969 	    lfs_dino_getsize(fs, ip->i_din) + lfs_sb_getbsize(fs));
    970 	ip->i_state |= IN_MODIFIED;
    971 
    972 	i = (blkno - lfs_sb_getsegtabsz(fs) - lfs_sb_getcleansz(fs)) *
    973 		lfs_sb_getifpb(fs);
    974 	LFS_GET_HEADFREE(fs, cip, cbp, &oldlast);
    975 	LFS_PUT_HEADFREE(fs, cip, cbp, i);
    976 	max = i + lfs_sb_getifpb(fs);
    977 	lfs_sb_subbfree(fs, lfs_btofsb(fs, lfs_sb_getbsize(fs)));
    978 
    979 	if (fs->lfs_is64) {
    980 		for (ifp64 = (IFILE64 *)bp->b_data; i < max; ++ifp64) {
    981 			ifp64->if_version = 1;
    982 			ifp64->if_daddr = LFS_UNUSED_DADDR;
    983 			ifp64->if_nextfree = ++i;
    984 		}
    985 		ifp64--;
    986 		ifp64->if_nextfree = oldlast;
    987 	} else if (lfs_sb_getversion(fs) > 1) {
    988 		for (ifp32 = (IFILE32 *)bp->b_data; i < max; ++ifp32) {
    989 			ifp32->if_version = 1;
    990 			ifp32->if_daddr = LFS_UNUSED_DADDR;
    991 			ifp32->if_nextfree = ++i;
    992 		}
    993 		ifp32--;
    994 		ifp32->if_nextfree = oldlast;
    995 	} else {
    996 		for (ifp_v1 = (IFILE_V1 *)bp->b_data; i < max; ++ifp_v1) {
    997 			ifp_v1->if_version = 1;
    998 			ifp_v1->if_daddr = LFS_UNUSED_DADDR;
    999 			ifp_v1->if_nextfree = ++i;
   1000 		}
   1001 		ifp_v1--;
   1002 		ifp_v1->if_nextfree = oldlast;
   1003 	}
   1004 	LFS_PUT_TAILFREE(fs, cip, cbp, max - 1);
   1005 
   1006 	LFS_BWRITE_LOG(bp);
   1007 
   1008 #ifdef IN_FSCK_LFS
   1009 	reset_maxino(((lfs_dino_getsize(fs, ip->i_din) >> lfs_sb_getbshift(fs))
   1010 		      - lfs_sb_getsegtabsz(fs)
   1011 		      - lfs_sb_getcleansz(fs)) * lfs_sb_getifpb(fs));
   1012 #endif
   1013 	return 0;
   1014 }
   1015 
   1016 /*
   1017  * Allocate a block, and to inode and filesystem block accounting for it
   1018  * and for any indirect blocks the may need to be created in order for
   1019  * this block to be created.
   1020  *
   1021  * Blocks which have never been accounted for (i.e., which "do not exist")
   1022  * have disk address 0, which is translated by ulfs_bmap to the special value
   1023  * UNASSIGNED == -1, as in the historical ULFS.
   1024  *
   1025  * Blocks which have been accounted for but which have not yet been written
   1026  * to disk are given the new special disk address UNWRITTEN == -2, so that
   1027  * they can be differentiated from completely new blocks.
   1028  */
   1029 int
   1030 lfs_balloc(struct uvnode *vp, off_t startoffset, int iosize, struct ubuf **bpp)
   1031 {
   1032 	int offset;
   1033 	daddr_t daddr, idaddr;
   1034 	struct ubuf *ibp, *bp;
   1035 	struct inode *ip;
   1036 	struct lfs *fs;
   1037 	struct indir indirs[ULFS_NIADDR+2], *idp;
   1038 	daddr_t	lbn, lastblock;
   1039 	int bcount;
   1040 	int error, frags, i, nsize, osize, num;
   1041 
   1042 	ip = VTOI(vp);
   1043 	fs = ip->i_lfs;
   1044 	offset = lfs_blkoff(fs, startoffset);
   1045 	lbn = lfs_lblkno(fs, startoffset);
   1046 
   1047 	/*
   1048 	 * Three cases: it's a block beyond the end of file, it's a block in
   1049 	 * the file that may or may not have been assigned a disk address or
   1050 	 * we're writing an entire block.
   1051 	 *
   1052 	 * Note, if the daddr is UNWRITTEN, the block already exists in
   1053 	 * the cache (it was read or written earlier).	If so, make sure
   1054 	 * we don't count it as a new block or zero out its contents. If
   1055 	 * it did not, make sure we allocate any necessary indirect
   1056 	 * blocks.
   1057 	 *
   1058 	 * If we are writing a block beyond the end of the file, we need to
   1059 	 * check if the old last block was a fragment.	If it was, we need
   1060 	 * to rewrite it.
   1061 	 */
   1062 
   1063 	if (bpp)
   1064 		*bpp = NULL;
   1065 
   1066 	/* Check for block beyond end of file and fragment extension needed. */
   1067 	lastblock = lfs_lblkno(fs, lfs_dino_getsize(fs, ip->i_din));
   1068 	if (lastblock < ULFS_NDADDR && lastblock < lbn) {
   1069 		osize = lfs_blksize(fs, ip, lastblock);
   1070 		if (osize < lfs_sb_getbsize(fs) && osize > 0) {
   1071 			if ((error = lfs_fragextend(vp, osize, lfs_sb_getbsize(fs),
   1072 						    lastblock,
   1073 						    (bpp ? &bp : NULL))))
   1074 				return (error);
   1075 			lfs_dino_setsize(fs, ip->i_din, (lastblock + 1) * lfs_sb_getbsize(fs));
   1076 			ip->i_state |= IN_CHANGE | IN_UPDATE;
   1077 			if (bpp)
   1078 				(void) VOP_BWRITE(bp);
   1079 		}
   1080 	}
   1081 
   1082 	/*
   1083 	 * If the block we are writing is a direct block, it's the last
   1084 	 * block in the file, and offset + iosize is less than a full
   1085 	 * block, we can write one or more fragments.  There are two cases:
   1086 	 * the block is brand new and we should allocate it the correct
   1087 	 * size or it already exists and contains some fragments and
   1088 	 * may need to extend it.
   1089 	 */
   1090 	if (lbn < ULFS_NDADDR && lfs_lblkno(fs, lfs_dino_getsize(fs, ip->i_din)) <= lbn) {
   1091 		osize = lfs_blksize(fs, ip, lbn);
   1092 		nsize = lfs_fragroundup(fs, offset + iosize);
   1093 		if (lfs_lblktosize(fs, lbn) >= lfs_dino_getsize(fs, ip->i_din)) {
   1094 			/* Brand new block or fragment */
   1095 			frags = lfs_numfrags(fs, nsize);
   1096 			if (bpp) {
   1097 				*bpp = bp = getblk(vp, lbn, nsize);
   1098 				bp->b_blkno = UNWRITTEN;
   1099 			}
   1100 			ip->i_lfs_effnblks += frags;
   1101 			lfs_sb_subbfree(fs, frags);
   1102 			lfs_dino_setdb(fs, ip->i_din, lbn, UNWRITTEN);
   1103 		} else {
   1104 			if (nsize <= osize) {
   1105 				/* No need to extend */
   1106 				if (bpp && (error = bread(vp, lbn, osize,
   1107 				    0, &bp)))
   1108 					return error;
   1109 			} else {
   1110 				/* Extend existing block */
   1111 				if ((error =
   1112 				     lfs_fragextend(vp, osize, nsize, lbn,
   1113 						    (bpp ? &bp : NULL))))
   1114 					return error;
   1115 			}
   1116 			if (bpp)
   1117 				*bpp = bp;
   1118 		}
   1119 		return 0;
   1120 	}
   1121 
   1122 	error = ulfs_bmaparray(fs, vp, lbn, &daddr, &indirs[0], &num);
   1123 	if (error)
   1124 		return (error);
   1125 
   1126 	/*
   1127 	 * Do byte accounting all at once, so we can gracefully fail *before*
   1128 	 * we start assigning blocks.
   1129 	 */
   1130         frags = LFS_FSBTODB(fs, 1); /* frags = VFSTOULFS(vp->v_mount)->um_seqinc; */
   1131 	bcount = 0;
   1132 	if (daddr == UNASSIGNED) {
   1133 		bcount = frags;
   1134 	}
   1135 	for (i = 1; i < num; ++i) {
   1136 		if (!indirs[i].in_exists) {
   1137 			bcount += frags;
   1138 		}
   1139 	}
   1140 	lfs_sb_subbfree(fs, bcount);
   1141 	ip->i_lfs_effnblks += bcount;
   1142 
   1143 	if (daddr == UNASSIGNED) {
   1144 		if (num > 0 && lfs_dino_getib(fs, ip->i_din, indirs[0].in_off) == 0) {
   1145 			lfs_dino_setib(fs, ip->i_din, indirs[0].in_off,
   1146 				       UNWRITTEN);
   1147 		}
   1148 
   1149 		/*
   1150 		 * Create new indirect blocks if necessary
   1151 		 */
   1152 		if (num > 1) {
   1153 			idaddr = lfs_dino_getib(fs, ip->i_din, indirs[0].in_off);
   1154 			for (i = 1; i < num; ++i) {
   1155 				ibp = getblk(vp, indirs[i].in_lbn,
   1156 				    lfs_sb_getbsize(fs));
   1157 				if (!indirs[i].in_exists) {
   1158 					memset(ibp->b_data, 0, ibp->b_bufsize);
   1159 					ibp->b_blkno = UNWRITTEN;
   1160 				} else if (!(ibp->b_flags & (B_DELWRI | B_DONE))) {
   1161 					ibp->b_blkno = LFS_FSBTODB(fs, idaddr);
   1162 					ibp->b_flags |= B_READ;
   1163 					VOP_STRATEGY(ibp);
   1164 				}
   1165 				/*
   1166 				 * This block exists, but the next one may not.
   1167 				 * If that is the case mark it UNWRITTEN to
   1168                                  * keep the accounting straight.
   1169 				 */
   1170 				if (lfs_iblock_get(fs, ibp->b_data,
   1171 						indirs[i].in_off) == 0)
   1172 					lfs_iblock_set(fs, ibp->b_data,
   1173 						indirs[i].in_off, UNWRITTEN);
   1174 				idaddr = lfs_iblock_get(fs, ibp->b_data,
   1175 						indirs[i].in_off);
   1176 				if ((error = VOP_BWRITE(ibp)))
   1177 					return error;
   1178 			}
   1179 		}
   1180 	}
   1181 
   1182 
   1183 	/*
   1184 	 * Get the existing block from the cache, if requested.
   1185 	 */
   1186 	if (bpp)
   1187 		*bpp = bp = getblk(vp, lbn, lfs_blksize(fs, ip, lbn));
   1188 
   1189 	/*
   1190 	 * The block we are writing may be a brand new block
   1191 	 * in which case we need to do accounting.
   1192 	 *
   1193 	 * We can tell a truly new block because ulfs_bmaparray will say
   1194 	 * it is UNASSIGNED.  Once we allocate it we will assign it the
   1195 	 * disk address UNWRITTEN.
   1196 	 */
   1197 	if (daddr == UNASSIGNED) {
   1198 		if (bpp) {
   1199 			/* Note the new address */
   1200 			bp->b_blkno = UNWRITTEN;
   1201 		}
   1202 
   1203 		switch (num) {
   1204 		    case 0:
   1205 			lfs_dino_setdb(fs, ip->i_din, lbn, UNWRITTEN);
   1206 			break;
   1207 		    case 1:
   1208 			lfs_dino_setib(fs, ip->i_din, indirs[0].in_off,
   1209 				       UNWRITTEN);
   1210 			break;
   1211 		    default:
   1212 			idp = &indirs[num - 1];
   1213 			if (bread(vp, idp->in_lbn, lfs_sb_getbsize(fs), 0, &ibp))
   1214 				panic("lfs_balloc: bread bno %lld",
   1215 				    (long long)idp->in_lbn);
   1216 			lfs_iblock_set(fs, ibp->b_data, idp->in_off,
   1217 				       UNWRITTEN);
   1218 			VOP_BWRITE(ibp);
   1219 		}
   1220 	} else if (bpp && !(bp->b_flags & (B_DONE|B_DELWRI))) {
   1221 		/*
   1222 		 * Not a brand new block, also not in the cache;
   1223 		 * read it in from disk.
   1224 		 */
   1225 		if (iosize == lfs_sb_getbsize(fs))
   1226 			/* Optimization: I/O is unnecessary. */
   1227 			bp->b_blkno = daddr;
   1228 		else {
   1229 			/*
   1230 			 * We need to read the block to preserve the
   1231 			 * existing bytes.
   1232 			 */
   1233 			bp->b_blkno = daddr;
   1234 			bp->b_flags |= B_READ;
   1235 			VOP_STRATEGY(bp);
   1236 			return 0;
   1237 		}
   1238 	}
   1239 
   1240 	return (0);
   1241 }
   1242 
   1243 int
   1244 lfs_fragextend(struct uvnode *vp, int osize, int nsize, daddr_t lbn,
   1245                struct ubuf **bpp)
   1246 {
   1247 	struct inode *ip;
   1248 	struct lfs *fs;
   1249 	int frags;
   1250 	int error;
   1251 
   1252 	ip = VTOI(vp);
   1253 	fs = ip->i_lfs;
   1254 	frags = (long)lfs_numfrags(fs, nsize - osize);
   1255 	error = 0;
   1256 
   1257 	/*
   1258 	 * If we are not asked to actually return the block, all we need
   1259 	 * to do is allocate space for it.  UBC will handle dirtying the
   1260 	 * appropriate things and making sure it all goes to disk.
   1261 	 * Don't bother to read in that case.
   1262 	 */
   1263 	if (bpp && (error = bread(vp, lbn, osize, 0, bpp))) {
   1264 		brelse(*bpp, 0);
   1265 		goto out;
   1266 	}
   1267 
   1268 	lfs_sb_subbfree(fs, frags);
   1269 	ip->i_lfs_effnblks += frags;
   1270 	ip->i_state |= IN_CHANGE | IN_UPDATE;
   1271 
   1272 	if (bpp) {
   1273 		(*bpp)->b_data = erealloc((*bpp)->b_data, nsize);
   1274 		(void)memset((*bpp)->b_data + osize, 0, nsize - osize);
   1275 	}
   1276 
   1277     out:
   1278 	return (error);
   1279 }
   1280