Home | History | Annotate | Line # | Download | only in lfs
lfs_vfsops.c revision 1.201
      1 /*	$NetBSD: lfs_vfsops.c,v 1.201 2006/04/10 18:42:48 perseant Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2001, 2002, 2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Konrad E. Schroder <perseant (at) hhhh.org>.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 /*-
     39  * Copyright (c) 1989, 1991, 1993, 1994
     40  *	The Regents of the University of California.  All rights reserved.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. Neither the name of the University nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     64  * SUCH DAMAGE.
     65  *
     66  *	@(#)lfs_vfsops.c	8.20 (Berkeley) 6/10/95
     67  */
     68 
     69 #include <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: lfs_vfsops.c,v 1.201 2006/04/10 18:42:48 perseant Exp $");
     71 
     72 #if defined(_KERNEL_OPT)
     73 #include "opt_quota.h"
     74 #endif
     75 
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/namei.h>
     79 #include <sys/proc.h>
     80 #include <sys/kernel.h>
     81 #include <sys/vnode.h>
     82 #include <sys/mount.h>
     83 #include <sys/kthread.h>
     84 #include <sys/buf.h>
     85 #include <sys/device.h>
     86 #include <sys/mbuf.h>
     87 #include <sys/file.h>
     88 #include <sys/disklabel.h>
     89 #include <sys/ioctl.h>
     90 #include <sys/errno.h>
     91 #include <sys/malloc.h>
     92 #include <sys/pool.h>
     93 #include <sys/socket.h>
     94 #include <sys/syslog.h>
     95 #include <uvm/uvm_extern.h>
     96 #include <sys/sysctl.h>
     97 #include <sys/conf.h>
     98 
     99 #include <miscfs/specfs/specdev.h>
    100 
    101 #include <ufs/ufs/quota.h>
    102 #include <ufs/ufs/inode.h>
    103 #include <ufs/ufs/ufsmount.h>
    104 #include <ufs/ufs/ufs_extern.h>
    105 
    106 #include <uvm/uvm.h>
    107 #include <uvm/uvm_stat.h>
    108 #include <uvm/uvm_pager.h>
    109 #include <uvm/uvm_pdaemon.h>
    110 
    111 #include <ufs/lfs/lfs.h>
    112 #include <ufs/lfs/lfs_extern.h>
    113 
    114 #include <miscfs/genfs/genfs.h>
    115 #include <miscfs/genfs/genfs_node.h>
    116 
    117 static int lfs_gop_write(struct vnode *, struct vm_page **, int, int);
    118 static boolean_t lfs_issequential_hole(const struct ufsmount *,
    119     daddr_t, daddr_t);
    120 
    121 static int lfs_mountfs(struct vnode *, struct mount *, struct lwp *);
    122 static void warn_ifile_size(struct lfs *);
    123 static daddr_t check_segsum(struct lfs *, daddr_t, u_int64_t,
    124     struct ucred *, int, int *, struct lwp *);
    125 
    126 extern const struct vnodeopv_desc lfs_vnodeop_opv_desc;
    127 extern const struct vnodeopv_desc lfs_specop_opv_desc;
    128 extern const struct vnodeopv_desc lfs_fifoop_opv_desc;
    129 
    130 pid_t lfs_writer_daemon = 0;
    131 int lfs_do_flush = 0;
    132 int lfs_do_rfw = 0;
    133 
    134 const struct vnodeopv_desc * const lfs_vnodeopv_descs[] = {
    135 	&lfs_vnodeop_opv_desc,
    136 	&lfs_specop_opv_desc,
    137 	&lfs_fifoop_opv_desc,
    138 	NULL,
    139 };
    140 
    141 struct vfsops lfs_vfsops = {
    142 	MOUNT_LFS,
    143 	lfs_mount,
    144 	ufs_start,
    145 	lfs_unmount,
    146 	ufs_root,
    147 	ufs_quotactl,
    148 	lfs_statvfs,
    149 	lfs_sync,
    150 	lfs_vget,
    151 	lfs_fhtovp,
    152 	lfs_vptofh,
    153 	lfs_init,
    154 	lfs_reinit,
    155 	lfs_done,
    156 	lfs_mountroot,
    157 	(int (*)(struct mount *, struct vnode *, struct timespec *)) eopnotsupp,
    158 	vfs_stdextattrctl,
    159 	lfs_vnodeopv_descs,
    160 };
    161 VFS_ATTACH(lfs_vfsops);
    162 
    163 const struct genfs_ops lfs_genfsops = {
    164 	.gop_size = lfs_gop_size,
    165 	.gop_alloc = ufs_gop_alloc,
    166 	.gop_write = lfs_gop_write,
    167 	.gop_markupdate = ufs_gop_markupdate,
    168 };
    169 
    170 static const struct ufs_ops lfs_ufsops = {
    171 	.uo_itimes = NULL,
    172 	.uo_update = lfs_update,
    173 	.uo_truncate = lfs_truncate,
    174 	.uo_valloc = lfs_valloc,
    175 	.uo_vfree = lfs_vfree,
    176 	.uo_balloc = lfs_balloc,
    177 };
    178 
    179 /*
    180  * XXX Same structure as FFS inodes?  Should we share a common pool?
    181  */
    182 POOL_INIT(lfs_inode_pool, sizeof(struct inode), 0, 0, 0, "lfsinopl",
    183     &pool_allocator_nointr);
    184 POOL_INIT(lfs_dinode_pool, sizeof(struct ufs1_dinode), 0, 0, 0, "lfsdinopl",
    185     &pool_allocator_nointr);
    186 POOL_INIT(lfs_inoext_pool, sizeof(struct lfs_inode_ext), 8, 0, 0, "lfsinoextpl",
    187     &pool_allocator_nointr);
    188 POOL_INIT(lfs_lbnentry_pool, sizeof(struct lbnentry), 0, 0, 0, "lfslbnpool",
    189     &pool_allocator_nointr);
    190 
    191 /*
    192  * The writer daemon.  UVM keeps track of how many dirty pages we are holding
    193  * in lfs_subsys_pages; the daemon flushes the filesystem when this value
    194  * crosses the (user-defined) threshhold LFS_MAX_PAGES.
    195  */
    196 static void
    197 lfs_writerd(void *arg)
    198 {
    199 	struct mount *mp, *nmp;
    200 	struct lfs *fs;
    201 	int loopcount;
    202 
    203 	lfs_writer_daemon = curproc->p_pid;
    204 
    205 	simple_lock(&lfs_subsys_lock);
    206 	for (;;) {
    207 		ltsleep(&lfs_writer_daemon, PVM | PNORELOCK, "lfswriter", hz/10,
    208 		    &lfs_subsys_lock);
    209 
    210 		/*
    211 		 * Look through the list of LFSs to see if any of them
    212 		 * have requested pageouts.
    213 		 */
    214 		simple_lock(&mountlist_slock);
    215 		for (mp = CIRCLEQ_FIRST(&mountlist); mp != (void *)&mountlist;
    216 		     mp = nmp) {
    217 			if (vfs_busy(mp, LK_NOWAIT, &mountlist_slock)) {
    218 				nmp = CIRCLEQ_NEXT(mp, mnt_list);
    219 				continue;
    220 			}
    221 			if (strncmp(&mp->mnt_stat.f_fstypename[0], MOUNT_LFS,
    222 				    MFSNAMELEN) == 0) {
    223 				fs = VFSTOUFS(mp)->um_lfs;
    224 				simple_lock(&fs->lfs_interlock);
    225 				if (fs->lfs_pdflush) {
    226 					DLOG((DLOG_FLUSH, "lfs_writerd: pdflush set\n"));
    227 					fs->lfs_pdflush = 0;
    228 					lfs_flush_fs(fs, 0);
    229 					simple_unlock(&fs->lfs_interlock);
    230 				} else if (!TAILQ_EMPTY(&fs->lfs_pchainhd)) {
    231 					DLOG((DLOG_FLUSH, "lfs_writerd: pchain non-empty\n"));
    232 					simple_unlock(&fs->lfs_interlock);
    233 					lfs_writer_enter(fs, "wrdirop");
    234 					lfs_flush_pchain(fs);
    235 					lfs_writer_leave(fs);
    236 				} else
    237 					simple_unlock(&fs->lfs_interlock);
    238 			}
    239 
    240 			simple_lock(&mountlist_slock);
    241 			nmp = CIRCLEQ_NEXT(mp, mnt_list);
    242 			vfs_unbusy(mp);
    243 		}
    244 		simple_unlock(&mountlist_slock);
    245 
    246 		/*
    247 		 * If global state wants a flush, flush everything.
    248 		 */
    249 		simple_lock(&lfs_subsys_lock);
    250 		loopcount = 0;
    251 		if (lfs_do_flush || locked_queue_count > LFS_MAX_BUFS ||
    252 			locked_queue_bytes > LFS_MAX_BYTES ||
    253 			lfs_subsys_pages > LFS_MAX_PAGES) {
    254 
    255 			if (lfs_do_flush)
    256 				DLOG((DLOG_FLUSH, "daemon: lfs_do_flush\n"));
    257 			if (locked_queue_count > LFS_MAX_BUFS)
    258 				DLOG((DLOG_FLUSH, "daemon: lqc = %d, max %d\n",
    259 				      locked_queue_count, LFS_MAX_BUFS));
    260 			if (locked_queue_bytes > LFS_MAX_BYTES)
    261 				DLOG((DLOG_FLUSH, "daemon: lqb = %ld, max %ld\n",
    262 				      locked_queue_bytes, LFS_MAX_BYTES));
    263 			if (lfs_subsys_pages > LFS_MAX_PAGES)
    264 				DLOG((DLOG_FLUSH, "daemon: lssp = %d, max %d\n",
    265 				      lfs_subsys_pages, LFS_MAX_PAGES));
    266 
    267 			lfs_flush(NULL, SEGM_WRITERD, 0);
    268 			lfs_do_flush = 0;
    269 		}
    270 	}
    271 	/* NOTREACHED */
    272 }
    273 
    274 /*
    275  * Initialize the filesystem, most work done by ufs_init.
    276  */
    277 void
    278 lfs_init()
    279 {
    280 #ifdef _LKM
    281 	malloc_type_attach(M_SEGMENT);
    282 	pool_init(&lfs_inode_pool, sizeof(struct inode), 0, 0, 0,
    283 	    "lfsinopl", &pool_allocator_nointr);
    284 	pool_init(&lfs_dinode_pool, sizeof(struct ufs1_dinode), 0, 0, 0,
    285 	    "lfsdinopl", &pool_allocator_nointr);
    286 	pool_init(&lfs_inoext_pool, sizeof(struct lfs_inode_ext), 8, 0, 0,
    287 	    "lfsinoextpl", &pool_allocator_nointr);
    288 	pool_init(&lfs_lbnentry_pool, sizeof(struct lbnentry), 0, 0, 0,
    289 	    "lfslbnpool", &pool_allocator_nointr);
    290 #endif
    291 	ufs_init();
    292 
    293 #ifdef DEBUG
    294 	memset(lfs_log, 0, sizeof(lfs_log));
    295 #endif
    296 	simple_lock_init(&lfs_subsys_lock);
    297 }
    298 
    299 void
    300 lfs_reinit()
    301 {
    302 	ufs_reinit();
    303 }
    304 
    305 void
    306 lfs_done()
    307 {
    308 	ufs_done();
    309 #ifdef _LKM
    310 	pool_destroy(&lfs_inode_pool);
    311 	pool_destroy(&lfs_dinode_pool);
    312 	pool_destroy(&lfs_inoext_pool);
    313 	pool_destroy(&lfs_lbnentry_pool);
    314 	malloc_type_detach(M_SEGMENT);
    315 #endif
    316 }
    317 
    318 /*
    319  * Called by main() when ufs is going to be mounted as root.
    320  */
    321 int
    322 lfs_mountroot()
    323 {
    324 	extern struct vnode *rootvp;
    325 	struct mount *mp;
    326 	struct lwp *l = curlwp;	/* XXX */
    327 	int error;
    328 
    329 	if (device_class(root_device) != DV_DISK)
    330 		return (ENODEV);
    331 
    332 	if (rootdev == NODEV)
    333 		return (ENODEV);
    334 	if ((error = vfs_rootmountalloc(MOUNT_LFS, "root_device", &mp))) {
    335 		vrele(rootvp);
    336 		return (error);
    337 	}
    338 	if ((error = lfs_mountfs(rootvp, mp, l))) {
    339 		mp->mnt_op->vfs_refcount--;
    340 		vfs_unbusy(mp);
    341 		free(mp, M_MOUNT);
    342 		return (error);
    343 	}
    344 	simple_lock(&mountlist_slock);
    345 	CIRCLEQ_INSERT_TAIL(&mountlist, mp, mnt_list);
    346 	simple_unlock(&mountlist_slock);
    347 	(void)lfs_statvfs(mp, &mp->mnt_stat, l);
    348 	vfs_unbusy(mp);
    349 	setrootfstime((time_t)(VFSTOUFS(mp)->um_lfs->lfs_tstamp));
    350 	return (0);
    351 }
    352 
    353 /*
    354  * VFS Operations.
    355  *
    356  * mount system call
    357  */
    358 int
    359 lfs_mount(struct mount *mp, const char *path, void *data, struct nameidata *ndp, struct lwp *l)
    360 {
    361 	struct vnode *devvp;
    362 	struct ufs_args args;
    363 	struct ufsmount *ump = NULL;
    364 	struct lfs *fs = NULL;				/* LFS */
    365 	struct proc *p;
    366 	int error, update;
    367 	mode_t accessmode;
    368 
    369 	p = l->l_proc;
    370 	if (mp->mnt_flag & MNT_GETARGS) {
    371 		ump = VFSTOUFS(mp);
    372 		if (ump == NULL)
    373 			return EIO;
    374 		args.fspec = NULL;
    375 		return copyout(&args, data, sizeof(args));
    376 	}
    377 	error = copyin(data, &args, sizeof (struct ufs_args));
    378 	if (error)
    379 		return (error);
    380 
    381 	update = mp->mnt_flag & MNT_UPDATE;
    382 
    383 	/* Check arguments */
    384 	if (args.fspec != NULL) {
    385 		/*
    386 		 * Look up the name and verify that it's sane.
    387 		 */
    388 		NDINIT(ndp, LOOKUP, FOLLOW, UIO_USERSPACE, args.fspec, l);
    389 		if ((error = namei(ndp)) != 0)
    390 			return (error);
    391 		devvp = ndp->ni_vp;
    392 
    393 		if (!update) {
    394 			/*
    395 			 * Be sure this is a valid block device
    396 			 */
    397 			if (devvp->v_type != VBLK)
    398 				error = ENOTBLK;
    399 			else if (bdevsw_lookup(devvp->v_rdev) == NULL)
    400 				error = ENXIO;
    401 		} else {
    402 			/*
    403 			 * Be sure we're still naming the same device
    404 			 * used for our initial mount
    405 			 */
    406 			ump = VFSTOUFS(mp);
    407 			if (devvp != ump->um_devvp)
    408 				error = EINVAL;
    409 		}
    410 	} else {
    411 		if (!update) {
    412 			/* New mounts must have a filename for the device */
    413 			return (EINVAL);
    414 		} else {
    415 			/* Use the extant mount */
    416 			ump = VFSTOUFS(mp);
    417 			devvp = ump->um_devvp;
    418 			vref(devvp);
    419 		}
    420 	}
    421 
    422 
    423 	/*
    424 	 * If mount by non-root, then verify that user has necessary
    425 	 * permissions on the device.
    426 	 */
    427 	if (error == 0 && p->p_ucred->cr_uid != 0) {
    428 		accessmode = VREAD;
    429 		if (update ?
    430 		    (mp->mnt_iflag & IMNT_WANTRDWR) != 0 :
    431 		    (mp->mnt_flag & MNT_RDONLY) == 0)
    432 			accessmode |= VWRITE;
    433 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    434 		error = VOP_ACCESS(devvp, accessmode, p->p_ucred, l);
    435 		VOP_UNLOCK(devvp, 0);
    436 	}
    437 
    438 	if (error) {
    439 		vrele(devvp);
    440 		return (error);
    441 	}
    442 
    443 	if (!update) {
    444 		int flags;
    445 
    446 		/*
    447 		 * Disallow multiple mounts of the same device.
    448 		 * Disallow mounting of a device that is currently in use
    449 		 * (except for root, which might share swap device for
    450 		 * miniroot).
    451 		 */
    452 		error = vfs_mountedon(devvp);
    453 		if (error)
    454 			goto fail;
    455 		if (vcount(devvp) > 1 && devvp != rootvp) {
    456 			error = EBUSY;
    457 			goto fail;
    458 		}
    459 		if (mp->mnt_flag & MNT_RDONLY)
    460 			flags = FREAD;
    461 		else
    462 			flags = FREAD|FWRITE;
    463 		error = VOP_OPEN(devvp, flags, FSCRED, l);
    464 		if (error)
    465 			goto fail;
    466 		error = lfs_mountfs(devvp, mp, l);		/* LFS */
    467 		if (error) {
    468 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    469 			(void)VOP_CLOSE(devvp, flags, NOCRED, l);
    470 			VOP_UNLOCK(devvp, 0);
    471 			goto fail;
    472 		}
    473 
    474 		ump = VFSTOUFS(mp);
    475 		fs = ump->um_lfs;
    476 	} else {
    477 		/*
    478 		 * Update the mount.
    479 		 */
    480 
    481 		/*
    482 		 * The initial mount got a reference on this
    483 		 * device, so drop the one obtained via
    484 		 * namei(), above.
    485 		 */
    486 		vrele(devvp);
    487 
    488 		ump = VFSTOUFS(mp);
    489 		fs = ump->um_lfs;
    490 		if (fs->lfs_ronly && (mp->mnt_iflag & IMNT_WANTRDWR)) {
    491 			/*
    492 			 * Changing from read-only to read/write.
    493 			 * Note in the superblocks that we're writing.
    494 			 */
    495 			fs->lfs_ronly = 0;
    496 			if (fs->lfs_pflags & LFS_PF_CLEAN) {
    497 				fs->lfs_pflags &= ~LFS_PF_CLEAN;
    498 				lfs_writesuper(fs, fs->lfs_sboffs[0]);
    499 				lfs_writesuper(fs, fs->lfs_sboffs[1]);
    500 			}
    501 		}
    502 		if (args.fspec == NULL)
    503 			return EINVAL;
    504 	}
    505 
    506 	error = set_statvfs_info(path, UIO_USERSPACE, args.fspec,
    507 	    UIO_USERSPACE, mp, l);
    508 	if (error == 0)
    509 		(void)strncpy(fs->lfs_fsmnt, mp->mnt_stat.f_mntonname,
    510 			      sizeof(fs->lfs_fsmnt));
    511 	return error;
    512 
    513 fail:
    514 	vrele(devvp);
    515 	return (error);
    516 }
    517 
    518 /*
    519  * Roll-forward code.
    520  */
    521 
    522 /*
    523  * Load the appropriate indirect block, and change the appropriate pointer.
    524  * Mark the block dirty.  Do segment and avail accounting.
    525  */
    526 static int
    527 update_meta(struct lfs *fs, ino_t ino, int vers, daddr_t lbn,
    528 	    daddr_t ndaddr, size_t size, struct lwp *l)
    529 {
    530 	int error;
    531 	struct vnode *vp;
    532 	struct inode *ip;
    533 #ifdef DEBUG
    534 	daddr_t odaddr;
    535 	struct indir a[NIADDR];
    536 	int num;
    537 	int i;
    538 #endif /* DEBUG */
    539 	struct buf *bp;
    540 	SEGUSE *sup;
    541 
    542 	KASSERT(lbn >= 0);	/* no indirect blocks */
    543 
    544 	if ((error = lfs_rf_valloc(fs, ino, vers, l, &vp)) != 0) {
    545 		DLOG((DLOG_RF, "update_meta: ino %d: lfs_rf_valloc"
    546 		      " returned %d\n", ino, error));
    547 		return error;
    548 	}
    549 
    550 	if ((error = lfs_balloc(vp, (lbn << fs->lfs_bshift), size,
    551 				NOCRED, 0, &bp)) != 0) {
    552 		vput(vp);
    553 		return (error);
    554 	}
    555 	/* No need to write, the block is already on disk */
    556 	if (bp->b_flags & B_DELWRI) {
    557 		LFS_UNLOCK_BUF(bp);
    558 		fs->lfs_avail += btofsb(fs, bp->b_bcount);
    559 	}
    560 	bp->b_flags |= B_INVAL;
    561 	brelse(bp);
    562 
    563 	/*
    564 	 * Extend the file, if it is not large enough already.
    565 	 * XXX this is not exactly right, we don't know how much of the
    566 	 * XXX last block is actually used.  We hope that an inode will
    567 	 * XXX appear later to give the correct size.
    568 	 */
    569 	ip = VTOI(vp);
    570 	if (ip->i_size <= (lbn << fs->lfs_bshift)) {
    571 		u_int64_t newsize;
    572 
    573 		if (lbn < NDADDR)
    574 			newsize = ip->i_ffs1_size = (lbn << fs->lfs_bshift) +
    575 				(size - fs->lfs_fsize) + 1;
    576 		else
    577 			newsize = ip->i_ffs1_size = (lbn << fs->lfs_bshift) + 1;
    578 
    579 		if (ip->i_size < newsize) {
    580 			ip->i_size = newsize;
    581 			/*
    582 			 * tell vm our new size for the case the inode won't
    583 			 * appear later.
    584 			 */
    585 			uvm_vnp_setsize(vp, newsize);
    586 		}
    587 	}
    588 
    589 	lfs_update_single(fs, NULL, vp, lbn, ndaddr, size);
    590 
    591 	LFS_SEGENTRY(sup, fs, dtosn(fs, ndaddr), bp);
    592 	sup->su_nbytes += size;
    593 	LFS_WRITESEGENTRY(sup, fs, dtosn(fs, ndaddr), bp);
    594 
    595 	/* differences here should be due to UNWRITTEN indirect blocks. */
    596 	KASSERT((lblkno(fs, ip->i_size) > NDADDR &&
    597 	    ip->i_lfs_effnblks == ip->i_ffs1_blocks) ||
    598 	    ip->i_lfs_effnblks >= ip->i_ffs1_blocks);
    599 
    600 #ifdef DEBUG
    601 	/* Now look again to make sure it worked */
    602 	ufs_bmaparray(vp, lbn, &odaddr, &a[0], &num, NULL, NULL);
    603 	for (i = num; i > 0; i--) {
    604 		if (!a[i].in_exists)
    605 			panic("update_meta: absent %d lv indirect block", i);
    606 	}
    607 	if (dbtofsb(fs, odaddr) != ndaddr)
    608 		DLOG((DLOG_RF, "update_meta: failed setting ino %d lbn %"
    609 		      PRId64 " to %" PRId64 "\n", ino, lbn, ndaddr));
    610 #endif /* DEBUG */
    611 	vput(vp);
    612 	return 0;
    613 }
    614 
    615 static int
    616 update_inoblk(struct lfs *fs, daddr_t offset, struct ucred *cred,
    617 	      struct lwp *l)
    618 {
    619 	struct vnode *devvp, *vp;
    620 	struct inode *ip;
    621 	struct ufs1_dinode *dip;
    622 	struct buf *dbp, *ibp;
    623 	int error;
    624 	daddr_t daddr;
    625 	IFILE *ifp;
    626 	SEGUSE *sup;
    627 
    628 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
    629 
    630 	/*
    631 	 * Get the inode, update times and perms.
    632 	 * DO NOT update disk blocks, we do that separately.
    633 	 */
    634 	error = bread(devvp, fsbtodb(fs, offset), fs->lfs_ibsize, cred, &dbp);
    635 	if (error) {
    636 		DLOG((DLOG_RF, "update_inoblk: bread returned %d\n", error));
    637 		return error;
    638 	}
    639 	dip = ((struct ufs1_dinode *)(dbp->b_data)) + INOPB(fs);
    640 	while (--dip >= (struct ufs1_dinode *)dbp->b_data) {
    641 		if (dip->di_inumber > LFS_IFILE_INUM) {
    642 			error = lfs_rf_valloc(fs, dip->di_inumber, dip->di_gen,
    643 					      l, &vp);
    644 			if (error) {
    645 				DLOG((DLOG_RF, "update_inoblk: lfs_rf_valloc"
    646 				      " returned %d\n", error));
    647 				continue;
    648 			}
    649 			ip = VTOI(vp);
    650 			if (dip->di_size != ip->i_size)
    651 				lfs_truncate(vp, dip->di_size, 0, NOCRED, l);
    652 			/* Get mode, link count, size, and times */
    653 			memcpy(ip->i_din.ffs1_din, dip,
    654 			       offsetof(struct ufs1_dinode, di_db[0]));
    655 
    656 			/* Then the rest, except di_blocks */
    657 			ip->i_flags = ip->i_ffs1_flags = dip->di_flags;
    658 			ip->i_gen = ip->i_ffs1_gen = dip->di_gen;
    659 			ip->i_uid = ip->i_ffs1_uid = dip->di_uid;
    660 			ip->i_gid = ip->i_ffs1_gid = dip->di_gid;
    661 
    662 			ip->i_mode = ip->i_ffs1_mode;
    663 			ip->i_nlink = ip->i_ffs_effnlink = ip->i_ffs1_nlink;
    664 			ip->i_size = ip->i_ffs1_size;
    665 
    666 			LFS_SET_UINO(ip, IN_CHANGE | IN_UPDATE);
    667 
    668 			/* Re-initialize to get type right */
    669 			ufs_vinit(vp->v_mount, lfs_specop_p, lfs_fifoop_p,
    670 				  &vp);
    671 			vput(vp);
    672 
    673 			/* Record change in location */
    674 			LFS_IENTRY(ifp, fs, dip->di_inumber, ibp);
    675 			daddr = ifp->if_daddr;
    676 			ifp->if_daddr = dbtofsb(fs, dbp->b_blkno);
    677 			error = LFS_BWRITE_LOG(ibp); /* Ifile */
    678 			/* And do segment accounting */
    679 			if (dtosn(fs, daddr) != dtosn(fs, dbtofsb(fs, dbp->b_blkno))) {
    680 				if (daddr > 0) {
    681 					LFS_SEGENTRY(sup, fs, dtosn(fs, daddr),
    682 						     ibp);
    683 					sup->su_nbytes -= sizeof (struct ufs1_dinode);
    684 					LFS_WRITESEGENTRY(sup, fs,
    685 							  dtosn(fs, daddr),
    686 							  ibp);
    687 				}
    688 				LFS_SEGENTRY(sup, fs, dtosn(fs, dbtofsb(fs, dbp->b_blkno)),
    689 					     ibp);
    690 				sup->su_nbytes += sizeof (struct ufs1_dinode);
    691 				LFS_WRITESEGENTRY(sup, fs,
    692 						  dtosn(fs, dbtofsb(fs, dbp->b_blkno)),
    693 						  ibp);
    694 			}
    695 		}
    696 	}
    697 	dbp->b_flags |= B_AGE;
    698 	brelse(dbp);
    699 
    700 	return 0;
    701 }
    702 
    703 #define CHECK_CKSUM   0x0001  /* Check the checksum to make sure it's valid */
    704 #define CHECK_UPDATE  0x0002  /* Update Ifile for new data blocks / inodes */
    705 
    706 static daddr_t
    707 check_segsum(struct lfs *fs, daddr_t offset, u_int64_t nextserial,
    708 	     struct ucred *cred, int flags, int *pseg_flags, struct lwp *l)
    709 {
    710 	struct vnode *devvp;
    711 	struct buf *bp, *dbp;
    712 	int error, nblocks = 0, ninos, i, j; /* XXX: gcc */
    713 	SEGSUM *ssp;
    714 	u_long *dp = NULL, *datap = NULL; /* XXX u_int32_t */
    715 	daddr_t oldoffset;
    716 	int32_t *iaddr;	/* XXX ondisk32 */
    717 	FINFO *fip;
    718 	SEGUSE *sup;
    719 	size_t size;
    720 
    721 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
    722 	/*
    723 	 * If the segment has a superblock and we're at the top
    724 	 * of the segment, skip the superblock.
    725 	 */
    726 	if (sntod(fs, dtosn(fs, offset)) == offset) {
    727 		LFS_SEGENTRY(sup, fs, dtosn(fs, offset), bp);
    728 		if (sup->su_flags & SEGUSE_SUPERBLOCK)
    729 			offset += btofsb(fs, LFS_SBPAD);
    730 		brelse(bp);
    731 	}
    732 
    733 	/* Read in the segment summary */
    734 	error = bread(devvp, fsbtodb(fs, offset), fs->lfs_sumsize, cred, &bp);
    735 	if (error)
    736 		return -1;
    737 
    738 	/* Check summary checksum */
    739 	ssp = (SEGSUM *)bp->b_data;
    740 	if (flags & CHECK_CKSUM) {
    741 		if (ssp->ss_sumsum != cksum(&ssp->ss_datasum,
    742 					   fs->lfs_sumsize -
    743 					   sizeof(ssp->ss_sumsum))) {
    744 			DLOG((DLOG_RF, "Sumsum error at 0x%" PRIx64 "\n", offset));
    745 			offset = -1;
    746 			goto err1;
    747 		}
    748 		if (ssp->ss_nfinfo == 0 && ssp->ss_ninos == 0) {
    749 			DLOG((DLOG_RF, "Empty pseg at 0x%" PRIx64 "\n", offset));
    750 			offset = -1;
    751 			goto err1;
    752 		}
    753 		if (ssp->ss_create < fs->lfs_tstamp) {
    754 			DLOG((DLOG_RF, "Old data at 0x%" PRIx64 "\n", offset));
    755 			offset = -1;
    756 			goto err1;
    757 		}
    758 	}
    759 	if (fs->lfs_version > 1) {
    760 		if (ssp->ss_serial != nextserial) {
    761 			DLOG((DLOG_RF, "Unexpected serial number at 0x%" PRIx64
    762 			      "\n", offset));
    763 			offset = -1;
    764 			goto err1;
    765 		}
    766 		if (ssp->ss_ident != fs->lfs_ident) {
    767 			DLOG((DLOG_RF, "Incorrect fsid (0x%x vs 0x%x) at 0x%"
    768 			      PRIx64 "\n", ssp->ss_ident, fs->lfs_ident, offset));
    769 			offset = -1;
    770 			goto err1;
    771 		}
    772 	}
    773 	if (pseg_flags)
    774 		*pseg_flags = ssp->ss_flags;
    775 	oldoffset = offset;
    776 	offset += btofsb(fs, fs->lfs_sumsize);
    777 
    778 	ninos = howmany(ssp->ss_ninos, INOPB(fs));
    779 	/* XXX ondisk32 */
    780 	iaddr = (int32_t *)(bp->b_data + fs->lfs_sumsize - sizeof(int32_t));
    781 	if (flags & CHECK_CKSUM) {
    782 		/* Count blocks */
    783 		nblocks = 0;
    784 		fip = (FINFO *)(bp->b_data + SEGSUM_SIZE(fs));
    785 		for (i = 0; i < ssp->ss_nfinfo; ++i) {
    786 			nblocks += fip->fi_nblocks;
    787 			if (fip->fi_nblocks <= 0)
    788 				break;
    789 			/* XXX ondisk32 */
    790 			fip = (FINFO *)(((char *)fip) + FINFOSIZE +
    791 					(fip->fi_nblocks * sizeof(int32_t)));
    792 		}
    793 		nblocks += ninos;
    794 		/* Create the sum array */
    795 		datap = dp = (u_long *)malloc(nblocks * sizeof(u_long),
    796 					      M_SEGMENT, M_WAITOK);
    797 	}
    798 
    799 	/* Handle individual blocks */
    800 	fip = (FINFO *)(bp->b_data + SEGSUM_SIZE(fs));
    801 	for (i = 0; i < ssp->ss_nfinfo || ninos; ++i) {
    802 		/* Inode block? */
    803 		if (ninos && *iaddr == offset) {
    804 			if (flags & CHECK_CKSUM) {
    805 				/* Read in the head and add to the buffer */
    806 				error = bread(devvp, fsbtodb(fs, offset), fs->lfs_bsize,
    807 					      cred, &dbp);
    808 				if (error) {
    809 					offset = -1;
    810 					goto err2;
    811 				}
    812 				(*dp++) = ((u_long *)(dbp->b_data))[0];
    813 				dbp->b_flags |= B_AGE;
    814 				brelse(dbp);
    815 			}
    816 			if (flags & CHECK_UPDATE) {
    817 				if ((error = update_inoblk(fs, offset, cred, l))
    818 				    != 0) {
    819 					offset = -1;
    820 					goto err2;
    821 				}
    822 			}
    823 			offset += btofsb(fs, fs->lfs_ibsize);
    824 			--iaddr;
    825 			--ninos;
    826 			--i; /* compensate */
    827 			continue;
    828 		}
    829 		size = fs->lfs_bsize;
    830 		for (j = 0; j < fip->fi_nblocks; ++j) {
    831 			if (j == fip->fi_nblocks - 1)
    832 				size = fip->fi_lastlength;
    833 			if (flags & CHECK_CKSUM) {
    834 				error = bread(devvp, fsbtodb(fs, offset), size, cred, &dbp);
    835 				if (error) {
    836 					offset = -1;
    837 					goto err2;
    838 				}
    839 				(*dp++) = ((u_long *)(dbp->b_data))[0];
    840 				dbp->b_flags |= B_AGE;
    841 				brelse(dbp);
    842 			}
    843 			/* Account for and update any direct blocks */
    844 			if ((flags & CHECK_UPDATE) &&
    845 			   fip->fi_ino > LFS_IFILE_INUM &&
    846 			   fip->fi_blocks[j] >= 0) {
    847 				update_meta(fs, fip->fi_ino, fip->fi_version,
    848 					    fip->fi_blocks[j], offset, size, l);
    849 			}
    850 			offset += btofsb(fs, size);
    851 		}
    852 		/* XXX ondisk32 */
    853 		fip = (FINFO *)(((char *)fip) + FINFOSIZE
    854 				+ fip->fi_nblocks * sizeof(int32_t));
    855 	}
    856 	/* Checksum the array, compare */
    857 	if ((flags & CHECK_CKSUM) &&
    858 	   ssp->ss_datasum != cksum(datap, nblocks * sizeof(u_long)))
    859 	{
    860 		DLOG((DLOG_RF, "Datasum error at 0x%" PRIx64
    861 		      " (wanted %x got %x)\n",
    862 		      offset, ssp->ss_datasum, cksum(datap, nblocks *
    863 						     sizeof(u_long))));
    864 		offset = -1;
    865 		goto err2;
    866 	}
    867 
    868 	/* If we're at the end of the segment, move to the next */
    869 	if (dtosn(fs, offset + btofsb(fs, fs->lfs_sumsize + fs->lfs_bsize)) !=
    870 	   dtosn(fs, offset)) {
    871 		if (dtosn(fs, offset) == dtosn(fs, ssp->ss_next)) {
    872 			offset = -1;
    873 			goto err2;
    874 		}
    875 		offset = ssp->ss_next;
    876 		DLOG((DLOG_RF, "LFS roll forward: moving to offset 0x%" PRIx64
    877 		       " -> segment %d\n", offset, dtosn(fs,offset)));
    878 	}
    879 
    880 	if (flags & CHECK_UPDATE) {
    881 		fs->lfs_avail -= (offset - oldoffset);
    882 		/* Don't clog the buffer queue */
    883 		simple_lock(&lfs_subsys_lock);
    884 		if (locked_queue_count > LFS_MAX_BUFS ||
    885 		    locked_queue_bytes > LFS_MAX_BYTES) {
    886 			lfs_flush(fs, SEGM_CKP, 0);
    887 		}
    888 		simple_unlock(&lfs_subsys_lock);
    889 	}
    890 
    891     err2:
    892 	if (flags & CHECK_CKSUM)
    893 		free(datap, M_SEGMENT);
    894     err1:
    895 	bp->b_flags |= B_AGE;
    896 	brelse(bp);
    897 
    898 	/* XXX should we update the serial number even for bad psegs? */
    899 	if ((flags & CHECK_UPDATE) && offset > 0 && fs->lfs_version > 1)
    900 		fs->lfs_serial = nextserial;
    901 	return offset;
    902 }
    903 
    904 /*
    905  * Common code for mount and mountroot
    906  * LFS specific
    907  */
    908 int
    909 lfs_mountfs(struct vnode *devvp, struct mount *mp, struct lwp *l)
    910 {
    911 	struct dlfs *tdfs, *dfs, *adfs;
    912 	struct lfs *fs;
    913 	struct ufsmount *ump;
    914 	struct vnode *vp;
    915 	struct buf *bp, *abp;
    916 	struct partinfo dpart;
    917 	struct proc *p;
    918 	dev_t dev;
    919 	int error, i, ronly, secsize, fsbsize;
    920 	struct ucred *cred;
    921 	CLEANERINFO *cip;
    922 	SEGUSE *sup;
    923 	int flags, dirty, do_rollforward;
    924 	daddr_t offset, oldoffset, lastgoodpseg, sb_addr;
    925 	int sn, curseg;
    926 
    927 	p = l ? l->l_proc : NULL;
    928 	cred = p ? p->p_ucred : NOCRED;
    929 
    930 	/*
    931 	 * Flush out any old buffers remaining from a previous use.
    932 	 */
    933 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    934 	error = vinvalbuf(devvp, V_SAVE, cred, l, 0, 0);
    935 	VOP_UNLOCK(devvp, 0);
    936 	if (error)
    937 		return (error);
    938 
    939 	ronly = (mp->mnt_flag & MNT_RDONLY) != 0;
    940 	if (VOP_IOCTL(devvp, DIOCGPART, &dpart, FREAD, cred, l) != 0)
    941 		secsize = DEV_BSIZE;
    942 	else
    943 		secsize = dpart.disklab->d_secsize;
    944 
    945 	/* Don't free random space on error. */
    946 	bp = NULL;
    947 	abp = NULL;
    948 	ump = NULL;
    949 
    950 	sb_addr = LFS_LABELPAD / secsize;
    951 	while (1) {
    952 		/* Read in the superblock. */
    953 		error = bread(devvp, sb_addr, LFS_SBPAD, cred, &bp);
    954 		if (error)
    955 			goto out;
    956 		dfs = (struct dlfs *)bp->b_data;
    957 
    958 		/* Check the basics. */
    959 		if (dfs->dlfs_magic != LFS_MAGIC || dfs->dlfs_bsize > MAXBSIZE ||
    960 		    dfs->dlfs_version > LFS_VERSION ||
    961 		    dfs->dlfs_bsize < sizeof(struct dlfs)) {
    962 			DLOG((DLOG_MOUNT, "lfs_mountfs: primary superblock sanity failed\n"));
    963 			error = EINVAL;		/* XXX needs translation */
    964 			goto out;
    965 		}
    966 		if (dfs->dlfs_inodefmt > LFS_MAXINODEFMT) {
    967 			DLOG((DLOG_MOUNT, "lfs_mountfs: unknown inode format %d\n",
    968 			       dfs->dlfs_inodefmt));
    969 			error = EINVAL;
    970 			goto out;
    971 		}
    972 
    973 		if (dfs->dlfs_version == 1)
    974 			fsbsize = secsize;
    975 		else {
    976 			fsbsize = 1 << (dfs->dlfs_bshift - dfs->dlfs_blktodb +
    977 				dfs->dlfs_fsbtodb);
    978 			/*
    979 			 * Could be, if the frag size is large enough, that we
    980 			 * don't have the "real" primary superblock.  If that's
    981 			 * the case, get the real one, and try again.
    982 			 */
    983 			if (sb_addr != dfs->dlfs_sboffs[0] <<
    984 				       dfs->dlfs_fsbtodb) {
    985 				DLOG((DLOG_MOUNT, "lfs_mountfs: sb daddr"
    986 				      " 0x%llx is not right, trying 0x%llx\n",
    987 				      (long long)sb_addr,
    988 				      (long long)(dfs->dlfs_sboffs[0] <<
    989 						  dfs->dlfs_fsbtodb)));
    990 				sb_addr = dfs->dlfs_sboffs[0] <<
    991 					  dfs->dlfs_fsbtodb;
    992 				brelse(bp);
    993 				continue;
    994 			}
    995 		}
    996 		break;
    997 	}
    998 
    999 	/*
   1000 	 * Check the second superblock to see which is newer; then mount
   1001 	 * using the older of the two.	This is necessary to ensure that
   1002 	 * the filesystem is valid if it was not unmounted cleanly.
   1003 	 */
   1004 
   1005 	if (dfs->dlfs_sboffs[1] &&
   1006 	    dfs->dlfs_sboffs[1] - LFS_LABELPAD / fsbsize > LFS_SBPAD / fsbsize)
   1007 	{
   1008 		error = bread(devvp, dfs->dlfs_sboffs[1] * (fsbsize / secsize),
   1009 			LFS_SBPAD, cred, &abp);
   1010 		if (error)
   1011 			goto out;
   1012 		adfs = (struct dlfs *)abp->b_data;
   1013 
   1014 		if (dfs->dlfs_version == 1) {
   1015 			/* 1s resolution comparison */
   1016 			if (adfs->dlfs_tstamp < dfs->dlfs_tstamp)
   1017 				tdfs = adfs;
   1018 			else
   1019 				tdfs = dfs;
   1020 		} else {
   1021 			/* monotonic infinite-resolution comparison */
   1022 			if (adfs->dlfs_serial < dfs->dlfs_serial)
   1023 				tdfs = adfs;
   1024 			else
   1025 				tdfs = dfs;
   1026 		}
   1027 
   1028 		/* Check the basics. */
   1029 		if (tdfs->dlfs_magic != LFS_MAGIC ||
   1030 		    tdfs->dlfs_bsize > MAXBSIZE ||
   1031 		    tdfs->dlfs_version > LFS_VERSION ||
   1032 		    tdfs->dlfs_bsize < sizeof(struct dlfs)) {
   1033 			DLOG((DLOG_MOUNT, "lfs_mountfs: alt superblock"
   1034 			      " sanity failed\n"));
   1035 			error = EINVAL;		/* XXX needs translation */
   1036 			goto out;
   1037 		}
   1038 	} else {
   1039 		DLOG((DLOG_MOUNT, "lfs_mountfs: invalid alt superblock"
   1040 		      " daddr=0x%x\n", dfs->dlfs_sboffs[1]));
   1041 		error = EINVAL;
   1042 		goto out;
   1043 	}
   1044 
   1045 	/* Allocate the mount structure, copy the superblock into it. */
   1046 	fs = malloc(sizeof(struct lfs), M_UFSMNT, M_WAITOK | M_ZERO);
   1047 	memcpy(&fs->lfs_dlfs, tdfs, sizeof(struct dlfs));
   1048 
   1049 	/* Compatibility */
   1050 	if (fs->lfs_version < 2) {
   1051 		fs->lfs_sumsize = LFS_V1_SUMMARY_SIZE;
   1052 		fs->lfs_ibsize = fs->lfs_bsize;
   1053 		fs->lfs_start = fs->lfs_sboffs[0];
   1054 		fs->lfs_tstamp = fs->lfs_otstamp;
   1055 		fs->lfs_fsbtodb = 0;
   1056 	}
   1057 
   1058 	/*
   1059 	 * If we aren't going to be able to write meaningfully to this
   1060 	 * filesystem, and were not mounted readonly, bomb out now.
   1061 	 */
   1062 	if (fsbtob(fs, LFS_NRESERVE(fs)) > LFS_MAX_BYTES && !ronly) {
   1063 		DLOG((DLOG_MOUNT, "lfs_mount: to mount this filesystem read/write,"
   1064 		      " we need BUFPAGES >= %lld\n",
   1065 		      (long long)((bufmem_hiwater / bufmem_lowater) *
   1066 				  LFS_INVERSE_MAX_BYTES(
   1067 					  fsbtob(fs, LFS_NRESERVE(fs))) >> PAGE_SHIFT)));
   1068 		free(fs, M_UFSMNT);
   1069 		error = EFBIG; /* XXX needs translation */
   1070 		goto out;
   1071 	}
   1072 
   1073 	/* Before rolling forward, lock so vget will sleep for other procs */
   1074 	fs->lfs_flags = LFS_NOTYET;
   1075 	fs->lfs_rfpid = p->p_pid;
   1076 
   1077 	ump = malloc(sizeof *ump, M_UFSMNT, M_WAITOK | M_ZERO);
   1078 	ump->um_lfs = fs;
   1079 	ump->um_ops = &lfs_ufsops;
   1080 	ump->um_fstype = UFS1;
   1081 	if (sizeof(struct lfs) < LFS_SBPAD) {			/* XXX why? */
   1082 		bp->b_flags |= B_INVAL;
   1083 		abp->b_flags |= B_INVAL;
   1084 	}
   1085 	brelse(bp);
   1086 	bp = NULL;
   1087 	brelse(abp);
   1088 	abp = NULL;
   1089 
   1090 	/* Set up the I/O information */
   1091 	fs->lfs_devbsize = secsize;
   1092 	fs->lfs_iocount = 0;
   1093 	fs->lfs_diropwait = 0;
   1094 	fs->lfs_activesb = 0;
   1095 	fs->lfs_uinodes = 0;
   1096 	fs->lfs_ravail = 0;
   1097 	fs->lfs_favail = 0;
   1098 	fs->lfs_sbactive = 0;
   1099 
   1100 	/* Set up the ifile and lock aflags */
   1101 	fs->lfs_doifile = 0;
   1102 	fs->lfs_writer = 0;
   1103 	fs->lfs_dirops = 0;
   1104 	fs->lfs_nadirop = 0;
   1105 	fs->lfs_seglock = 0;
   1106 	fs->lfs_pdflush = 0;
   1107 	fs->lfs_sleepers = 0;
   1108 	fs->lfs_pages = 0;
   1109 	simple_lock_init(&fs->lfs_interlock);
   1110 	lockinit(&fs->lfs_fraglock, PINOD, "lfs_fraglock", 0, 0);
   1111 	lockinit(&fs->lfs_iflock, PINOD, "lfs_iflock", 0, 0);
   1112 
   1113 	/* Set the file system readonly/modify bits. */
   1114 	fs->lfs_ronly = ronly;
   1115 	if (ronly == 0)
   1116 		fs->lfs_fmod = 1;
   1117 
   1118 	/* Initialize the mount structure. */
   1119 	dev = devvp->v_rdev;
   1120 	mp->mnt_data = ump;
   1121 	mp->mnt_stat.f_fsidx.__fsid_val[0] = (long)dev;
   1122 	mp->mnt_stat.f_fsidx.__fsid_val[1] = makefstype(MOUNT_LFS);
   1123 	mp->mnt_stat.f_fsid = mp->mnt_stat.f_fsidx.__fsid_val[0];
   1124 	mp->mnt_stat.f_namemax = LFS_MAXNAMLEN;
   1125 	mp->mnt_stat.f_iosize = fs->lfs_bsize;
   1126 	mp->mnt_flag |= MNT_LOCAL;
   1127 	mp->mnt_fs_bshift = fs->lfs_bshift;
   1128 	ump->um_flags = 0;
   1129 	ump->um_mountp = mp;
   1130 	ump->um_dev = dev;
   1131 	ump->um_devvp = devvp;
   1132 	ump->um_bptrtodb = fs->lfs_fsbtodb;
   1133 	ump->um_seqinc = fragstofsb(fs, fs->lfs_frag);
   1134 	ump->um_nindir = fs->lfs_nindir;
   1135 	ump->um_lognindir = ffs(fs->lfs_nindir) - 1;
   1136 	for (i = 0; i < MAXQUOTAS; i++)
   1137 		ump->um_quotas[i] = NULLVP;
   1138 	ump->um_maxsymlinklen = fs->lfs_maxsymlinklen;
   1139 	ump->um_dirblksiz = DIRBLKSIZ;
   1140 	ump->um_maxfilesize = fs->lfs_maxfilesize;
   1141 	if (ump->um_maxsymlinklen > 0)
   1142 		mp->mnt_iflag |= IMNT_DTYPE;
   1143 	devvp->v_specmountpoint = mp;
   1144 
   1145 	/* Set up reserved memory for pageout */
   1146 	lfs_setup_resblks(fs);
   1147 	/* Set up vdirop tailq */
   1148 	TAILQ_INIT(&fs->lfs_dchainhd);
   1149 	/* and paging tailq */
   1150 	TAILQ_INIT(&fs->lfs_pchainhd);
   1151 
   1152 	/*
   1153 	 * We use the ifile vnode for almost every operation.  Instead of
   1154 	 * retrieving it from the hash table each time we retrieve it here,
   1155 	 * artificially increment the reference count and keep a pointer
   1156 	 * to it in the incore copy of the superblock.
   1157 	 */
   1158 	if ((error = VFS_VGET(mp, LFS_IFILE_INUM, &vp)) != 0) {
   1159 		DLOG((DLOG_MOUNT, "lfs_mountfs: ifile vget failed, error=%d\n", error));
   1160 		goto out;
   1161 	}
   1162 	fs->lfs_ivnode = vp;
   1163 	VREF(vp);
   1164 
   1165 	/* Set up inode bitmap and order free list */
   1166 	lfs_order_freelist(fs);
   1167 
   1168 	/* Set up segment usage flags for the autocleaner. */
   1169 	fs->lfs_nactive = 0;
   1170 	fs->lfs_suflags = (u_int32_t **)malloc(2 * sizeof(u_int32_t *),
   1171 						M_SEGMENT, M_WAITOK);
   1172 	fs->lfs_suflags[0] = (u_int32_t *)malloc(fs->lfs_nseg * sizeof(u_int32_t),
   1173 						 M_SEGMENT, M_WAITOK);
   1174 	fs->lfs_suflags[1] = (u_int32_t *)malloc(fs->lfs_nseg * sizeof(u_int32_t),
   1175 						 M_SEGMENT, M_WAITOK);
   1176 	memset(fs->lfs_suflags[1], 0, fs->lfs_nseg * sizeof(u_int32_t));
   1177 	for (i = 0; i < fs->lfs_nseg; i++) {
   1178 		int changed;
   1179 
   1180 		LFS_SEGENTRY(sup, fs, i, bp);
   1181 		changed = 0;
   1182 		if (!ronly) {
   1183 			if (sup->su_nbytes == 0 &&
   1184 			    !(sup->su_flags & SEGUSE_EMPTY)) {
   1185 				sup->su_flags |= SEGUSE_EMPTY;
   1186 				++changed;
   1187 			} else if (!(sup->su_nbytes == 0) &&
   1188 				   (sup->su_flags & SEGUSE_EMPTY)) {
   1189 				sup->su_flags &= ~SEGUSE_EMPTY;
   1190 				++changed;
   1191 			}
   1192 			if (sup->su_flags & (SEGUSE_ACTIVE|SEGUSE_INVAL)) {
   1193 				sup->su_flags &= ~(SEGUSE_ACTIVE|SEGUSE_INVAL);
   1194 				++changed;
   1195 			}
   1196 		}
   1197 		fs->lfs_suflags[0][i] = sup->su_flags;
   1198 		if (changed)
   1199 			LFS_WRITESEGENTRY(sup, fs, i, bp);
   1200 		else
   1201 			brelse(bp);
   1202 	}
   1203 
   1204 	/*
   1205 	 * Roll forward.
   1206 	 *
   1207 	 * We don't roll forward for v1 filesystems, because
   1208 	 * of the danger that the clock was turned back between the last
   1209 	 * checkpoint and crash.  This would roll forward garbage.
   1210 	 *
   1211 	 * v2 filesystems don't have this problem because they use a
   1212 	 * monotonically increasing serial number instead of a timestamp.
   1213 	 */
   1214 	do_rollforward = (!(fs->lfs_pflags & LFS_PF_CLEAN) &&
   1215 			  lfs_do_rfw && fs->lfs_version > 1);
   1216 	if (do_rollforward) {
   1217 		u_int64_t nextserial;
   1218 		/*
   1219 		 * Phase I: Find the address of the last good partial
   1220 		 * segment that was written after the checkpoint.  Mark
   1221 		 * the segments in question dirty, so they won't be
   1222 		 * reallocated.
   1223 		 */
   1224 		lastgoodpseg = oldoffset = offset = fs->lfs_offset;
   1225 		flags = 0x0;
   1226 		DLOG((DLOG_RF, "LFS roll forward phase 1: start at offset 0x%"
   1227 		      PRIx64 "\n", offset));
   1228 		LFS_SEGENTRY(sup, fs, dtosn(fs, offset), bp);
   1229 		if (!(sup->su_flags & SEGUSE_DIRTY))
   1230 			--fs->lfs_nclean;
   1231 		sup->su_flags |= SEGUSE_DIRTY;
   1232 		LFS_WRITESEGENTRY(sup, fs, dtosn(fs, offset), bp);
   1233 		nextserial = fs->lfs_serial + 1;
   1234 		while ((offset = check_segsum(fs, offset, nextserial,
   1235 		    cred, CHECK_CKSUM, &flags, l)) > 0) {
   1236 			nextserial++;
   1237 			if (sntod(fs, oldoffset) != sntod(fs, offset)) {
   1238 				LFS_SEGENTRY(sup, fs, dtosn(fs, oldoffset),
   1239 					     bp);
   1240 				if (!(sup->su_flags & SEGUSE_DIRTY))
   1241 					--fs->lfs_nclean;
   1242 				sup->su_flags |= SEGUSE_DIRTY;
   1243 				LFS_WRITESEGENTRY(sup, fs, dtosn(fs, oldoffset),
   1244 					     bp);
   1245 			}
   1246 
   1247 			DLOG((DLOG_RF, "LFS roll forward phase 1: offset=0x%"
   1248 			      PRIx64 "\n", offset));
   1249 			if (flags & SS_DIROP) {
   1250 				DLOG((DLOG_RF, "lfs_mountfs: dirops at 0x%"
   1251 				      PRIx64 "\n", oldoffset));
   1252 				if (!(flags & SS_CONT))
   1253 				     DLOG((DLOG_RF, "lfs_mountfs: dirops end "
   1254 					   "at 0x%" PRIx64 "\n", oldoffset));
   1255 			}
   1256 			if (!(flags & SS_CONT))
   1257 				lastgoodpseg = offset;
   1258 			oldoffset = offset;
   1259 		}
   1260 		if (flags & SS_CONT) {
   1261 			DLOG((DLOG_RF, "LFS roll forward: warning: incomplete "
   1262 			      "dirops discarded\n"));
   1263 		}
   1264 		DLOG((DLOG_RF, "LFS roll forward phase 1: completed: "
   1265 		      "lastgoodpseg=0x%" PRIx64 "\n", lastgoodpseg));
   1266 		oldoffset = fs->lfs_offset;
   1267 		if (fs->lfs_offset != lastgoodpseg) {
   1268 			/* Don't overwrite what we're trying to preserve */
   1269 			offset = fs->lfs_offset;
   1270 			fs->lfs_offset = lastgoodpseg;
   1271 			fs->lfs_curseg = sntod(fs, dtosn(fs, fs->lfs_offset));
   1272 			for (sn = curseg = dtosn(fs, fs->lfs_curseg);;) {
   1273 				sn = (sn + 1) % fs->lfs_nseg;
   1274 				if (sn == curseg)
   1275 					panic("lfs_mountfs: no clean segments");
   1276 				LFS_SEGENTRY(sup, fs, sn, bp);
   1277 				dirty = (sup->su_flags & SEGUSE_DIRTY);
   1278 				brelse(bp);
   1279 				if (!dirty)
   1280 					break;
   1281 			}
   1282 			fs->lfs_nextseg = sntod(fs, sn);
   1283 
   1284 			/*
   1285 			 * Phase II: Roll forward from the first superblock.
   1286 			 */
   1287 			while (offset != lastgoodpseg) {
   1288 				DLOG((DLOG_RF, "LFS roll forward phase 2: 0x%"
   1289 				      PRIx64 "\n", offset));
   1290 				offset = check_segsum(fs, offset,
   1291 				    fs->lfs_serial + 1, cred, CHECK_UPDATE,
   1292 				    NULL, l);
   1293 			}
   1294 
   1295 			/*
   1296 			 * Finish: flush our changes to disk.
   1297 			 */
   1298 			lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
   1299 			DLOG((DLOG_RF, "lfs_mountfs: roll forward ",
   1300 			      "recovered %lld blocks\n",
   1301 			      (long long)(lastgoodpseg - oldoffset)));
   1302 		}
   1303 		DLOG((DLOG_RF, "LFS roll forward complete\n"));
   1304 	}
   1305 	/* If writing, sb is not clean; record in case of immediate crash */
   1306 	if (!fs->lfs_ronly) {
   1307 		fs->lfs_pflags &= ~LFS_PF_CLEAN;
   1308 		lfs_writesuper(fs, fs->lfs_sboffs[0]);
   1309 		lfs_writesuper(fs, fs->lfs_sboffs[1]);
   1310 	}
   1311 
   1312 	/* Allow vget now that roll-forward is complete */
   1313 	fs->lfs_flags &= ~(LFS_NOTYET);
   1314 	wakeup(&fs->lfs_flags);
   1315 
   1316 	/*
   1317 	 * Initialize the ifile cleaner info with information from
   1318 	 * the superblock.
   1319 	 */
   1320 	LFS_CLEANERINFO(cip, fs, bp);
   1321 	cip->clean = fs->lfs_nclean;
   1322 	cip->dirty = fs->lfs_nseg - fs->lfs_nclean;
   1323 	cip->avail = fs->lfs_avail;
   1324 	cip->bfree = fs->lfs_bfree;
   1325 	(void) LFS_BWRITE_LOG(bp); /* Ifile */
   1326 
   1327 	/*
   1328 	 * Mark the current segment as ACTIVE, since we're going to
   1329 	 * be writing to it.
   1330 	 */
   1331 	LFS_SEGENTRY(sup, fs, dtosn(fs, fs->lfs_offset), bp);
   1332 	sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
   1333 	fs->lfs_nactive++;
   1334 	LFS_WRITESEGENTRY(sup, fs, dtosn(fs, fs->lfs_offset), bp);  /* Ifile */
   1335 
   1336 	/* Now that roll-forward is done, unlock the Ifile */
   1337 	vput(vp);
   1338 
   1339 	/* Comment on ifile size if it is too large */
   1340 	warn_ifile_size(fs);
   1341 
   1342 	/* Start the pagedaemon-anticipating daemon */
   1343 	if (lfs_writer_daemon == 0 &&
   1344 	    kthread_create1(lfs_writerd, NULL, NULL, "lfs_writer") != 0)
   1345 		panic("fork lfs_writer");
   1346 
   1347 	return (0);
   1348 
   1349 out:
   1350 	if (bp)
   1351 		brelse(bp);
   1352 	if (abp)
   1353 		brelse(abp);
   1354 	if (ump) {
   1355 		free(ump->um_lfs, M_UFSMNT);
   1356 		free(ump, M_UFSMNT);
   1357 		mp->mnt_data = NULL;
   1358 	}
   1359 
   1360 	return (error);
   1361 }
   1362 
   1363 /*
   1364  * unmount system call
   1365  */
   1366 int
   1367 lfs_unmount(struct mount *mp, int mntflags, struct lwp *l)
   1368 {
   1369 	struct ufsmount *ump;
   1370 	struct lfs *fs;
   1371 	int error, flags, ronly;
   1372 	int s;
   1373 
   1374 	flags = 0;
   1375 	if (mntflags & MNT_FORCE)
   1376 		flags |= FORCECLOSE;
   1377 
   1378 	ump = VFSTOUFS(mp);
   1379 	fs = ump->um_lfs;
   1380 
   1381 	/* Two checkpoints */
   1382 	lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
   1383 	lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
   1384 
   1385 	/* wake up the cleaner so it can die */
   1386 	wakeup(&fs->lfs_nextseg);
   1387 	wakeup(&lfs_allclean_wakeup);
   1388 	simple_lock(&fs->lfs_interlock);
   1389 	while (fs->lfs_sleepers)
   1390 		ltsleep(&fs->lfs_sleepers, PRIBIO + 1, "lfs_sleepers", 0,
   1391 			&fs->lfs_interlock);
   1392 	simple_unlock(&fs->lfs_interlock);
   1393 
   1394 #ifdef QUOTA
   1395 	if (mp->mnt_flag & MNT_QUOTA) {
   1396 		int i;
   1397 		error = vflush(mp, fs->lfs_ivnode, SKIPSYSTEM|flags);
   1398 		if (error)
   1399 			return (error);
   1400 		for (i = 0; i < MAXQUOTAS; i++) {
   1401 			if (ump->um_quotas[i] == NULLVP)
   1402 				continue;
   1403 			quotaoff(l, mp, i);
   1404 		}
   1405 		/*
   1406 		 * Here we fall through to vflush again to ensure
   1407 		 * that we have gotten rid of all the system vnodes.
   1408 		 */
   1409 	}
   1410 #endif
   1411 	if ((error = vflush(mp, fs->lfs_ivnode, flags)) != 0)
   1412 		return (error);
   1413 	if ((error = VFS_SYNC(mp, 1, l->l_proc->p_ucred, l)) != 0)
   1414 		return (error);
   1415 	s = splbio();
   1416 	if (LIST_FIRST(&fs->lfs_ivnode->v_dirtyblkhd))
   1417 		panic("lfs_unmount: still dirty blocks on ifile vnode");
   1418 	splx(s);
   1419 
   1420 	/* Comment on ifile size if it has become too large */
   1421 	if (!(fs->lfs_flags & LFS_WARNED))
   1422 		warn_ifile_size(fs);
   1423 
   1424 	/* Explicitly write the superblock, to update serial and pflags */
   1425 	fs->lfs_pflags |= LFS_PF_CLEAN;
   1426 	lfs_writesuper(fs, fs->lfs_sboffs[0]);
   1427 	lfs_writesuper(fs, fs->lfs_sboffs[1]);
   1428 	simple_lock(&fs->lfs_interlock);
   1429 	while (fs->lfs_iocount)
   1430 		ltsleep(&fs->lfs_iocount, PRIBIO + 1, "lfs_umount", 0,
   1431 			&fs->lfs_interlock);
   1432 	simple_unlock(&fs->lfs_interlock);
   1433 
   1434 	/* Finish with the Ifile, now that we're done with it */
   1435 	vrele(fs->lfs_ivnode);
   1436 	vgone(fs->lfs_ivnode);
   1437 
   1438 	ronly = !fs->lfs_ronly;
   1439 	if (ump->um_devvp->v_type != VBAD)
   1440 		ump->um_devvp->v_specmountpoint = NULL;
   1441 	vn_lock(ump->um_devvp, LK_EXCLUSIVE | LK_RETRY);
   1442 	error = VOP_CLOSE(ump->um_devvp,
   1443 	    ronly ? FREAD : FREAD|FWRITE, NOCRED, l);
   1444 	vput(ump->um_devvp);
   1445 
   1446 	/* Complain about page leakage */
   1447 	if (fs->lfs_pages > 0)
   1448 		printf("lfs_unmount: still claim %d pages (%d in subsystem)\n",
   1449 			fs->lfs_pages, lfs_subsys_pages);
   1450 
   1451 	/* Free per-mount data structures */
   1452 	free(fs->lfs_suflags[0], M_SEGMENT);
   1453 	free(fs->lfs_suflags[1], M_SEGMENT);
   1454 	free(fs->lfs_suflags, M_SEGMENT);
   1455 	lfs_free_resblks(fs);
   1456 	free(fs, M_UFSMNT);
   1457 	free(ump, M_UFSMNT);
   1458 
   1459 	mp->mnt_data = NULL;
   1460 	mp->mnt_flag &= ~MNT_LOCAL;
   1461 	return (error);
   1462 }
   1463 
   1464 /*
   1465  * Get file system statistics.
   1466  *
   1467  * NB: We don't lock to access the superblock here, because it's not
   1468  * really that important if we get it wrong.
   1469  */
   1470 int
   1471 lfs_statvfs(struct mount *mp, struct statvfs *sbp, struct lwp *l)
   1472 {
   1473 	struct lfs *fs;
   1474 	struct ufsmount *ump;
   1475 
   1476 	ump = VFSTOUFS(mp);
   1477 	fs = ump->um_lfs;
   1478 	if (fs->lfs_magic != LFS_MAGIC)
   1479 		panic("lfs_statvfs: magic");
   1480 
   1481 	sbp->f_bsize = fs->lfs_bsize;
   1482 	sbp->f_frsize = fs->lfs_fsize;
   1483 	sbp->f_iosize = fs->lfs_bsize;
   1484 	sbp->f_blocks = fsbtofrags(fs, LFS_EST_NONMETA(fs) - VTOI(fs->lfs_ivnode)->i_lfs_effnblks);
   1485 
   1486 	sbp->f_bfree = fsbtofrags(fs, LFS_EST_BFREE(fs));
   1487 	KASSERT(sbp->f_bfree <= fs->lfs_dsize);
   1488 	if (sbp->f_bfree < 0)
   1489 		sbp->f_bfree = 0;
   1490 
   1491 	sbp->f_bresvd = fsbtofrags(fs, LFS_EST_RSVD(fs));
   1492 	if (sbp->f_bfree > sbp->f_bresvd)
   1493 		sbp->f_bavail = sbp->f_bfree - sbp->f_bresvd;
   1494 	else
   1495 		sbp->f_bavail = 0;
   1496 
   1497 	sbp->f_files = fs->lfs_bfree / btofsb(fs, fs->lfs_ibsize) * INOPB(fs);
   1498 	sbp->f_ffree = sbp->f_files - fs->lfs_nfiles;
   1499 	sbp->f_favail = sbp->f_ffree;
   1500 	sbp->f_fresvd = 0;
   1501 	copy_statvfs_info(sbp, mp);
   1502 	return (0);
   1503 }
   1504 
   1505 /*
   1506  * Go through the disk queues to initiate sandbagged IO;
   1507  * go through the inodes to write those that have been modified;
   1508  * initiate the writing of the super block if it has been modified.
   1509  *
   1510  * Note: we are always called with the filesystem marked `MPBUSY'.
   1511  */
   1512 int
   1513 lfs_sync(struct mount *mp, int waitfor, struct ucred *cred, struct lwp *l)
   1514 {
   1515 	int error;
   1516 	struct lfs *fs;
   1517 
   1518 	fs = VFSTOUFS(mp)->um_lfs;
   1519 	if (fs->lfs_ronly)
   1520 		return 0;
   1521 	lfs_writer_enter(fs, "lfs_dirops");
   1522 
   1523 	/* All syncs must be checkpoints until roll-forward is implemented. */
   1524 	error = lfs_segwrite(mp, SEGM_CKP | (waitfor ? SEGM_SYNC : 0));
   1525 	lfs_writer_leave(fs);
   1526 #ifdef QUOTA
   1527 	qsync(mp);
   1528 #endif
   1529 	return (error);
   1530 }
   1531 
   1532 extern struct lock ufs_hashlock;
   1533 
   1534 /*
   1535  * Look up an LFS dinode number to find its incore vnode.  If not already
   1536  * in core, read it in from the specified device.  Return the inode locked.
   1537  * Detection and handling of mount points must be done by the calling routine.
   1538  */
   1539 int
   1540 lfs_vget(struct mount *mp, ino_t ino, struct vnode **vpp)
   1541 {
   1542 	struct lfs *fs;
   1543 	struct ufs1_dinode *dip;
   1544 	struct inode *ip;
   1545 	struct buf *bp;
   1546 	struct ifile *ifp;
   1547 	struct vnode *vp;
   1548 	struct ufsmount *ump;
   1549 	daddr_t daddr;
   1550 	dev_t dev;
   1551 	int error, retries;
   1552 	struct timespec ts;
   1553 
   1554 	ump = VFSTOUFS(mp);
   1555 	dev = ump->um_dev;
   1556 	fs = ump->um_lfs;
   1557 
   1558 	/*
   1559 	 * If the filesystem is not completely mounted yet, suspend
   1560 	 * any access requests (wait for roll-forward to complete).
   1561 	 */
   1562 	simple_lock(&fs->lfs_interlock);
   1563 	while ((fs->lfs_flags & LFS_NOTYET) && curproc->p_pid != fs->lfs_rfpid)
   1564 		ltsleep(&fs->lfs_flags, PRIBIO+1, "lfs_notyet", 0,
   1565 			&fs->lfs_interlock);
   1566 	simple_unlock(&fs->lfs_interlock);
   1567 
   1568 	if ((*vpp = ufs_ihashget(dev, ino, LK_EXCLUSIVE)) != NULL)
   1569 		return (0);
   1570 
   1571 	if ((error = getnewvnode(VT_LFS, mp, lfs_vnodeop_p, &vp)) != 0) {
   1572 		*vpp = NULL;
   1573 		 return (error);
   1574 	}
   1575 
   1576 	do {
   1577 		if ((*vpp = ufs_ihashget(dev, ino, LK_EXCLUSIVE)) != NULL) {
   1578 			ungetnewvnode(vp);
   1579 			return (0);
   1580 		}
   1581 	} while (lockmgr(&ufs_hashlock, LK_EXCLUSIVE|LK_SLEEPFAIL, 0));
   1582 
   1583 	/* Translate the inode number to a disk address. */
   1584 	if (ino == LFS_IFILE_INUM)
   1585 		daddr = fs->lfs_idaddr;
   1586 	else {
   1587 		/* XXX bounds-check this too */
   1588 		LFS_IENTRY(ifp, fs, ino, bp);
   1589 		daddr = ifp->if_daddr;
   1590 		if (fs->lfs_version > 1) {
   1591 			ts.tv_sec = ifp->if_atime_sec;
   1592 			ts.tv_nsec = ifp->if_atime_nsec;
   1593 		}
   1594 
   1595 		brelse(bp);
   1596 		if (daddr == LFS_UNUSED_DADDR) {
   1597 			*vpp = NULLVP;
   1598 			ungetnewvnode(vp);
   1599 			lockmgr(&ufs_hashlock, LK_RELEASE, 0);
   1600 			return (ENOENT);
   1601 		}
   1602 	}
   1603 
   1604 	/* Allocate/init new vnode/inode. */
   1605 	lfs_vcreate(mp, ino, vp);
   1606 
   1607 	/*
   1608 	 * Put it onto its hash chain and lock it so that other requests for
   1609 	 * this inode will block if they arrive while we are sleeping waiting
   1610 	 * for old data structures to be purged or for the contents of the
   1611 	 * disk portion of this inode to be read.
   1612 	 */
   1613 	ip = VTOI(vp);
   1614 	ufs_ihashins(ip);
   1615 	lockmgr(&ufs_hashlock, LK_RELEASE, 0);
   1616 
   1617 	/*
   1618 	 * XXX
   1619 	 * This may not need to be here, logically it should go down with
   1620 	 * the i_devvp initialization.
   1621 	 * Ask Kirk.
   1622 	 */
   1623 	ip->i_lfs = ump->um_lfs;
   1624 
   1625 	/* Read in the disk contents for the inode, copy into the inode. */
   1626 	retries = 0;
   1627     again:
   1628 	error = bread(ump->um_devvp, fsbtodb(fs, daddr),
   1629 		(fs->lfs_version == 1 ? fs->lfs_bsize : fs->lfs_ibsize),
   1630 		NOCRED, &bp);
   1631 	if (error) {
   1632 		/*
   1633 		 * The inode does not contain anything useful, so it would
   1634 		 * be misleading to leave it on its hash chain. With mode
   1635 		 * still zero, it will be unlinked and returned to the free
   1636 		 * list by vput().
   1637 		 */
   1638 		vput(vp);
   1639 		brelse(bp);
   1640 		*vpp = NULL;
   1641 		return (error);
   1642 	}
   1643 
   1644 	dip = lfs_ifind(fs, ino, bp);
   1645 	if (dip == NULL) {
   1646 		/* Assume write has not completed yet; try again */
   1647 		bp->b_flags |= B_INVAL;
   1648 		brelse(bp);
   1649 		++retries;
   1650 		if (retries > LFS_IFIND_RETRIES) {
   1651 #ifdef DEBUG
   1652 			/* If the seglock is held look at the bpp to see
   1653 			   what is there anyway */
   1654 			simple_lock(&fs->lfs_interlock);
   1655 			if (fs->lfs_seglock > 0) {
   1656 				struct buf **bpp;
   1657 				struct ufs1_dinode *dp;
   1658 				int i;
   1659 
   1660 				for (bpp = fs->lfs_sp->bpp;
   1661 				     bpp != fs->lfs_sp->cbpp; ++bpp) {
   1662 					if ((*bpp)->b_vp == fs->lfs_ivnode &&
   1663 					    bpp != fs->lfs_sp->bpp) {
   1664 						/* Inode block */
   1665 						printf("lfs_vget: block 0x%" PRIx64 ": ",
   1666 						       (*bpp)->b_blkno);
   1667 						dp = (struct ufs1_dinode *)(*bpp)->b_data;
   1668 						for (i = 0; i < INOPB(fs); i++)
   1669 							if (dp[i].di_u.inumber)
   1670 								printf("%d ", dp[i].di_u.inumber);
   1671 						printf("\n");
   1672 					}
   1673 				}
   1674 			}
   1675 			simple_unlock(&fs->lfs_interlock);
   1676 #endif /* DEBUG */
   1677 			panic("lfs_vget: dinode not found");
   1678 		}
   1679 		simple_lock(&fs->lfs_interlock);
   1680 		if (fs->lfs_iocount) {
   1681 			DLOG((DLOG_VNODE, "lfs_vget: dinode %d not found, retrying...\n", ino));
   1682 			(void)ltsleep(&fs->lfs_iocount, PRIBIO + 1,
   1683 				      "lfs ifind", 1, &fs->lfs_interlock);
   1684 		} else
   1685 			retries = LFS_IFIND_RETRIES;
   1686 		simple_unlock(&fs->lfs_interlock);
   1687 		goto again;
   1688 	}
   1689 	*ip->i_din.ffs1_din = *dip;
   1690 	brelse(bp);
   1691 
   1692 	if (fs->lfs_version > 1) {
   1693 		ip->i_ffs1_atime = ts.tv_sec;
   1694 		ip->i_ffs1_atimensec = ts.tv_nsec;
   1695 	}
   1696 
   1697 	lfs_vinit(mp, &vp);
   1698 
   1699 	*vpp = vp;
   1700 
   1701 	KASSERT(VOP_ISLOCKED(vp));
   1702 
   1703 	return (0);
   1704 }
   1705 
   1706 /*
   1707  * File handle to vnode
   1708  */
   1709 int
   1710 lfs_fhtovp(struct mount *mp, struct fid *fhp, struct vnode **vpp)
   1711 {
   1712 	struct lfid *lfhp;
   1713 	struct buf *bp;
   1714 	IFILE *ifp;
   1715 	int32_t daddr;
   1716 	struct lfs *fs;
   1717 
   1718 	lfhp = (struct lfid *)fhp;
   1719 	if (lfhp->lfid_ino < LFS_IFILE_INUM)
   1720 		return ESTALE;
   1721 
   1722 	fs = VFSTOUFS(mp)->um_lfs;
   1723 	if (lfhp->lfid_ident != fs->lfs_ident)
   1724 		return ESTALE;
   1725 
   1726 	if (lfhp->lfid_ino >
   1727 	    ((VTOI(fs->lfs_ivnode)->i_ffs1_size >> fs->lfs_bshift) -
   1728 	     fs->lfs_cleansz - fs->lfs_segtabsz) * fs->lfs_ifpb)
   1729 		return ESTALE;
   1730 
   1731 	if (ufs_ihashlookup(VFSTOUFS(mp)->um_dev, lfhp->lfid_ino) == NULLVP) {
   1732 		LFS_IENTRY(ifp, fs, lfhp->lfid_ino, bp);
   1733 		daddr = ifp->if_daddr;
   1734 		brelse(bp);
   1735 		if (daddr == LFS_UNUSED_DADDR)
   1736 			return ESTALE;
   1737 	}
   1738 
   1739 	return (ufs_fhtovp(mp, &lfhp->lfid_ufid, vpp));
   1740 }
   1741 
   1742 /*
   1743  * Vnode pointer to File handle
   1744  */
   1745 /* ARGSUSED */
   1746 int
   1747 lfs_vptofh(struct vnode *vp, struct fid *fhp)
   1748 {
   1749 	struct inode *ip;
   1750 	struct lfid *lfhp;
   1751 
   1752 	ip = VTOI(vp);
   1753 	lfhp = (struct lfid *)fhp;
   1754 	lfhp->lfid_len = sizeof(struct lfid);
   1755 	lfhp->lfid_ino = ip->i_number;
   1756 	lfhp->lfid_gen = ip->i_gen;
   1757 	lfhp->lfid_ident = ip->i_lfs->lfs_ident;
   1758 	return (0);
   1759 }
   1760 
   1761 static int
   1762 sysctl_lfs_dostats(SYSCTLFN_ARGS)
   1763 {
   1764 	extern struct lfs_stats lfs_stats;
   1765 	extern int lfs_dostats;
   1766 	int error;
   1767 
   1768 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
   1769 	if (error || newp == NULL)
   1770 		return (error);
   1771 
   1772 	if (lfs_dostats == 0)
   1773 		memset(&lfs_stats, 0, sizeof(lfs_stats));
   1774 
   1775 	return (0);
   1776 }
   1777 
   1778 struct shortlong {
   1779 	const char *sname;
   1780 	const char *lname;
   1781 };
   1782 
   1783 SYSCTL_SETUP(sysctl_vfs_lfs_setup, "sysctl vfs.lfs subtree setup")
   1784 {
   1785 	int i;
   1786 	extern int lfs_writeindir, lfs_dostats, lfs_clean_vnhead,
   1787 		   lfs_fs_pagetrip;
   1788 #ifdef DEBUG
   1789 	extern int lfs_debug_log_subsys[DLOG_MAX];
   1790 	struct shortlong dlog_names[DLOG_MAX] = { /* Must match lfs.h ! */
   1791 		{ "rollforward", "Debug roll-forward code" },
   1792 		{ "alloc",	"Debug inode allocation and free list" },
   1793 		{ "avail",	"Debug space-available-now accounting" },
   1794 		{ "flush",	"Debug flush triggers" },
   1795 		{ "lockedlist",	"Debug locked list accounting" },
   1796 		{ "vnode_verbose", "Verbose per-vnode-written debugging" },
   1797 		{ "vnode",	"Debug vnode use during segment write" },
   1798 		{ "segment",	"Debug segment writing" },
   1799 		{ "seguse",	"Debug segment used-bytes accounting" },
   1800 		{ "cleaner",	"Debug cleaning routines" },
   1801 		{ "mount",	"Debug mount/unmount routines" },
   1802 		{ "pagecache",	"Debug UBC interactions" },
   1803 		{ "dirop",	"Debug directory-operation accounting" },
   1804 		{ "malloc",	"Debug private malloc accounting" },
   1805 	};
   1806 #endif /* DEBUG */
   1807 	struct shortlong stat_names[] = { /* Must match lfs.h! */
   1808 		{ "segsused",	    "Number of new segments allocated" },
   1809 		{ "psegwrites",	    "Number of partial-segment writes" },
   1810 		{ "psyncwrites",    "Number of synchronous partial-segment"
   1811 				    " writes" },
   1812 		{ "pcleanwrites",   "Number of partial-segment writes by the"
   1813 				    " cleaner" },
   1814 		{ "blocktot",       "Number of blocks written" },
   1815 		{ "cleanblocks",    "Number of blocks written by the cleaner" },
   1816 		{ "ncheckpoints",   "Number of checkpoints made" },
   1817 		{ "nwrites",        "Number of whole writes" },
   1818 		{ "nsync_writes",   "Number of synchronous writes" },
   1819 		{ "wait_exceeded",  "Number of times writer waited for"
   1820 				    " cleaner" },
   1821 		{ "write_exceeded", "Number of times writer invoked flush" },
   1822 		{ "flush_invoked",  "Number of times flush was invoked" },
   1823 		{ "vflush_invoked", "Number of time vflush was called" },
   1824 		{ "clean_inlocked", "Number of vnodes skipped for VXLOCK" },
   1825 		{ "clean_vnlocked", "Number of vnodes skipped for vget failure" },
   1826 		{ "segs_reclaimed", "Number of segments reclaimed" },
   1827 	};
   1828 
   1829 	sysctl_createv(clog, 0, NULL, NULL,
   1830 		       CTLFLAG_PERMANENT,
   1831 		       CTLTYPE_NODE, "vfs", NULL,
   1832 		       NULL, 0, NULL, 0,
   1833 		       CTL_VFS, CTL_EOL);
   1834 	sysctl_createv(clog, 0, NULL, NULL,
   1835 		       CTLFLAG_PERMANENT,
   1836 		       CTLTYPE_NODE, "lfs",
   1837 		       SYSCTL_DESCR("Log-structured file system"),
   1838 		       NULL, 0, NULL, 0,
   1839 		       CTL_VFS, 5, CTL_EOL);
   1840 	/*
   1841 	 * XXX the "5" above could be dynamic, thereby eliminating one
   1842 	 * more instance of the "number to vfs" mapping problem, but
   1843 	 * "5" is the order as taken from sys/mount.h
   1844 	 */
   1845 
   1846 	sysctl_createv(clog, 0, NULL, NULL,
   1847 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1848 		       CTLTYPE_INT, "flushindir", NULL,
   1849 		       NULL, 0, &lfs_writeindir, 0,
   1850 		       CTL_VFS, 5, LFS_WRITEINDIR, CTL_EOL);
   1851 	sysctl_createv(clog, 0, NULL, NULL,
   1852 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1853 		       CTLTYPE_INT, "clean_vnhead", NULL,
   1854 		       NULL, 0, &lfs_clean_vnhead, 0,
   1855 		       CTL_VFS, 5, LFS_CLEAN_VNHEAD, CTL_EOL);
   1856 	sysctl_createv(clog, 0, NULL, NULL,
   1857 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1858 		       CTLTYPE_INT, "dostats",
   1859 		       SYSCTL_DESCR("Maintain statistics on LFS operations"),
   1860 		       sysctl_lfs_dostats, 0, &lfs_dostats, 0,
   1861 		       CTL_VFS, 5, LFS_DOSTATS, CTL_EOL);
   1862 	sysctl_createv(clog, 0, NULL, NULL,
   1863 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1864 		       CTLTYPE_INT, "pagetrip",
   1865 		       SYSCTL_DESCR("How many dirty pages in fs triggers"
   1866 				    " a flush"),
   1867 		       NULL, 0, &lfs_fs_pagetrip, 0,
   1868 		       CTL_VFS, 5, LFS_FS_PAGETRIP, CTL_EOL);
   1869 	sysctl_createv(clog, 0, NULL, NULL,
   1870 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1871 		       CTLTYPE_INT, "rfw",
   1872 		       SYSCTL_DESCR("Use in-kernel roll-forward on mount"),
   1873 		       NULL, 0, &lfs_do_rfw, 0,
   1874 		       CTL_VFS, 5, LFS_DO_RFW, CTL_EOL);
   1875 
   1876 	sysctl_createv(clog, 0, NULL, NULL,
   1877 		       CTLFLAG_PERMANENT,
   1878 		       CTLTYPE_NODE, "stats",
   1879 		       SYSCTL_DESCR("Debugging options"),
   1880 		       NULL, 0, NULL, 0,
   1881 		       CTL_VFS, 5, LFS_STATS, CTL_EOL);
   1882 	for (i = 0; i < sizeof(struct lfs_stats) / sizeof(u_int); i++) {
   1883 		sysctl_createv(clog, 0, NULL, NULL,
   1884 			       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
   1885 			       CTLTYPE_INT, stat_names[i].sname,
   1886 			       SYSCTL_DESCR(stat_names[i].lname),
   1887 			       NULL, 0, &(((u_int *)&lfs_stats.segsused)[i]),
   1888 			       0, CTL_VFS, 5, LFS_STATS, i, CTL_EOL);
   1889 	}
   1890 
   1891 #ifdef DEBUG
   1892 	sysctl_createv(clog, 0, NULL, NULL,
   1893 		       CTLFLAG_PERMANENT,
   1894 		       CTLTYPE_NODE, "debug",
   1895 		       SYSCTL_DESCR("Debugging options"),
   1896 		       NULL, 0, NULL, 0,
   1897 		       CTL_VFS, 5, LFS_DEBUGLOG, CTL_EOL);
   1898 	for (i = 0; i < DLOG_MAX; i++) {
   1899 		sysctl_createv(clog, 0, NULL, NULL,
   1900 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
   1901 			       CTLTYPE_INT, dlog_names[i].sname,
   1902 			       SYSCTL_DESCR(dlog_names[i].lname),
   1903 			       NULL, 0, &(lfs_debug_log_subsys[i]), 0,
   1904 			       CTL_VFS, 5, LFS_DEBUGLOG, i, CTL_EOL);
   1905 	}
   1906 #endif
   1907 }
   1908 
   1909 /*
   1910  * ufs_bmaparray callback function for writing.
   1911  *
   1912  * Since blocks will be written to the new segment anyway,
   1913  * we don't care about current daddr of them.
   1914  */
   1915 static boolean_t
   1916 lfs_issequential_hole(const struct ufsmount *ump,
   1917     daddr_t daddr0, daddr_t daddr1)
   1918 {
   1919 	daddr0 = (daddr_t)((int32_t)daddr0); /* XXX ondisk32 */
   1920 	daddr1 = (daddr_t)((int32_t)daddr1); /* XXX ondisk32 */
   1921 
   1922 	KASSERT(daddr0 == UNWRITTEN ||
   1923 	    (0 <= daddr0 && daddr0 <= LFS_MAX_DADDR));
   1924 	KASSERT(daddr1 == UNWRITTEN ||
   1925 	    (0 <= daddr1 && daddr1 <= LFS_MAX_DADDR));
   1926 
   1927 	/* NOTE: all we want to know here is 'hole or not'. */
   1928 	/* NOTE: UNASSIGNED is converted to 0 by ufs_bmaparray. */
   1929 
   1930 	/*
   1931 	 * treat UNWRITTENs and all resident blocks as 'contiguous'
   1932 	 */
   1933 	if (daddr0 != 0 && daddr1 != 0)
   1934 		return TRUE;
   1935 
   1936 	/*
   1937 	 * both are in hole?
   1938 	 */
   1939 	if (daddr0 == 0 && daddr1 == 0)
   1940 		return TRUE; /* all holes are 'contiguous' for us. */
   1941 
   1942 	return FALSE;
   1943 }
   1944 
   1945 /*
   1946  * lfs_gop_write functions exactly like genfs_gop_write, except that
   1947  * (1) it requires the seglock to be held by its caller, and sp->fip
   1948  *     to be properly initialized (it will return without re-initializing
   1949  *     sp->fip, and without calling lfs_writeseg).
   1950  * (2) it uses the remaining space in the segment, rather than VOP_BMAP,
   1951  *     to determine how large a block it can write at once (though it does
   1952  *     still use VOP_BMAP to find holes in the file);
   1953  * (3) it calls lfs_gatherblock instead of VOP_STRATEGY on its blocks
   1954  *     (leaving lfs_writeseg to deal with the cluster blocks, so we might
   1955  *     now have clusters of clusters, ick.)
   1956  */
   1957 static int
   1958 lfs_gop_write(struct vnode *vp, struct vm_page **pgs, int npages, int flags)
   1959 {
   1960 	int i, s, error, run;
   1961 	int fs_bshift;
   1962 	vaddr_t kva;
   1963 	off_t eof, offset, startoffset = 0;
   1964 	size_t bytes, iobytes, skipbytes;
   1965 	daddr_t lbn, blkno;
   1966 	struct vm_page *pg;
   1967 	struct buf *mbp, *bp;
   1968 	struct vnode *devvp = VTOI(vp)->i_devvp;
   1969 	struct inode *ip = VTOI(vp);
   1970 	struct lfs *fs = ip->i_lfs;
   1971 	struct segment *sp = fs->lfs_sp;
   1972 	UVMHIST_FUNC("lfs_gop_write"); UVMHIST_CALLED(ubchist);
   1973 
   1974 	ASSERT_SEGLOCK(fs);
   1975 
   1976 	/* The Ifile lives in the buffer cache */
   1977 	KASSERT(vp != fs->lfs_ivnode);
   1978 
   1979         /*
   1980          * We don't want to fill the disk before the cleaner has a chance
   1981          * to make room for us.  If we're in danger of doing that, fail
   1982          * with EAGAIN.  The caller will have to notice this, unlock
   1983          * so the cleaner can run, relock and try again.
   1984          */
   1985         if (LFS_STARVED_FOR_SEGS(fs))
   1986                 goto tryagain;
   1987 
   1988 	/*
   1989 	 * Sometimes things slip past the filters in lfs_putpages,
   1990 	 * and the pagedaemon tries to write pages---problem is
   1991 	 * that the pagedaemon never acquires the segment lock.
   1992 	 *
   1993 	 * Alternatively, pages that were clean when we called
   1994 	 * genfs_putpages may have become dirty in the meantime.  In this
   1995 	 * case the segment header is not properly set up for blocks
   1996 	 * to be added to it.
   1997 	 *
   1998 	 * Unbusy and unclean the pages, and put them on the ACTIVE
   1999 	 * queue under the hypothesis that they couldn't have got here
   2000 	 * unless they were modified *quite* recently.
   2001 	 *
   2002 	 * XXXUBC that last statement is an oversimplification of course.
   2003 	 */
   2004 	if (!LFS_SEGLOCK_HELD(fs) ||
   2005 	    (ip->i_lfs_iflags & LFSI_NO_GOP_WRITE) ||
   2006 	    (pgs[0]->offset & fs->lfs_bmask) != 0) {
   2007 		goto tryagain;
   2008 	}
   2009 
   2010 	UVMHIST_LOG(ubchist, "vp %p pgs %p npages %d flags 0x%x",
   2011 	    vp, pgs, npages, flags);
   2012 
   2013 	GOP_SIZE(vp, vp->v_size, &eof, 0);
   2014 
   2015 	if (vp->v_type == VREG)
   2016 		fs_bshift = vp->v_mount->mnt_fs_bshift;
   2017 	else
   2018 		fs_bshift = DEV_BSHIFT;
   2019 	error = 0;
   2020 	pg = pgs[0];
   2021 	startoffset = pg->offset;
   2022 	KASSERT(eof >= 0);
   2023 	if (startoffset >= eof) {
   2024 		goto tryagain;
   2025 	} else
   2026 		bytes = MIN(npages << PAGE_SHIFT, eof - startoffset);
   2027 	skipbytes = 0;
   2028 
   2029 	KASSERT(bytes != 0);
   2030 
   2031 	/* Swap PG_DELWRI for PG_PAGEOUT */
   2032 	for (i = 0; i < npages; i++)
   2033 		if (pgs[i]->flags & PG_DELWRI) {
   2034 			KASSERT(!(pgs[i]->flags & PG_PAGEOUT));
   2035 			pgs[i]->flags &= ~PG_DELWRI;
   2036 			pgs[i]->flags |= PG_PAGEOUT;
   2037 			uvmexp.paging++;
   2038 			uvm_lock_pageq();
   2039 			uvm_pageunwire(pgs[i]);
   2040 			uvm_unlock_pageq();
   2041 		}
   2042 
   2043 	/*
   2044 	 * Check to make sure we're starting on a block boundary.
   2045 	 * We'll check later to make sure we always write entire
   2046 	 * blocks (or fragments).
   2047 	 */
   2048 	if (startoffset & fs->lfs_bmask)
   2049 		printf("%" PRId64 " & %" PRId64 " = %" PRId64 "\n",
   2050 		       startoffset, fs->lfs_bmask,
   2051 		       startoffset & fs->lfs_bmask);
   2052 	KASSERT((startoffset & fs->lfs_bmask) == 0);
   2053 	if (bytes & fs->lfs_ffmask) {
   2054 		printf("lfs_gop_write: asked to write %ld bytes\n", (long)bytes);
   2055 		panic("lfs_gop_write: non-integer blocks");
   2056 	}
   2057 
   2058 	/*
   2059 	 * We could deadlock here on pager_map with UVMPAGER_MAPIN_WAITOK.
   2060 	 * If we would, write what we have and try again.  If we don't
   2061 	 * have anything to write, we'll have to sleep.
   2062 	 */
   2063 	if ((kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
   2064 				      (((SEGSUM *)(sp->segsum))->ss_nfinfo < 1 ?
   2065 				       UVMPAGER_MAPIN_WAITOK : 0))) == 0x0) {
   2066 		int vers;
   2067 
   2068 		DLOG((DLOG_PAGE, "lfs_gop_write: forcing write\n"));
   2069 #if 0
   2070 		      " with nfinfo=%d at offset 0x%x\n",
   2071 		      (int)((SEGSUM *)(sp->segsum))->ss_nfinfo,
   2072 		      (unsigned)fs->lfs_offset));
   2073 #endif
   2074 		if (sp->fip->fi_nblocks == 0) {
   2075 			/* Don't write zero-length finfos */
   2076 			--((SEGSUM *)(sp->segsum))->ss_nfinfo;
   2077 			sp->sum_bytes_left += FINFOSIZE;
   2078 		} else
   2079 			lfs_updatemeta(sp);
   2080 
   2081 		vers = sp->fip->fi_version;
   2082 		(void) lfs_writeseg(fs, sp);
   2083 
   2084 		sp->fip->fi_version = vers;
   2085 		sp->fip->fi_ino = ip->i_number;
   2086 		/* Add the current file to the segment summary. */
   2087 		++((SEGSUM *)(sp->segsum))->ss_nfinfo;
   2088 		sp->sum_bytes_left -= FINFOSIZE;
   2089 
   2090 		/*
   2091 		 * Having given up all of the pager_map we were holding,
   2092 		 * we can now wait for aiodoned to reclaim it for us
   2093 		 * without fear of deadlock.
   2094 		 */
   2095 		kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
   2096 				     UVMPAGER_MAPIN_WAITOK);
   2097 	}
   2098 
   2099 	s = splbio();
   2100 	simple_lock(&global_v_numoutput_slock);
   2101 	vp->v_numoutput += 2; /* one for biodone, one for aiodone */
   2102 	simple_unlock(&global_v_numoutput_slock);
   2103 	splx(s);
   2104 
   2105 	mbp = getiobuf();
   2106 	UVMHIST_LOG(ubchist, "vp %p mbp %p num now %d bytes 0x%x",
   2107 	    vp, mbp, vp->v_numoutput, bytes);
   2108 	mbp->b_bufsize = npages << PAGE_SHIFT;
   2109 	mbp->b_data = (void *)kva;
   2110 	mbp->b_resid = mbp->b_bcount = bytes;
   2111 	mbp->b_flags = B_BUSY|B_WRITE|B_AGE|B_CALL;
   2112 	mbp->b_iodone = uvm_aio_biodone;
   2113 	mbp->b_vp = vp;
   2114 
   2115 	bp = NULL;
   2116 	for (offset = startoffset;
   2117 	    bytes > 0;
   2118 	    offset += iobytes, bytes -= iobytes) {
   2119 		lbn = offset >> fs_bshift;
   2120 		error = ufs_bmaparray(vp, lbn, &blkno, NULL, NULL, &run,
   2121 		    lfs_issequential_hole);
   2122 		if (error) {
   2123 			UVMHIST_LOG(ubchist, "ufs_bmaparray() -> %d",
   2124 			    error,0,0,0);
   2125 			skipbytes += bytes;
   2126 			bytes = 0;
   2127 			break;
   2128 		}
   2129 
   2130 		iobytes = MIN((((off_t)lbn + 1 + run) << fs_bshift) - offset,
   2131 		    bytes);
   2132 		if (blkno == (daddr_t)-1) {
   2133 			skipbytes += iobytes;
   2134 			continue;
   2135 		}
   2136 
   2137 		/*
   2138 		 * Discover how much we can really pack into this buffer.
   2139 		 */
   2140 		/* If no room in the current segment, finish it up */
   2141 		if (sp->sum_bytes_left < sizeof(int32_t) ||
   2142 		    sp->seg_bytes_left < (1 << fs->lfs_bshift)) {
   2143 			int vers;
   2144 
   2145 			lfs_updatemeta(sp);
   2146 
   2147 			vers = sp->fip->fi_version;
   2148 			(void) lfs_writeseg(fs, sp);
   2149 
   2150 			sp->fip->fi_version = vers;
   2151 			sp->fip->fi_ino = ip->i_number;
   2152 			/* Add the current file to the segment summary. */
   2153 			++((SEGSUM *)(sp->segsum))->ss_nfinfo;
   2154 			sp->sum_bytes_left -= FINFOSIZE;
   2155 		}
   2156 		/* Check both for space in segment and space in segsum */
   2157 		iobytes = MIN(iobytes, (sp->seg_bytes_left >> fs_bshift)
   2158 					<< fs_bshift);
   2159 		iobytes = MIN(iobytes, (sp->sum_bytes_left / sizeof(int32_t))
   2160 				       << fs_bshift);
   2161 		KASSERT(iobytes > 0);
   2162 
   2163 		/* if it's really one i/o, don't make a second buf */
   2164 		if (offset == startoffset && iobytes == bytes) {
   2165 			bp = mbp;
   2166 			/* correct overcount if there is no second buffer */
   2167 			s = splbio();
   2168 			simple_lock(&global_v_numoutput_slock);
   2169 			--vp->v_numoutput;
   2170 			simple_unlock(&global_v_numoutput_slock);
   2171 			splx(s);
   2172 		} else {
   2173 			bp = getiobuf();
   2174 			UVMHIST_LOG(ubchist, "vp %p bp %p num now %d",
   2175 			    vp, bp, vp->v_numoutput, 0);
   2176 			bp->b_data = (char *)kva +
   2177 			    (vaddr_t)(offset - pg->offset);
   2178 			bp->b_resid = bp->b_bcount = iobytes;
   2179 			bp->b_flags = B_BUSY|B_WRITE|B_CALL;
   2180 			bp->b_iodone = uvm_aio_biodone1;
   2181 		}
   2182 
   2183 		/* XXX This is silly ... is this necessary? */
   2184 		bp->b_vp = NULL;
   2185 		s = splbio();
   2186 		bgetvp(vp, bp);
   2187 		splx(s);
   2188 
   2189 		bp->b_lblkno = lblkno(fs, offset);
   2190 		bp->b_private = mbp;
   2191 		if (devvp->v_type == VBLK) {
   2192 			bp->b_dev = devvp->v_rdev;
   2193 		}
   2194 		VOP_BWRITE(bp);
   2195 		while (lfs_gatherblock(sp, bp, NULL))
   2196 			continue;
   2197 	}
   2198 
   2199 	if (skipbytes) {
   2200 		UVMHIST_LOG(ubchist, "skipbytes %d", skipbytes, 0,0,0);
   2201 		s = splbio();
   2202 		if (error) {
   2203 			mbp->b_flags |= B_ERROR;
   2204 			mbp->b_error = error;
   2205 		}
   2206 		mbp->b_resid -= skipbytes;
   2207 		if (mbp->b_resid == 0) {
   2208 			biodone(mbp);
   2209 		}
   2210 		splx(s);
   2211 	}
   2212 	UVMHIST_LOG(ubchist, "returning 0", 0,0,0,0);
   2213 	return (0);
   2214 
   2215     tryagain:
   2216 	/*
   2217 	 * We can't write the pages, for whatever reason.
   2218 	 * Clean up after ourselves, and make the caller try again.
   2219 	 */
   2220 	simple_lock(&vp->v_interlock);
   2221 
   2222 	/* Tell why we're here, if we know */
   2223 	if (ip->i_lfs_iflags & LFSI_NO_GOP_WRITE)
   2224 		DLOG((DLOG_PAGE, "lfs_gop_write: clean pages dirtied\n"));
   2225 	else if ((pgs[0]->offset & fs->lfs_bmask) != 0)
   2226 		DLOG((DLOG_PAGE, "lfs_gop_write: not on block boundary\n"));
   2227 	else if (startoffset >= eof)
   2228 		DLOG((DLOG_PAGE, "lfs_gop_write: ino %d start 0x%" PRIx64
   2229 		      " eof 0x%" PRIx64 " npages=%d\n", VTOI(vp)->i_number,
   2230 		      pgs[0]->offset, eof, npages));
   2231 	else if (LFS_STARVED_FOR_SEGS(fs))
   2232 		DLOG((DLOG_PAGE, "lfs_gop_write: avail too low\n"));
   2233 	else
   2234 		DLOG((DLOG_PAGE, "lfs_gop_write: seglock not held\n"));
   2235 
   2236 	uvm_lock_pageq();
   2237 	for (i = 0; i < npages; i++) {
   2238 		pg = pgs[i];
   2239 
   2240 		if (pg->flags & PG_PAGEOUT)
   2241 			uvmexp.paging--;
   2242 		if (pg->flags & PG_DELWRI) {
   2243 			uvm_pageunwire(pg);
   2244 		}
   2245 		uvm_pageactivate(pg);
   2246 		pg->flags &= ~(PG_CLEAN|PG_DELWRI|PG_PAGEOUT|PG_RELEASED);
   2247 		DLOG((DLOG_PAGE, "pg[%d] = %p (vp %p off %" PRIx64 ")\n", i, pg,
   2248 			vp, pg->offset));
   2249 		DLOG((DLOG_PAGE, "pg[%d]->flags = %x\n", i, pg->flags));
   2250 		DLOG((DLOG_PAGE, "pg[%d]->pqflags = %x\n", i, pg->pqflags));
   2251 		DLOG((DLOG_PAGE, "pg[%d]->uanon = %p\n", i, pg->uanon));
   2252 		DLOG((DLOG_PAGE, "pg[%d]->uobject = %p\n", i, pg->uobject));
   2253 		DLOG((DLOG_PAGE, "pg[%d]->wire_count = %d\n", i,
   2254 		      pg->wire_count));
   2255 		DLOG((DLOG_PAGE, "pg[%d]->loan_count = %d\n", i,
   2256 		      pg->loan_count));
   2257 	}
   2258 	/* uvm_pageunbusy takes care of PG_BUSY, PG_WANTED */
   2259 	uvm_page_unbusy(pgs, npages);
   2260 	uvm_unlock_pageq();
   2261 	simple_unlock(&vp->v_interlock);
   2262 	return EAGAIN;
   2263 }
   2264 
   2265 /*
   2266  * finish vnode/inode initialization.
   2267  * used by lfs_vget and lfs_fastvget.
   2268  */
   2269 void
   2270 lfs_vinit(struct mount *mp, struct vnode **vpp)
   2271 {
   2272 	struct vnode *vp = *vpp;
   2273 	struct inode *ip = VTOI(vp);
   2274 	struct ufsmount *ump = VFSTOUFS(mp);
   2275 	int i;
   2276 
   2277 	ip->i_mode = ip->i_ffs1_mode;
   2278 	ip->i_ffs_effnlink = ip->i_nlink = ip->i_ffs1_nlink;
   2279 	ip->i_lfs_osize = ip->i_size = ip->i_ffs1_size;
   2280 	ip->i_flags = ip->i_ffs1_flags;
   2281 	ip->i_gen = ip->i_ffs1_gen;
   2282 	ip->i_uid = ip->i_ffs1_uid;
   2283 	ip->i_gid = ip->i_ffs1_gid;
   2284 
   2285 	ip->i_lfs_effnblks = ip->i_ffs1_blocks;
   2286 
   2287 	/*
   2288 	 * Initialize the vnode from the inode, check for aliases.  In all
   2289 	 * cases re-init ip, the underlying vnode/inode may have changed.
   2290 	 */
   2291 	ufs_vinit(mp, lfs_specop_p, lfs_fifoop_p, &vp);
   2292 	ip = VTOI(vp);
   2293 
   2294 	memset(ip->i_lfs_fragsize, 0, NDADDR * sizeof(*ip->i_lfs_fragsize));
   2295 	if (vp->v_type != VLNK || ip->i_size >= ip->i_ump->um_maxsymlinklen) {
   2296 		struct lfs *fs = ump->um_lfs;
   2297 #ifdef DEBUG
   2298 		for (i = (ip->i_size + fs->lfs_bsize - 1) >> fs->lfs_bshift;
   2299 		    i < NDADDR; i++) {
   2300 			if ((vp->v_type == VBLK || vp->v_type == VCHR) &&
   2301 			    i == 0)
   2302 				continue;
   2303 			if (ip->i_ffs1_db[i] != 0) {
   2304 inconsistent:
   2305 				lfs_dump_dinode(ip->i_din.ffs1_din);
   2306 				panic("inconsistent inode");
   2307 			}
   2308 		}
   2309 		for ( ; i < NDADDR + NIADDR; i++) {
   2310 			if (ip->i_ffs1_ib[i - NDADDR] != 0) {
   2311 				goto inconsistent;
   2312 			}
   2313 		}
   2314 #endif /* DEBUG */
   2315 		for (i = 0; i < NDADDR; i++)
   2316 			if (ip->i_ffs1_db[i] != 0)
   2317 				ip->i_lfs_fragsize[i] = blksize(fs, ip, i);
   2318 	}
   2319 
   2320 #ifdef DIAGNOSTIC
   2321 	if (vp->v_type == VNON) {
   2322 # ifdef DEBUG
   2323 		lfs_dump_dinode(ip->i_din.ffs1_din);
   2324 # endif
   2325 		panic("lfs_vinit: ino %llu is type VNON! (ifmt=%o)\n",
   2326 		      (unsigned long long)ip->i_number,
   2327 		      (ip->i_mode & IFMT) >> 12);
   2328 	}
   2329 #endif /* DIAGNOSTIC */
   2330 
   2331 	/*
   2332 	 * Finish inode initialization now that aliasing has been resolved.
   2333 	 */
   2334 
   2335 	ip->i_devvp = ump->um_devvp;
   2336 	VREF(ip->i_devvp);
   2337 	genfs_node_init(vp, &lfs_genfsops);
   2338 	uvm_vnp_setsize(vp, ip->i_size);
   2339 
   2340 	/* Initialize hiblk from file size */
   2341 	ip->i_lfs_hiblk = lblkno(ip->i_lfs, ip->i_size + ip->i_lfs->lfs_bsize - 1) - 1;
   2342 
   2343 	*vpp = vp;
   2344 }
   2345 
   2346 /*
   2347  * Warn if the inode portion of the Ifile is too large to be contained
   2348  * in the buffer cache, according to LFS_MAX_BUFS / LFS_MAX_BYTES.
   2349  * XXX the estimates don't take multiple LFSs into account.
   2350  */
   2351 static void
   2352 warn_ifile_size(struct lfs *fs)
   2353 {
   2354 	KASSERT(LFS_MAX_BUFS > 0);
   2355 	KASSERT(LFS_MAX_BYTES > 0);
   2356 	if (((fs->lfs_ivnode->v_size >> fs->lfs_bshift) - fs->lfs_segtabsz) >
   2357 	    LFS_MAX_BUFS) {
   2358 		simple_lock(&fs->lfs_interlock);
   2359 		fs->lfs_flags |= LFS_WARNED;
   2360 		simple_unlock(&fs->lfs_interlock);
   2361 		log(LOG_WARNING, "lfs_mountfs: inode part of ifile of length %"
   2362 				 PRId64 " cannot fit in %d buffers\n",
   2363 				 fs->lfs_ivnode->v_size -
   2364 				 (fs->lfs_segtabsz << fs->lfs_bshift),
   2365 				 LFS_MAX_BUFS);
   2366 		log(LOG_WARNING, "lfs_mountfs: please consider increasing NBUF"
   2367 				 " to at least %" PRId64 "\n",
   2368 				 LFS_INVERSE_MAX_BUFS((fs->lfs_ivnode->v_size >>
   2369 						       fs->lfs_bshift) -
   2370 						      fs->lfs_segtabsz));
   2371 	} else if ((fs->lfs_ivnode->v_size >> fs->lfs_bshift) > LFS_MAX_BUFS) {
   2372 		/* Same thing but LOG_NOTICE */
   2373 		simple_lock(&fs->lfs_interlock);
   2374 		fs->lfs_flags |= LFS_WARNED;
   2375 		simple_unlock(&fs->lfs_interlock);
   2376 		log(LOG_NOTICE, "lfs_mountfs: entire ifile of length %"
   2377 				PRId64 " cannot fit in %d buffers\n",
   2378 				fs->lfs_ivnode->v_size, LFS_MAX_BUFS);
   2379 		log(LOG_NOTICE, "lfs_mountfs: please consider increasing NBUF"
   2380 				" to at least %" PRId64 "\n",
   2381 				LFS_INVERSE_MAX_BUFS(fs->lfs_ivnode->v_size >>
   2382 						     fs->lfs_bshift));
   2383 	}
   2384 
   2385 	if (fs->lfs_ivnode->v_size - (fs->lfs_segtabsz << fs->lfs_bshift) >
   2386 	    LFS_MAX_BYTES) {
   2387 		simple_lock(&fs->lfs_interlock);
   2388 		fs->lfs_flags |= LFS_WARNED;
   2389 		simple_unlock(&fs->lfs_interlock);
   2390 		log(LOG_WARNING, "lfs_mountfs: inode part of ifile of length %"
   2391 				 PRId64 " cannot fit in %lu bytes\n",
   2392 				 fs->lfs_ivnode->v_size - (fs->lfs_segtabsz <<
   2393 							   fs->lfs_bshift),
   2394 				 LFS_MAX_BYTES);
   2395 		log(LOG_WARNING, "lfs_mountfs: please consider increasing"
   2396 				 " BUFPAGES to at least %" PRId64 "\n",
   2397 				 LFS_INVERSE_MAX_BYTES(fs->lfs_ivnode->v_size -
   2398 						       (fs->lfs_segtabsz <<
   2399 							fs->lfs_bshift)) >>
   2400 				 PAGE_SHIFT);
   2401 	} else if(fs->lfs_ivnode->v_size > LFS_MAX_BYTES) {
   2402 		simple_lock(&fs->lfs_interlock);
   2403 		fs->lfs_flags |= LFS_WARNED;
   2404 		simple_unlock(&fs->lfs_interlock);
   2405 		log(LOG_NOTICE, "lfs_mountfs: entire ifile of length %" PRId64
   2406 				" cannot fit in %lu buffer bytes\n",
   2407 				fs->lfs_ivnode->v_size, LFS_MAX_BYTES);
   2408 		log(LOG_NOTICE, "lfs_mountfs: please consider increasing"
   2409 				" BUFPAGES to at least %" PRId64 "\n",
   2410 				LFS_INVERSE_MAX_BYTES(fs->lfs_ivnode->v_size -
   2411 						      (fs->lfs_segtabsz <<
   2412 						       fs->lfs_bshift)) >>
   2413 				PAGE_SHIFT);
   2414 	}
   2415 }
   2416 
   2417 /*
   2418  * Resize the filesystem to contain the specified number of segments.
   2419  */
   2420 int
   2421 lfs_resize_fs(struct lfs *fs, int newnsegs)
   2422 {
   2423 	SEGUSE *sup;
   2424 	struct buf *bp, *obp;
   2425 	daddr_t olast, nlast, ilast, noff, start, end;
   2426 	struct vnode *ivp;
   2427 	struct inode *ip;
   2428 	int error, badnews, inc, oldnsegs;
   2429 	int sbbytes, csbbytes, gain, cgain;
   2430 	int i;
   2431 
   2432 	/* Only support v2 and up */
   2433 	if (fs->lfs_version < 2)
   2434 		return EOPNOTSUPP;
   2435 
   2436 	/* If we're doing nothing, do it fast */
   2437 	oldnsegs = fs->lfs_nseg;
   2438 	if (newnsegs == oldnsegs)
   2439 		return 0;
   2440 
   2441 	/* We always have to have two superblocks */
   2442 	if (newnsegs <= dtosn(fs, fs->lfs_sboffs[1]))
   2443 		return EFBIG;
   2444 
   2445 	ivp = fs->lfs_ivnode;
   2446 	ip = VTOI(ivp);
   2447 	error = 0;
   2448 
   2449 	/* Take the segment lock so no one else calls lfs_newseg() */
   2450 	lfs_seglock(fs, SEGM_PROT);
   2451 
   2452 	/*
   2453 	 * Make sure the segments we're going to be losing, if any,
   2454 	 * are in fact empty.  We hold the seglock, so their status
   2455 	 * cannot change underneath us.  Count the superblocks we lose,
   2456 	 * while we're at it.
   2457 	 */
   2458 	sbbytes = csbbytes = 0;
   2459 	cgain = 0;
   2460 	for (i = newnsegs; i < oldnsegs; i++) {
   2461 		LFS_SEGENTRY(sup, fs, i, bp);
   2462 		badnews = sup->su_nbytes || !(sup->su_flags & SEGUSE_INVAL);
   2463 		if (sup->su_flags & SEGUSE_SUPERBLOCK)
   2464 			sbbytes += LFS_SBPAD;
   2465 		if (!(sup->su_flags & SEGUSE_DIRTY)) {
   2466 			++cgain;
   2467 			if (sup->su_flags & SEGUSE_SUPERBLOCK)
   2468 				csbbytes += LFS_SBPAD;
   2469 		}
   2470 		brelse(bp);
   2471 		if (badnews) {
   2472 			error = EBUSY;
   2473 			goto out;
   2474 		}
   2475 	}
   2476 
   2477 	/* Note old and new segment table endpoints, and old ifile size */
   2478 	olast = fs->lfs_cleansz + fs->lfs_segtabsz;
   2479 	nlast = howmany(newnsegs, fs->lfs_sepb) + fs->lfs_cleansz;
   2480 	ilast = ivp->v_size >> fs->lfs_bshift;
   2481 	noff = nlast - olast;
   2482 
   2483 	/*
   2484 	 * Make sure no one can use the Ifile while we change it around.
   2485 	 * Even after taking the iflock we need to make sure no one still
   2486 	 * is holding Ifile buffers, so we get each one, to drain them.
   2487 	 * (XXX this could be done better.)
   2488 	 */
   2489 	simple_lock(&fs->lfs_interlock);
   2490 	lockmgr(&fs->lfs_iflock, LK_EXCLUSIVE, &fs->lfs_interlock);
   2491 	simple_unlock(&fs->lfs_interlock);
   2492 	vn_lock(ivp, LK_EXCLUSIVE | LK_RETRY);
   2493 	for (i = 0; i < ilast; i++) {
   2494 		bread(ivp, i, fs->lfs_bsize, NOCRED, &bp);
   2495 		brelse(bp);
   2496 	}
   2497 
   2498 	/* Allocate new Ifile blocks */
   2499 	for (i = ilast; i < ilast + noff; i++) {
   2500 		if (lfs_balloc(ivp, i * fs->lfs_bsize, fs->lfs_bsize, NOCRED, 0,
   2501 			       &bp) != 0)
   2502 			panic("balloc extending ifile");
   2503 		memset(bp->b_data, 0, fs->lfs_bsize);
   2504 		VOP_BWRITE(bp);
   2505 	}
   2506 
   2507 	/* Register new ifile size */
   2508 	ip->i_size += noff * fs->lfs_bsize;
   2509 	ip->i_ffs1_size = ip->i_size;
   2510 	uvm_vnp_setsize(ivp, ip->i_size);
   2511 
   2512 	/* Copy the inode table to its new position */
   2513 	if (noff != 0) {
   2514 		if (noff < 0) {
   2515 			start = nlast;
   2516 			end = ilast + noff;
   2517 			inc = 1;
   2518 		} else {
   2519 			start = ilast + noff - 1;
   2520 			end = nlast - 1;
   2521 			inc = -1;
   2522 		}
   2523 		for (i = start; i != end; i += inc) {
   2524 			if (bread(ivp, i, fs->lfs_bsize, NOCRED, &bp) != 0)
   2525 				panic("resize: bread dst blk failed");
   2526 			if (bread(ivp, i - noff, fs->lfs_bsize, NOCRED, &obp))
   2527 				panic("resize: bread src blk failed");
   2528 			memcpy(bp->b_data, obp->b_data, fs->lfs_bsize);
   2529 			VOP_BWRITE(bp);
   2530 			brelse(obp);
   2531 		}
   2532 	}
   2533 
   2534 	/* If we are expanding, write the new empty SEGUSE entries */
   2535 	if (newnsegs > oldnsegs) {
   2536 		for (i = oldnsegs; i < newnsegs; i++) {
   2537 			if ((error = bread(ivp, i / fs->lfs_sepb +
   2538 					   fs->lfs_cleansz,
   2539 					   fs->lfs_bsize, NOCRED, &bp)) != 0)
   2540 				panic("lfs: ifile read: %d", error);
   2541 			while ((i + 1) % fs->lfs_sepb && i < newnsegs) {
   2542 				sup = &((SEGUSE *)bp->b_data)[i % fs->lfs_sepb];
   2543 				memset(sup, 0, sizeof(*sup));
   2544 				i++;
   2545 			}
   2546 			VOP_BWRITE(bp);
   2547 		}
   2548 	}
   2549 
   2550 	/* Zero out unused superblock offsets */
   2551 	for (i = 2; i < LFS_MAXNUMSB; i++)
   2552 		if (dtosn(fs, fs->lfs_sboffs[i]) >= newnsegs)
   2553 			fs->lfs_sboffs[i] = 0x0;
   2554 
   2555 	/*
   2556 	 * Correct superblock entries that depend on fs size.
   2557 	 * The computations of these are as follows:
   2558 	 *
   2559 	 * size  = segtod(fs, nseg)
   2560 	 * dsize = segtod(fs, nseg - minfreeseg) - btofsb(#super * LFS_SBPAD)
   2561 	 * bfree = dsize - btofsb(fs, bsize * nseg / 2) - blocks_actually_used
   2562 	 * avail = segtod(fs, nclean) - btofsb(#clean_super * LFS_SBPAD)
   2563 	 *         + (segtod(fs, 1) - (offset - curseg))
   2564 	 *	   - segtod(fs, minfreeseg - (minfreeseg / 2))
   2565 	 *
   2566 	 * XXX - we should probably adjust minfreeseg as well.
   2567 	 */
   2568 	gain = (newnsegs - oldnsegs);
   2569 	fs->lfs_nseg = newnsegs;
   2570 	fs->lfs_segtabsz = nlast - fs->lfs_cleansz;
   2571 	fs->lfs_size += gain * btofsb(fs, fs->lfs_ssize);
   2572 	fs->lfs_dsize += gain * btofsb(fs, fs->lfs_ssize) - btofsb(fs, sbbytes);
   2573 	fs->lfs_bfree += gain * btofsb(fs, fs->lfs_ssize) - btofsb(fs, sbbytes)
   2574 		       - gain * btofsb(fs, fs->lfs_bsize / 2);
   2575 	if (gain > 0) {
   2576 		fs->lfs_nclean += gain;
   2577 		fs->lfs_avail += gain * btofsb(fs, fs->lfs_ssize);
   2578 	} else {
   2579 		fs->lfs_nclean -= cgain;
   2580 		fs->lfs_avail -= cgain * btofsb(fs, fs->lfs_ssize) -
   2581 				 btofsb(fs, csbbytes);
   2582 	}
   2583 
   2584 	/* Resize segment flag cache */
   2585 	fs->lfs_suflags[0] = (u_int32_t *)realloc(fs->lfs_suflags[0],
   2586 						  fs->lfs_nseg * sizeof(u_int32_t),
   2587 						  M_SEGMENT, M_WAITOK);
   2588 	fs->lfs_suflags[1] = (u_int32_t *)realloc(fs->lfs_suflags[0],
   2589 						  fs->lfs_nseg * sizeof(u_int32_t),
   2590 						  M_SEGMENT, M_WAITOK);
   2591 	for (i = oldnsegs; i < newnsegs; i++)
   2592 		fs->lfs_suflags[0][i] = fs->lfs_suflags[1][i] = 0x0;
   2593 
   2594 	/* Truncate Ifile if necessary */
   2595 	if (noff < 0)
   2596 		lfs_truncate(ivp, ivp->v_size + (noff << fs->lfs_bshift), 0,
   2597 			     NOCRED, curlwp);
   2598 
   2599 	/* Update cleaner info so the cleaner can die */
   2600 	bread(ivp, 0, fs->lfs_bsize, NOCRED, &bp);
   2601 	((CLEANERINFO *)bp->b_data)->clean = fs->lfs_nclean;
   2602 	((CLEANERINFO *)bp->b_data)->dirty = fs->lfs_nseg - fs->lfs_nclean;
   2603 	VOP_BWRITE(bp);
   2604 
   2605 	/* Let Ifile accesses proceed */
   2606 	VOP_UNLOCK(ivp, 0);
   2607 	simple_lock(&fs->lfs_interlock);
   2608 	lockmgr(&fs->lfs_iflock, LK_RELEASE, &fs->lfs_interlock);
   2609 	simple_unlock(&fs->lfs_interlock);
   2610 
   2611     out:
   2612 	lfs_segunlock(fs);
   2613 	return error;
   2614 }
   2615