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