Home | History | Annotate | Line # | Download | only in lfs
lfs_vfsops.c revision 1.310
      1 /*	$NetBSD: lfs_vfsops.c,v 1.310 2013/07/28 01:10:49 dholland Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000, 2001, 2002, 2003, 2007, 2007
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Konrad E. Schroder <perseant (at) hhhh.org>.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 /*-
     33  * Copyright (c) 1989, 1991, 1993, 1994
     34  *	The Regents of the University of California.  All rights reserved.
     35  *
     36  * Redistribution and use in source and binary forms, with or without
     37  * modification, are permitted provided that the following conditions
     38  * are met:
     39  * 1. Redistributions of source code must retain the above copyright
     40  *    notice, this list of conditions and the following disclaimer.
     41  * 2. Redistributions in binary form must reproduce the above copyright
     42  *    notice, this list of conditions and the following disclaimer in the
     43  *    documentation and/or other materials provided with the distribution.
     44  * 3. Neither the name of the University nor the names of its contributors
     45  *    may be used to endorse or promote products derived from this software
     46  *    without specific prior written permission.
     47  *
     48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     58  * SUCH DAMAGE.
     59  *
     60  *	@(#)lfs_vfsops.c	8.20 (Berkeley) 6/10/95
     61  */
     62 
     63 #include <sys/cdefs.h>
     64 __KERNEL_RCSID(0, "$NetBSD: lfs_vfsops.c,v 1.310 2013/07/28 01:10:49 dholland Exp $");
     65 
     66 #if defined(_KERNEL_OPT)
     67 #include "opt_lfs.h"
     68 #include "opt_quota.h"
     69 #endif
     70 
     71 #include <sys/param.h>
     72 #include <sys/systm.h>
     73 #include <sys/namei.h>
     74 #include <sys/proc.h>
     75 #include <sys/kernel.h>
     76 #include <sys/vnode.h>
     77 #include <sys/mount.h>
     78 #include <sys/kthread.h>
     79 #include <sys/buf.h>
     80 #include <sys/device.h>
     81 #include <sys/mbuf.h>
     82 #include <sys/file.h>
     83 #include <sys/disklabel.h>
     84 #include <sys/ioctl.h>
     85 #include <sys/errno.h>
     86 #include <sys/malloc.h>
     87 #include <sys/pool.h>
     88 #include <sys/socket.h>
     89 #include <sys/syslog.h>
     90 #include <uvm/uvm_extern.h>
     91 #include <sys/sysctl.h>
     92 #include <sys/conf.h>
     93 #include <sys/kauth.h>
     94 #include <sys/module.h>
     95 #include <sys/syscallvar.h>
     96 #include <sys/syscall.h>
     97 #include <sys/syscallargs.h>
     98 
     99 #include <miscfs/specfs/specdev.h>
    100 
    101 #include <ufs/lfs/ulfs_quotacommon.h>
    102 #include <ufs/lfs/ulfs_inode.h>
    103 #include <ufs/lfs/ulfsmount.h>
    104 #include <ufs/lfs/ulfs_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_kernel.h>
    113 #include <ufs/lfs/lfs_extern.h>
    114 
    115 #include <miscfs/genfs/genfs.h>
    116 #include <miscfs/genfs/genfs_node.h>
    117 
    118 MODULE(MODULE_CLASS_VFS, lfs, NULL);
    119 
    120 static int lfs_gop_write(struct vnode *, struct vm_page **, int, int);
    121 static int lfs_mountfs(struct vnode *, struct mount *, struct lwp *);
    122 
    123 static struct sysctllog *lfs_sysctl_log;
    124 
    125 extern const struct vnodeopv_desc lfs_vnodeop_opv_desc;
    126 extern const struct vnodeopv_desc lfs_specop_opv_desc;
    127 extern const struct vnodeopv_desc lfs_fifoop_opv_desc;
    128 
    129 pid_t lfs_writer_daemon = 0;
    130 lwpid_t lfs_writer_lid = 0;
    131 int lfs_do_flush = 0;
    132 #ifdef LFS_KERNEL_RFW
    133 int lfs_do_rfw = 0;
    134 #endif
    135 
    136 const struct vnodeopv_desc * const lfs_vnodeopv_descs[] = {
    137 	&lfs_vnodeop_opv_desc,
    138 	&lfs_specop_opv_desc,
    139 	&lfs_fifoop_opv_desc,
    140 	NULL,
    141 };
    142 
    143 struct vfsops lfs_vfsops = {
    144 	MOUNT_LFS,
    145 	sizeof (struct ulfs_args),
    146 	lfs_mount,
    147 	ulfs_start,
    148 	lfs_unmount,
    149 	ulfs_root,
    150 	ulfs_quotactl,
    151 	lfs_statvfs,
    152 	lfs_sync,
    153 	lfs_vget,
    154 	lfs_fhtovp,
    155 	lfs_vptofh,
    156 	lfs_init,
    157 	lfs_reinit,
    158 	lfs_done,
    159 	lfs_mountroot,
    160 	(int (*)(struct mount *, struct vnode *, struct timespec *)) eopnotsupp,
    161 	vfs_stdextattrctl,
    162 	(void *)eopnotsupp,	/* vfs_suspendctl */
    163 	genfs_renamelock_enter,
    164 	genfs_renamelock_exit,
    165 	(void *)eopnotsupp,
    166 	lfs_vnodeopv_descs,
    167 	0,
    168 	{ NULL, NULL },
    169 };
    170 
    171 const struct genfs_ops lfs_genfsops = {
    172 	.gop_size = lfs_gop_size,
    173 	.gop_alloc = ulfs_gop_alloc,
    174 	.gop_write = lfs_gop_write,
    175 	.gop_markupdate = ulfs_gop_markupdate,
    176 };
    177 
    178 struct shortlong {
    179 	const char *sname;
    180 	const char *lname;
    181 };
    182 
    183 static int
    184 sysctl_lfs_dostats(SYSCTLFN_ARGS)
    185 {
    186 	extern struct lfs_stats lfs_stats;
    187 	extern int lfs_dostats;
    188 	int error;
    189 
    190 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
    191 	if (error || newp == NULL)
    192 		return (error);
    193 
    194 	if (lfs_dostats == 0)
    195 		memset(&lfs_stats, 0, sizeof(lfs_stats));
    196 
    197 	return (0);
    198 }
    199 
    200 static void
    201 lfs_sysctl_setup(struct sysctllog **clog)
    202 {
    203 	int i;
    204 	extern int lfs_writeindir, lfs_dostats, lfs_clean_vnhead,
    205 		   lfs_fs_pagetrip, lfs_ignore_lazy_sync;
    206 #ifdef DEBUG
    207 	extern int lfs_debug_log_subsys[DLOG_MAX];
    208 	struct shortlong dlog_names[DLOG_MAX] = { /* Must match lfs.h ! */
    209 		{ "rollforward", "Debug roll-forward code" },
    210 		{ "alloc",	"Debug inode allocation and free list" },
    211 		{ "avail",	"Debug space-available-now accounting" },
    212 		{ "flush",	"Debug flush triggers" },
    213 		{ "lockedlist",	"Debug locked list accounting" },
    214 		{ "vnode_verbose", "Verbose per-vnode-written debugging" },
    215 		{ "vnode",	"Debug vnode use during segment write" },
    216 		{ "segment",	"Debug segment writing" },
    217 		{ "seguse",	"Debug segment used-bytes accounting" },
    218 		{ "cleaner",	"Debug cleaning routines" },
    219 		{ "mount",	"Debug mount/unmount routines" },
    220 		{ "pagecache",	"Debug UBC interactions" },
    221 		{ "dirop",	"Debug directory-operation accounting" },
    222 		{ "malloc",	"Debug private malloc accounting" },
    223 	};
    224 #endif /* DEBUG */
    225 	struct shortlong stat_names[] = { /* Must match lfs.h! */
    226 		{ "segsused",	    "Number of new segments allocated" },
    227 		{ "psegwrites",	    "Number of partial-segment writes" },
    228 		{ "psyncwrites",    "Number of synchronous partial-segment"
    229 				    " writes" },
    230 		{ "pcleanwrites",   "Number of partial-segment writes by the"
    231 				    " cleaner" },
    232 		{ "blocktot",       "Number of blocks written" },
    233 		{ "cleanblocks",    "Number of blocks written by the cleaner" },
    234 		{ "ncheckpoints",   "Number of checkpoints made" },
    235 		{ "nwrites",        "Number of whole writes" },
    236 		{ "nsync_writes",   "Number of synchronous writes" },
    237 		{ "wait_exceeded",  "Number of times writer waited for"
    238 				    " cleaner" },
    239 		{ "write_exceeded", "Number of times writer invoked flush" },
    240 		{ "flush_invoked",  "Number of times flush was invoked" },
    241 		{ "vflush_invoked", "Number of time vflush was called" },
    242 		{ "clean_inlocked", "Number of vnodes skipped for VI_XLOCK" },
    243 		{ "clean_vnlocked", "Number of vnodes skipped for vget failure" },
    244 		{ "segs_reclaimed", "Number of segments reclaimed" },
    245 	};
    246 
    247 	sysctl_createv(clog, 0, NULL, NULL,
    248 		       CTLFLAG_PERMANENT,
    249 		       CTLTYPE_NODE, "vfs", NULL,
    250 		       NULL, 0, NULL, 0,
    251 		       CTL_VFS, CTL_EOL);
    252 	sysctl_createv(clog, 0, NULL, NULL,
    253 		       CTLFLAG_PERMANENT,
    254 		       CTLTYPE_NODE, "lfs",
    255 		       SYSCTL_DESCR("Log-structured file system"),
    256 		       NULL, 0, NULL, 0,
    257 		       CTL_VFS, 5, CTL_EOL);
    258 	/*
    259 	 * XXX the "5" above could be dynamic, thereby eliminating one
    260 	 * more instance of the "number to vfs" mapping problem, but
    261 	 * "5" is the order as taken from sys/mount.h
    262 	 */
    263 
    264 	sysctl_createv(clog, 0, NULL, NULL,
    265 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    266 		       CTLTYPE_INT, "flushindir", NULL,
    267 		       NULL, 0, &lfs_writeindir, 0,
    268 		       CTL_VFS, 5, LFS_WRITEINDIR, CTL_EOL);
    269 	sysctl_createv(clog, 0, NULL, NULL,
    270 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    271 		       CTLTYPE_INT, "clean_vnhead", NULL,
    272 		       NULL, 0, &lfs_clean_vnhead, 0,
    273 		       CTL_VFS, 5, LFS_CLEAN_VNHEAD, CTL_EOL);
    274 	sysctl_createv(clog, 0, NULL, NULL,
    275 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    276 		       CTLTYPE_INT, "dostats",
    277 		       SYSCTL_DESCR("Maintain statistics on LFS operations"),
    278 		       sysctl_lfs_dostats, 0, &lfs_dostats, 0,
    279 		       CTL_VFS, 5, LFS_DOSTATS, CTL_EOL);
    280 	sysctl_createv(clog, 0, NULL, NULL,
    281 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    282 		       CTLTYPE_INT, "pagetrip",
    283 		       SYSCTL_DESCR("How many dirty pages in fs triggers"
    284 				    " a flush"),
    285 		       NULL, 0, &lfs_fs_pagetrip, 0,
    286 		       CTL_VFS, 5, LFS_FS_PAGETRIP, CTL_EOL);
    287 	sysctl_createv(clog, 0, NULL, NULL,
    288 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    289 		       CTLTYPE_INT, "ignore_lazy_sync",
    290 		       SYSCTL_DESCR("Lazy Sync is ignored entirely"),
    291 		       NULL, 0, &lfs_ignore_lazy_sync, 0,
    292 		       CTL_VFS, 5, LFS_IGNORE_LAZY_SYNC, CTL_EOL);
    293 #ifdef LFS_KERNEL_RFW
    294 	sysctl_createv(clog, 0, NULL, NULL,
    295 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    296 		       CTLTYPE_INT, "rfw",
    297 		       SYSCTL_DESCR("Use in-kernel roll-forward on mount"),
    298 		       NULL, 0, &lfs_do_rfw, 0,
    299 		       CTL_VFS, 5, LFS_DO_RFW, CTL_EOL);
    300 #endif
    301 
    302 	sysctl_createv(clog, 0, NULL, NULL,
    303 		       CTLFLAG_PERMANENT,
    304 		       CTLTYPE_NODE, "stats",
    305 		       SYSCTL_DESCR("Debugging options"),
    306 		       NULL, 0, NULL, 0,
    307 		       CTL_VFS, 5, LFS_STATS, CTL_EOL);
    308 	for (i = 0; i < sizeof(struct lfs_stats) / sizeof(u_int); i++) {
    309 		sysctl_createv(clog, 0, NULL, NULL,
    310 			       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
    311 			       CTLTYPE_INT, stat_names[i].sname,
    312 			       SYSCTL_DESCR(stat_names[i].lname),
    313 			       NULL, 0, &(((u_int *)&lfs_stats.segsused)[i]),
    314 			       0, CTL_VFS, 5, LFS_STATS, i, CTL_EOL);
    315 	}
    316 
    317 #ifdef DEBUG
    318 	sysctl_createv(clog, 0, NULL, NULL,
    319 		       CTLFLAG_PERMANENT,
    320 		       CTLTYPE_NODE, "debug",
    321 		       SYSCTL_DESCR("Debugging options"),
    322 		       NULL, 0, NULL, 0,
    323 		       CTL_VFS, 5, LFS_DEBUGLOG, CTL_EOL);
    324 	for (i = 0; i < DLOG_MAX; i++) {
    325 		sysctl_createv(clog, 0, NULL, NULL,
    326 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    327 			       CTLTYPE_INT, dlog_names[i].sname,
    328 			       SYSCTL_DESCR(dlog_names[i].lname),
    329 			       NULL, 0, &(lfs_debug_log_subsys[i]), 0,
    330 			       CTL_VFS, 5, LFS_DEBUGLOG, i, CTL_EOL);
    331 	}
    332 #endif
    333 }
    334 
    335 /* old cleaner syscall interface.  see VOP_FCNTL() */
    336 static const struct syscall_package lfs_syscalls[] = {
    337 	{ SYS_lfs_bmapv,	0, (sy_call_t *)sys_lfs_bmapv		},
    338 	{ SYS_lfs_markv,	0, (sy_call_t *)sys_lfs_markv		},
    339 	{ SYS_lfs_segclean,	0, (sy_call_t *)sys___lfs_segwait50	},
    340 	{ 0, 0, NULL },
    341 };
    342 
    343 static int
    344 lfs_modcmd(modcmd_t cmd, void *arg)
    345 {
    346 	int error;
    347 
    348 	switch (cmd) {
    349 	case MODULE_CMD_INIT:
    350 		error = syscall_establish(NULL, lfs_syscalls);
    351 		if (error)
    352 			return error;
    353 		error = vfs_attach(&lfs_vfsops);
    354 		if (error != 0) {
    355 			syscall_disestablish(NULL, lfs_syscalls);
    356 			break;
    357 		}
    358 		lfs_sysctl_setup(&lfs_sysctl_log);
    359 		break;
    360 	case MODULE_CMD_FINI:
    361 		error = vfs_detach(&lfs_vfsops);
    362 		if (error != 0)
    363 			break;
    364 		syscall_disestablish(NULL, lfs_syscalls);
    365 		sysctl_teardown(&lfs_sysctl_log);
    366 		break;
    367 	default:
    368 		error = ENOTTY;
    369 		break;
    370 	}
    371 
    372 	return (error);
    373 }
    374 
    375 /*
    376  * XXX Same structure as FFS inodes?  Should we share a common pool?
    377  */
    378 struct pool lfs_inode_pool;
    379 struct pool lfs_dinode_pool;
    380 struct pool lfs_inoext_pool;
    381 struct pool lfs_lbnentry_pool;
    382 
    383 /*
    384  * The writer daemon.  UVM keeps track of how many dirty pages we are holding
    385  * in lfs_subsys_pages; the daemon flushes the filesystem when this value
    386  * crosses the (user-defined) threshhold LFS_MAX_PAGES.
    387  */
    388 static void
    389 lfs_writerd(void *arg)
    390 {
    391  	struct mount *mp, *nmp;
    392  	struct lfs *fs;
    393 	struct vfsops *vfs = NULL;
    394  	int fsflags;
    395  	int loopcount;
    396 	int skipc;
    397 	int lfsc;
    398 	int wrote_something = 0;
    399 
    400 	mutex_enter(&lfs_lock);
    401  	lfs_writer_daemon = curproc->p_pid;
    402 	lfs_writer_lid = curlwp->l_lid;
    403 	mutex_exit(&lfs_lock);
    404 
    405 	/* Take an extra reference to the LFS vfsops. */
    406 	vfs = vfs_getopsbyname(MOUNT_LFS);
    407 
    408  	mutex_enter(&lfs_lock);
    409  	for (;;) {
    410 		KASSERT(mutex_owned(&lfs_lock));
    411 		if (wrote_something == 0)
    412 			mtsleep(&lfs_writer_daemon, PVM, "lfswriter", hz/10 + 1,
    413 				&lfs_lock);
    414 
    415 		KASSERT(mutex_owned(&lfs_lock));
    416 		loopcount = 0;
    417 		wrote_something = 0;
    418 
    419 		/*
    420 		 * If global state wants a flush, flush everything.
    421 		 */
    422 		if (lfs_do_flush || locked_queue_count > LFS_MAX_BUFS ||
    423 			locked_queue_bytes > LFS_MAX_BYTES ||
    424 			lfs_subsys_pages > LFS_MAX_PAGES) {
    425 
    426 			if (lfs_do_flush) {
    427 				DLOG((DLOG_FLUSH, "lfs_writerd: lfs_do_flush\n"));
    428 			}
    429 			if (locked_queue_count > LFS_MAX_BUFS) {
    430 				DLOG((DLOG_FLUSH, "lfs_writerd: lqc = %d, max %d\n",
    431 				      locked_queue_count, LFS_MAX_BUFS));
    432 			}
    433 			if (locked_queue_bytes > LFS_MAX_BYTES) {
    434 				DLOG((DLOG_FLUSH, "lfs_writerd: lqb = %ld, max %ld\n",
    435 				      locked_queue_bytes, LFS_MAX_BYTES));
    436 			}
    437 			if (lfs_subsys_pages > LFS_MAX_PAGES) {
    438 				DLOG((DLOG_FLUSH, "lfs_writerd: lssp = %d, max %d\n",
    439 				      lfs_subsys_pages, LFS_MAX_PAGES));
    440 			}
    441 
    442 			lfs_flush(NULL, SEGM_WRITERD, 0);
    443 			lfs_do_flush = 0;
    444 			KASSERT(mutex_owned(&lfs_lock));
    445 			continue;
    446 		}
    447 		KASSERT(mutex_owned(&lfs_lock));
    448 		mutex_exit(&lfs_lock);
    449 
    450  		/*
    451  		 * Look through the list of LFSs to see if any of them
    452  		 * have requested pageouts.
    453  		 */
    454  		mutex_enter(&mountlist_lock);
    455 		lfsc = 0;
    456 		skipc = 0;
    457  		for (mp = CIRCLEQ_FIRST(&mountlist); mp != (void *)&mountlist;
    458  		     mp = nmp) {
    459  			if (vfs_busy(mp, &nmp)) {
    460 				++skipc;
    461  				continue;
    462  			}
    463 			KASSERT(!mutex_owned(&lfs_lock));
    464  			if (strncmp(mp->mnt_stat.f_fstypename, MOUNT_LFS,
    465  			    sizeof(mp->mnt_stat.f_fstypename)) == 0) {
    466 				++lfsc;
    467  				fs = VFSTOULFS(mp)->um_lfs;
    468 				int32_t ooffset = 0;
    469 				fsflags = SEGM_SINGLE;
    470 
    471  				mutex_enter(&lfs_lock);
    472 				ooffset = fs->lfs_offset;
    473 
    474 				if (fs->lfs_nextseg < fs->lfs_curseg && fs->lfs_nowrap) {
    475 					/* Don't try to write if we're suspended */
    476 					mutex_exit(&lfs_lock);
    477 					vfs_unbusy(mp, false, &nmp);
    478 					continue;
    479 				}
    480 				if (LFS_STARVED_FOR_SEGS(fs)) {
    481 					mutex_exit(&lfs_lock);
    482 
    483 					DLOG((DLOG_FLUSH, "lfs_writerd: need cleaning before writing possible\n"));
    484 					lfs_wakeup_cleaner(fs);
    485 					vfs_unbusy(mp, false, &nmp);
    486 					continue;
    487 				}
    488 
    489  				if ((fs->lfs_dirvcount > LFS_MAX_FSDIROP(fs) ||
    490  				     lfs_dirvcount > LFS_MAX_DIROP) &&
    491 				    fs->lfs_dirops == 0) {
    492 					fsflags &= ~SEGM_SINGLE;
    493  					fsflags |= SEGM_CKP;
    494 					DLOG((DLOG_FLUSH, "lfs_writerd: checkpoint\n"));
    495 					lfs_flush_fs(fs, fsflags);
    496 				} else if (fs->lfs_pdflush) {
    497  					DLOG((DLOG_FLUSH, "lfs_writerd: pdflush set\n"));
    498  					lfs_flush_fs(fs, fsflags);
    499  				} else if (!TAILQ_EMPTY(&fs->lfs_pchainhd)) {
    500  					DLOG((DLOG_FLUSH, "lfs_writerd: pchain non-empty\n"));
    501  					mutex_exit(&lfs_lock);
    502  					lfs_writer_enter(fs, "wrdirop");
    503  					lfs_flush_pchain(fs);
    504  					lfs_writer_leave(fs);
    505 					mutex_enter(&lfs_lock);
    506 				}
    507 				if (fs->lfs_offset != ooffset)
    508 					++wrote_something;
    509 				mutex_exit(&lfs_lock);
    510  			}
    511 			KASSERT(!mutex_owned(&lfs_lock));
    512  			vfs_unbusy(mp, false, &nmp);
    513  		}
    514 		if (lfsc + skipc == 0) {
    515 			mutex_enter(&lfs_lock);
    516 			lfs_writer_daemon = 0;
    517 			lfs_writer_lid = 0;
    518 			mutex_exit(&lfs_lock);
    519 			mutex_exit(&mountlist_lock);
    520 			break;
    521 		}
    522  		mutex_exit(&mountlist_lock);
    523 
    524  		mutex_enter(&lfs_lock);
    525  	}
    526 	KASSERT(!mutex_owned(&lfs_lock));
    527 	KASSERT(!mutex_owned(&mountlist_lock));
    528 
    529 	/* Give up our extra reference so the module can be unloaded. */
    530 	mutex_enter(&vfs_list_lock);
    531 	if (vfs != NULL)
    532 		vfs->vfs_refcount--;
    533 	mutex_exit(&vfs_list_lock);
    534 
    535 	/* Done! */
    536 	kthread_exit(0);
    537 }
    538 
    539 /*
    540  * Initialize the filesystem, most work done by ulfs_init.
    541  */
    542 void
    543 lfs_init(void)
    544 {
    545 
    546 	malloc_type_attach(M_SEGMENT);
    547 	pool_init(&lfs_inode_pool, sizeof(struct inode), 0, 0, 0,
    548 	    "lfsinopl", &pool_allocator_nointr, IPL_NONE);
    549 	pool_init(&lfs_dinode_pool, sizeof(struct ulfs1_dinode), 0, 0, 0,
    550 	    "lfsdinopl", &pool_allocator_nointr, IPL_NONE);
    551 	pool_init(&lfs_inoext_pool, sizeof(struct lfs_inode_ext), 8, 0, 0,
    552 	    "lfsinoextpl", &pool_allocator_nointr, IPL_NONE);
    553 	pool_init(&lfs_lbnentry_pool, sizeof(struct lbnentry), 0, 0, 0,
    554 	    "lfslbnpool", &pool_allocator_nointr, IPL_NONE);
    555 	ulfs_init();
    556 
    557 #ifdef DEBUG
    558 	memset(lfs_log, 0, sizeof(lfs_log));
    559 #endif
    560 	mutex_init(&lfs_lock, MUTEX_DEFAULT, IPL_NONE);
    561 	cv_init(&locked_queue_cv, "lfsbuf");
    562 	cv_init(&lfs_writing_cv, "lfsflush");
    563 }
    564 
    565 void
    566 lfs_reinit(void)
    567 {
    568 	ulfs_reinit();
    569 }
    570 
    571 void
    572 lfs_done(void)
    573 {
    574 	ulfs_done();
    575 	mutex_destroy(&lfs_lock);
    576 	cv_destroy(&locked_queue_cv);
    577 	cv_destroy(&lfs_writing_cv);
    578 	pool_destroy(&lfs_inode_pool);
    579 	pool_destroy(&lfs_dinode_pool);
    580 	pool_destroy(&lfs_inoext_pool);
    581 	pool_destroy(&lfs_lbnentry_pool);
    582 	malloc_type_detach(M_SEGMENT);
    583 }
    584 
    585 /*
    586  * Called by main() when ulfs is going to be mounted as root.
    587  */
    588 int
    589 lfs_mountroot(void)
    590 {
    591 	extern struct vnode *rootvp;
    592 	struct lfs *fs = NULL;				/* LFS */
    593 	struct mount *mp;
    594 	struct lwp *l = curlwp;
    595 	struct ulfsmount *ump;
    596 	int error;
    597 
    598 	if (device_class(root_device) != DV_DISK)
    599 		return (ENODEV);
    600 
    601 	if (rootdev == NODEV)
    602 		return (ENODEV);
    603 	if ((error = vfs_rootmountalloc(MOUNT_LFS, "root_device", &mp))) {
    604 		vrele(rootvp);
    605 		return (error);
    606 	}
    607 	if ((error = lfs_mountfs(rootvp, mp, l))) {
    608 		vfs_unbusy(mp, false, NULL);
    609 		vfs_destroy(mp);
    610 		return (error);
    611 	}
    612 	mutex_enter(&mountlist_lock);
    613 	CIRCLEQ_INSERT_TAIL(&mountlist, mp, mnt_list);
    614 	mutex_exit(&mountlist_lock);
    615 	ump = VFSTOULFS(mp);
    616 	fs = ump->um_lfs;
    617 	memset(fs->lfs_fsmnt, 0, sizeof(fs->lfs_fsmnt));
    618 	(void)copystr(mp->mnt_stat.f_mntonname, fs->lfs_fsmnt, MNAMELEN - 1, 0);
    619 	(void)lfs_statvfs(mp, &mp->mnt_stat);
    620 	vfs_unbusy(mp, false, NULL);
    621 	setrootfstime((time_t)(VFSTOULFS(mp)->um_lfs->lfs_tstamp));
    622 	return (0);
    623 }
    624 
    625 /*
    626  * VFS Operations.
    627  *
    628  * mount system call
    629  */
    630 int
    631 lfs_mount(struct mount *mp, const char *path, void *data, size_t *data_len)
    632 {
    633 	struct lwp *l = curlwp;
    634 	struct vnode *devvp;
    635 	struct ulfs_args *args = data;
    636 	struct ulfsmount *ump = NULL;
    637 	struct lfs *fs = NULL;				/* LFS */
    638 	int error = 0, update;
    639 	mode_t accessmode;
    640 
    641 	if (*data_len < sizeof *args)
    642 		return EINVAL;
    643 
    644 	if (mp->mnt_flag & MNT_GETARGS) {
    645 		ump = VFSTOULFS(mp);
    646 		if (ump == NULL)
    647 			return EIO;
    648 		args->fspec = NULL;
    649 		*data_len = sizeof *args;
    650 		return 0;
    651 	}
    652 
    653 	update = mp->mnt_flag & MNT_UPDATE;
    654 
    655 	/* Check arguments */
    656 	if (args->fspec != NULL) {
    657 		/*
    658 		 * Look up the name and verify that it's sane.
    659 		 */
    660 		error = namei_simple_user(args->fspec,
    661 					NSM_FOLLOW_NOEMULROOT, &devvp);
    662 		if (error != 0)
    663 			return (error);
    664 
    665 		if (!update) {
    666 			/*
    667 			 * Be sure this is a valid block device
    668 			 */
    669 			if (devvp->v_type != VBLK)
    670 				error = ENOTBLK;
    671 			else if (bdevsw_lookup(devvp->v_rdev) == NULL)
    672 				error = ENXIO;
    673 		} else {
    674 			/*
    675 			 * Be sure we're still naming the same device
    676 			 * used for our initial mount
    677 			 */
    678 			ump = VFSTOULFS(mp);
    679 			if (devvp != ump->um_devvp) {
    680 				if (devvp->v_rdev != ump->um_devvp->v_rdev)
    681 					error = EINVAL;
    682 				else {
    683 					vrele(devvp);
    684 					devvp = ump->um_devvp;
    685 					vref(devvp);
    686 				}
    687 			}
    688 		}
    689 	} else {
    690 		if (!update) {
    691 			/* New mounts must have a filename for the device */
    692 			return (EINVAL);
    693 		} else {
    694 			/* Use the extant mount */
    695 			ump = VFSTOULFS(mp);
    696 			devvp = ump->um_devvp;
    697 			vref(devvp);
    698 		}
    699 	}
    700 
    701 
    702 	/*
    703 	 * If mount by non-root, then verify that user has necessary
    704 	 * permissions on the device.
    705 	 */
    706 	if (error == 0) {
    707 		accessmode = VREAD;
    708 		if (update ?
    709 		    (mp->mnt_iflag & IMNT_WANTRDWR) != 0 :
    710 		    (mp->mnt_flag & MNT_RDONLY) == 0)
    711 			accessmode |= VWRITE;
    712 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    713 		error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_MOUNT,
    714 		    KAUTH_REQ_SYSTEM_MOUNT_DEVICE, mp, devvp,
    715 		    KAUTH_ARG(accessmode));
    716 		VOP_UNLOCK(devvp);
    717 	}
    718 
    719 	if (error) {
    720 		vrele(devvp);
    721 		return (error);
    722 	}
    723 
    724 	if (!update) {
    725 		int flags;
    726 
    727 		if (mp->mnt_flag & MNT_RDONLY)
    728 			flags = FREAD;
    729 		else
    730 			flags = FREAD|FWRITE;
    731 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    732 		error = VOP_OPEN(devvp, flags, FSCRED);
    733 		VOP_UNLOCK(devvp);
    734 		if (error)
    735 			goto fail;
    736 		error = lfs_mountfs(devvp, mp, l);		/* LFS */
    737 		if (error) {
    738 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    739 			(void)VOP_CLOSE(devvp, flags, NOCRED);
    740 			VOP_UNLOCK(devvp);
    741 			goto fail;
    742 		}
    743 
    744 		ump = VFSTOULFS(mp);
    745 		fs = ump->um_lfs;
    746 	} else {
    747 		/*
    748 		 * Update the mount.
    749 		 */
    750 
    751 		/*
    752 		 * The initial mount got a reference on this
    753 		 * device, so drop the one obtained via
    754 		 * namei(), above.
    755 		 */
    756 		vrele(devvp);
    757 
    758 		ump = VFSTOULFS(mp);
    759 		fs = ump->um_lfs;
    760 		if (fs->lfs_ronly && (mp->mnt_iflag & IMNT_WANTRDWR)) {
    761 			/*
    762 			 * Changing from read-only to read/write.
    763 			 * Note in the superblocks that we're writing.
    764 			 */
    765 			fs->lfs_ronly = 0;
    766 			if (fs->lfs_pflags & LFS_PF_CLEAN) {
    767 				fs->lfs_pflags &= ~LFS_PF_CLEAN;
    768 				lfs_writesuper(fs, fs->lfs_sboffs[0]);
    769 				lfs_writesuper(fs, fs->lfs_sboffs[1]);
    770 			}
    771 		}
    772 		if (args->fspec == NULL)
    773 			return EINVAL;
    774 	}
    775 
    776 	error = set_statvfs_info(path, UIO_USERSPACE, args->fspec,
    777 	    UIO_USERSPACE, mp->mnt_op->vfs_name, mp, l);
    778 	if (error == 0)
    779 		(void)strncpy(fs->lfs_fsmnt, mp->mnt_stat.f_mntonname,
    780 			      sizeof(fs->lfs_fsmnt));
    781 	return error;
    782 
    783 fail:
    784 	vrele(devvp);
    785 	return (error);
    786 }
    787 
    788 
    789 /*
    790  * Common code for mount and mountroot
    791  * LFS specific
    792  */
    793 int
    794 lfs_mountfs(struct vnode *devvp, struct mount *mp, struct lwp *l)
    795 {
    796 	struct dlfs *tdfs, *dfs, *adfs;
    797 	struct lfs *fs;
    798 	struct ulfsmount *ump;
    799 	struct vnode *vp;
    800 	struct buf *bp, *abp;
    801 	dev_t dev;
    802 	int error, i, ronly, fsbsize;
    803 	kauth_cred_t cred;
    804 	CLEANERINFO *cip;
    805 	SEGUSE *sup;
    806 	daddr_t sb_addr;
    807 
    808 	cred = l ? l->l_cred : NOCRED;
    809 
    810 	/*
    811 	 * Flush out any old buffers remaining from a previous use.
    812 	 */
    813 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    814 	error = vinvalbuf(devvp, V_SAVE, cred, l, 0, 0);
    815 	VOP_UNLOCK(devvp);
    816 	if (error)
    817 		return (error);
    818 
    819 	ronly = (mp->mnt_flag & MNT_RDONLY) != 0;
    820 
    821 	/* Don't free random space on error. */
    822 	bp = NULL;
    823 	abp = NULL;
    824 	ump = NULL;
    825 
    826 	sb_addr = LFS_LABELPAD / DEV_BSIZE;
    827 	while (1) {
    828 		/* Read in the superblock. */
    829 		error = bread(devvp, sb_addr, LFS_SBPAD, cred, 0, &bp);
    830 		if (error)
    831 			goto out;
    832 		dfs = (struct dlfs *)bp->b_data;
    833 
    834 		/* Check the basics. */
    835 		if (dfs->dlfs_magic != LFS_MAGIC || dfs->dlfs_bsize > MAXBSIZE ||
    836 		    dfs->dlfs_version > LFS_VERSION ||
    837 		    dfs->dlfs_bsize < sizeof(struct dlfs)) {
    838 			DLOG((DLOG_MOUNT, "lfs_mountfs: primary superblock sanity failed\n"));
    839 			error = EINVAL;		/* XXX needs translation */
    840 			goto out;
    841 		}
    842 		if (dfs->dlfs_inodefmt > LFS_MAXINODEFMT) {
    843 			DLOG((DLOG_MOUNT, "lfs_mountfs: unknown inode format %d\n",
    844 			       dfs->dlfs_inodefmt));
    845 			error = EINVAL;
    846 			goto out;
    847 		}
    848 
    849 		if (dfs->dlfs_version == 1)
    850 			fsbsize = DEV_BSIZE;
    851 		else {
    852 			fsbsize = 1 << dfs->dlfs_ffshift;
    853 			/*
    854 			 * Could be, if the frag size is large enough, that we
    855 			 * don't have the "real" primary superblock.  If that's
    856 			 * the case, get the real one, and try again.
    857 			 */
    858 			if (sb_addr != (dfs->dlfs_sboffs[0] << (dfs->dlfs_ffshift - DEV_BSHIFT))) {
    859 				DLOG((DLOG_MOUNT, "lfs_mountfs: sb daddr"
    860 				      " 0x%llx is not right, trying 0x%llx\n",
    861 				      (long long)sb_addr,
    862 				      (long long)(dfs->dlfs_sboffs[0] << (dfs->dlfs_ffshift - DEV_BSHIFT))));
    863 				sb_addr = dfs->dlfs_sboffs[0] << (dfs->dlfs_ffshift - DEV_BSHIFT);
    864 				brelse(bp, 0);
    865 				continue;
    866 			}
    867 		}
    868 		break;
    869 	}
    870 
    871 	/*
    872 	 * Check the second superblock to see which is newer; then mount
    873 	 * using the older of the two.	This is necessary to ensure that
    874 	 * the filesystem is valid if it was not unmounted cleanly.
    875 	 */
    876 
    877 	if (dfs->dlfs_sboffs[1] &&
    878 	    dfs->dlfs_sboffs[1] - LFS_LABELPAD / fsbsize > LFS_SBPAD / fsbsize)
    879 	{
    880 		error = bread(devvp, dfs->dlfs_sboffs[1] * (fsbsize / DEV_BSIZE),
    881 			LFS_SBPAD, cred, 0, &abp);
    882 		if (error)
    883 			goto out;
    884 		adfs = (struct dlfs *)abp->b_data;
    885 
    886 		if (dfs->dlfs_version == 1) {
    887 			/* 1s resolution comparison */
    888 			if (adfs->dlfs_tstamp < dfs->dlfs_tstamp)
    889 				tdfs = adfs;
    890 			else
    891 				tdfs = dfs;
    892 		} else {
    893 			/* monotonic infinite-resolution comparison */
    894 			if (adfs->dlfs_serial < dfs->dlfs_serial)
    895 				tdfs = adfs;
    896 			else
    897 				tdfs = dfs;
    898 		}
    899 
    900 		/* Check the basics. */
    901 		if (tdfs->dlfs_magic != LFS_MAGIC ||
    902 		    tdfs->dlfs_bsize > MAXBSIZE ||
    903 		    tdfs->dlfs_version > LFS_VERSION ||
    904 		    tdfs->dlfs_bsize < sizeof(struct dlfs)) {
    905 			DLOG((DLOG_MOUNT, "lfs_mountfs: alt superblock"
    906 			      " sanity failed\n"));
    907 			error = EINVAL;		/* XXX needs translation */
    908 			goto out;
    909 		}
    910 	} else {
    911 		DLOG((DLOG_MOUNT, "lfs_mountfs: invalid alt superblock"
    912 		      " daddr=0x%x\n", dfs->dlfs_sboffs[1]));
    913 		error = EINVAL;
    914 		goto out;
    915 	}
    916 
    917 	/* Allocate the mount structure, copy the superblock into it. */
    918 	fs = kmem_zalloc(sizeof(struct lfs), KM_SLEEP);
    919 	memcpy(&fs->lfs_dlfs, tdfs, sizeof(struct dlfs));
    920 
    921 	/* Compatibility */
    922 	if (fs->lfs_version < 2) {
    923 		fs->lfs_sumsize = LFS_V1_SUMMARY_SIZE;
    924 		fs->lfs_ibsize = fs->lfs_bsize;
    925 		fs->lfs_start = fs->lfs_sboffs[0];
    926 		fs->lfs_tstamp = fs->lfs_otstamp;
    927 		fs->lfs_fsbtodb = 0;
    928 	}
    929 	if (fs->lfs_resvseg == 0)
    930 		fs->lfs_resvseg = MIN(fs->lfs_minfreeseg - 1, \
    931 			MAX(MIN_RESV_SEGS, fs->lfs_minfreeseg / 2 + 1));
    932 
    933 	/*
    934 	 * If we aren't going to be able to write meaningfully to this
    935 	 * filesystem, and were not mounted readonly, bomb out now.
    936 	 */
    937 	if (lfs_fsbtob(fs, LFS_NRESERVE(fs)) > LFS_MAX_BYTES && !ronly) {
    938 		DLOG((DLOG_MOUNT, "lfs_mount: to mount this filesystem read/write,"
    939 		      " we need BUFPAGES >= %lld\n",
    940 		      (long long)((bufmem_hiwater / bufmem_lowater) *
    941 				  LFS_INVERSE_MAX_BYTES(
    942 					  lfs_fsbtob(fs, LFS_NRESERVE(fs))) >> PAGE_SHIFT)));
    943 		kmem_free(fs, sizeof(struct lfs));
    944 		error = EFBIG; /* XXX needs translation */
    945 		goto out;
    946 	}
    947 
    948 	/* Before rolling forward, lock so vget will sleep for other procs */
    949 	if (l != NULL) {
    950 		fs->lfs_flags = LFS_NOTYET;
    951 		fs->lfs_rfpid = l->l_proc->p_pid;
    952 	}
    953 
    954 	ump = kmem_zalloc(sizeof(*ump), KM_SLEEP);
    955 	ump->um_lfs = fs;
    956 	ump->um_fstype = ULFS1;
    957 	if (sizeof(struct lfs) < LFS_SBPAD) {			/* XXX why? */
    958 		brelse(bp, BC_INVAL);
    959 		brelse(abp, BC_INVAL);
    960 	} else {
    961 		brelse(bp, 0);
    962 		brelse(abp, 0);
    963 	}
    964 	bp = NULL;
    965 	abp = NULL;
    966 
    967 
    968 	/* Set up the I/O information */
    969 	fs->lfs_devbsize = DEV_BSIZE;
    970 	fs->lfs_iocount = 0;
    971 	fs->lfs_diropwait = 0;
    972 	fs->lfs_activesb = 0;
    973 	fs->lfs_uinodes = 0;
    974 	fs->lfs_ravail = 0;
    975 	fs->lfs_favail = 0;
    976 	fs->lfs_sbactive = 0;
    977 
    978 	/* Set up the ifile and lock aflags */
    979 	fs->lfs_doifile = 0;
    980 	fs->lfs_writer = 0;
    981 	fs->lfs_dirops = 0;
    982 	fs->lfs_nadirop = 0;
    983 	fs->lfs_seglock = 0;
    984 	fs->lfs_pdflush = 0;
    985 	fs->lfs_sleepers = 0;
    986 	fs->lfs_pages = 0;
    987 	rw_init(&fs->lfs_fraglock);
    988 	rw_init(&fs->lfs_iflock);
    989 	cv_init(&fs->lfs_stopcv, "lfsstop");
    990 
    991 	/* Set the file system readonly/modify bits. */
    992 	fs->lfs_ronly = ronly;
    993 	if (ronly == 0)
    994 		fs->lfs_fmod = 1;
    995 
    996 	/* ulfs-level information */
    997 	fs->um_flags = 0;
    998 	fs->um_bptrtodb = fs->lfs_ffshift - DEV_BSHIFT;
    999 	fs->um_seqinc = fs->lfs_frag;
   1000 	fs->um_nindir = fs->lfs_nindir;
   1001 	fs->um_lognindir = ffs(fs->lfs_nindir) - 1;
   1002 	fs->um_maxsymlinklen = fs->lfs_maxsymlinklen;
   1003 	fs->um_dirblksiz = LFS_DIRBLKSIZ;
   1004 	fs->um_maxfilesize = fs->lfs_maxfilesize;
   1005 
   1006 	/* Initialize the mount structure. */
   1007 	dev = devvp->v_rdev;
   1008 	mp->mnt_data = ump;
   1009 	mp->mnt_stat.f_fsidx.__fsid_val[0] = (long)dev;
   1010 	mp->mnt_stat.f_fsidx.__fsid_val[1] = makefstype(MOUNT_LFS);
   1011 	mp->mnt_stat.f_fsid = mp->mnt_stat.f_fsidx.__fsid_val[0];
   1012 	mp->mnt_stat.f_namemax = LFS_MAXNAMLEN;
   1013 	mp->mnt_stat.f_iosize = fs->lfs_bsize;
   1014 	mp->mnt_flag |= MNT_LOCAL;
   1015 	mp->mnt_fs_bshift = fs->lfs_bshift;
   1016 	if (fs->um_maxsymlinklen > 0)
   1017 		mp->mnt_iflag |= IMNT_DTYPE;
   1018 
   1019 	ump->um_mountp = mp;
   1020 	ump->um_dev = dev;
   1021 	ump->um_devvp = devvp;
   1022 	for (i = 0; i < ULFS_MAXQUOTAS; i++)
   1023 		ump->um_quotas[i] = NULLVP;
   1024 	devvp->v_specmountpoint = mp;
   1025 
   1026 	/* Set up reserved memory for pageout */
   1027 	lfs_setup_resblks(fs);
   1028 	/* Set up vdirop tailq */
   1029 	TAILQ_INIT(&fs->lfs_dchainhd);
   1030 	/* and paging tailq */
   1031 	TAILQ_INIT(&fs->lfs_pchainhd);
   1032 	/* and delayed segment accounting for truncation list */
   1033 	LIST_INIT(&fs->lfs_segdhd);
   1034 
   1035 	/*
   1036 	 * We use the ifile vnode for almost every operation.  Instead of
   1037 	 * retrieving it from the hash table each time we retrieve it here,
   1038 	 * artificially increment the reference count and keep a pointer
   1039 	 * to it in the incore copy of the superblock.
   1040 	 */
   1041 	if ((error = VFS_VGET(mp, LFS_IFILE_INUM, &vp)) != 0) {
   1042 		DLOG((DLOG_MOUNT, "lfs_mountfs: ifile vget failed, error=%d\n", error));
   1043 		goto out;
   1044 	}
   1045 	fs->lfs_ivnode = vp;
   1046 	vref(vp);
   1047 
   1048 	/* Set up inode bitmap and order free list */
   1049 	lfs_order_freelist(fs);
   1050 
   1051 	/* Set up segment usage flags for the autocleaner. */
   1052 	fs->lfs_nactive = 0;
   1053 	fs->lfs_suflags = (u_int32_t **)malloc(2 * sizeof(u_int32_t *),
   1054 						M_SEGMENT, M_WAITOK);
   1055 	fs->lfs_suflags[0] = (u_int32_t *)malloc(fs->lfs_nseg * sizeof(u_int32_t),
   1056 						 M_SEGMENT, M_WAITOK);
   1057 	fs->lfs_suflags[1] = (u_int32_t *)malloc(fs->lfs_nseg * sizeof(u_int32_t),
   1058 						 M_SEGMENT, M_WAITOK);
   1059 	memset(fs->lfs_suflags[1], 0, fs->lfs_nseg * sizeof(u_int32_t));
   1060 	for (i = 0; i < fs->lfs_nseg; i++) {
   1061 		int changed;
   1062 
   1063 		LFS_SEGENTRY(sup, fs, i, bp);
   1064 		changed = 0;
   1065 		if (!ronly) {
   1066 			if (sup->su_nbytes == 0 &&
   1067 			    !(sup->su_flags & SEGUSE_EMPTY)) {
   1068 				sup->su_flags |= SEGUSE_EMPTY;
   1069 				++changed;
   1070 			} else if (!(sup->su_nbytes == 0) &&
   1071 				   (sup->su_flags & SEGUSE_EMPTY)) {
   1072 				sup->su_flags &= ~SEGUSE_EMPTY;
   1073 				++changed;
   1074 			}
   1075 			if (sup->su_flags & (SEGUSE_ACTIVE|SEGUSE_INVAL)) {
   1076 				sup->su_flags &= ~(SEGUSE_ACTIVE|SEGUSE_INVAL);
   1077 				++changed;
   1078 			}
   1079 		}
   1080 		fs->lfs_suflags[0][i] = sup->su_flags;
   1081 		if (changed)
   1082 			LFS_WRITESEGENTRY(sup, fs, i, bp);
   1083 		else
   1084 			brelse(bp, 0);
   1085 	}
   1086 
   1087 #ifdef LFS_KERNEL_RFW
   1088 	lfs_roll_forward(fs, mp, l);
   1089 #endif
   1090 
   1091 	/* If writing, sb is not clean; record in case of immediate crash */
   1092 	if (!fs->lfs_ronly) {
   1093 		fs->lfs_pflags &= ~LFS_PF_CLEAN;
   1094 		lfs_writesuper(fs, fs->lfs_sboffs[0]);
   1095 		lfs_writesuper(fs, fs->lfs_sboffs[1]);
   1096 	}
   1097 
   1098 	/* Allow vget now that roll-forward is complete */
   1099 	fs->lfs_flags &= ~(LFS_NOTYET);
   1100 	wakeup(&fs->lfs_flags);
   1101 
   1102 	/*
   1103 	 * Initialize the ifile cleaner info with information from
   1104 	 * the superblock.
   1105 	 */
   1106 	LFS_CLEANERINFO(cip, fs, bp);
   1107 	cip->clean = fs->lfs_nclean;
   1108 	cip->dirty = fs->lfs_nseg - fs->lfs_nclean;
   1109 	cip->avail = fs->lfs_avail;
   1110 	cip->bfree = fs->lfs_bfree;
   1111 	(void) LFS_BWRITE_LOG(bp); /* Ifile */
   1112 
   1113 	/*
   1114 	 * Mark the current segment as ACTIVE, since we're going to
   1115 	 * be writing to it.
   1116 	 */
   1117 	LFS_SEGENTRY(sup, fs, lfs_dtosn(fs, fs->lfs_offset), bp);
   1118 	sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
   1119 	fs->lfs_nactive++;
   1120 	LFS_WRITESEGENTRY(sup, fs, lfs_dtosn(fs, fs->lfs_offset), bp);  /* Ifile */
   1121 
   1122 	/* Now that roll-forward is done, unlock the Ifile */
   1123 	vput(vp);
   1124 
   1125 	/* Start the pagedaemon-anticipating daemon */
   1126 	mutex_enter(&lfs_lock);
   1127 	if (lfs_writer_daemon == 0 && lfs_writer_lid == 0 &&
   1128 	    kthread_create(PRI_BIO, 0, NULL,
   1129 	    lfs_writerd, NULL, NULL, "lfs_writer") != 0)
   1130 		panic("fork lfs_writer");
   1131 	mutex_exit(&lfs_lock);
   1132 
   1133 	printf("WARNING: the log-structured file system is experimental\n"
   1134 	    "WARNING: it may cause system crashes and/or corrupt data\n");
   1135 
   1136 	return (0);
   1137 
   1138 out:
   1139 	if (bp)
   1140 		brelse(bp, 0);
   1141 	if (abp)
   1142 		brelse(abp, 0);
   1143 	if (ump) {
   1144 		kmem_free(ump->um_lfs, sizeof(struct lfs));
   1145 		kmem_free(ump, sizeof(*ump));
   1146 		mp->mnt_data = NULL;
   1147 	}
   1148 
   1149 	return (error);
   1150 }
   1151 
   1152 /*
   1153  * unmount system call
   1154  */
   1155 int
   1156 lfs_unmount(struct mount *mp, int mntflags)
   1157 {
   1158 	struct lwp *l = curlwp;
   1159 	struct ulfsmount *ump;
   1160 	struct lfs *fs;
   1161 	int error, flags, ronly;
   1162 	vnode_t *vp;
   1163 
   1164 	flags = 0;
   1165 	if (mntflags & MNT_FORCE)
   1166 		flags |= FORCECLOSE;
   1167 
   1168 	ump = VFSTOULFS(mp);
   1169 	fs = ump->um_lfs;
   1170 
   1171 	/* Two checkpoints */
   1172 	lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
   1173 	lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
   1174 
   1175 	/* wake up the cleaner so it can die */
   1176 	lfs_wakeup_cleaner(fs);
   1177 	mutex_enter(&lfs_lock);
   1178 	while (fs->lfs_sleepers)
   1179 		mtsleep(&fs->lfs_sleepers, PRIBIO + 1, "lfs_sleepers", 0,
   1180 			&lfs_lock);
   1181 	mutex_exit(&lfs_lock);
   1182 
   1183 #ifdef LFS_QUOTA
   1184         if ((error = lfsquota1_umount(mp, flags)) != 0)
   1185 		return (error);
   1186 #endif
   1187 	if ((error = vflush(mp, fs->lfs_ivnode, flags)) != 0)
   1188 		return (error);
   1189 	if ((error = VFS_SYNC(mp, 1, l->l_cred)) != 0)
   1190 		return (error);
   1191 	vp = fs->lfs_ivnode;
   1192 	mutex_enter(vp->v_interlock);
   1193 	if (LIST_FIRST(&vp->v_dirtyblkhd))
   1194 		panic("lfs_unmount: still dirty blocks on ifile vnode");
   1195 	mutex_exit(vp->v_interlock);
   1196 
   1197 	/* Explicitly write the superblock, to update serial and pflags */
   1198 	fs->lfs_pflags |= LFS_PF_CLEAN;
   1199 	lfs_writesuper(fs, fs->lfs_sboffs[0]);
   1200 	lfs_writesuper(fs, fs->lfs_sboffs[1]);
   1201 	mutex_enter(&lfs_lock);
   1202 	while (fs->lfs_iocount)
   1203 		mtsleep(&fs->lfs_iocount, PRIBIO + 1, "lfs_umount", 0,
   1204 			&lfs_lock);
   1205 	mutex_exit(&lfs_lock);
   1206 
   1207 	/* Finish with the Ifile, now that we're done with it */
   1208 	vgone(fs->lfs_ivnode);
   1209 
   1210 	ronly = !fs->lfs_ronly;
   1211 	if (ump->um_devvp->v_type != VBAD)
   1212 		ump->um_devvp->v_specmountpoint = NULL;
   1213 	vn_lock(ump->um_devvp, LK_EXCLUSIVE | LK_RETRY);
   1214 	error = VOP_CLOSE(ump->um_devvp,
   1215 	    ronly ? FREAD : FREAD|FWRITE, NOCRED);
   1216 	vput(ump->um_devvp);
   1217 
   1218 	/* Complain about page leakage */
   1219 	if (fs->lfs_pages > 0)
   1220 		printf("lfs_unmount: still claim %d pages (%d in subsystem)\n",
   1221 			fs->lfs_pages, lfs_subsys_pages);
   1222 
   1223 	/* Free per-mount data structures */
   1224 	free(fs->lfs_ino_bitmap, M_SEGMENT);
   1225 	free(fs->lfs_suflags[0], M_SEGMENT);
   1226 	free(fs->lfs_suflags[1], M_SEGMENT);
   1227 	free(fs->lfs_suflags, M_SEGMENT);
   1228 	lfs_free_resblks(fs);
   1229 	cv_destroy(&fs->lfs_stopcv);
   1230 	rw_destroy(&fs->lfs_fraglock);
   1231 	rw_destroy(&fs->lfs_iflock);
   1232 
   1233 	kmem_free(fs, sizeof(struct lfs));
   1234 	kmem_free(ump, sizeof(*ump));
   1235 
   1236 	mp->mnt_data = NULL;
   1237 	mp->mnt_flag &= ~MNT_LOCAL;
   1238 	return (error);
   1239 }
   1240 
   1241 /*
   1242  * Get file system statistics.
   1243  *
   1244  * NB: We don't lock to access the superblock here, because it's not
   1245  * really that important if we get it wrong.
   1246  */
   1247 int
   1248 lfs_statvfs(struct mount *mp, struct statvfs *sbp)
   1249 {
   1250 	struct lfs *fs;
   1251 	struct ulfsmount *ump;
   1252 
   1253 	ump = VFSTOULFS(mp);
   1254 	fs = ump->um_lfs;
   1255 	if (fs->lfs_magic != LFS_MAGIC)
   1256 		panic("lfs_statvfs: magic");
   1257 
   1258 	sbp->f_bsize = fs->lfs_bsize;
   1259 	sbp->f_frsize = fs->lfs_fsize;
   1260 	sbp->f_iosize = fs->lfs_bsize;
   1261 	sbp->f_blocks = LFS_EST_NONMETA(fs) - VTOI(fs->lfs_ivnode)->i_lfs_effnblks;
   1262 
   1263 	sbp->f_bfree = LFS_EST_BFREE(fs);
   1264 	KASSERT(sbp->f_bfree <= fs->lfs_dsize);
   1265 #if 0
   1266 	if (sbp->f_bfree < 0)
   1267 		sbp->f_bfree = 0;
   1268 #endif
   1269 
   1270 	sbp->f_bresvd = LFS_EST_RSVD(fs);
   1271 	if (sbp->f_bfree > sbp->f_bresvd)
   1272 		sbp->f_bavail = sbp->f_bfree - sbp->f_bresvd;
   1273 	else
   1274 		sbp->f_bavail = 0;
   1275 
   1276 	sbp->f_files = fs->lfs_bfree / lfs_btofsb(fs, fs->lfs_ibsize)
   1277 	    * LFS_INOPB(fs);
   1278 	sbp->f_ffree = sbp->f_files - fs->lfs_nfiles;
   1279 	sbp->f_favail = sbp->f_ffree;
   1280 	sbp->f_fresvd = 0;
   1281 	copy_statvfs_info(sbp, mp);
   1282 	return (0);
   1283 }
   1284 
   1285 /*
   1286  * Go through the disk queues to initiate sandbagged IO;
   1287  * go through the inodes to write those that have been modified;
   1288  * initiate the writing of the super block if it has been modified.
   1289  *
   1290  * Note: we are always called with the filesystem marked `MPBUSY'.
   1291  */
   1292 int
   1293 lfs_sync(struct mount *mp, int waitfor, kauth_cred_t cred)
   1294 {
   1295 	int error;
   1296 	struct lfs *fs;
   1297 
   1298 	fs = VFSTOULFS(mp)->um_lfs;
   1299 	if (fs->lfs_ronly)
   1300 		return 0;
   1301 
   1302 	/* Snapshots should not hose the syncer */
   1303 	/*
   1304 	 * XXX Sync can block here anyway, since we don't have a very
   1305 	 * XXX good idea of how much data is pending.  If it's more
   1306 	 * XXX than a segment and lfs_nextseg is close to the end of
   1307 	 * XXX the log, we'll likely block.
   1308 	 */
   1309 	mutex_enter(&lfs_lock);
   1310 	if (fs->lfs_nowrap && fs->lfs_nextseg < fs->lfs_curseg) {
   1311 		mutex_exit(&lfs_lock);
   1312 		return 0;
   1313 	}
   1314 	mutex_exit(&lfs_lock);
   1315 
   1316 	lfs_writer_enter(fs, "lfs_dirops");
   1317 
   1318 	/* All syncs must be checkpoints until roll-forward is implemented. */
   1319 	DLOG((DLOG_FLUSH, "lfs_sync at 0x%x\n", fs->lfs_offset));
   1320 	error = lfs_segwrite(mp, SEGM_CKP | (waitfor ? SEGM_SYNC : 0));
   1321 	lfs_writer_leave(fs);
   1322 #ifdef LFS_QUOTA
   1323 	lfs_qsync(mp);
   1324 #endif
   1325 	return (error);
   1326 }
   1327 
   1328 /*
   1329  * Look up an LFS dinode number to find its incore vnode.  If not already
   1330  * in core, read it in from the specified device.  Return the inode locked.
   1331  * Detection and handling of mount points must be done by the calling routine.
   1332  */
   1333 int
   1334 lfs_vget(struct mount *mp, ino_t ino, struct vnode **vpp)
   1335 {
   1336 	struct lfs *fs;
   1337 	struct ulfs1_dinode *dip;
   1338 	struct inode *ip;
   1339 	struct buf *bp;
   1340 	struct ifile *ifp;
   1341 	struct vnode *vp;
   1342 	struct ulfsmount *ump;
   1343 	daddr_t daddr;
   1344 	dev_t dev;
   1345 	int error, retries;
   1346 	struct timespec ts;
   1347 
   1348 	memset(&ts, 0, sizeof ts);	/* XXX gcc */
   1349 
   1350 	ump = VFSTOULFS(mp);
   1351 	dev = ump->um_dev;
   1352 	fs = ump->um_lfs;
   1353 
   1354 	/*
   1355 	 * If the filesystem is not completely mounted yet, suspend
   1356 	 * any access requests (wait for roll-forward to complete).
   1357 	 */
   1358 	mutex_enter(&lfs_lock);
   1359 	while ((fs->lfs_flags & LFS_NOTYET) && curproc->p_pid != fs->lfs_rfpid)
   1360 		mtsleep(&fs->lfs_flags, PRIBIO+1, "lfs_notyet", 0,
   1361 			&lfs_lock);
   1362 	mutex_exit(&lfs_lock);
   1363 
   1364 retry:
   1365 	if ((*vpp = ulfs_ihashget(dev, ino, LK_EXCLUSIVE)) != NULL)
   1366 		return (0);
   1367 
   1368 	error = getnewvnode(VT_LFS, mp, lfs_vnodeop_p, NULL, &vp);
   1369 	if (error) {
   1370 		*vpp = NULL;
   1371 		 return (error);
   1372 	}
   1373 
   1374 	mutex_enter(&ulfs_hashlock);
   1375 	if (ulfs_ihashget(dev, ino, 0) != NULL) {
   1376 		mutex_exit(&ulfs_hashlock);
   1377 		ungetnewvnode(vp);
   1378 		goto retry;
   1379 	}
   1380 
   1381 	/* Translate the inode number to a disk address. */
   1382 	if (ino == LFS_IFILE_INUM)
   1383 		daddr = fs->lfs_idaddr;
   1384 	else {
   1385 		/* XXX bounds-check this too */
   1386 		LFS_IENTRY(ifp, fs, ino, bp);
   1387 		daddr = ifp->if_daddr;
   1388 		if (fs->lfs_version > 1) {
   1389 			ts.tv_sec = ifp->if_atime_sec;
   1390 			ts.tv_nsec = ifp->if_atime_nsec;
   1391 		}
   1392 
   1393 		brelse(bp, 0);
   1394 		if (daddr == LFS_UNUSED_DADDR) {
   1395 			*vpp = NULLVP;
   1396 			mutex_exit(&ulfs_hashlock);
   1397 			ungetnewvnode(vp);
   1398 			return (ENOENT);
   1399 		}
   1400 	}
   1401 
   1402 	/* Allocate/init new vnode/inode. */
   1403 	lfs_vcreate(mp, ino, vp);
   1404 
   1405 	/*
   1406 	 * Put it onto its hash chain and lock it so that other requests for
   1407 	 * this inode will block if they arrive while we are sleeping waiting
   1408 	 * for old data structures to be purged or for the contents of the
   1409 	 * disk portion of this inode to be read.
   1410 	 */
   1411 	ip = VTOI(vp);
   1412 	ulfs_ihashins(ip);
   1413 	mutex_exit(&ulfs_hashlock);
   1414 
   1415 	/*
   1416 	 * XXX
   1417 	 * This may not need to be here, logically it should go down with
   1418 	 * the i_devvp initialization.
   1419 	 * Ask Kirk.
   1420 	 */
   1421 	ip->i_lfs = ump->um_lfs;
   1422 
   1423 	/* Read in the disk contents for the inode, copy into the inode. */
   1424 	retries = 0;
   1425     again:
   1426 	error = bread(ump->um_devvp, LFS_FSBTODB(fs, daddr),
   1427 		(fs->lfs_version == 1 ? fs->lfs_bsize : fs->lfs_ibsize),
   1428 		NOCRED, 0, &bp);
   1429 	if (error) {
   1430 		/*
   1431 		 * The inode does not contain anything useful, so it would
   1432 		 * be misleading to leave it on its hash chain. With mode
   1433 		 * still zero, it will be unlinked and returned to the free
   1434 		 * list by vput().
   1435 		 */
   1436 		vput(vp);
   1437 		*vpp = NULL;
   1438 		return (error);
   1439 	}
   1440 
   1441 	dip = lfs_ifind(fs, ino, bp);
   1442 	if (dip == NULL) {
   1443 		/* Assume write has not completed yet; try again */
   1444 		brelse(bp, BC_INVAL);
   1445 		++retries;
   1446 		if (retries > LFS_IFIND_RETRIES) {
   1447 #ifdef DEBUG
   1448 			/* If the seglock is held look at the bpp to see
   1449 			   what is there anyway */
   1450 			mutex_enter(&lfs_lock);
   1451 			if (fs->lfs_seglock > 0) {
   1452 				struct buf **bpp;
   1453 				struct ulfs1_dinode *dp;
   1454 				int i;
   1455 
   1456 				for (bpp = fs->lfs_sp->bpp;
   1457 				     bpp != fs->lfs_sp->cbpp; ++bpp) {
   1458 					if ((*bpp)->b_vp == fs->lfs_ivnode &&
   1459 					    bpp != fs->lfs_sp->bpp) {
   1460 						/* Inode block */
   1461 						printf("lfs_vget: block 0x%" PRIx64 ": ",
   1462 						       (*bpp)->b_blkno);
   1463 						dp = (struct ulfs1_dinode *)(*bpp)->b_data;
   1464 						for (i = 0; i < LFS_INOPB(fs); i++)
   1465 							if (dp[i].di_inumber)
   1466 								printf("%d ", dp[i].di_inumber);
   1467 						printf("\n");
   1468 					}
   1469 				}
   1470 			}
   1471 			mutex_exit(&lfs_lock);
   1472 #endif /* DEBUG */
   1473 			panic("lfs_vget: dinode not found");
   1474 		}
   1475 		mutex_enter(&lfs_lock);
   1476 		if (fs->lfs_iocount) {
   1477 			DLOG((DLOG_VNODE, "lfs_vget: dinode %d not found, retrying...\n", ino));
   1478 			(void)mtsleep(&fs->lfs_iocount, PRIBIO + 1,
   1479 				      "lfs ifind", 1, &lfs_lock);
   1480 		} else
   1481 			retries = LFS_IFIND_RETRIES;
   1482 		mutex_exit(&lfs_lock);
   1483 		goto again;
   1484 	}
   1485 	*ip->i_din.ffs1_din = *dip;
   1486 	brelse(bp, 0);
   1487 
   1488 	if (fs->lfs_version > 1) {
   1489 		ip->i_ffs1_atime = ts.tv_sec;
   1490 		ip->i_ffs1_atimensec = ts.tv_nsec;
   1491 	}
   1492 
   1493 	lfs_vinit(mp, &vp);
   1494 
   1495 	*vpp = vp;
   1496 
   1497 	KASSERT(VOP_ISLOCKED(vp));
   1498 
   1499 	return (0);
   1500 }
   1501 
   1502 /*
   1503  * File handle to vnode
   1504  */
   1505 int
   1506 lfs_fhtovp(struct mount *mp, struct fid *fhp, struct vnode **vpp)
   1507 {
   1508 	struct lfid lfh;
   1509 	struct buf *bp;
   1510 	IFILE *ifp;
   1511 	int32_t daddr;
   1512 	struct lfs *fs;
   1513 	vnode_t *vp;
   1514 
   1515 	if (fhp->fid_len != sizeof(struct lfid))
   1516 		return EINVAL;
   1517 
   1518 	memcpy(&lfh, fhp, sizeof(lfh));
   1519 	if (lfh.lfid_ino < LFS_IFILE_INUM)
   1520 		return ESTALE;
   1521 
   1522 	fs = VFSTOULFS(mp)->um_lfs;
   1523 	if (lfh.lfid_ident != fs->lfs_ident)
   1524 		return ESTALE;
   1525 
   1526 	if (lfh.lfid_ino >
   1527 	    ((VTOI(fs->lfs_ivnode)->i_ffs1_size >> fs->lfs_bshift) -
   1528 	     fs->lfs_cleansz - fs->lfs_segtabsz) * fs->lfs_ifpb)
   1529 		return ESTALE;
   1530 
   1531 	mutex_enter(&ulfs_ihash_lock);
   1532 	vp = ulfs_ihashlookup(VFSTOULFS(mp)->um_dev, lfh.lfid_ino);
   1533 	mutex_exit(&ulfs_ihash_lock);
   1534 	if (vp == NULL) {
   1535 		LFS_IENTRY(ifp, fs, lfh.lfid_ino, bp);
   1536 		daddr = ifp->if_daddr;
   1537 		brelse(bp, 0);
   1538 		if (daddr == LFS_UNUSED_DADDR)
   1539 			return ESTALE;
   1540 	}
   1541 
   1542 	return (ulfs_fhtovp(mp, &lfh.lfid_ufid, vpp));
   1543 }
   1544 
   1545 /*
   1546  * Vnode pointer to File handle
   1547  */
   1548 /* ARGSUSED */
   1549 int
   1550 lfs_vptofh(struct vnode *vp, struct fid *fhp, size_t *fh_size)
   1551 {
   1552 	struct inode *ip;
   1553 	struct lfid lfh;
   1554 
   1555 	if (*fh_size < sizeof(struct lfid)) {
   1556 		*fh_size = sizeof(struct lfid);
   1557 		return E2BIG;
   1558 	}
   1559 	*fh_size = sizeof(struct lfid);
   1560 	ip = VTOI(vp);
   1561 	memset(&lfh, 0, sizeof(lfh));
   1562 	lfh.lfid_len = sizeof(struct lfid);
   1563 	lfh.lfid_ino = ip->i_number;
   1564 	lfh.lfid_gen = ip->i_gen;
   1565 	lfh.lfid_ident = ip->i_lfs->lfs_ident;
   1566 	memcpy(fhp, &lfh, sizeof(lfh));
   1567 	return (0);
   1568 }
   1569 
   1570 /*
   1571  * ulfs_bmaparray callback function for writing.
   1572  *
   1573  * Since blocks will be written to the new segment anyway,
   1574  * we don't care about current daddr of them.
   1575  */
   1576 static bool
   1577 lfs_issequential_hole(const struct lfs *fs,
   1578     daddr_t daddr0, daddr_t daddr1)
   1579 {
   1580 	(void)fs; /* not used */
   1581 
   1582 	daddr0 = (daddr_t)((int32_t)daddr0); /* XXX ondisk32 */
   1583 	daddr1 = (daddr_t)((int32_t)daddr1); /* XXX ondisk32 */
   1584 
   1585 	KASSERT(daddr0 == UNWRITTEN ||
   1586 	    (0 <= daddr0 && daddr0 <= LFS_MAX_DADDR));
   1587 	KASSERT(daddr1 == UNWRITTEN ||
   1588 	    (0 <= daddr1 && daddr1 <= LFS_MAX_DADDR));
   1589 
   1590 	/* NOTE: all we want to know here is 'hole or not'. */
   1591 	/* NOTE: UNASSIGNED is converted to 0 by ulfs_bmaparray. */
   1592 
   1593 	/*
   1594 	 * treat UNWRITTENs and all resident blocks as 'contiguous'
   1595 	 */
   1596 	if (daddr0 != 0 && daddr1 != 0)
   1597 		return true;
   1598 
   1599 	/*
   1600 	 * both are in hole?
   1601 	 */
   1602 	if (daddr0 == 0 && daddr1 == 0)
   1603 		return true; /* all holes are 'contiguous' for us. */
   1604 
   1605 	return false;
   1606 }
   1607 
   1608 /*
   1609  * lfs_gop_write functions exactly like genfs_gop_write, except that
   1610  * (1) it requires the seglock to be held by its caller, and sp->fip
   1611  *     to be properly initialized (it will return without re-initializing
   1612  *     sp->fip, and without calling lfs_writeseg).
   1613  * (2) it uses the remaining space in the segment, rather than VOP_BMAP,
   1614  *     to determine how large a block it can write at once (though it does
   1615  *     still use VOP_BMAP to find holes in the file);
   1616  * (3) it calls lfs_gatherblock instead of VOP_STRATEGY on its blocks
   1617  *     (leaving lfs_writeseg to deal with the cluster blocks, so we might
   1618  *     now have clusters of clusters, ick.)
   1619  */
   1620 static int
   1621 lfs_gop_write(struct vnode *vp, struct vm_page **pgs, int npages,
   1622     int flags)
   1623 {
   1624 	int i, error, run, haveeof = 0;
   1625 	int fs_bshift;
   1626 	vaddr_t kva;
   1627 	off_t eof, offset, startoffset = 0;
   1628 	size_t bytes, iobytes, skipbytes;
   1629 	bool async = (flags & PGO_SYNCIO) == 0;
   1630 	daddr_t lbn, blkno;
   1631 	struct vm_page *pg;
   1632 	struct buf *mbp, *bp;
   1633 	struct vnode *devvp = VTOI(vp)->i_devvp;
   1634 	struct inode *ip = VTOI(vp);
   1635 	struct lfs *fs = ip->i_lfs;
   1636 	struct segment *sp = fs->lfs_sp;
   1637 	UVMHIST_FUNC("lfs_gop_write"); UVMHIST_CALLED(ubchist);
   1638 	const char * failreason = NULL;
   1639 
   1640 	ASSERT_SEGLOCK(fs);
   1641 
   1642 	/* The Ifile lives in the buffer cache */
   1643 	KASSERT(vp != fs->lfs_ivnode);
   1644 
   1645 	/*
   1646 	 * We don't want to fill the disk before the cleaner has a chance
   1647 	 * to make room for us.  If we're in danger of doing that, fail
   1648 	 * with EAGAIN.  The caller will have to notice this, unlock
   1649 	 * so the cleaner can run, relock and try again.
   1650 	 *
   1651 	 * We must write everything, however, if our vnode is being
   1652 	 * reclaimed.
   1653 	 */
   1654 	if (LFS_STARVED_FOR_SEGS(fs) && !(vp->v_iflag & VI_XLOCK)) {
   1655 		failreason = "Starved for segs and not flushing vp";
   1656  		goto tryagain;
   1657 	}
   1658 
   1659 	/*
   1660 	 * Sometimes things slip past the filters in lfs_putpages,
   1661 	 * and the pagedaemon tries to write pages---problem is
   1662 	 * that the pagedaemon never acquires the segment lock.
   1663 	 *
   1664 	 * Alternatively, pages that were clean when we called
   1665 	 * genfs_putpages may have become dirty in the meantime.  In this
   1666 	 * case the segment header is not properly set up for blocks
   1667 	 * to be added to it.
   1668 	 *
   1669 	 * Unbusy and unclean the pages, and put them on the ACTIVE
   1670 	 * queue under the hypothesis that they couldn't have got here
   1671 	 * unless they were modified *quite* recently.
   1672 	 *
   1673 	 * XXXUBC that last statement is an oversimplification of course.
   1674 	 */
   1675 	if (!LFS_SEGLOCK_HELD(fs)) {
   1676 		failreason = "Seglock not held";
   1677 		goto tryagain;
   1678 	}
   1679 	if (ip->i_lfs_iflags & LFSI_NO_GOP_WRITE) {
   1680 		failreason = "Inode with no_gop_write";
   1681 		goto tryagain;
   1682 	}
   1683 	if ((pgs[0]->offset & fs->lfs_bmask) != 0) {
   1684 		failreason = "Bad page offset";
   1685 		goto tryagain;
   1686 	}
   1687 
   1688 	UVMHIST_LOG(ubchist, "vp %p pgs %p npages %d flags 0x%x",
   1689 	    vp, pgs, npages, flags);
   1690 
   1691 	GOP_SIZE(vp, vp->v_size, &eof, 0);
   1692 	haveeof = 1;
   1693 
   1694 	if (vp->v_type == VREG)
   1695 		fs_bshift = vp->v_mount->mnt_fs_bshift;
   1696 	else
   1697 		fs_bshift = DEV_BSHIFT;
   1698 	error = 0;
   1699 	pg = pgs[0];
   1700 	startoffset = pg->offset;
   1701 	KASSERT(eof >= 0);
   1702 
   1703 	if (startoffset >= eof) {
   1704 		failreason = "Offset beyond EOF";
   1705 		goto tryagain;
   1706 	} else
   1707 		bytes = MIN(npages << PAGE_SHIFT, eof - startoffset);
   1708 	skipbytes = 0;
   1709 
   1710 	KASSERT(bytes != 0);
   1711 
   1712 	/* Swap PG_DELWRI for PG_PAGEOUT */
   1713 	for (i = 0; i < npages; i++) {
   1714 		if (pgs[i]->flags & PG_DELWRI) {
   1715 			KASSERT(!(pgs[i]->flags & PG_PAGEOUT));
   1716 			pgs[i]->flags &= ~PG_DELWRI;
   1717 			pgs[i]->flags |= PG_PAGEOUT;
   1718 			uvm_pageout_start(1);
   1719 			mutex_enter(vp->v_interlock);
   1720 			mutex_enter(&uvm_pageqlock);
   1721 			uvm_pageunwire(pgs[i]);
   1722 			mutex_exit(&uvm_pageqlock);
   1723 			mutex_exit(vp->v_interlock);
   1724 		}
   1725 	}
   1726 
   1727 	/*
   1728 	 * Check to make sure we're starting on a block boundary.
   1729 	 * We'll check later to make sure we always write entire
   1730 	 * blocks (or fragments).
   1731 	 */
   1732 	if (startoffset & fs->lfs_bmask)
   1733 		printf("%" PRId64 " & %" PRId64 " = %" PRId64 "\n",
   1734 		       startoffset, fs->lfs_bmask,
   1735 		       startoffset & fs->lfs_bmask);
   1736 	KASSERT((startoffset & fs->lfs_bmask) == 0);
   1737 	if (bytes & fs->lfs_ffmask) {
   1738 		printf("lfs_gop_write: asked to write %ld bytes\n", (long)bytes);
   1739 		panic("lfs_gop_write: non-integer blocks");
   1740 	}
   1741 
   1742 	/*
   1743 	 * We could deadlock here on pager_map with UVMPAGER_MAPIN_WAITOK.
   1744 	 * If we would, write what we have and try again.  If we don't
   1745 	 * have anything to write, we'll have to sleep.
   1746 	 */
   1747 	if ((kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
   1748 				      (((SEGSUM *)(sp->segsum))->ss_nfinfo < 1 ?
   1749 				       UVMPAGER_MAPIN_WAITOK : 0))) == 0x0) {
   1750 		DLOG((DLOG_PAGE, "lfs_gop_write: forcing write\n"));
   1751 #if 0
   1752 		      " with nfinfo=%d at offset 0x%x\n",
   1753 		      (int)((SEGSUM *)(sp->segsum))->ss_nfinfo,
   1754 		      (unsigned)fs->lfs_offset));
   1755 #endif
   1756 		lfs_updatemeta(sp);
   1757 		lfs_release_finfo(fs);
   1758 		(void) lfs_writeseg(fs, sp);
   1759 
   1760 		lfs_acquire_finfo(fs, ip->i_number, ip->i_gen);
   1761 
   1762 		/*
   1763 		 * Having given up all of the pager_map we were holding,
   1764 		 * we can now wait for aiodoned to reclaim it for us
   1765 		 * without fear of deadlock.
   1766 		 */
   1767 		kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
   1768 				     UVMPAGER_MAPIN_WAITOK);
   1769 	}
   1770 
   1771 	mbp = getiobuf(NULL, true);
   1772 	UVMHIST_LOG(ubchist, "vp %p mbp %p num now %d bytes 0x%x",
   1773 	    vp, mbp, vp->v_numoutput, bytes);
   1774 	mbp->b_bufsize = npages << PAGE_SHIFT;
   1775 	mbp->b_data = (void *)kva;
   1776 	mbp->b_resid = mbp->b_bcount = bytes;
   1777 	mbp->b_cflags = BC_BUSY|BC_AGE;
   1778 	mbp->b_iodone = uvm_aio_biodone;
   1779 
   1780 	bp = NULL;
   1781 	for (offset = startoffset;
   1782 	    bytes > 0;
   1783 	    offset += iobytes, bytes -= iobytes) {
   1784 		lbn = offset >> fs_bshift;
   1785 		error = ulfs_bmaparray(vp, lbn, &blkno, NULL, NULL, &run,
   1786 		    lfs_issequential_hole);
   1787 		if (error) {
   1788 			UVMHIST_LOG(ubchist, "ulfs_bmaparray() -> %d",
   1789 			    error,0,0,0);
   1790 			skipbytes += bytes;
   1791 			bytes = 0;
   1792 			break;
   1793 		}
   1794 
   1795 		iobytes = MIN((((off_t)lbn + 1 + run) << fs_bshift) - offset,
   1796 		    bytes);
   1797 		if (blkno == (daddr_t)-1) {
   1798 			skipbytes += iobytes;
   1799 			continue;
   1800 		}
   1801 
   1802 		/*
   1803 		 * Discover how much we can really pack into this buffer.
   1804 		 */
   1805 		/* If no room in the current segment, finish it up */
   1806 		if (sp->sum_bytes_left < sizeof(int32_t) ||
   1807 		    sp->seg_bytes_left < (1 << fs->lfs_bshift)) {
   1808 			int vers;
   1809 
   1810 			lfs_updatemeta(sp);
   1811 			vers = sp->fip->fi_version;
   1812 			lfs_release_finfo(fs);
   1813 			(void) lfs_writeseg(fs, sp);
   1814 
   1815 			lfs_acquire_finfo(fs, ip->i_number, vers);
   1816 		}
   1817 		/* Check both for space in segment and space in segsum */
   1818 		iobytes = MIN(iobytes, (sp->seg_bytes_left >> fs_bshift)
   1819 					<< fs_bshift);
   1820 		iobytes = MIN(iobytes, (sp->sum_bytes_left / sizeof(int32_t))
   1821 				       << fs_bshift);
   1822 		KASSERT(iobytes > 0);
   1823 
   1824 		/* if it's really one i/o, don't make a second buf */
   1825 		if (offset == startoffset && iobytes == bytes) {
   1826 			bp = mbp;
   1827 			/*
   1828 			 * All the LFS output is done by the segwriter.  It
   1829 			 * will increment numoutput by one for all the bufs it
   1830 			 * recieves.  However this buffer needs one extra to
   1831 			 * account for aiodone.
   1832 			 */
   1833 			mutex_enter(vp->v_interlock);
   1834 			vp->v_numoutput++;
   1835 			mutex_exit(vp->v_interlock);
   1836 		} else {
   1837 			bp = getiobuf(NULL, true);
   1838 			UVMHIST_LOG(ubchist, "vp %p bp %p num now %d",
   1839 			    vp, bp, vp->v_numoutput, 0);
   1840 			nestiobuf_setup(mbp, bp, offset - pg->offset, iobytes);
   1841 			/*
   1842 			 * LFS doesn't like async I/O here, dies with
   1843 			 * an assert in lfs_bwrite().  Is that assert
   1844 			 * valid?  I retained non-async behaviour when
   1845 			 * converted this to use nestiobuf --pooka
   1846 			 */
   1847 			bp->b_flags &= ~B_ASYNC;
   1848 		}
   1849 
   1850 		/* XXX This is silly ... is this necessary? */
   1851 		mutex_enter(&bufcache_lock);
   1852 		mutex_enter(vp->v_interlock);
   1853 		bgetvp(vp, bp);
   1854 		mutex_exit(vp->v_interlock);
   1855 		mutex_exit(&bufcache_lock);
   1856 
   1857 		bp->b_lblkno = lfs_lblkno(fs, offset);
   1858 		bp->b_private = mbp;
   1859 		if (devvp->v_type == VBLK) {
   1860 			bp->b_dev = devvp->v_rdev;
   1861 		}
   1862 		VOP_BWRITE(bp->b_vp, bp);
   1863 		while (lfs_gatherblock(sp, bp, NULL))
   1864 			continue;
   1865 	}
   1866 
   1867 	nestiobuf_done(mbp, skipbytes, error);
   1868 	if (skipbytes) {
   1869 		UVMHIST_LOG(ubchist, "skipbytes %d", skipbytes, 0,0,0);
   1870 	}
   1871 	UVMHIST_LOG(ubchist, "returning 0", 0,0,0,0);
   1872 
   1873 	if (!async) {
   1874 		/* Start a segment write. */
   1875 		UVMHIST_LOG(ubchist, "flushing", 0,0,0,0);
   1876 		mutex_enter(&lfs_lock);
   1877 		lfs_flush(fs, 0, 1);
   1878 		mutex_exit(&lfs_lock);
   1879 	}
   1880 
   1881 	if ((sp->seg_flags & SEGM_SINGLE) && fs->lfs_curseg != fs->lfs_startseg)
   1882 		return EAGAIN;
   1883 
   1884 	return (0);
   1885 
   1886     tryagain:
   1887 	/*
   1888 	 * We can't write the pages, for whatever reason.
   1889 	 * Clean up after ourselves, and make the caller try again.
   1890 	 */
   1891 	mutex_enter(vp->v_interlock);
   1892 
   1893 	/* Tell why we're here, if we know */
   1894 	if (failreason != NULL) {
   1895 		DLOG((DLOG_PAGE, "lfs_gop_write: %s\n", failreason));
   1896 	}
   1897 	if (haveeof && startoffset >= eof) {
   1898  		DLOG((DLOG_PAGE, "lfs_gop_write: ino %d start 0x%" PRIx64
   1899  		      " eof 0x%" PRIx64 " npages=%d\n", VTOI(vp)->i_number,
   1900  		      pgs[0]->offset, eof, npages));
   1901 	}
   1902 
   1903 	mutex_enter(&uvm_pageqlock);
   1904 	for (i = 0; i < npages; i++) {
   1905 		pg = pgs[i];
   1906 
   1907 		if (pg->flags & PG_PAGEOUT)
   1908 			uvm_pageout_done(1);
   1909 		if (pg->flags & PG_DELWRI) {
   1910 			uvm_pageunwire(pg);
   1911 		}
   1912 		uvm_pageactivate(pg);
   1913 		pg->flags &= ~(PG_CLEAN|PG_DELWRI|PG_PAGEOUT|PG_RELEASED);
   1914 		DLOG((DLOG_PAGE, "pg[%d] = %p (vp %p off %" PRIx64 ")\n", i, pg,
   1915 			vp, pg->offset));
   1916 		DLOG((DLOG_PAGE, "pg[%d]->flags = %x\n", i, pg->flags));
   1917 		DLOG((DLOG_PAGE, "pg[%d]->pqflags = %x\n", i, pg->pqflags));
   1918 		DLOG((DLOG_PAGE, "pg[%d]->uanon = %p\n", i, pg->uanon));
   1919 		DLOG((DLOG_PAGE, "pg[%d]->uobject = %p\n", i, pg->uobject));
   1920 		DLOG((DLOG_PAGE, "pg[%d]->wire_count = %d\n", i,
   1921 		      pg->wire_count));
   1922 		DLOG((DLOG_PAGE, "pg[%d]->loan_count = %d\n", i,
   1923 		      pg->loan_count));
   1924 	}
   1925 	/* uvm_pageunbusy takes care of PG_BUSY, PG_WANTED */
   1926 	uvm_page_unbusy(pgs, npages);
   1927 	mutex_exit(&uvm_pageqlock);
   1928 	mutex_exit(vp->v_interlock);
   1929 	return EAGAIN;
   1930 }
   1931 
   1932 /*
   1933  * finish vnode/inode initialization.
   1934  * used by lfs_vget and lfs_fastvget.
   1935  */
   1936 void
   1937 lfs_vinit(struct mount *mp, struct vnode **vpp)
   1938 {
   1939 	struct vnode *vp = *vpp;
   1940 	struct inode *ip = VTOI(vp);
   1941 	struct ulfsmount *ump = VFSTOULFS(mp);
   1942 	struct lfs *fs = ump->um_lfs;
   1943 	int i;
   1944 
   1945 	ip->i_mode = ip->i_ffs1_mode;
   1946 	ip->i_nlink = ip->i_ffs1_nlink;
   1947 	ip->i_lfs_osize = ip->i_size = ip->i_ffs1_size;
   1948 	ip->i_flags = ip->i_ffs1_flags;
   1949 	ip->i_gen = ip->i_ffs1_gen;
   1950 	ip->i_uid = ip->i_ffs1_uid;
   1951 	ip->i_gid = ip->i_ffs1_gid;
   1952 
   1953 	ip->i_lfs_effnblks = ip->i_ffs1_blocks;
   1954 	ip->i_lfs_odnlink = ip->i_ffs1_nlink;
   1955 
   1956 	/*
   1957 	 * Initialize the vnode from the inode, check for aliases.  In all
   1958 	 * cases re-init ip, the underlying vnode/inode may have changed.
   1959 	 */
   1960 	ulfs_vinit(mp, lfs_specop_p, lfs_fifoop_p, &vp);
   1961 	ip = VTOI(vp);
   1962 
   1963 	memset(ip->i_lfs_fragsize, 0, ULFS_NDADDR * sizeof(*ip->i_lfs_fragsize));
   1964 	if (vp->v_type != VLNK || ip->i_size >= ip->i_lfs->um_maxsymlinklen) {
   1965 #ifdef DEBUG
   1966 		for (i = (ip->i_size + fs->lfs_bsize - 1) >> fs->lfs_bshift;
   1967 		    i < ULFS_NDADDR; i++) {
   1968 			if ((vp->v_type == VBLK || vp->v_type == VCHR) &&
   1969 			    i == 0)
   1970 				continue;
   1971 			if (ip->i_ffs1_db[i] != 0) {
   1972 				lfs_dump_dinode(ip->i_din.ffs1_din);
   1973 				panic("inconsistent inode (direct)");
   1974 			}
   1975 		}
   1976 		for ( ; i < ULFS_NDADDR + ULFS_NIADDR; i++) {
   1977 			if (ip->i_ffs1_ib[i - ULFS_NDADDR] != 0) {
   1978 				lfs_dump_dinode(ip->i_din.ffs1_din);
   1979 				panic("inconsistent inode (indirect)");
   1980 			}
   1981 		}
   1982 #endif /* DEBUG */
   1983 		for (i = 0; i < ULFS_NDADDR; i++)
   1984 			if (ip->i_ffs1_db[i] != 0)
   1985 				ip->i_lfs_fragsize[i] = lfs_blksize(fs, ip, i);
   1986 	}
   1987 
   1988 #ifdef DIAGNOSTIC
   1989 	if (vp->v_type == VNON) {
   1990 # ifdef DEBUG
   1991 		lfs_dump_dinode(ip->i_din.ffs1_din);
   1992 # endif
   1993 		panic("lfs_vinit: ino %llu is type VNON! (ifmt=%o)\n",
   1994 		      (unsigned long long)ip->i_number,
   1995 		      (ip->i_mode & LFS_IFMT) >> 12);
   1996 	}
   1997 #endif /* DIAGNOSTIC */
   1998 
   1999 	/*
   2000 	 * Finish inode initialization now that aliasing has been resolved.
   2001 	 */
   2002 
   2003 	ip->i_devvp = ump->um_devvp;
   2004 	vref(ip->i_devvp);
   2005 	genfs_node_init(vp, &lfs_genfsops);
   2006 	uvm_vnp_setsize(vp, ip->i_size);
   2007 
   2008 	/* Initialize hiblk from file size */
   2009 	ip->i_lfs_hiblk = lfs_lblkno(ip->i_lfs, ip->i_size + ip->i_lfs->lfs_bsize - 1) - 1;
   2010 
   2011 	*vpp = vp;
   2012 }
   2013 
   2014 /*
   2015  * Resize the filesystem to contain the specified number of segments.
   2016  */
   2017 int
   2018 lfs_resize_fs(struct lfs *fs, int newnsegs)
   2019 {
   2020 	SEGUSE *sup;
   2021 	struct buf *bp, *obp;
   2022 	daddr_t olast, nlast, ilast, noff, start, end;
   2023 	struct vnode *ivp;
   2024 	struct inode *ip;
   2025 	int error, badnews, inc, oldnsegs;
   2026 	int sbbytes, csbbytes, gain, cgain;
   2027 	int i;
   2028 
   2029 	/* Only support v2 and up */
   2030 	if (fs->lfs_version < 2)
   2031 		return EOPNOTSUPP;
   2032 
   2033 	/* If we're doing nothing, do it fast */
   2034 	oldnsegs = fs->lfs_nseg;
   2035 	if (newnsegs == oldnsegs)
   2036 		return 0;
   2037 
   2038 	/* We always have to have two superblocks */
   2039 	if (newnsegs <= lfs_dtosn(fs, fs->lfs_sboffs[1]))
   2040 		return EFBIG;
   2041 
   2042 	ivp = fs->lfs_ivnode;
   2043 	ip = VTOI(ivp);
   2044 	error = 0;
   2045 
   2046 	/* Take the segment lock so no one else calls lfs_newseg() */
   2047 	lfs_seglock(fs, SEGM_PROT);
   2048 
   2049 	/*
   2050 	 * Make sure the segments we're going to be losing, if any,
   2051 	 * are in fact empty.  We hold the seglock, so their status
   2052 	 * cannot change underneath us.  Count the superblocks we lose,
   2053 	 * while we're at it.
   2054 	 */
   2055 	sbbytes = csbbytes = 0;
   2056 	cgain = 0;
   2057 	for (i = newnsegs; i < oldnsegs; i++) {
   2058 		LFS_SEGENTRY(sup, fs, i, bp);
   2059 		badnews = sup->su_nbytes || !(sup->su_flags & SEGUSE_INVAL);
   2060 		if (sup->su_flags & SEGUSE_SUPERBLOCK)
   2061 			sbbytes += LFS_SBPAD;
   2062 		if (!(sup->su_flags & SEGUSE_DIRTY)) {
   2063 			++cgain;
   2064 			if (sup->su_flags & SEGUSE_SUPERBLOCK)
   2065 				csbbytes += LFS_SBPAD;
   2066 		}
   2067 		brelse(bp, 0);
   2068 		if (badnews) {
   2069 			error = EBUSY;
   2070 			goto out;
   2071 		}
   2072 	}
   2073 
   2074 	/* Note old and new segment table endpoints, and old ifile size */
   2075 	olast = fs->lfs_cleansz + fs->lfs_segtabsz;
   2076 	nlast = howmany(newnsegs, fs->lfs_sepb) + fs->lfs_cleansz;
   2077 	ilast = ivp->v_size >> fs->lfs_bshift;
   2078 	noff = nlast - olast;
   2079 
   2080 	/*
   2081 	 * Make sure no one can use the Ifile while we change it around.
   2082 	 * Even after taking the iflock we need to make sure no one still
   2083 	 * is holding Ifile buffers, so we get each one, to drain them.
   2084 	 * (XXX this could be done better.)
   2085 	 */
   2086 	rw_enter(&fs->lfs_iflock, RW_WRITER);
   2087 	for (i = 0; i < ilast; i++) {
   2088 		/* XXX what to do if bread fails? */
   2089 		bread(ivp, i, fs->lfs_bsize, NOCRED, 0, &bp);
   2090 		brelse(bp, 0);
   2091 	}
   2092 
   2093 	/* Allocate new Ifile blocks */
   2094 	for (i = ilast; i < ilast + noff; i++) {
   2095 		if (lfs_balloc(ivp, i * fs->lfs_bsize, fs->lfs_bsize, NOCRED, 0,
   2096 			       &bp) != 0)
   2097 			panic("balloc extending ifile");
   2098 		memset(bp->b_data, 0, fs->lfs_bsize);
   2099 		VOP_BWRITE(bp->b_vp, bp);
   2100 	}
   2101 
   2102 	/* Register new ifile size */
   2103 	ip->i_size += noff * fs->lfs_bsize;
   2104 	ip->i_ffs1_size = ip->i_size;
   2105 	uvm_vnp_setsize(ivp, ip->i_size);
   2106 
   2107 	/* Copy the inode table to its new position */
   2108 	if (noff != 0) {
   2109 		if (noff < 0) {
   2110 			start = nlast;
   2111 			end = ilast + noff;
   2112 			inc = 1;
   2113 		} else {
   2114 			start = ilast + noff - 1;
   2115 			end = nlast - 1;
   2116 			inc = -1;
   2117 		}
   2118 		for (i = start; i != end; i += inc) {
   2119 			if (bread(ivp, i, fs->lfs_bsize, NOCRED,
   2120 			    B_MODIFY, &bp) != 0)
   2121 				panic("resize: bread dst blk failed");
   2122 			if (bread(ivp, i - noff, fs->lfs_bsize,
   2123 			    NOCRED, 0, &obp))
   2124 				panic("resize: bread src blk failed");
   2125 			memcpy(bp->b_data, obp->b_data, fs->lfs_bsize);
   2126 			VOP_BWRITE(bp->b_vp, bp);
   2127 			brelse(obp, 0);
   2128 		}
   2129 	}
   2130 
   2131 	/* If we are expanding, write the new empty SEGUSE entries */
   2132 	if (newnsegs > oldnsegs) {
   2133 		for (i = oldnsegs; i < newnsegs; i++) {
   2134 			if ((error = bread(ivp, i / fs->lfs_sepb +
   2135 					   fs->lfs_cleansz, fs->lfs_bsize,
   2136 					   NOCRED, B_MODIFY, &bp)) != 0)
   2137 				panic("lfs: ifile read: %d", error);
   2138 			while ((i + 1) % fs->lfs_sepb && i < newnsegs) {
   2139 				sup = &((SEGUSE *)bp->b_data)[i % fs->lfs_sepb];
   2140 				memset(sup, 0, sizeof(*sup));
   2141 				i++;
   2142 			}
   2143 			VOP_BWRITE(bp->b_vp, bp);
   2144 		}
   2145 	}
   2146 
   2147 	/* Zero out unused superblock offsets */
   2148 	for (i = 2; i < LFS_MAXNUMSB; i++)
   2149 		if (lfs_dtosn(fs, fs->lfs_sboffs[i]) >= newnsegs)
   2150 			fs->lfs_sboffs[i] = 0x0;
   2151 
   2152 	/*
   2153 	 * Correct superblock entries that depend on fs size.
   2154 	 * The computations of these are as follows:
   2155 	 *
   2156 	 * size  = lfs_segtod(fs, nseg)
   2157 	 * dsize = lfs_segtod(fs, nseg - minfreeseg) - lfs_btofsb(#super * LFS_SBPAD)
   2158 	 * bfree = dsize - lfs_btofsb(fs, bsize * nseg / 2) - blocks_actually_used
   2159 	 * avail = lfs_segtod(fs, nclean) - lfs_btofsb(#clean_super * LFS_SBPAD)
   2160 	 *         + (lfs_segtod(fs, 1) - (offset - curseg))
   2161 	 *	   - lfs_segtod(fs, minfreeseg - (minfreeseg / 2))
   2162 	 *
   2163 	 * XXX - we should probably adjust minfreeseg as well.
   2164 	 */
   2165 	gain = (newnsegs - oldnsegs);
   2166 	fs->lfs_nseg = newnsegs;
   2167 	fs->lfs_segtabsz = nlast - fs->lfs_cleansz;
   2168 	fs->lfs_size += gain * lfs_btofsb(fs, fs->lfs_ssize);
   2169 	fs->lfs_dsize += gain * lfs_btofsb(fs, fs->lfs_ssize) - lfs_btofsb(fs, sbbytes);
   2170 	fs->lfs_bfree += gain * lfs_btofsb(fs, fs->lfs_ssize) - lfs_btofsb(fs, sbbytes)
   2171 		       - gain * lfs_btofsb(fs, fs->lfs_bsize / 2);
   2172 	if (gain > 0) {
   2173 		fs->lfs_nclean += gain;
   2174 		fs->lfs_avail += gain * lfs_btofsb(fs, fs->lfs_ssize);
   2175 	} else {
   2176 		fs->lfs_nclean -= cgain;
   2177 		fs->lfs_avail -= cgain * lfs_btofsb(fs, fs->lfs_ssize) -
   2178 				 lfs_btofsb(fs, csbbytes);
   2179 	}
   2180 
   2181 	/* Resize segment flag cache */
   2182 	fs->lfs_suflags[0] = realloc(fs->lfs_suflags[0],
   2183 	    fs->lfs_nseg * sizeof(u_int32_t), M_SEGMENT, M_WAITOK);
   2184 	fs->lfs_suflags[1] = realloc(fs->lfs_suflags[1],
   2185 	    fs->lfs_nseg * sizeof(u_int32_t), M_SEGMENT, M_WAITOK);
   2186 	for (i = oldnsegs; i < newnsegs; i++)
   2187 		fs->lfs_suflags[0][i] = fs->lfs_suflags[1][i] = 0x0;
   2188 
   2189 	/* Truncate Ifile if necessary */
   2190 	if (noff < 0)
   2191 		lfs_truncate(ivp, ivp->v_size + (noff << fs->lfs_bshift), 0,
   2192 		    NOCRED);
   2193 
   2194 	/* Update cleaner info so the cleaner can die */
   2195 	/* XXX what to do if bread fails? */
   2196 	bread(ivp, 0, fs->lfs_bsize, NOCRED, B_MODIFY, &bp);
   2197 	((CLEANERINFO *)bp->b_data)->clean = fs->lfs_nclean;
   2198 	((CLEANERINFO *)bp->b_data)->dirty = fs->lfs_nseg - fs->lfs_nclean;
   2199 	VOP_BWRITE(bp->b_vp, bp);
   2200 
   2201 	/* Let Ifile accesses proceed */
   2202 	rw_exit(&fs->lfs_iflock);
   2203 
   2204     out:
   2205 	lfs_segunlock(fs);
   2206 	return error;
   2207 }
   2208