Home | History | Annotate | Line # | Download | only in fsck_lfs
      1 /* $NetBSD: lfs.c,v 1.77 2025/11/04 00:50:36 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 (idaddr == 0)
    585 		idaddr = lfs_sb_getidaddr(fs);
    586 	else
    587 		lfs_sb_setidaddr(fs, idaddr);
    588 	/* NB: If dummy_read!=0, idaddr==0 here so we get a fake inode. */
    589 	fs->lfs_ivnode = lfs_raw_vget(fs, LFS_IFILE_INUM,
    590 		devvp->v_fd, idaddr);
    591 	if (fs->lfs_ivnode == NULL)
    592 		return NULL;
    593 
    594 	register_vget((void *)fs, lfs_vget);
    595 
    596 	return fs;
    597 }
    598 
    599 /*
    600  * Check partial segment validity between fs->lfs_offset and the given goal.
    601  *
    602  * If goal == 0, just keep on going until the segments stop making sense,
    603  * and return the address of the last valid partial segment.
    604  *
    605  * If goal != 0, return the address of the first partial segment that failed,
    606  * or "goal" if we reached it without failure (the partial segment *at* goal
    607  * need not be valid).
    608  */
    609 daddr_t
    610 try_verify(struct lfs *osb, struct uvnode *devvp, daddr_t goal, int debug)
    611 {
    612 	daddr_t daddr, odaddr;
    613 	SEGSUM *sp;
    614 	int i, bc, hitclean;
    615 	struct ubuf *bp;
    616 	daddr_t nodirop_daddr;
    617 	u_int64_t serial;
    618 
    619 	bc = 0;
    620 	hitclean = 0;
    621 	odaddr = -1;
    622 	daddr = lfs_sb_getoffset(osb);
    623 	nodirop_daddr = daddr;
    624 	serial = lfs_sb_getserial(osb);
    625 	while (daddr != goal) {
    626 		/*
    627 		 * Don't mistakenly read a superblock, if there is one here.
    628 		 */
    629 		if (lfs_sntod(osb, lfs_dtosn(osb, daddr)) == daddr) {
    630 			if (daddr == lfs_sb_gets0addr(osb))
    631 				daddr += lfs_btofsb(osb, LFS_LABELPAD);
    632 			for (i = 0; i < LFS_MAXNUMSB; i++) {
    633 				/* XXX dholland 20150828 I think this is wrong */
    634 				if (lfs_sb_getsboff(osb, i) < daddr)
    635 					break;
    636 				if (lfs_sb_getsboff(osb, i) == daddr)
    637 					daddr += lfs_btofsb(osb, LFS_SBPAD);
    638 			}
    639 		}
    640 
    641 		/* Read in summary block */
    642 		bread(devvp, LFS_FSBTODB(osb, daddr), lfs_sb_getsumsize(osb),
    643 		    0, &bp);
    644 		sp = (SEGSUM *)bp->b_data;
    645 
    646 		/*
    647 		 * Check for a valid segment summary belonging to our fs.
    648 		 */
    649 		if (lfs_ss_getmagic(osb, sp) != SS_MAGIC ||
    650 		    lfs_ss_getident(osb, sp) != lfs_sb_getident(osb) ||
    651 		    lfs_ss_getserial(osb, sp) < serial ||	/* XXX strengthen this */
    652 		    lfs_ss_getsumsum(osb, sp) !=
    653 		            cksum((char *)sp + lfs_ss_getsumstart(osb),
    654 				  lfs_sb_getsumsize(osb) - lfs_ss_getsumstart(osb))) {
    655 			brelse(bp, 0);
    656 			if (debug) {
    657 				if (lfs_ss_getmagic(osb, sp) != SS_MAGIC)
    658 					pwarn("pseg at 0x%jx: "
    659 					      "wrong magic number\n",
    660 					      (uintmax_t)daddr);
    661 				else if (lfs_ss_getident(osb, sp) != lfs_sb_getident(osb))
    662 					pwarn("pseg at 0x%jx: "
    663 					      "expected ident %jx, got %jx\n",
    664 					      (uintmax_t)daddr,
    665 					      (uintmax_t)lfs_ss_getident(osb, sp),
    666 					      (uintmax_t)lfs_sb_getident(osb));
    667 				else if (lfs_ss_getserial(osb, sp) >= serial)
    668 					pwarn("pseg at 0x%jx: "
    669 					      "serial %d < %d\n",
    670 					      (uintmax_t)daddr,
    671 					      (int)lfs_ss_getserial(osb, sp), (int)serial);
    672 				else
    673 					pwarn("pseg at 0x%jx: "
    674 					      "summary checksum wrong\n",
    675 					      (uintmax_t)daddr);
    676 			}
    677 			break;
    678 		}
    679 		if (debug && lfs_ss_getserial(osb, sp) != serial)
    680 			pwarn("warning, serial=%d ss_serial=%d\n",
    681 				(int)serial, (int)lfs_ss_getserial(osb, sp));
    682 		++serial;
    683 		bc = check_summary(osb, sp, daddr, debug, devvp, NULL);
    684 		if (bc == 0) {
    685 			brelse(bp, 0);
    686 			break;
    687 		}
    688 		if (debug)
    689 			pwarn("summary good: 0x%jx/%d\n", (uintmax_t)daddr,
    690 			      (int)lfs_ss_getserial(osb, sp));
    691 		assert (bc > 0);
    692 		odaddr = daddr;
    693 		daddr += lfs_btofsb(osb, lfs_sb_getsumsize(osb) + bc);
    694 		if (lfs_dtosn(osb, odaddr) != lfs_dtosn(osb, daddr) ||
    695 		    lfs_dtosn(osb, daddr) != lfs_dtosn(osb, daddr +
    696 			lfs_btofsb(osb, lfs_sb_getsumsize(osb) + lfs_sb_getbsize(osb)) - 1)) {
    697 			daddr = lfs_ss_getnext(osb, sp);
    698 		}
    699 
    700 		/*
    701 		 * Check for the beginning and ending of a sequence of
    702 		 * dirops.  Writes from the cleaner never involve new
    703 		 * information, and are always checkpoints; so don't try
    704 		 * to roll forward through them.  Likewise, psegs written
    705 		 * by a previous roll-forward attempt are not interesting.
    706 		 */
    707 		if (lfs_ss_getflags(osb, sp) & (SS_CLEAN | SS_RFW))
    708 			hitclean = 1;
    709 		if (hitclean == 0 && (lfs_ss_getflags(osb, sp) & SS_CONT) == 0)
    710 			nodirop_daddr = daddr;
    711 
    712 		brelse(bp, 0);
    713 	}
    714 
    715 	if (goal == 0)
    716 		return nodirop_daddr;
    717 	else
    718 		return daddr;
    719 }
    720 
    721 /* Use try_verify to check whether the newer superblock is valid. */
    722 struct lfs *
    723 lfs_verify(struct lfs *sb0, struct lfs *sb1, struct uvnode *devvp, int debug)
    724 {
    725 	daddr_t daddr;
    726 	struct lfs *osb, *nsb;
    727 
    728 	/*
    729 	 * Verify the checkpoint of the newer superblock,
    730 	 * if the timestamp/serial number of the two superblocks is
    731 	 * different.
    732 	 */
    733 
    734 	osb = NULL;
    735 	if (debug)
    736 		pwarn("sb0 %ju, sb1 %ju",
    737 		      (uintmax_t) lfs_sb_getserial(sb0),
    738 		      (uintmax_t) lfs_sb_getserial(sb1));
    739 
    740 	if ((lfs_sb_getversion(sb0) == 1 &&
    741 		lfs_sb_getotstamp(sb0) != lfs_sb_getotstamp(sb1)) ||
    742 	    (lfs_sb_getversion(sb0) > 1 &&
    743 		lfs_sb_getserial(sb0) != lfs_sb_getserial(sb1))) {
    744 		if (lfs_sb_getversion(sb0) == 1) {
    745 			if (lfs_sb_getotstamp(sb0) > lfs_sb_getotstamp(sb1)) {
    746 				osb = sb1;
    747 				nsb = sb0;
    748 			} else {
    749 				osb = sb0;
    750 				nsb = sb1;
    751 			}
    752 		} else {
    753 			if (lfs_sb_getserial(sb0) > lfs_sb_getserial(sb1)) {
    754 				osb = sb1;
    755 				nsb = sb0;
    756 			} else {
    757 				osb = sb0;
    758 				nsb = sb1;
    759 			}
    760 		}
    761 		if (debug) {
    762 			printf("Attempting to verify newer checkpoint...");
    763 			fflush(stdout);
    764 		}
    765 		daddr = try_verify(osb, devvp, lfs_sb_getoffset(nsb), debug);
    766 
    767 		if (debug)
    768 			printf("done.\n");
    769 		if (daddr == lfs_sb_getoffset(nsb)) {
    770 			pwarn("** Newer checkpoint verified; recovered %jd seconds of data\n",
    771 			    (intmax_t)(lfs_sb_gettstamp(nsb) - lfs_sb_gettstamp(osb)));
    772 			sbdirty();
    773 		} else {
    774 			pwarn("** Newer checkpoint invalid; lost %jd seconds of data\n", (intmax_t)(lfs_sb_gettstamp(nsb) - lfs_sb_gettstamp(osb)));
    775 		}
    776 		return (daddr == lfs_sb_getoffset(nsb) ? nsb : osb);
    777 	}
    778 	/* Nothing to check */
    779 	return osb;
    780 }
    781 
    782 /* Verify a partial-segment summary; return the number of bytes on disk. */
    783 int
    784 check_summary(struct lfs *fs, SEGSUM *sp, daddr_t pseg_addr, int debug,
    785 	      struct uvnode *devvp, void (func(daddr_t, FINFO *)))
    786 {
    787 	FINFO *fp;
    788 	int bc;			/* Bytes in partial segment */
    789 	int nblocks;
    790 	daddr_t daddr;
    791 	IINFO *iibase, *iip;
    792 	struct ubuf *bp;
    793 	int i, j, k, datac, len;
    794 	lfs_checkword *datap;
    795 	u_int32_t ccksum;
    796 
    797 	/* We've already checked the sumsum, just do the data bounds and sum */
    798 
    799 	/* Count the blocks. */
    800 	nblocks = howmany(lfs_ss_getninos(fs, sp), LFS_INOPB(fs));
    801 	bc = nblocks << (lfs_sb_getversion(fs) > 1 ? lfs_sb_getffshift(fs) : lfs_sb_getbshift(fs));
    802 	assert(bc >= 0);
    803 
    804 	fp = SEGSUM_FINFOBASE(fs, sp);
    805 	for (i = 0; i < lfs_ss_getnfinfo(fs, sp); i++) {
    806 		nblocks += lfs_fi_getnblocks(fs, fp);
    807 		bc += lfs_fi_getlastlength(fs, fp) + ((lfs_fi_getnblocks(fs, fp) - 1)
    808 					   << lfs_sb_getbshift(fs));
    809 		assert(bc >= 0);
    810 		fp = NEXT_FINFO(fs, fp);
    811 		if (((char *)fp) - (char *)sp > lfs_sb_getsumsize(fs))
    812 			return 0;
    813 	}
    814 	datap = emalloc(nblocks * sizeof(*datap));
    815 	datac = 0;
    816 
    817 	iibase = SEGSUM_IINFOSTART(fs, sp);
    818 
    819 	iip = iibase;
    820 	daddr = pseg_addr + lfs_btofsb(fs, lfs_sb_getsumsize(fs));
    821 	fp = SEGSUM_FINFOBASE(fs, sp);
    822 	for (i = 0, j = 0;
    823 	     i < lfs_ss_getnfinfo(fs, sp) || j < howmany(lfs_ss_getninos(fs, sp), LFS_INOPB(fs)); i++) {
    824 		if (i >= lfs_ss_getnfinfo(fs, sp) && lfs_ii_getblock(fs, iip) != daddr) {
    825 			pwarn("Not enough inode blocks in pseg at 0x%jx: "
    826 			      "found %d, wanted %d\n",
    827 			      pseg_addr, j, howmany(lfs_ss_getninos(fs, sp),
    828 						    LFS_INOPB(fs)));
    829 			if (debug)
    830 				pwarn("iip=0x%jx, daddr=0x%jx\n",
    831 				    (uintmax_t)lfs_ii_getblock(fs, iip),
    832 				    (intmax_t)daddr);
    833 			break;
    834 		}
    835 		while (j < howmany(lfs_ss_getninos(fs, sp), LFS_INOPB(fs)) && lfs_ii_getblock(fs, iip) == daddr) {
    836 			bread(devvp, LFS_FSBTODB(fs, daddr), lfs_sb_getibsize(fs),
    837 			    0, &bp);
    838 			datap[datac++] = ((lfs_checkword *)bp->b_data)[0];
    839 			brelse(bp, 0);
    840 
    841 			++j;
    842 			daddr += lfs_btofsb(fs, lfs_sb_getibsize(fs));
    843 			iip = NEXTLOWER_IINFO(fs, iip);
    844 		}
    845 		if (i < lfs_ss_getnfinfo(fs, sp)) {
    846 			if (func)
    847 				func(daddr, fp);
    848 			for (k = 0; k < lfs_fi_getnblocks(fs, fp); k++) {
    849 				len = (k == lfs_fi_getnblocks(fs, fp) - 1 ?
    850 				       lfs_fi_getlastlength(fs, fp)
    851 				       : lfs_sb_getbsize(fs));
    852 				bread(devvp, LFS_FSBTODB(fs, daddr), len,
    853 				    0, &bp);
    854 				datap[datac++] = ((lfs_checkword *)bp->b_data)[0];
    855 				brelse(bp, 0);
    856 				daddr += lfs_btofsb(fs, len);
    857 			}
    858 			fp = NEXT_FINFO(fs, fp);
    859 		}
    860 	}
    861 
    862 	if (datac != nblocks) {
    863 		pwarn("Partial segment at 0x%jx expected %d blocks counted %d\n",
    864 		    (intmax_t)pseg_addr, nblocks, datac);
    865 	}
    866 	ccksum = cksum(datap, nblocks * sizeof(datap[0]));
    867 	/* Check the data checksum */
    868 	if (ccksum != lfs_ss_getdatasum(fs, sp)) {
    869 		pwarn("Partial segment at 0x%jx data checksum"
    870 		      " mismatch: given 0x%x, computed 0x%x\n",
    871 		      (uintmax_t)pseg_addr, lfs_ss_getdatasum(fs, sp), ccksum);
    872 		free(datap);
    873 		return 0;
    874 	}
    875 	free(datap);
    876 	assert(bc >= 0);
    877 	return bc;
    878 }
    879 
    880 /* print message and exit */
    881 void
    882 my_vpanic(int fatal, const char *fmt, va_list ap)
    883 {
    884         (void) vprintf(fmt, ap);
    885 	exit(8);
    886 }
    887 
    888 void
    889 call_panic(const char *fmt, ...)
    890 {
    891 	va_list ap;
    892 
    893 	va_start(ap, fmt);
    894         panic_func(1, fmt, ap);
    895 	va_end(ap);
    896 }
    897 
    898 /* Allocate a new inode. */
    899 struct uvnode *
    900 lfs_valloc(struct lfs *fs, ino_t ino)
    901 {
    902 	struct ubuf *bp, *cbp;
    903 	IFILE *ifp;
    904 	ino_t new_ino;
    905 	int error;
    906 	CLEANERINFO *cip;
    907 
    908 	/* Get the head of the freelist. */
    909 	LFS_GET_HEADFREE(fs, cip, cbp, &new_ino);
    910 
    911 	/*
    912 	 * Remove the inode from the free list and write the new start
    913 	 * of the free list into the superblock.
    914 	 */
    915 	LFS_IENTRY(ifp, fs, new_ino, bp);
    916 	if (lfs_if_getdaddr(fs, ifp) != LFS_UNUSED_DADDR)
    917 		panic("lfs_valloc: inuse inode %d on the free list", new_ino);
    918 	LFS_PUT_HEADFREE(fs, cip, cbp, lfs_if_getnextfree(fs, ifp));
    919 
    920 	brelse(bp, 0);
    921 
    922 	/* Extend IFILE so that the next lfs_valloc will succeed. */
    923 	if (lfs_sb_getfreehd(fs) == LFS_UNUSED_INUM) {
    924 		if ((error = extend_ifile(fs)) != 0) {
    925 			LFS_PUT_HEADFREE(fs, cip, cbp, new_ino);
    926 			return NULL;
    927 		}
    928 	}
    929 
    930 	/* Set superblock modified bit and increment file count. */
    931         sbdirty();
    932 	lfs_sb_addnfiles(fs, 1);
    933 
    934         return lfs_raw_vget(fs, ino, fs->lfs_devvp->v_fd, 0x0);
    935 }
    936 
    937 #ifdef IN_FSCK_LFS
    938 void reset_maxino(ino_t);
    939 #endif
    940 
    941 /*
    942  * Add a new block to the Ifile, to accommodate future file creations.
    943  */
    944 int
    945 extend_ifile(struct lfs *fs)
    946 {
    947 	struct uvnode *vp;
    948 	struct inode *ip;
    949 	IFILE64 *ifp64;
    950 	IFILE32 *ifp32;
    951 	IFILE_V1 *ifp_v1;
    952 	struct ubuf *bp, *cbp;
    953 	daddr_t i, blkno, max;
    954 	ino_t oldlast;
    955 	CLEANERINFO *cip;
    956 
    957 	vp = fs->lfs_ivnode;
    958 	ip = VTOI(vp);
    959 	blkno = lfs_lblkno(fs, lfs_dino_getsize(fs, ip->i_din));
    960 
    961 	lfs_balloc(vp, lfs_dino_getsize(fs, ip->i_din), lfs_sb_getbsize(fs), &bp);
    962 	lfs_dino_setsize(fs, ip->i_din,
    963 	    lfs_dino_getsize(fs, ip->i_din) + lfs_sb_getbsize(fs));
    964 	ip->i_state |= IN_MODIFIED;
    965 
    966 	i = (blkno - lfs_sb_getsegtabsz(fs) - lfs_sb_getcleansz(fs)) *
    967 		lfs_sb_getifpb(fs);
    968 	LFS_GET_HEADFREE(fs, cip, cbp, &oldlast);
    969 	LFS_PUT_HEADFREE(fs, cip, cbp, i);
    970 	max = i + lfs_sb_getifpb(fs);
    971 	lfs_sb_subbfree(fs, lfs_btofsb(fs, lfs_sb_getbsize(fs)));
    972 
    973 	if (fs->lfs_is64) {
    974 		for (ifp64 = (IFILE64 *)bp->b_data; i < max; ++ifp64) {
    975 			ifp64->if_version = 1;
    976 			ifp64->if_daddr = LFS_UNUSED_DADDR;
    977 			ifp64->if_nextfree = ++i;
    978 		}
    979 		ifp64--;
    980 		ifp64->if_nextfree = oldlast;
    981 	} else if (lfs_sb_getversion(fs) > 1) {
    982 		for (ifp32 = (IFILE32 *)bp->b_data; i < max; ++ifp32) {
    983 			ifp32->if_version = 1;
    984 			ifp32->if_daddr = LFS_UNUSED_DADDR;
    985 			ifp32->if_nextfree = ++i;
    986 		}
    987 		ifp32--;
    988 		ifp32->if_nextfree = oldlast;
    989 	} else {
    990 		for (ifp_v1 = (IFILE_V1 *)bp->b_data; i < max; ++ifp_v1) {
    991 			ifp_v1->if_version = 1;
    992 			ifp_v1->if_daddr = LFS_UNUSED_DADDR;
    993 			ifp_v1->if_nextfree = ++i;
    994 		}
    995 		ifp_v1--;
    996 		ifp_v1->if_nextfree = oldlast;
    997 	}
    998 	LFS_PUT_TAILFREE(fs, cip, cbp, max - 1);
    999 
   1000 	LFS_BWRITE_LOG(bp);
   1001 
   1002 #ifdef IN_FSCK_LFS
   1003 	reset_maxino(((lfs_dino_getsize(fs, ip->i_din) >> lfs_sb_getbshift(fs))
   1004 		      - lfs_sb_getsegtabsz(fs)
   1005 		      - lfs_sb_getcleansz(fs)) * lfs_sb_getifpb(fs));
   1006 #endif
   1007 	return 0;
   1008 }
   1009 
   1010 /*
   1011  * Allocate a block, and to inode and filesystem block accounting for it
   1012  * and for any indirect blocks the may need to be created in order for
   1013  * this block to be created.
   1014  *
   1015  * Blocks which have never been accounted for (i.e., which "do not exist")
   1016  * have disk address 0, which is translated by ulfs_bmap to the special value
   1017  * UNASSIGNED == -1, as in the historical ULFS.
   1018  *
   1019  * Blocks which have been accounted for but which have not yet been written
   1020  * to disk are given the new special disk address UNWRITTEN == -2, so that
   1021  * they can be differentiated from completely new blocks.
   1022  */
   1023 int
   1024 lfs_balloc(struct uvnode *vp, off_t startoffset, int iosize, struct ubuf **bpp)
   1025 {
   1026 	int offset;
   1027 	daddr_t daddr, idaddr;
   1028 	struct ubuf *ibp, *bp;
   1029 	struct inode *ip;
   1030 	struct lfs *fs;
   1031 	struct indir indirs[ULFS_NIADDR+2], *idp;
   1032 	daddr_t	lbn, lastblock;
   1033 	int bcount;
   1034 	int error, frags, i, nsize, osize, num;
   1035 
   1036 	ip = VTOI(vp);
   1037 	fs = ip->i_lfs;
   1038 	offset = lfs_blkoff(fs, startoffset);
   1039 	lbn = lfs_lblkno(fs, startoffset);
   1040 
   1041 	/*
   1042 	 * Three cases: it's a block beyond the end of file, it's a block in
   1043 	 * the file that may or may not have been assigned a disk address or
   1044 	 * we're writing an entire block.
   1045 	 *
   1046 	 * Note, if the daddr is UNWRITTEN, the block already exists in
   1047 	 * the cache (it was read or written earlier).	If so, make sure
   1048 	 * we don't count it as a new block or zero out its contents. If
   1049 	 * it did not, make sure we allocate any necessary indirect
   1050 	 * blocks.
   1051 	 *
   1052 	 * If we are writing a block beyond the end of the file, we need to
   1053 	 * check if the old last block was a fragment.	If it was, we need
   1054 	 * to rewrite it.
   1055 	 */
   1056 
   1057 	if (bpp)
   1058 		*bpp = NULL;
   1059 
   1060 	/* Check for block beyond end of file and fragment extension needed. */
   1061 	lastblock = lfs_lblkno(fs, lfs_dino_getsize(fs, ip->i_din));
   1062 	if (lastblock < ULFS_NDADDR && lastblock < lbn) {
   1063 		osize = lfs_blksize(fs, ip, lastblock);
   1064 		if (osize < lfs_sb_getbsize(fs) && osize > 0) {
   1065 			if ((error = lfs_fragextend(vp, osize, lfs_sb_getbsize(fs),
   1066 						    lastblock,
   1067 						    (bpp ? &bp : NULL))))
   1068 				return (error);
   1069 			lfs_dino_setsize(fs, ip->i_din, (lastblock + 1) * lfs_sb_getbsize(fs));
   1070 			ip->i_state |= IN_CHANGE | IN_UPDATE;
   1071 			if (bpp)
   1072 				(void) VOP_BWRITE(bp);
   1073 		}
   1074 	}
   1075 
   1076 	/*
   1077 	 * If the block we are writing is a direct block, it's the last
   1078 	 * block in the file, and offset + iosize is less than a full
   1079 	 * block, we can write one or more fragments.  There are two cases:
   1080 	 * the block is brand new and we should allocate it the correct
   1081 	 * size or it already exists and contains some fragments and
   1082 	 * may need to extend it.
   1083 	 */
   1084 	if (lbn < ULFS_NDADDR && lfs_lblkno(fs, lfs_dino_getsize(fs, ip->i_din)) <= lbn) {
   1085 		osize = lfs_blksize(fs, ip, lbn);
   1086 		nsize = lfs_fragroundup(fs, offset + iosize);
   1087 		if (lfs_lblktosize(fs, lbn) >= lfs_dino_getsize(fs, ip->i_din)) {
   1088 			/* Brand new block or fragment */
   1089 			frags = lfs_numfrags(fs, nsize);
   1090 			if (bpp) {
   1091 				*bpp = bp = getblk(vp, lbn, nsize);
   1092 				bp->b_blkno = UNWRITTEN;
   1093 			}
   1094 			ip->i_lfs_effnblks += frags;
   1095 			lfs_sb_subbfree(fs, frags);
   1096 			lfs_dino_setdb(fs, ip->i_din, lbn, UNWRITTEN);
   1097 		} else {
   1098 			if (nsize <= osize) {
   1099 				/* No need to extend */
   1100 				if (bpp && (error = bread(vp, lbn, osize,
   1101 				    0, &bp)))
   1102 					return error;
   1103 			} else {
   1104 				/* Extend existing block */
   1105 				if ((error =
   1106 				     lfs_fragextend(vp, osize, nsize, lbn,
   1107 						    (bpp ? &bp : NULL))))
   1108 					return error;
   1109 			}
   1110 			if (bpp)
   1111 				*bpp = bp;
   1112 		}
   1113 		return 0;
   1114 	}
   1115 
   1116 	error = ulfs_bmaparray(fs, vp, lbn, &daddr, &indirs[0], &num);
   1117 	if (error)
   1118 		return (error);
   1119 
   1120 	/*
   1121 	 * Do byte accounting all at once, so we can gracefully fail *before*
   1122 	 * we start assigning blocks.
   1123 	 */
   1124         frags = LFS_FSBTODB(fs, 1); /* frags = VFSTOULFS(vp->v_mount)->um_seqinc; */
   1125 	bcount = 0;
   1126 	if (daddr == UNASSIGNED) {
   1127 		bcount = frags;
   1128 	}
   1129 	for (i = 1; i < num; ++i) {
   1130 		if (!indirs[i].in_exists) {
   1131 			bcount += frags;
   1132 		}
   1133 	}
   1134 	lfs_sb_subbfree(fs, bcount);
   1135 	ip->i_lfs_effnblks += bcount;
   1136 
   1137 	if (daddr == UNASSIGNED) {
   1138 		if (num > 0 && lfs_dino_getib(fs, ip->i_din, indirs[0].in_off) == 0) {
   1139 			lfs_dino_setib(fs, ip->i_din, indirs[0].in_off,
   1140 				       UNWRITTEN);
   1141 		}
   1142 
   1143 		/*
   1144 		 * Create new indirect blocks if necessary
   1145 		 */
   1146 		if (num > 1) {
   1147 			idaddr = lfs_dino_getib(fs, ip->i_din, indirs[0].in_off);
   1148 			for (i = 1; i < num; ++i) {
   1149 				ibp = getblk(vp, indirs[i].in_lbn,
   1150 				    lfs_sb_getbsize(fs));
   1151 				if (!indirs[i].in_exists) {
   1152 					memset(ibp->b_data, 0, ibp->b_bufsize);
   1153 					ibp->b_blkno = UNWRITTEN;
   1154 				} else if (!(ibp->b_flags & (B_DELWRI | B_DONE))) {
   1155 					ibp->b_blkno = LFS_FSBTODB(fs, idaddr);
   1156 					ibp->b_flags |= B_READ;
   1157 					VOP_STRATEGY(ibp);
   1158 				}
   1159 				/*
   1160 				 * This block exists, but the next one may not.
   1161 				 * If that is the case mark it UNWRITTEN to
   1162                                  * keep the accounting straight.
   1163 				 */
   1164 				if (lfs_iblock_get(fs, ibp->b_data,
   1165 						indirs[i].in_off) == 0)
   1166 					lfs_iblock_set(fs, ibp->b_data,
   1167 						indirs[i].in_off, UNWRITTEN);
   1168 				idaddr = lfs_iblock_get(fs, ibp->b_data,
   1169 						indirs[i].in_off);
   1170 				if ((error = VOP_BWRITE(ibp)))
   1171 					return error;
   1172 			}
   1173 		}
   1174 	}
   1175 
   1176 
   1177 	/*
   1178 	 * Get the existing block from the cache, if requested.
   1179 	 */
   1180 	if (bpp)
   1181 		*bpp = bp = getblk(vp, lbn, lfs_blksize(fs, ip, lbn));
   1182 
   1183 	/*
   1184 	 * The block we are writing may be a brand new block
   1185 	 * in which case we need to do accounting.
   1186 	 *
   1187 	 * We can tell a truly new block because ulfs_bmaparray will say
   1188 	 * it is UNASSIGNED.  Once we allocate it we will assign it the
   1189 	 * disk address UNWRITTEN.
   1190 	 */
   1191 	if (daddr == UNASSIGNED) {
   1192 		if (bpp) {
   1193 			/* Note the new address */
   1194 			bp->b_blkno = UNWRITTEN;
   1195 		}
   1196 
   1197 		switch (num) {
   1198 		    case 0:
   1199 			lfs_dino_setdb(fs, ip->i_din, lbn, UNWRITTEN);
   1200 			break;
   1201 		    case 1:
   1202 			lfs_dino_setib(fs, ip->i_din, indirs[0].in_off,
   1203 				       UNWRITTEN);
   1204 			break;
   1205 		    default:
   1206 			idp = &indirs[num - 1];
   1207 			if (bread(vp, idp->in_lbn, lfs_sb_getbsize(fs), 0, &ibp))
   1208 				panic("lfs_balloc: bread bno %lld",
   1209 				    (long long)idp->in_lbn);
   1210 			lfs_iblock_set(fs, ibp->b_data, idp->in_off,
   1211 				       UNWRITTEN);
   1212 			VOP_BWRITE(ibp);
   1213 		}
   1214 	} else if (bpp && !(bp->b_flags & (B_DONE|B_DELWRI))) {
   1215 		/*
   1216 		 * Not a brand new block, also not in the cache;
   1217 		 * read it in from disk.
   1218 		 */
   1219 		if (iosize == lfs_sb_getbsize(fs))
   1220 			/* Optimization: I/O is unnecessary. */
   1221 			bp->b_blkno = daddr;
   1222 		else {
   1223 			/*
   1224 			 * We need to read the block to preserve the
   1225 			 * existing bytes.
   1226 			 */
   1227 			bp->b_blkno = daddr;
   1228 			bp->b_flags |= B_READ;
   1229 			VOP_STRATEGY(bp);
   1230 			return 0;
   1231 		}
   1232 	}
   1233 
   1234 	return (0);
   1235 }
   1236 
   1237 int
   1238 lfs_fragextend(struct uvnode *vp, int osize, int nsize, daddr_t lbn,
   1239                struct ubuf **bpp)
   1240 {
   1241 	struct inode *ip;
   1242 	struct lfs *fs;
   1243 	int frags;
   1244 	int error;
   1245 
   1246 	ip = VTOI(vp);
   1247 	fs = ip->i_lfs;
   1248 	frags = (long)lfs_numfrags(fs, nsize - osize);
   1249 	error = 0;
   1250 
   1251 	/*
   1252 	 * If we are not asked to actually return the block, all we need
   1253 	 * to do is allocate space for it.  UBC will handle dirtying the
   1254 	 * appropriate things and making sure it all goes to disk.
   1255 	 * Don't bother to read in that case.
   1256 	 */
   1257 	if (bpp && (error = bread(vp, lbn, osize, 0, bpp))) {
   1258 		brelse(*bpp, 0);
   1259 		goto out;
   1260 	}
   1261 
   1262 	lfs_sb_subbfree(fs, frags);
   1263 	ip->i_lfs_effnblks += frags;
   1264 	ip->i_state |= IN_CHANGE | IN_UPDATE;
   1265 
   1266 	if (bpp) {
   1267 		(*bpp)->b_data = erealloc((*bpp)->b_data, nsize);
   1268 		(void)memset((*bpp)->b_data + osize, 0, nsize - osize);
   1269 	}
   1270 
   1271     out:
   1272 	return (error);
   1273 }
   1274