Home | History | Annotate | Line # | Download | only in lfs
      1 /*	$NetBSD: lfs_vfsops.c,v 1.408 2026/10/30 01:03:04 perseant 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.408 2026/10/30 01:03:04 perseant Exp $");
     65 
     66 #if defined(_KERNEL_OPT)
     67 #include "opt_lfs.h"
     68 #include "opt_quota.h"
     69 #include "opt_uvmhist.h"
     70 #endif
     71 
     72 #include <sys/param.h>
     73 #include <sys/systm.h>
     74 #include <sys/namei.h>
     75 #include <sys/proc.h>
     76 #include <sys/kernel.h>
     77 #include <sys/vnode.h>
     78 #include <sys/mount.h>
     79 #include <sys/kthread.h>
     80 #include <sys/buf.h>
     81 #include <sys/device.h>
     82 #include <sys/file.h>
     83 #include <sys/fstypes.h>
     84 #include <sys/disklabel.h>
     85 #include <sys/ioctl.h>
     86 #include <sys/errno.h>
     87 #include <sys/malloc.h>
     88 #include <sys/pool.h>
     89 #include <sys/socket.h>
     90 #include <sys/syslog.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_bswap.h>
    105 #include <ufs/lfs/ulfs_extern.h>
    106 
    107 #ifdef UVMHIST
    108 #include <uvm/uvm.h>
    109 #endif
    110 #include <uvm/uvm_extern.h>
    111 #include <uvm/uvm_object.h>
    112 #include <uvm/uvm_page.h>
    113 #include <uvm/uvm_stat.h>
    114 
    115 #include <ufs/lfs/lfs.h>
    116 #include <ufs/lfs/lfs_accessors.h>
    117 #include <ufs/lfs/lfs_kernel.h>
    118 #include <ufs/lfs/lfs_extern.h>
    119 
    120 #include <miscfs/genfs/genfs.h>
    121 #include <miscfs/genfs/genfs_node.h>
    122 
    123 MODULE(MODULE_CLASS_VFS, lfs, NULL);
    124 
    125 static int lfs_gop_write(struct vnode *, struct vm_page **, int, int);
    126 static int lfs_mountfs(struct vnode *, struct mount *, struct lwp *);
    127 static int lfs_flushfiles(struct mount *, int);
    128 static int compare_nodes_sd(void *, const void *, const void *);
    129 static int compare_key_sd(void *, const void *, const void *);
    130 static void lfs_reclaimd(void *);
    131 
    132 extern const struct vnodeopv_desc lfs_vnodeop_opv_desc;
    133 extern const struct vnodeopv_desc lfs_specop_opv_desc;
    134 extern const struct vnodeopv_desc lfs_fifoop_opv_desc;
    135 
    136 extern int locked_queue_rcount;
    137 extern long locked_queue_rbytes;
    138 
    139 static const rb_tree_ops_t lfs_rbtree_ops = {
    140 	.rbto_compare_nodes = compare_nodes_sd,
    141 	.rbto_compare_key = compare_key_sd,
    142 	.rbto_node_offset = offsetof(struct segdelta, rb_entry),
    143 	.rbto_context = NULL
    144 };
    145 
    146 struct lwp * lfs_writer_daemon = NULL;
    147 kcondvar_t lfs_writerd_cv;
    148 
    149 struct workqueue *lfs_cluster_wq = NULL;
    150 struct workqueue *lfs_super_wq = NULL;
    151 
    152 int lfs_do_flush = 0;
    153 int lfs_do_rfw = 1;
    154 
    155 const struct vnodeopv_desc * const lfs_vnodeopv_descs[] = {
    156 	&lfs_vnodeop_opv_desc,
    157 	&lfs_specop_opv_desc,
    158 	&lfs_fifoop_opv_desc,
    159 	NULL,
    160 };
    161 
    162 struct vfsops lfs_vfsops = {
    163 	.vfs_name = MOUNT_LFS,
    164 	.vfs_min_mount_data = sizeof (struct ulfs_args),
    165 	.vfs_mount = lfs_mount,
    166 	.vfs_start = ulfs_start,
    167 	.vfs_unmount = lfs_unmount,
    168 	.vfs_root = ulfs_root,
    169 	.vfs_quotactl = ulfs_quotactl,
    170 	.vfs_statvfs = lfs_statvfs,
    171 	.vfs_sync = lfs_sync,
    172 	.vfs_vget = lfs_vget,
    173 	.vfs_loadvnode = lfs_loadvnode,
    174 	.vfs_newvnode = lfs_newvnode,
    175 	.vfs_fhtovp = lfs_fhtovp,
    176 	.vfs_vptofh = lfs_vptofh,
    177 	.vfs_init = lfs_init,
    178 	.vfs_reinit = lfs_reinit,
    179 	.vfs_done = lfs_done,
    180 	.vfs_mountroot = lfs_mountroot,
    181 	.vfs_snapshot = (void *)eopnotsupp,
    182 	.vfs_extattrctl = lfs_extattrctl,
    183 	.vfs_suspendctl = genfs_suspendctl,
    184 	.vfs_renamelock_enter = genfs_renamelock_enter,
    185 	.vfs_renamelock_exit = genfs_renamelock_exit,
    186 	.vfs_fsync = (void *)eopnotsupp,
    187 	.vfs_opv_descs = lfs_vnodeopv_descs
    188 };
    189 
    190 const struct genfs_ops lfs_genfsops = {
    191 	.gop_size = lfs_gop_size,
    192 	.gop_alloc = ulfs_gop_alloc,
    193 	.gop_write = lfs_gop_write,
    194 	.gop_markupdate = ulfs_gop_markupdate,
    195 	.gop_putrange = genfs_gop_putrange,
    196 };
    197 
    198 struct shortlong {
    199 	const char *sname;
    200 	const char *lname;
    201 };
    202 
    203 static int
    204 sysctl_lfs_dostats(SYSCTLFN_ARGS)
    205 {
    206 	extern struct lfs_stats lfs_stats;
    207 	extern int lfs_dostats;
    208 	int error;
    209 
    210 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
    211 	if (error || newp == NULL)
    212 		return (error);
    213 
    214 	if (lfs_dostats == 0)
    215 		memset(&lfs_stats, 0, sizeof(lfs_stats));
    216 
    217 	return (0);
    218 }
    219 
    220 SYSCTL_SETUP(lfs_sysctl_setup, "lfs sysctl")
    221 {
    222 	int i;
    223 	extern int lfs_writeindir, lfs_dostats, lfs_clean_vnhead,
    224 		   lfs_fs_pagetrip, lfs_ignore_lazy_sync;
    225 #ifdef DEBUG
    226 	extern int lfs_debug_log_subsys[DLOG_MAX];
    227 	struct shortlong dlog_names[DLOG_MAX] = { /* Must match lfs.h ! */
    228 		{ "rollforward", "Debug roll-forward code" },
    229 		{ "alloc",	"Debug inode allocation and free list" },
    230 		{ "avail",	"Debug space-available-now accounting" },
    231 		{ "flush",	"Debug flush triggers" },
    232 		{ "lockedlist",	"Debug locked list accounting" },
    233 		{ "vnode_verbose", "Verbose per-vnode-written debugging" },
    234 		{ "vnode",	"Debug vnode use during segment write" },
    235 		{ "segment",	"Debug segment writing" },
    236 		{ "seguse",	"Debug segment used-bytes accounting" },
    237 		{ "cleaner",	"Debug cleaning routines" },
    238 		{ "mount",	"Debug mount/unmount routines" },
    239 		{ "pagecache",	"Debug UBC interactions" },
    240 		{ "dirop",	"Debug directory-operation accounting" },
    241 		{ "malloc",	"Debug private malloc accounting" },
    242 	};
    243 #endif /* DEBUG */
    244 	struct shortlong stat_names[] = { /* Must match lfs.h! */
    245 		{ "segsused",	    "Number of new segments allocated" },
    246 		{ "psegwrites",	    "Number of partial-segment writes" },
    247 		{ "psyncwrites",    "Number of synchronous partial-segment"
    248 				    " writes" },
    249 		{ "pcleanwrites",   "Number of partial-segment writes by the"
    250 				    " cleaner" },
    251 		{ "blocktot",       "Number of blocks written" },
    252 		{ "cleanblocks",    "Number of blocks written by the cleaner" },
    253 		{ "ncheckpoints",   "Number of checkpoints made" },
    254 		{ "nwrites",        "Number of whole writes" },
    255 		{ "nsync_writes",   "Number of synchronous writes" },
    256 		{ "wait_exceeded",  "Number of times writer waited for"
    257 				    " cleaner" },
    258 		{ "write_exceeded", "Number of times writer invoked flush" },
    259 		{ "flush_invoked",  "Number of times flush was invoked" },
    260 		{ "vflush_invoked", "Number of time vflush was called" },
    261 		{ "clean_inlocked", "Number of vnodes skipped for being dead" },
    262 		{ "clean_vnlocked", "Number of vnodes skipped for vget failure" },
    263 		{ "segs_reclaimed", "Number of segments reclaimed" },
    264 	};
    265 
    266 	sysctl_createv(clog, 0, NULL, NULL,
    267 		       CTLFLAG_PERMANENT,
    268 		       CTLTYPE_NODE, "lfs",
    269 		       SYSCTL_DESCR("Log-structured file system"),
    270 		       NULL, 0, NULL, 0,
    271 		       CTL_VFS, 5, CTL_EOL);
    272 	/*
    273 	 * XXX the "5" above could be dynamic, thereby eliminating one
    274 	 * more instance of the "number to vfs" mapping problem, but
    275 	 * "5" is the order as taken from sys/mount.h
    276 	 */
    277 
    278 	sysctl_createv(clog, 0, NULL, NULL,
    279 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    280 		       CTLTYPE_INT, "flushindir", NULL,
    281 		       NULL, 0, &lfs_writeindir, 0,
    282 		       CTL_VFS, 5, LFS_WRITEINDIR, CTL_EOL);
    283 	sysctl_createv(clog, 0, NULL, NULL,
    284 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    285 		       CTLTYPE_INT, "clean_vnhead", NULL,
    286 		       NULL, 0, &lfs_clean_vnhead, 0,
    287 		       CTL_VFS, 5, LFS_CLEAN_VNHEAD, CTL_EOL);
    288 	sysctl_createv(clog, 0, NULL, NULL,
    289 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    290 		       CTLTYPE_INT, "dostats",
    291 		       SYSCTL_DESCR("Maintain statistics on LFS operations"),
    292 		       sysctl_lfs_dostats, 0, &lfs_dostats, 0,
    293 		       CTL_VFS, 5, LFS_DOSTATS, CTL_EOL);
    294 	sysctl_createv(clog, 0, NULL, NULL,
    295 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    296 		       CTLTYPE_INT, "pagetrip",
    297 		       SYSCTL_DESCR("How many dirty pages in fs triggers"
    298 				    " a flush"),
    299 		       NULL, 0, &lfs_fs_pagetrip, 0,
    300 		       CTL_VFS, 5, LFS_FS_PAGETRIP, CTL_EOL);
    301 	sysctl_createv(clog, 0, NULL, NULL,
    302 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    303 		       CTLTYPE_INT, "ignore_lazy_sync",
    304 		       SYSCTL_DESCR("Lazy Sync is ignored entirely"),
    305 		       NULL, 0, &lfs_ignore_lazy_sync, 0,
    306 		       CTL_VFS, 5, LFS_IGNORE_LAZY_SYNC, CTL_EOL);
    307 	sysctl_createv(clog, 0, NULL, NULL,
    308 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    309 		       CTLTYPE_INT, "rfw",
    310 		       SYSCTL_DESCR("Use in-kernel roll-forward on mount"),
    311 		       NULL, 0, &lfs_do_rfw, 0,
    312 		       CTL_VFS, 5, LFS_DO_RFW, CTL_EOL);
    313 	sysctl_createv(clog, 0, NULL, NULL,
    314 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    315 		       CTLTYPE_INT, "rfw_limit",
    316 		       SYSCTL_DESCR("Maximum number of partial segments"
    317 				    " to roll forward"),
    318 		       NULL, 0, &lfs_rfw_max_psegs, 0,
    319 		       CTL_VFS, 5, LFS_RFW_LIMIT, CTL_EOL);
    320 
    321 	sysctl_createv(clog, 0, NULL, NULL,
    322 		       CTLFLAG_PERMANENT,
    323 		       CTLTYPE_NODE, "stats",
    324 		       SYSCTL_DESCR("Statistics"),
    325 		       NULL, 0, NULL, 0,
    326 		       CTL_VFS, 5, LFS_STATS, CTL_EOL);
    327 	for (i = 0; i < sizeof(struct lfs_stats) / sizeof(u_int); i++) {
    328 		sysctl_createv(clog, 0, NULL, NULL,
    329 			       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
    330 			       CTLTYPE_INT, stat_names[i].sname,
    331 			       SYSCTL_DESCR(stat_names[i].lname),
    332 			       NULL, 0, &(((u_int *)&lfs_stats.segsused)[i]),
    333 			       0, CTL_VFS, 5, LFS_STATS, i, CTL_EOL);
    334 	}
    335 
    336 #ifdef DEBUG
    337 	sysctl_createv(clog, 0, NULL, NULL,
    338 		       CTLFLAG_PERMANENT,
    339 		       CTLTYPE_NODE, "debug",
    340 		       SYSCTL_DESCR("Debug options"),
    341 		       NULL, 0, NULL, 0,
    342 		       CTL_VFS, 5, LFS_DEBUG, CTL_EOL);
    343 	sysctl_createv(clog, 0, NULL, NULL,
    344 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    345 		       CTLTYPE_INT, "freelist",
    346 		       SYSCTL_DESCR("Track consistency of inode freelist"),
    347 		       NULL, 0, &lfs_do_check_freelist, 0,
    348 		       CTL_VFS, 5, LFS_DEBUG, LFS_DEBUG_FREELIST, CTL_EOL);
    349 	sysctl_createv(clog, 0, NULL, NULL,
    350 		       CTLFLAG_PERMANENT,
    351 		       CTLTYPE_NODE, "log",
    352 		       SYSCTL_DESCR("Verbose logging"),
    353 		       NULL, 0, NULL, 0,
    354 		       CTL_VFS, 5, LFS_DEBUG, LFS_DEBUG_LOG, CTL_EOL);
    355 	for (i = 0; i < DLOG_MAX; i++) {
    356 		sysctl_createv(clog, 0, NULL, NULL,
    357 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    358 			       CTLTYPE_INT, dlog_names[i].sname,
    359 			       SYSCTL_DESCR(dlog_names[i].lname),
    360 			       NULL, 0, &(lfs_debug_log_subsys[i]), 0,
    361 			       CTL_VFS, 5, LFS_DEBUG, LFS_DEBUG_LOG, i, CTL_EOL);
    362 	}
    363 #endif
    364 }
    365 
    366 /* old cleaner syscall interface.  see VOP_FCNTL() */
    367 static const struct syscall_package lfs_syscalls[] = {
    368 	{ SYS_lfs_bmapv,	0, (sy_call_t *)sys_lfs_bmapv		},
    369 	{ SYS_lfs_markv,	0, (sy_call_t *)sys_lfs_markv		},
    370 	{ SYS___lfs_segwait50,	0, (sy_call_t *)sys___lfs_segwait50	},
    371 	{ SYS_lfs_segclean,	0, (sy_call_t *)sys_lfs_segclean	},
    372 	{ 0, 0, NULL },
    373 };
    374 
    375 static int
    376 lfs_modcmd(modcmd_t cmd, void *arg)
    377 {
    378 	int error;
    379 
    380 	switch (cmd) {
    381 	case MODULE_CMD_INIT:
    382 		error = syscall_establish(NULL, lfs_syscalls);
    383 		if (error)
    384 			return error;
    385 		error = vfs_attach(&lfs_vfsops);
    386 		if (error != 0) {
    387 			syscall_disestablish(NULL, lfs_syscalls);
    388 			break;
    389 		}
    390 		cv_init(&lfs_allclean_wakeup, "segment");
    391 		break;
    392 	case MODULE_CMD_FINI:
    393 		error = vfs_detach(&lfs_vfsops);
    394 		if (error != 0)
    395 			break;
    396 		syscall_disestablish(NULL, lfs_syscalls);
    397 		cv_destroy(&lfs_allclean_wakeup);
    398 		break;
    399 	default:
    400 		error = ENOTTY;
    401 		break;
    402 	}
    403 
    404 	return (error);
    405 }
    406 
    407 /*
    408  * XXX Same structure as FFS inodes?  Should we share a common pool?
    409  */
    410 struct pool lfs_inode_pool;
    411 struct pool lfs_dinode_pool;
    412 struct pool lfs_inoext_pool;
    413 struct pool lfs_lbnentry_pool;
    414 
    415 /*
    416  * The writer daemon.  UVM keeps track of how many dirty pages we are holding
    417  * in lfs_subsys_pages; the daemon flushes the filesystem when this value
    418  * crosses the (user-defined) threshold LFS_MAX_PAGES.
    419  */
    420 static void
    421 lfs_writerd(void *arg)
    422 {
    423 	mount_iterator_t *iter;
    424  	struct mount *mp;
    425  	struct lfs *fs;
    426 	struct vfsops *vfs = NULL;
    427  	int fsflags;
    428 	int lfsc;
    429 	int wrote_something = 0;
    430 
    431 	mutex_enter(&lfs_lock);
    432 	KASSERTMSG(lfs_writer_daemon == NULL, "more than one LFS writer daemon");
    433 	lfs_writer_daemon = curlwp;
    434 	mutex_exit(&lfs_lock);
    435 
    436 	/* Take an extra reference to the LFS vfsops. */
    437 	vfs = vfs_getopsbyname(MOUNT_LFS);
    438 
    439  	mutex_enter(&lfs_lock);
    440  	for (;;) {
    441 		KASSERT(mutex_owned(&lfs_lock));
    442 		if (wrote_something == 0)
    443 			cv_timedwait(&lfs_writerd_cv, &lfs_lock, 2 * hz);
    444 		KASSERT(mutex_owned(&lfs_lock));
    445 		wrote_something = 0;
    446 
    447 		/*
    448 		 * If global state wants a flush, flush everything.
    449 		 */
    450 		if (lfs_do_flush || locked_queue_count + locked_queue_rcount > LFS_MAX_BUFS ||
    451 			locked_queue_bytes + locked_queue_rbytes > LFS_MAX_BYTES ||
    452 			lfs_subsys_pages > LFS_MAX_PAGES) {
    453 
    454 			if (lfs_do_flush) {
    455 				DLOG((DLOG_FLUSH, "lfs_writerd: lfs_do_flush\n"));
    456 			}
    457 			if (locked_queue_count + locked_queue_rcount > LFS_MAX_BUFS) {
    458 				DLOG((DLOG_FLUSH, "lfs_writerd: lqc+lqrc = %d, max %d\n",
    459 				      locked_queue_count, LFS_MAX_BUFS));
    460 			}
    461 			if (locked_queue_bytes + locked_queue_rbytes > LFS_MAX_BYTES) {
    462 				DLOG((DLOG_FLUSH, "lfs_writerd: lqb + lqrb = %ld, max %ld\n",
    463 				      locked_queue_bytes, LFS_MAX_BYTES));
    464 			}
    465 			if (lfs_subsys_pages > LFS_MAX_PAGES) {
    466 				DLOG((DLOG_FLUSH, "lfs_writerd: lssp = %d, max %d\n",
    467 				      lfs_subsys_pages, LFS_MAX_PAGES));
    468 			}
    469 
    470 			lfs_flush(NULL, SEGM_WRITERD, 0);
    471 			lfs_do_flush = 0;
    472 			KASSERT(mutex_owned(&lfs_lock));
    473 			continue;
    474 		}
    475 		KASSERT(mutex_owned(&lfs_lock));
    476 		mutex_exit(&lfs_lock);
    477 
    478  		/*
    479  		 * Look through the list of LFSs to see if any of them
    480  		 * have requested pageouts.
    481  		 */
    482  		mountlist_iterator_init(&iter);
    483 		lfsc = 0;
    484 		while ((mp = mountlist_iterator_next(iter)) != NULL) {
    485 			KASSERT(!mutex_owned(&lfs_lock));
    486  			if (strncmp(mp->mnt_stat.f_fstypename, MOUNT_LFS,
    487  			    sizeof(mp->mnt_stat.f_fstypename)) == 0) {
    488 				++lfsc;
    489  				fs = VFSTOULFS(mp)->um_lfs;
    490 				daddr_t ooffset = 0;
    491 				fsflags = SEGM_SINGLE;
    492 
    493  				mutex_enter(&lfs_lock);
    494 				ooffset = lfs_sb_getoffset(fs);
    495 
    496 				if (lfs_sb_getnextseg(fs) < lfs_sb_getcurseg(fs) && fs->lfs_nowrap) {
    497 					/* Don't try to write if we're suspended */
    498 					mutex_exit(&lfs_lock);
    499 					continue;
    500 				}
    501 				if (LFS_STARVED_FOR_SEGS(fs)) {
    502 					mutex_exit(&lfs_lock);
    503 
    504 					DLOG((DLOG_FLUSH, "lfs_writerd: need cleaning before writing possible\n"));
    505 					lfs_wakeup_cleaner(fs);
    506 					continue;
    507 				}
    508 
    509  				if ((fs->lfs_dirvcount > LFS_MAX_FSDIROP(fs) ||
    510  				     lfs_dirvcount > LFS_MAX_DIROP) &&
    511 				    fs->lfs_dirops == 0) {
    512 					fsflags &= ~SEGM_SINGLE;
    513  					fsflags |= SEGM_CKP;
    514 					DLOG((DLOG_FLUSH, "lfs_writerd: checkpoint\n"));
    515 					lfs_flush_fs(fs, fsflags);
    516 				} else if (fs->lfs_pdflush) {
    517  					DLOG((DLOG_FLUSH, "lfs_writerd: pdflush set\n"));
    518  					lfs_flush_fs(fs, fsflags);
    519  				} else if (!TAILQ_EMPTY(&fs->lfs_pchainhd)) {
    520  					DLOG((DLOG_FLUSH, "lfs_writerd: pchain non-empty\n"));
    521  					mutex_exit(&lfs_lock);
    522  					lfs_writer_enter(fs, "wrdirop");
    523  					lfs_flush_pchain(fs);
    524  					lfs_writer_leave(fs);
    525 					mutex_enter(&lfs_lock);
    526 				}
    527 				if (lfs_sb_getoffset(fs) != ooffset)
    528 					++wrote_something;
    529 				mutex_exit(&lfs_lock);
    530  			}
    531 			KASSERT(!mutex_owned(&lfs_lock));
    532  		}
    533 		if (lfsc == 0) {
    534 			mutex_enter(&lfs_lock);
    535 			lfs_writer_daemon = NULL;
    536 			mutex_exit(&lfs_lock);
    537 			mountlist_iterator_destroy(iter);
    538 			break;
    539 		}
    540  		mountlist_iterator_destroy(iter);
    541 
    542  		mutex_enter(&lfs_lock);
    543  	}
    544 	KASSERT(!mutex_owned(&lfs_lock));
    545 
    546 	/* Give up our extra reference so the module can be unloaded. */
    547 	mutex_enter(&vfs_list_lock);
    548 	if (vfs != NULL)
    549 		vfs->vfs_refcount--;
    550 	mutex_exit(&vfs_list_lock);
    551 
    552 	/* Done! */
    553 	kthread_exit(0);
    554 }
    555 
    556 /*
    557  * Initialize the filesystem, most work done by ulfs_init.
    558  */
    559 void
    560 lfs_init(void)
    561 {
    562 
    563 	/*
    564 	 * XXX: should we use separate pools for 32-bit and 64-bit
    565 	 * dinodes?
    566 	 */
    567 	malloc_type_attach(M_SEGMENT);
    568 	pool_init(&lfs_inode_pool, sizeof(struct inode), 0, 0, 0,
    569 	    "lfsinopl", &pool_allocator_nointr, IPL_NONE);
    570 	pool_init(&lfs_dinode_pool, sizeof(union lfs_dinode), 0, 0, 0,
    571 	    "lfsdinopl", &pool_allocator_nointr, IPL_NONE);
    572 	pool_init(&lfs_inoext_pool, sizeof(struct lfs_inode_ext), 8, 0, 0,
    573 	    "lfsinoextpl", &pool_allocator_nointr, IPL_NONE);
    574 	pool_init(&lfs_lbnentry_pool, sizeof(struct lbnentry), 0, 0, 0,
    575 	    "lfslbnpool", &pool_allocator_nointr, IPL_NONE);
    576 	ulfs_init();
    577 
    578 #ifdef DEBUG
    579 	memset(lfs_log, 0, sizeof(lfs_log));
    580 #endif
    581 	mutex_init(&lfs_lock, MUTEX_DEFAULT, IPL_NONE);
    582 	cv_init(&lfs_writerd_cv, "lfswrite");
    583 	cv_init(&locked_queue_cv, "lfsbuf");
    584 	cv_init(&lfs_writing_cv, "lfsflush");
    585 	workqueue_create(&lfs_cluster_wq, "lfscwq", lfs_cluster_work, NULL,
    586 					PRI_BIO, IPL_BIO, WQ_MPSAFE);
    587 	workqueue_create(&lfs_super_wq, "lfsswq", lfs_super_work, NULL,
    588  					PRI_BIO, IPL_BIO, WQ_MPSAFE);
    589 }
    590 
    591 void
    592 lfs_reinit(void)
    593 {
    594 	ulfs_reinit();
    595 }
    596 
    597 void
    598 lfs_done(void)
    599 {
    600 	ulfs_done();
    601 	mutex_destroy(&lfs_lock);
    602 	cv_destroy(&lfs_writerd_cv);
    603 	cv_destroy(&locked_queue_cv);
    604 	cv_destroy(&lfs_writing_cv);
    605 	workqueue_destroy(lfs_cluster_wq);
    606 	workqueue_destroy(lfs_super_wq);
    607 	pool_destroy(&lfs_inode_pool);
    608 	pool_destroy(&lfs_dinode_pool);
    609 	pool_destroy(&lfs_inoext_pool);
    610 	pool_destroy(&lfs_lbnentry_pool);
    611 	malloc_type_detach(M_SEGMENT);
    612 }
    613 
    614 /*
    615  * Called by main() when ulfs is going to be mounted as root.
    616  */
    617 int
    618 lfs_mountroot(void)
    619 {
    620 	extern struct vnode *rootvp;
    621 	struct lfs *fs = NULL;				/* LFS */
    622 	struct mount *mp;
    623 	struct lwp *l = curlwp;
    624 	struct ulfsmount *ump;
    625 	int error;
    626 
    627 	if (device_class(root_device) != DV_DISK)
    628 		return (ENODEV);
    629 
    630 	if (rootdev == NODEV)
    631 		return (ENODEV);
    632 	if ((error = vfs_rootmountalloc(MOUNT_LFS, "root_device", &mp))) {
    633 		vrele(rootvp);
    634 		return (error);
    635 	}
    636 	if ((error = lfs_mountfs(rootvp, mp, l))) {
    637 		vfs_unbusy(mp);
    638 		vfs_rele(mp);
    639 		return (error);
    640 	}
    641 	mountlist_append(mp);
    642 	ump = VFSTOULFS(mp);
    643 	fs = ump->um_lfs;
    644 	lfs_sb_setfsmnt(fs, mp->mnt_stat.f_mntonname);
    645 	(void)lfs_statvfs(mp, &mp->mnt_stat);
    646 	vfs_unbusy(mp);
    647 	setrootfstime((time_t)lfs_sb_gettstamp(VFSTOULFS(mp)->um_lfs));
    648 	return (0);
    649 }
    650 
    651 /*
    652  * VFS Operations.
    653  *
    654  * mount system call
    655  */
    656 int
    657 lfs_mount(struct mount *mp, const char *path, void *data, size_t *data_len)
    658 {
    659 	struct lwp *l = curlwp;
    660 	struct vnode *devvp;
    661 	struct ulfs_args *args = data;
    662 	struct ulfsmount *ump = NULL;
    663 	struct lfs *fs = NULL;				/* LFS */
    664 	int error = 0, update;
    665 	mode_t accessmode;
    666 
    667 	if (args == NULL)
    668 		return EINVAL;
    669 	if (*data_len < sizeof *args)
    670 		return EINVAL;
    671 
    672 	if (mp->mnt_flag & MNT_GETARGS) {
    673 		ump = VFSTOULFS(mp);
    674 		if (ump == NULL)
    675 			return EIO;
    676 		args->fspec = NULL;
    677 		*data_len = sizeof *args;
    678 		return 0;
    679 	}
    680 
    681 	update = mp->mnt_flag & MNT_UPDATE;
    682 
    683 	/* Check arguments */
    684 	if (args->fspec != NULL) {
    685 		/*
    686 		 * Look up the name and verify that it's sane.
    687 		 */
    688 		error = namei_simple_user(args->fspec,
    689 					NSM_FOLLOW_NOEMULROOT, &devvp);
    690 		if (error != 0)
    691 			return (error);
    692 
    693 		if (!update) {
    694 			/*
    695 			 * Be sure this is a valid block device
    696 			 */
    697 			if (devvp->v_type != VBLK)
    698 				error = ENOTBLK;
    699 			else if (bdevsw_lookup(devvp->v_rdev) == NULL)
    700 				error = ENXIO;
    701 		} else {
    702 			/*
    703 			 * Be sure we're still naming the same device
    704 			 * used for our initial mount
    705 			 *
    706 			 * XXX dholland 20151010: if namei gives us a
    707 			 * different vnode for the same device,
    708 			 * wouldn't it be better to use it going
    709 			 * forward rather than ignore it in favor of
    710 			 * the old one?
    711 			 */
    712 			ump = VFSTOULFS(mp);
    713 			fs = ump->um_lfs;
    714 			if (devvp != fs->lfs_devvp) {
    715 				if (devvp->v_rdev != fs->lfs_devvp->v_rdev)
    716 					error = EINVAL;
    717 				else {
    718 					vrele(devvp);
    719 					devvp = fs->lfs_devvp;
    720 					vref(devvp);
    721 				}
    722 			}
    723 		}
    724 	} else {
    725 		if (!update) {
    726 			/* New mounts must have a filename for the device */
    727 			return (EINVAL);
    728 		} else {
    729 			/* Use the extant mount */
    730 			ump = VFSTOULFS(mp);
    731 			fs = ump->um_lfs;
    732 			devvp = fs->lfs_devvp;
    733 			vref(devvp);
    734 		}
    735 	}
    736 
    737 
    738 	/*
    739 	 * If mount by non-root, then verify that user has necessary
    740 	 * permissions on the device.
    741 	 */
    742 	if (error == 0) {
    743 		accessmode = VREAD;
    744 		if (update ?
    745 		    (mp->mnt_iflag & IMNT_WANTRDWR) != 0 :
    746 		    (mp->mnt_flag & MNT_RDONLY) == 0)
    747 			accessmode |= VWRITE;
    748 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    749 		error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_MOUNT,
    750 		    KAUTH_REQ_SYSTEM_MOUNT_DEVICE, mp, devvp,
    751 		    KAUTH_ARG(accessmode));
    752 		VOP_UNLOCK(devvp);
    753 	}
    754 
    755 	if (error) {
    756 		vrele(devvp);
    757 		return (error);
    758 	}
    759 
    760 	if (!update) {
    761 		int flags;
    762 
    763 		if (mp->mnt_flag & MNT_RDONLY)
    764 			flags = FREAD;
    765 		else
    766 			flags = FREAD|FWRITE;
    767 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    768 		error = VOP_OPEN(devvp, flags, FSCRED);
    769 		VOP_UNLOCK(devvp);
    770 		if (error)
    771 			goto fail;
    772 		error = lfs_mountfs(devvp, mp, l);		/* LFS */
    773 		if (error) {
    774 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    775 			(void)VOP_CLOSE(devvp, flags, NOCRED);
    776 			VOP_UNLOCK(devvp);
    777 			goto fail;
    778 		}
    779 
    780 		ump = VFSTOULFS(mp);
    781 		fs = ump->um_lfs;
    782 	} else {
    783 		/*
    784 		 * Update the mount.
    785 		 */
    786 
    787 		/*
    788 		 * The initial mount got a reference on this
    789 		 * device, so drop the one obtained via
    790 		 * namei(), above.
    791 		 */
    792 		vrele(devvp);
    793 
    794 		ump = VFSTOULFS(mp);
    795 		fs = ump->um_lfs;
    796 
    797 		if (!fs->lfs_ronly && (mp->mnt_iflag & IMNT_WANTRDONLY)) {
    798 			/*
    799 			 * Changing from read/write to read-only.
    800 			 */
    801 			int flags = WRITECLOSE;
    802 			if (mp->mnt_flag & MNT_FORCE)
    803 				flags |= FORCECLOSE;
    804 			error = lfs_flushfiles(mp, flags);
    805 			if (error)
    806 				return error;
    807 			fs->lfs_ronly = 1;
    808 
    809 			/* Wake up reclaimd so it can die */
    810 			cv_broadcast(&fs->lfs_reclaim_cv);
    811 			kthread_join(fs->lfs_reclaimd_lwp);
    812 
    813 			/*
    814 			 * Drain pending I/O now that we have declared
    815 			 * read-only.  We compare against 1 because
    816 			 * seglock increments by one.
    817 			 */
    818 			lfs_prelock(fs, 0);
    819 			mutex_enter(&lfs_lock);
    820 			while (fs->lfs_iocount > 1)
    821 				(void)mtsleep(&fs->lfs_iocount, PRIBIO + 1,
    822 					      "lfs_roio", 0, &lfs_lock);
    823 			mutex_exit(&lfs_lock);
    824 			lfs_preunlock(fs);
    825 		} else if (fs->lfs_ronly && (mp->mnt_iflag & IMNT_WANTRDWR)) {
    826 			/*
    827 			 * Changing from read-only to read/write.
    828 			 * Note in the superblocks that we're writing.
    829 			 */
    830 
    831 			/* Start reclaimd */
    832 			error = kthread_create(PRI_BIO, KTHREAD_MUSTJOIN, NULL,
    833 				lfs_reclaimd, mp, &fs->lfs_reclaimd_lwp,
    834 				"lfs_reclaim");
    835 			if (error)
    836 				return error;
    837 
    838 			/* XXX: quotas should have been on even if readonly */
    839 			if (fs->lfs_use_quota2) {
    840 #ifdef LFS_QUOTA2
    841 				error = lfs_quota2_mount(mp);
    842 #else
    843 				uprintf("%s: no kernel support for this "
    844 					"filesystem's quotas\n",
    845 					mp->mnt_stat.f_mntonname);
    846 				if (mp->mnt_flag & MNT_FORCE) {
    847 					uprintf("%s: mounting anyway; "
    848 						"fsck afterwards\n",
    849 						mp->mnt_stat.f_mntonname);
    850 				} else {
    851 					error = EINVAL;
    852 				}
    853 #endif
    854 				if (error) {
    855 					return error;
    856 				}
    857 			}
    858 
    859 			fs->lfs_ronly = 0;
    860 			if (lfs_sb_getpflags(fs) & LFS_PF_CLEAN) {
    861 				lfs_sb_setpflags(fs, lfs_sb_getpflags(fs) & ~LFS_PF_CLEAN);
    862 				lfs_writesuper(fs, lfs_sb_getsboff(fs, 0));
    863 				lfs_writesuper(fs, lfs_sb_getsboff(fs, 1));
    864 			}
    865 		}
    866 
    867 		if (args->fspec == NULL)
    868 			return 0;
    869 	}
    870 
    871 	error = set_statvfs_info(path, UIO_USERSPACE, args->fspec,
    872 	    UIO_USERSPACE, mp->mnt_op->vfs_name, mp, l);
    873 	if (error == 0)
    874 		lfs_sb_setfsmnt(fs, mp->mnt_stat.f_mntonname);
    875 	return error;
    876 
    877 fail:
    878 	vrele(devvp);
    879 	return (error);
    880 }
    881 
    882 /*
    883  * Helper for mountfs. Note that the fs pointer may be a dummy one
    884  * pointing into a superblock buffer. (Which is gross; see below.)
    885  */
    886 static int
    887 lfs_checkmagic(struct lfs *fs)
    888 {
    889 	switch (fs->lfs_dlfs_u.u_32.dlfs_magic) {
    890 	    case LFS_MAGIC:
    891 		fs->lfs_is64 = false;
    892 		fs->lfs_dobyteswap = false;
    893 		break;
    894 	    case LFS64_MAGIC:
    895 		fs->lfs_is64 = true;
    896 		fs->lfs_dobyteswap = false;
    897 		break;
    898 #ifdef LFS_EI
    899 	    case LFS_MAGIC_SWAPPED:
    900 		fs->lfs_is64 = false;
    901 		fs->lfs_dobyteswap = true;
    902 		break;
    903 	    case LFS64_MAGIC_SWAPPED:
    904 		fs->lfs_is64 = true;
    905 		fs->lfs_dobyteswap = true;
    906 		break;
    907 #endif
    908 	    default:
    909 		/* XXX needs translation */
    910 		return EINVAL;
    911 	}
    912 	return 0;
    913 }
    914 
    915 /*
    916  * Common code for mount and mountroot
    917  * LFS specific
    918  */
    919 int
    920 lfs_mountfs(struct vnode *devvp, struct mount *mp, struct lwp *l)
    921 {
    922 	struct lfs *primarysb, *altsb, *thesb;
    923 	struct buf *primarybuf, *altbuf;
    924 	struct lfs *fs;
    925 	struct ulfsmount *ump;
    926 	struct vnode *vp;
    927 	dev_t dev;
    928 	int error, i, ronly, fsbsize, rfw;
    929 	kauth_cred_t cred;
    930 	CLEANERINFO *cip;
    931 	SEGUSE *sup;
    932 	daddr_t sb_addr;
    933 
    934 	cred = l ? l->l_cred : NOCRED;
    935 
    936 	/* The superblock is supposed to be 512 bytes. */
    937 	__CTASSERT(sizeof(struct dlfs) == DEV_BSIZE);
    938 
    939 	/*
    940 	 * Flush out any old buffers remaining from a previous use.
    941 	 */
    942 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
    943 	error = vinvalbuf(devvp, V_SAVE, cred, l, 0, 0);
    944 	VOP_UNLOCK(devvp);
    945 	if (error)
    946 		return (error);
    947 
    948 	ronly = (mp->mnt_flag & MNT_RDONLY) != 0;
    949 	rfw = (mp->mnt_flag & MNT_LOG) != 0;
    950 
    951 	/* Don't free random space on error. */
    952 	primarybuf = NULL;
    953 	altbuf = NULL;
    954 	ump = NULL;
    955 
    956 	sb_addr = LFS_LABELPAD / DEV_BSIZE;
    957 	while (1) {
    958 		/*
    959 		 * Read in the superblock.
    960 		 *
    961 		 * Note that because LFS_SBPAD is substantially larger
    962 		 * (8K) than the actual on-disk superblock (512 bytes)
    963 		 * the buffer contains enough space to be used as a
    964 		 * whole struct lfs (in-memory superblock) - we do this
    965 		 * only so we can set and use the is64 and dobyteswap
    966 		 * members. XXX this is gross and the logic here should
    967 		 * be reworked.
    968 		 */
    969 		error = bread(devvp, sb_addr, LFS_SBPAD, 0, &primarybuf);
    970 		if (error)
    971 			goto out;
    972 		primarysb = (struct lfs *)primarybuf->b_data;
    973 
    974 		/* Check the basics. */
    975 		error = lfs_checkmagic(primarysb);
    976 		if (error) {
    977 			DLOG((DLOG_MOUNT, "lfs_mountfs: primary superblock wrong magic\n"));
    978 			goto out;
    979 		}
    980 		if (lfs_sb_getbsize(primarysb) > MAXBSIZE ||
    981 		    lfs_sb_getversion(primarysb) > LFS_VERSION ||
    982 		    lfs_sb_getbsize(primarysb) < sizeof(struct dlfs)) {
    983 			DLOG((DLOG_MOUNT, "lfs_mountfs: primary superblock sanity failed\n"));
    984 			/* XXX needs translation */
    985 			error = EINVAL;
    986 			goto out;
    987 		}
    988 		if (lfs_sb_getinodefmt(primarysb) > LFS_MAXINODEFMT) {
    989 			DLOG((DLOG_MOUNT, "lfs_mountfs: unknown inode format %d\n",
    990 			       lfs_sb_getinodefmt(primarysb)));
    991 			error = EINVAL;
    992 			goto out;
    993 		}
    994 
    995 		if (lfs_sb_getversion(primarysb) == 1)
    996 			fsbsize = DEV_BSIZE;
    997 		else {
    998 			fsbsize = 1 << lfs_sb_getffshift(primarysb);
    999 			/*
   1000 			 * Could be, if the frag size is large enough, that we
   1001 			 * don't have the "real" primary superblock.  If that's
   1002 			 * the case, get the real one, and try again.
   1003 			 */
   1004 			if (sb_addr != (lfs_sb_getsboff(primarysb, 0) << (lfs_sb_getffshift(primarysb) - DEV_BSHIFT))) {
   1005 				DLOG((DLOG_MOUNT, "lfs_mountfs: sb daddr"
   1006 				      " 0x%llx is not right, trying 0x%llx\n",
   1007 				      (long long)sb_addr,
   1008 				      (long long)(lfs_sb_getsboff(primarysb, 0) << (lfs_sb_getffshift(primarysb) - DEV_BSHIFT))));
   1009 				sb_addr = lfs_sb_getsboff(primarysb, 0) << (lfs_sb_getffshift(primarysb) - DEV_BSHIFT);
   1010 				brelse(primarybuf, BC_INVAL);
   1011 				continue;
   1012 			}
   1013 		}
   1014 		break;
   1015 	}
   1016 
   1017 	/*
   1018 	 * Check the second superblock to see which is newer; then mount
   1019 	 * using the older of the two.	This is necessary to ensure that
   1020 	 * the filesystem is valid if it was not unmounted cleanly.
   1021 	 */
   1022 
   1023 	if (lfs_sb_getsboff(primarysb, 1) &&
   1024 	    lfs_sb_getsboff(primarysb, 1) - LFS_LABELPAD / fsbsize > LFS_SBPAD / fsbsize)
   1025 	{
   1026 		error = bread(devvp, lfs_sb_getsboff(primarysb, 1) * (fsbsize / DEV_BSIZE),
   1027 			LFS_SBPAD, 0, &altbuf);
   1028 		if (error)
   1029 			goto out;
   1030 		altsb = (struct lfs *)altbuf->b_data;
   1031 
   1032 		/*
   1033 		 * Note: this used to do the sanity check only if the
   1034 		 * timestamp/serial comparison required use of altsb;
   1035 		 * this way is less tolerant, but if altsb is corrupted
   1036 		 * enough that the magic number, version, and blocksize
   1037 		 * are bogus, why would the timestamp or serial fields
   1038 		 * mean anything either? If this kind of thing happens,
   1039 		 * you need to fsck anyway.
   1040 		 */
   1041 
   1042 		error = lfs_checkmagic(altsb);
   1043 		if (error)
   1044 			goto out;
   1045 
   1046 		/* Check the basics. */
   1047 		if (lfs_sb_getbsize(altsb) > MAXBSIZE ||
   1048 		    lfs_sb_getversion(altsb) > LFS_VERSION ||
   1049 		    lfs_sb_getbsize(altsb) < sizeof(struct dlfs)) {
   1050 			DLOG((DLOG_MOUNT, "lfs_mountfs: alt superblock"
   1051 			      " sanity failed\n"));
   1052 			error = EINVAL;		/* XXX needs translation */
   1053 			goto out;
   1054 		}
   1055 
   1056 		if (lfs_sb_getversion(primarysb) == 1) {
   1057 			/* 1s resolution comparison */
   1058 			if (lfs_sb_gettstamp(altsb) < lfs_sb_gettstamp(primarysb))
   1059 				thesb = altsb;
   1060 			else
   1061 				thesb = primarysb;
   1062 		} else {
   1063 			/* monotonic infinite-resolution comparison */
   1064 			if (lfs_sb_getserial(altsb) < lfs_sb_getserial(primarysb))
   1065 				thesb = altsb;
   1066 			else
   1067 				thesb = primarysb;
   1068 		}
   1069 	} else {
   1070 		DLOG((DLOG_MOUNT, "lfs_mountfs: invalid alt superblock location"
   1071 		      " daddr=0x%x\n", lfs_sb_getsboff(primarysb, 1)));
   1072 		error = EINVAL;
   1073 		goto out;
   1074 	}
   1075 
   1076 	/*
   1077 	 * Allocate the mount structure, copy the superblock into it.
   1078 	 * Note that the 32-bit and 64-bit superblocks are the same size.
   1079 	 */
   1080 	fs = kmem_zalloc(sizeof(struct lfs), KM_SLEEP);
   1081 	memcpy(&fs->lfs_dlfs_u.u_32, &thesb->lfs_dlfs_u.u_32,
   1082 	       sizeof(struct dlfs));
   1083 	fs->lfs_is64 = thesb->lfs_is64;
   1084 	fs->lfs_dobyteswap = thesb->lfs_dobyteswap;
   1085 	fs->lfs_hasolddirfmt = false; /* set for real below */
   1086 
   1087 	/* Compatibility */
   1088 	if (lfs_sb_getversion(fs) < 2) {
   1089 		lfs_sb_setsumsize(fs, LFS_V1_SUMMARY_SIZE);
   1090 		lfs_sb_setibsize(fs, lfs_sb_getbsize(fs));
   1091 		lfs_sb_sets0addr(fs, lfs_sb_getsboff(fs, 0));
   1092 		lfs_sb_settstamp(fs, lfs_sb_getotstamp(fs));
   1093 		lfs_sb_setfsbtodb(fs, 0);
   1094 	}
   1095 	if (lfs_sb_getresvseg(fs) == 0)
   1096 		lfs_sb_setresvseg(fs, MIN(lfs_sb_getminfreeseg(fs) - 1, \
   1097 			MAX(MIN_RESV_SEGS, lfs_sb_getminfreeseg(fs) / 2 + 1)));
   1098 
   1099 	/*
   1100 	 * If we aren't going to be able to write meaningfully to this
   1101 	 * filesystem, and were not mounted readonly, bomb out now.
   1102 	 */
   1103 	if (lfs_fsbtob(fs, LFS_NRESERVE(fs)) > LFS_MAX_BYTES && !ronly) {
   1104 		DLOG((DLOG_MOUNT, "lfs_mount: to mount this filesystem read/write,"
   1105 		      " we need BUFPAGES >= %lld\n",
   1106 		      (long long)((bufmem_hiwater / bufmem_lowater) *
   1107 				  LFS_INVERSE_MAX_BYTES(
   1108 					  lfs_fsbtob(fs, LFS_NRESERVE(fs))) >> PAGE_SHIFT)));
   1109 		kmem_free(fs, sizeof(struct lfs));
   1110 		error = EFBIG; /* XXX needs translation */
   1111 		goto out;
   1112 	}
   1113 
   1114 	/* Before rolling forward, lock so vget will sleep for other procs */
   1115 	if (l != NULL) {
   1116 		fs->lfs_flags = LFS_NOTYET;
   1117 		fs->lfs_rfpid = l->l_proc->p_pid;
   1118 	}
   1119 
   1120 	ump = kmem_zalloc(sizeof(*ump), KM_SLEEP);
   1121 	ump->um_lfs = fs;
   1122 	ump->um_fstype = fs->lfs_is64 ? ULFS2 : ULFS1;
   1123 	/* ump->um_cleaner_thread = NULL; */
   1124 	brelse(primarybuf, BC_INVAL);
   1125 	brelse(altbuf, BC_INVAL);
   1126 	primarybuf = NULL;
   1127 	altbuf = NULL;
   1128 
   1129 
   1130 	/* Set up the I/O information */
   1131 	fs->lfs_devbsize = DEV_BSIZE;
   1132 	fs->lfs_iocount = 0;
   1133 	fs->lfs_diropwait = 0;
   1134 	fs->lfs_activesb = 0;
   1135 	lfs_sb_setuinodes(fs, 0);
   1136 	fs->lfs_ravail = 0;
   1137 	fs->lfs_favail = 0;
   1138 	fs->lfs_sbactive = 0;
   1139 
   1140 	/* Set up the ifile and lock aflags */
   1141 	fs->lfs_doifile = 0;
   1142 	fs->lfs_writer = 0;
   1143 	fs->lfs_dirops = 0;
   1144 	fs->lfs_nadirop = 0;
   1145 	fs->lfs_prelock = 0;
   1146 	fs->lfs_seglock = 0;
   1147 	fs->lfs_cleanlock = 0;
   1148 	fs->lfs_pdflush = 0;
   1149 	fs->lfs_sleepers = 0;
   1150 	fs->lfs_pages = 0;
   1151 	fs->lfs_prelocklwp = NULL;
   1152 	rw_init(&fs->lfs_fraglock);
   1153 	rw_init(&fs->lfs_iflock);
   1154 	cv_init(&fs->lfs_sleeperscv, "lfs_slp");
   1155 	cv_init(&fs->lfs_diropscv, "lfs_dirop");
   1156 	cv_init(&fs->lfs_stopcv, "lfsstop");
   1157 	cv_init(&fs->lfs_nextsegsleep, "segment");
   1158 	cv_init(&fs->lfs_cleanercv, "cleancv");
   1159 	cv_init(&fs->lfs_prelockcv, "prelockcv");
   1160 	cv_init(&fs->lfs_cleanquitcv, "cleanquit");
   1161 	cv_init(&fs->lfs_reclaim_cv, "seg reclaim");
   1162 
   1163 	/* Set the file system readonly/modify bits. */
   1164 	fs->lfs_ronly = ronly;
   1165 	if (ronly == 0)
   1166 		fs->lfs_fmod = 1;
   1167 
   1168 	/* Device we're using */
   1169 	dev = devvp->v_rdev;
   1170 	fs->lfs_dev = dev;
   1171 	fs->lfs_devvp = devvp;
   1172 
   1173 	/* ulfs-level information */
   1174 	fs->um_flags = 0;
   1175 	fs->um_bptrtodb = lfs_sb_getffshift(fs) - DEV_BSHIFT;
   1176 	fs->um_seqinc = lfs_sb_getfrag(fs);
   1177 	fs->um_nindir = lfs_sb_getnindir(fs);
   1178 	fs->um_lognindir = ffs(lfs_sb_getnindir(fs)) - 1;
   1179 	fs->um_maxsymlinklen = lfs_sb_getmaxsymlinklen(fs);
   1180 	fs->um_dirblksiz = LFS_DIRBLKSIZ;
   1181 	fs->um_maxfilesize = lfs_sb_getmaxfilesize(fs);
   1182 
   1183 	/* quota stuff */
   1184 	/* XXX: these need to come from the on-disk superblock to be used */
   1185 	fs->lfs_use_quota2 = 0;
   1186 	fs->lfs_quota_magic = 0;
   1187 	fs->lfs_quota_flags = 0;
   1188 	fs->lfs_quotaino[0] = 0;
   1189 	fs->lfs_quotaino[1] = 0;
   1190 
   1191 	/* Initialize the mount structure. */
   1192 	mp->mnt_data = ump;
   1193 	mp->mnt_stat.f_fsidx.__fsid_val[0] = (long)dev;
   1194 	mp->mnt_stat.f_fsidx.__fsid_val[1] = makefstype(MOUNT_LFS);
   1195 	mp->mnt_stat.f_fsid = mp->mnt_stat.f_fsidx.__fsid_val[0];
   1196 	mp->mnt_stat.f_namemax = LFS_MAXNAMLEN;
   1197 	mp->mnt_stat.f_iosize = lfs_sb_getbsize(fs);
   1198 	mp->mnt_flag |= MNT_LOCAL;
   1199 	mp->mnt_iflag |= IMNT_SHRLOOKUP;
   1200 	mp->mnt_fs_bshift = lfs_sb_getbshift(fs);
   1201 	mp->mnt_iflag |= IMNT_CAN_RWTORO;
   1202 	if (fs->um_maxsymlinklen > 0)
   1203 		mp->mnt_iflag |= IMNT_DTYPE;
   1204 	else
   1205 		fs->lfs_hasolddirfmt = true;
   1206 
   1207 	ump->um_mountp = mp;
   1208 	for (i = 0; i < ULFS_MAXQUOTAS; i++)
   1209 		ump->um_quotas[i] = NULLVP;
   1210 	spec_node_setmountedfs(devvp, mp);
   1211 
   1212 	/* Set up reserved memory for pageout */
   1213 	lfs_setup_resblks(fs);
   1214 	/* Set up vdirop tailq */
   1215 	TAILQ_INIT(&fs->lfs_dchainhd);
   1216 	/* and cleaning vnode tailq */
   1217 	TAILQ_INIT(&fs->lfs_cleanhd);
   1218 	/* and paging tailq */
   1219 	TAILQ_INIT(&fs->lfs_pchainhd);
   1220 	/* and delayed segment accounting for truncation list */
   1221 	rb_tree_init(&fs->lfs_segdhd, &lfs_rbtree_ops);
   1222 
   1223 	/*
   1224 	 * We use the ifile vnode for almost every operation.  Instead of
   1225 	 * retrieving it from the hash table each time we retrieve it here,
   1226 	 * artificially increment the reference count and keep a pointer
   1227 	 * to it in the incore copy of the superblock.
   1228 	 */
   1229 	if ((error = VFS_VGET(mp, LFS_IFILE_INUM, LK_EXCLUSIVE, &vp)) != 0) {
   1230 		DLOG((DLOG_MOUNT, "lfs_mountfs: ifile vget failed, error=%d\n", error));
   1231 		goto out;
   1232 	}
   1233 	fs->lfs_ivnode = vp;
   1234 	vref(vp);
   1235 
   1236 	/* Set up segment usage flags for the autocleaner. */
   1237 	fs->lfs_nactive = 0;
   1238 	for (i = 0; i < lfs_sb_getnseg(fs); i++) {
   1239 		int changed;
   1240 		struct buf *bp;
   1241 
   1242 		LFS_SEGENTRY(sup, fs, i, bp);
   1243 		changed = 0;
   1244 		if (!ronly) {
   1245 			uint32_t nflags = sup->su_flags;
   1246 			nflags &= ~(SEGUSE_ACTIVE | SEGUSE_EMPTY
   1247 				    | SEGUSE_READY | SEGUSE_INVAL
   1248 				    | SEGUSE_ERROR);
   1249 			if (sup->su_nbytes == 0) {
   1250 				if (sup->su_flags & SEGUSE_DIRTY)
   1251 					nflags |= SEGUSE_EMPTY | SEGUSE_READY;
   1252 			} else {
   1253 				nflags &= ~(SEGUSE_EMPTY | SEGUSE_READY);
   1254 			}
   1255 			if (nflags != sup->su_flags) {
   1256 				sup->su_flags = nflags;
   1257 				++changed;
   1258 			}
   1259 		}
   1260 		if (changed)
   1261 			LFS_WRITESEGENTRY(sup, fs, i, bp);
   1262 		else
   1263 			LFS_RELEASESEGENTRY(sup, fs, i, bp);
   1264 	}
   1265 	/* Set lastcleaned to an invalid value */
   1266 	fs->lfs_lastcleaned = (uint32_t)-1;
   1267 
   1268 	if (rfw && !ronly) {
   1269 		/* Roll forward */
   1270 		lfs_roll_forward(fs, mp, l);
   1271 		lfs_reset_avail(fs);
   1272 	}
   1273 
   1274 	/* Init reclaimd */
   1275 	if (!ronly) {
   1276 		error = kthread_create(PRI_BIO, KTHREAD_MUSTJOIN, NULL,
   1277 			lfs_reclaimd, mp, &fs->lfs_reclaimd_lwp, "lfs_reclaim");
   1278 		if (error != 0)
   1279 			goto out;
   1280 	}
   1281 	fs->lfs_rfpid = 0;
   1282 
   1283 	/*
   1284 	 * XXX: if the fs has quotas, quotas should be on even if
   1285 	 * readonly. Otherwise you can't query the quota info!
   1286 	 * However, that's not how the quota2 code got written and I
   1287 	 * don't know if it'll behave itself if enabled while
   1288 	 * readonly, so for now use the same enable logic as ffs.
   1289 	 *
   1290 	 * XXX: also, if you use the -f behavior allowed here (and
   1291 	 * equivalently above for remount) it will corrupt the fs. It
   1292 	 * ought not to allow that. It should allow mounting readonly
   1293 	 * if there are quotas and the kernel doesn't have the quota
   1294 	 * code, but only readonly.
   1295 	 *
   1296 	 * XXX: and if you use the -f behavior allowed here it will
   1297 	 * likely crash at unmount time (or remount time) because we
   1298 	 * think quotas are active.
   1299 	 *
   1300 	 * Although none of this applies until there's a way to set
   1301 	 * lfs_use_quota2 and have quotas in the fs at all.
   1302 	 */
   1303 	if (!ronly && fs->lfs_use_quota2) {
   1304 #ifdef LFS_QUOTA2
   1305 		error = lfs_quota2_mount(mp);
   1306 #else
   1307 		uprintf("%s: no kernel support for this filesystem's quotas\n",
   1308 			mp->mnt_stat.f_mntonname);
   1309 		if (mp->mnt_flag & MNT_FORCE) {
   1310 			uprintf("%s: mounting anyway; fsck afterwards\n",
   1311 				mp->mnt_stat.f_mntonname);
   1312 		} else {
   1313 			error = EINVAL;
   1314 		}
   1315 #endif
   1316 		if (error) {
   1317 			/* XXX XXX must clean up the stuff immediately above */
   1318 			printf("lfs_mountfs: sorry, leaking some memory\n");
   1319 			goto out;
   1320 		}
   1321 	}
   1322 
   1323 	/* If writing, sb is not clean; record in case of immediate crash */
   1324 	if (!fs->lfs_ronly) {
   1325 		lfs_sb_setpflags(fs, lfs_sb_getpflags(fs) & ~LFS_PF_CLEAN);
   1326 		lfs_writesuper(fs, lfs_sb_getsboff(fs, 0));
   1327 		lfs_writesuper(fs, lfs_sb_getsboff(fs, 1));
   1328 	}
   1329 
   1330 	/* Allow vget now that roll-forward is complete */
   1331 	fs->lfs_flags &= ~(LFS_NOTYET);
   1332 	wakeup(&fs->lfs_flags);
   1333 
   1334 	/*
   1335 	 * Initialize the ifile cleaner info with information from
   1336 	 * the superblock.
   1337 	 */
   1338 	{
   1339 		struct buf *bp;
   1340 
   1341 		LFS_CLEANERINFO(cip, fs, bp);
   1342 		lfs_ci_setclean(fs, cip, lfs_sb_getnclean(fs));
   1343 		lfs_ci_setdirty(fs, cip, lfs_sb_getnseg(fs) - lfs_sb_getnclean(fs));
   1344 		lfs_ci_setavail(fs, cip, lfs_sb_getavail(fs));
   1345 		lfs_ci_setbfree(fs, cip, lfs_sb_getbfree(fs));
   1346 		(void) LFS_BWRITE_LOG(bp); /* Ifile */
   1347 	}
   1348 
   1349 	/*
   1350 	 * Mark the current segment as ACTIVE, since we're going to
   1351 	 * be writing to it.
   1352 	 */
   1353 	{
   1354 		struct buf *bp;
   1355 
   1356 		LFS_SEGENTRY(sup, fs, lfs_dtosn(fs, lfs_sb_getoffset(fs)), bp);
   1357 		sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
   1358 		fs->lfs_nactive++;
   1359 		LFS_WRITESEGENTRY(sup, fs, lfs_dtosn(fs, lfs_sb_getoffset(fs)), bp);  /* Ifile */
   1360 	}
   1361 
   1362 	/* Now that roll-forward is done, unlock the Ifile */
   1363 	vput(vp);
   1364 
   1365 	/* Free any file orphaned during a crash */
   1366 	lfs_free_orphans(fs);
   1367 
   1368 	/* Start the pagedaemon-anticipating daemon */
   1369 	mutex_enter(&lfs_lock);
   1370 	if (lfs_writer_daemon == NULL &&
   1371 	    kthread_create(PRI_BIO, 0, NULL,
   1372 	    lfs_writerd, NULL, NULL, "lfs_writer") != 0)
   1373 		panic("fork lfs_writer");
   1374 	mutex_exit(&lfs_lock);
   1375 
   1376 	printf("WARNING: the log-structured file system is experimental\n"
   1377 	    "WARNING: it may cause system crashes and/or corrupt data\n");
   1378 
   1379 	return (0);
   1380 
   1381 out:
   1382 	if (primarybuf)
   1383 		brelse(primarybuf, BC_INVAL);
   1384 	if (altbuf)
   1385 		brelse(altbuf, BC_INVAL);
   1386 	if (ump) {
   1387 		kmem_free(ump->um_lfs, sizeof(struct lfs));
   1388 		kmem_free(ump, sizeof(*ump));
   1389 		mp->mnt_data = NULL;
   1390 	}
   1391 
   1392 	return (error);
   1393 }
   1394 
   1395 static void
   1396 lfs_reclaimd(void *v)
   1397 {
   1398 	struct mount *mp = (struct mount *)v;
   1399 	struct lfs *fs = VFSTOULFS(mp)->um_lfs;
   1400 
   1401 	for (;;) {
   1402 		mutex_enter(&lfs_lock);
   1403 		cv_wait(&fs->lfs_reclaim_cv, &lfs_lock);
   1404 		if (mp->mnt_iflag & (IMNT_UNMOUNT|IMNT_WANTRDONLY))
   1405 			goto out;
   1406 		mutex_exit(&lfs_lock);
   1407 
   1408 		EXCL_IFLOCK(fs);
   1409 		lfs_auto_segclean(fs);
   1410 		UNEXCL_IFLOCK(fs);
   1411 	}
   1412 
   1413  out:
   1414 	mutex_exit(&lfs_lock);
   1415 	kthread_exit(0);
   1416 }
   1417 
   1418 void
   1419 lfs_reset_avail(struct lfs *fs)
   1420 {
   1421 	daddr_t avail;
   1422 	int sn, nclean, nsb, labelcorrect, curr, mfs;
   1423 	SEGUSE *sup;
   1424 	struct buf *bp;
   1425 
   1426 	KASSERT(!fs->lfs_ronly);
   1427 
   1428 	avail = nclean = nsb = labelcorrect = 0;
   1429 	for (sn = 0; sn < lfs_sb_getnseg(fs); ++sn) {
   1430 		LFS_SEGENTRY(sup, fs, sn, bp);
   1431 
   1432 		/* Count all clean segments and the remainder of this one */
   1433 		if (!(sup->su_flags & SEGUSE_DIRTY)) {
   1434 			++nclean;
   1435 			avail += lfs_segtod(fs, 1);
   1436 
   1437 			/* Correct for label and superblock, if present */
   1438 			if (sup->su_flags & SEGUSE_SUPERBLOCK)
   1439 				++nsb;
   1440 			if (sn == 0 && lfs_sb_getversion(fs) > 1
   1441 			    && lfs_sb_gets0addr(fs) < lfs_btofsb(fs, LFS_LABELPAD))
   1442 				labelcorrect = lfs_btofsb(fs, LFS_LABELPAD)
   1443 					- lfs_sb_gets0addr(fs);
   1444 		}
   1445 
   1446 		LFS_RELEASESEGENTRY(sup, fs, sn, bp);
   1447 	}
   1448 
   1449 	/* Also may be available bytes in current seg */
   1450 	sn = lfs_dtosn(fs, lfs_sb_getoffset(fs));
   1451 	curr = lfs_sntod(fs, sn + 1) - lfs_sb_getoffset(fs);
   1452 	/* But do not count minfreesegs */
   1453 	mfs = lfs_segtod(fs, (lfs_sb_getminfreeseg(fs) -
   1454 		(lfs_sb_getminfreeseg(fs) / 2)));
   1455 
   1456 	avail = nclean * lfs_segtod(fs, 1);
   1457 	avail -= nsb * lfs_btofsb(fs, LFS_SBPAD);
   1458 	avail -= labelcorrect;
   1459 	avail += curr;
   1460 	avail -= mfs;
   1461 
   1462 	DLOG((DLOG_AVAIL, "avail := %jd*%jd-%jd*%jd-%jd+%jd-%jd=%jd\n",
   1463 	       (intmax_t)nclean,
   1464 	       (intmax_t)lfs_segtod(fs, 1),
   1465 	       (intmax_t)nsb,
   1466 	       (intmax_t)lfs_btofsb(fs, LFS_SBPAD),
   1467 	       (intmax_t)labelcorrect,
   1468 	       (intmax_t)curr,
   1469 	       (intmax_t)mfs,
   1470 	       (intmax_t)avail));
   1471 
   1472 	lfs_sb_setavail(fs, avail);
   1473 	lfs_sb_setnclean(fs, nclean);
   1474 }
   1475 
   1476 /*
   1477  * unmount system call
   1478  */
   1479 int
   1480 lfs_unmount(struct mount *mp, int mntflags)
   1481 {
   1482 	struct ulfsmount *ump;
   1483 	struct lfs *fs;
   1484 	int error, ronly;
   1485 
   1486 	ump = VFSTOULFS(mp);
   1487 	fs = ump->um_lfs;
   1488 
   1489 	if (!fs->lfs_ronly) {
   1490 		/* Wake up reclaimd so it can die */
   1491 		cv_broadcast(&fs->lfs_reclaim_cv);
   1492 		kthread_join(fs->lfs_reclaimd_lwp);
   1493 	}
   1494 
   1495 	error = lfs_flushfiles(mp, mntflags & MNT_FORCE ? FORCECLOSE : 0);
   1496 	if (error)
   1497 		return error;
   1498 
   1499 	DEBUG_CHECK_FREELIST(fs);
   1500 
   1501 	/* Check for dirty blocks on ifile */
   1502 	KASSERT(LIST_FIRST(&fs->lfs_ivnode->v_dirtyblkhd) == NULL);
   1503 
   1504 	/* Finish with the Ifile, now that we're done with it */
   1505 	vgone(fs->lfs_ivnode);
   1506 
   1507 	ronly = !fs->lfs_ronly;
   1508 	if (fs->lfs_devvp->v_type != VBAD)
   1509 		spec_node_setmountedfs(fs->lfs_devvp, NULL);
   1510 	vn_lock(fs->lfs_devvp, LK_EXCLUSIVE | LK_RETRY);
   1511 	error = VOP_CLOSE(fs->lfs_devvp,
   1512 	    ronly ? FREAD : FREAD|FWRITE, NOCRED);
   1513 	vput(fs->lfs_devvp);
   1514 
   1515 	/* Complain about page leakage */
   1516 	if (fs->lfs_pages > 0)
   1517 		printf("lfs_unmount: still claim %d pages (%d in subsystem)\n",
   1518 			fs->lfs_pages, lfs_subsys_pages);
   1519 
   1520 	/*
   1521 	 * Make doubly sure we have no outstanding I/O before we
   1522 	 * call lfs_free_resblks(), to avoid a busy pool panic.
   1523 	 */
   1524 	mutex_enter(&lfs_lock);
   1525 	while (fs->lfs_iocount)
   1526 		mtsleep(&fs->lfs_iocount, PRIBIO + 1, "lfs_umount2", 0,
   1527 			&lfs_lock);
   1528 	mutex_exit(&lfs_lock);
   1529 
   1530 	/* Free per-mount data structures */
   1531 	lfs_free_resblks(fs);
   1532 	cv_destroy(&fs->lfs_sleeperscv);
   1533 	cv_destroy(&fs->lfs_diropscv);
   1534 	cv_destroy(&fs->lfs_stopcv);
   1535 	cv_destroy(&fs->lfs_nextsegsleep);
   1536 	cv_destroy(&fs->lfs_reclaim_cv);
   1537 
   1538 	rw_destroy(&fs->lfs_fraglock);
   1539 	rw_destroy(&fs->lfs_iflock);
   1540 
   1541 	kmem_free(fs, sizeof(struct lfs));
   1542 	kmem_free(ump, sizeof(*ump));
   1543 
   1544 	mp->mnt_data = NULL;
   1545 	mp->mnt_flag &= ~MNT_LOCAL;
   1546 	return (error);
   1547 }
   1548 
   1549 static int
   1550 lfs_flushfiles(struct mount *mp, int flags)
   1551 {
   1552 	struct lwp *l = curlwp;
   1553 	struct ulfsmount *ump;
   1554 	struct lfs *fs;
   1555 	struct vnode *vp;
   1556 	int error;
   1557 
   1558 	ump = VFSTOULFS(mp);
   1559 	fs = ump->um_lfs;
   1560 
   1561 	/* Two checkpoints */
   1562 	if (!fs->lfs_ronly) {
   1563 		lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
   1564 		lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
   1565 	}
   1566 
   1567 	/* wake up the cleaner so it can die */
   1568 	/* XXX: shouldn't this be *after* the error cases below? */
   1569 	lfs_wakeup_cleaner(fs);
   1570 	mutex_enter(&lfs_lock);
   1571 	while (fs->lfs_sleepers)
   1572 		cv_wait(&fs->lfs_sleeperscv, &lfs_lock);
   1573 	mutex_exit(&lfs_lock);
   1574 
   1575 #ifdef LFS_EXTATTR
   1576 	if (ump->um_fstype == ULFS1) {
   1577 		if (ump->um_extattr.uepm_flags & ULFS_EXTATTR_UEPM_STARTED) {
   1578 			ulfs_extattr_stop(mp, curlwp);
   1579 		}
   1580 		if (ump->um_extattr.uepm_flags & ULFS_EXTATTR_UEPM_INITIALIZED) {
   1581 			ulfs_extattr_uepm_destroy(&ump->um_extattr);
   1582 			mp->mnt_flag &= ~MNT_EXTATTR;
   1583 		}
   1584 	}
   1585 #endif
   1586 #ifdef LFS_QUOTA
   1587         if ((error = lfsquota1_umount(mp, flags)) != 0)
   1588 		return (error);
   1589 #endif
   1590 #ifdef LFS_QUOTA2
   1591         if ((error = lfsquota2_umount(mp, flags)) != 0)
   1592 		return (error);
   1593 #endif
   1594 	if ((error = vflush(mp, fs->lfs_ivnode, flags)) != 0)
   1595 		return (error);
   1596 	if ((error = VFS_SYNC(mp, MNT_WAIT, l->l_cred)) != 0)
   1597 		return (error);
   1598 	vp = fs->lfs_ivnode;
   1599 	mutex_enter(vp->v_interlock);
   1600 	if (LIST_FIRST(&vp->v_dirtyblkhd))
   1601 		panic("lfs_flushfiles: still dirty blocks on ifile vnode");
   1602 	mutex_exit(vp->v_interlock);
   1603 
   1604 	/* Explicitly write the superblock, to update serial and pflags */
   1605 	if (!fs->lfs_ronly) {
   1606 		lfs_sb_setpflags(fs, lfs_sb_getpflags(fs) | LFS_PF_CLEAN);
   1607 		lfs_writesuper(fs, lfs_sb_getsboff(fs, 0));
   1608 		lfs_writesuper(fs, lfs_sb_getsboff(fs, 1));
   1609 	}
   1610 	mutex_enter(&lfs_lock);
   1611 	while (fs->lfs_iocount)
   1612 		mtsleep(&fs->lfs_iocount, PRIBIO + 1, "lfs_umount", 0,
   1613 			&lfs_lock);
   1614 	mutex_exit(&lfs_lock);
   1615 
   1616 	return 0;
   1617 }
   1618 
   1619 /*
   1620  * Get file system statistics.
   1621  *
   1622  * NB: We don't lock to access the superblock here, because it's not
   1623  * really that important if we get it wrong.
   1624  */
   1625 int
   1626 lfs_statvfs(struct mount *mp, struct statvfs *sbp)
   1627 {
   1628 	struct lfs *fs;
   1629 	struct ulfsmount *ump;
   1630 
   1631 	ump = VFSTOULFS(mp);
   1632 	fs = ump->um_lfs;
   1633 
   1634 	sbp->f_bsize = lfs_sb_getbsize(fs);
   1635 	sbp->f_frsize = lfs_sb_getfsize(fs);
   1636 	sbp->f_iosize = lfs_sb_getbsize(fs);
   1637 	sbp->f_blocks = LFS_EST_NONMETA(fs) - VTOI(fs->lfs_ivnode)->i_lfs_effnblks;
   1638 
   1639 	sbp->f_bfree = LFS_EST_BFREE(fs);
   1640 	/*
   1641 	 * XXX this should be lfs_sb_getsize (measured in frags)
   1642 	 * rather than dsize (measured in diskblocks). However,
   1643 	 * getsize needs a format version check (for version 1 it
   1644 	 * needs to be blockstofrags'd) so for the moment I'm going to
   1645 	 * leave this...  it won't fire wrongly as frags are at least
   1646 	 * as big as diskblocks.
   1647 	 */
   1648 	KASSERT(sbp->f_bfree <= lfs_sb_getdsize(fs));
   1649 #if 0
   1650 	if (sbp->f_bfree < 0)
   1651 		sbp->f_bfree = 0;
   1652 #endif
   1653 
   1654 	sbp->f_bresvd = LFS_EST_RSVD(fs);
   1655 	if (sbp->f_bfree > sbp->f_bresvd)
   1656 		sbp->f_bavail = sbp->f_bfree - sbp->f_bresvd;
   1657 	else
   1658 		sbp->f_bavail = 0;
   1659 
   1660 	/* XXX: huh? - dholland 20150728 */
   1661 	sbp->f_files = lfs_sb_getbfree(fs) / lfs_btofsb(fs, lfs_sb_getibsize(fs))
   1662 	    * LFS_INOPB(fs);
   1663 	sbp->f_ffree = sbp->f_files - lfs_sb_getnfiles(fs);
   1664 	sbp->f_favail = sbp->f_ffree;
   1665 	sbp->f_fresvd = 0;
   1666 	copy_statvfs_info(sbp, mp);
   1667 	return (0);
   1668 }
   1669 
   1670 /*
   1671  * Go through the disk queues to initiate sandbagged IO;
   1672  * go through the inodes to write those that have been modified;
   1673  * initiate the writing of the super block if it has been modified.
   1674  */
   1675 int
   1676 lfs_sync(struct mount *mp, int waitfor, kauth_cred_t cred)
   1677 {
   1678 	int error, segflags;
   1679 	struct lfs *fs;
   1680 
   1681 	fs = VFSTOULFS(mp)->um_lfs;
   1682 	if (fs->lfs_ronly)
   1683 		return 0;
   1684 
   1685 	/* Snapshots should not hose the syncer */
   1686 	/*
   1687 	 * XXX Sync can block here anyway, since we don't have a very
   1688 	 * XXX good idea of how much data is pending.  If it's more
   1689 	 * XXX than a segment and lfs_nextseg is close to the end of
   1690 	 * XXX the log, we'll likely block.
   1691 	 */
   1692 	mutex_enter(&lfs_lock);
   1693 	if (fs->lfs_nowrap && lfs_sb_getnextseg(fs) < lfs_sb_getcurseg(fs)) {
   1694 		mutex_exit(&lfs_lock);
   1695 		return 0;
   1696 	}
   1697 	mutex_exit(&lfs_lock);
   1698 
   1699 	lfs_writer_enter(fs, "lfs_wsync");
   1700 
   1701 	DLOG((DLOG_FLUSH, "lfs_sync waitfor=%x at 0x%jx\n", waitfor,
   1702 	      (uintmax_t)lfs_sb_getoffset(fs)));
   1703 
   1704 	segflags = 0;
   1705 	if (waitfor == MNT_LAZY)
   1706 		segflags = 0;
   1707 	else if (waitfor == MNT_NOWAIT)
   1708 		segflags = SEGM_CKP;
   1709 	else /* MNT_WAIT, or unknown value */
   1710 		segflags = SEGM_SYNC | SEGM_CKP;
   1711 
   1712 	error = lfs_segwrite(mp, segflags);
   1713 	lfs_writer_leave(fs);
   1714 #ifdef LFS_QUOTA
   1715 	lfs_qsync(mp);
   1716 #endif
   1717 	return (error);
   1718 }
   1719 
   1720 /*
   1721  * Look up an LFS dinode number to find its incore vnode.  If not already
   1722  * in core, read it in from the specified device.  Return the inode locked.
   1723  * Detection and handling of mount points must be done by the calling routine.
   1724  */
   1725 int
   1726 lfs_vget(struct mount *mp, ino_t ino, int lktype, struct vnode **vpp)
   1727 {
   1728 	int error;
   1729 
   1730 	error = vcache_get(mp, &ino, sizeof(ino), vpp);
   1731 	if (error)
   1732 		return error;
   1733 	error = vn_lock(*vpp, lktype);
   1734 	if (error) {
   1735 		vrele(*vpp);
   1736 		*vpp = NULL;
   1737 		return error;
   1738 	}
   1739 
   1740 	return 0;
   1741 }
   1742 
   1743 static int
   1744 compare_nodes_sd(void *context, const void *v1, const void *v2)
   1745 {
   1746 	const struct segdelta *sd1, *sd2;
   1747 
   1748 	sd1 = (const struct segdelta *)v1;
   1749 	sd2 = (const struct segdelta *)v2;
   1750 	return sd1->segnum - sd2->segnum;
   1751 }
   1752 
   1753 static int
   1754 compare_key_sd(void *context, const void *nv, const void *kv)
   1755 {
   1756 	const struct segdelta *sd;
   1757 	long key;
   1758 
   1759 	sd = (const struct segdelta *)nv;
   1760 	key = *(const long *)kv;
   1761 	return sd->segnum - key;
   1762 }
   1763 
   1764 /*
   1765  * Create a new vnode/inode pair and initialize what fields we can.
   1766  */
   1767 static void
   1768 lfs_init_vnode(struct ulfsmount *ump, ino_t ino, struct vnode *vp)
   1769 {
   1770 	struct lfs *fs = ump->um_lfs;
   1771 	struct inode *ip;
   1772 	union lfs_dinode *dp;
   1773 
   1774 	ASSERT_NO_SEGLOCK(fs);
   1775 
   1776 	/* Initialize the inode. */
   1777 	ip = pool_get(&lfs_inode_pool, PR_WAITOK);
   1778 	memset(ip, 0, sizeof(*ip));
   1779 	dp = pool_get(&lfs_dinode_pool, PR_WAITOK);
   1780 	memset(dp, 0, sizeof(*dp));
   1781 	ip->inode_ext.lfs = pool_get(&lfs_inoext_pool, PR_WAITOK);
   1782 	memset(ip->inode_ext.lfs, 0, sizeof(*ip->inode_ext.lfs));
   1783 	ip->i_din = dp;
   1784 	ip->i_ump = ump;
   1785 	ip->i_vnode = vp;
   1786 	ip->i_dev = fs->lfs_dev;
   1787 	lfs_dino_setinumber(fs, dp, ino);
   1788 	ip->i_number = ino;
   1789 	ip->i_lfs = fs;
   1790 	ip->i_lfs_effnblks = 0;
   1791 	SPLAY_INIT(&ip->i_lfs_lbtree);
   1792 	ip->i_lfs_nbtree = 0;
   1793 	rb_tree_init(&ip->i_lfs_segdhd, &lfs_rbtree_ops);
   1794 
   1795 	vp->v_tag = VT_LFS;
   1796 	vp->v_op = lfs_vnodeop_p;
   1797 	vp->v_data = ip;
   1798 }
   1799 
   1800 /*
   1801  * Undo lfs_init_vnode().
   1802  */
   1803 static void
   1804 lfs_deinit_vnode(struct ulfsmount *ump, struct vnode *vp)
   1805 {
   1806 	struct inode *ip = VTOI(vp);
   1807 
   1808 	pool_put(&lfs_inoext_pool, ip->inode_ext.lfs);
   1809 	pool_put(&lfs_dinode_pool, ip->i_din);
   1810 	pool_put(&lfs_inode_pool, ip);
   1811 	vp->v_data = NULL;
   1812 }
   1813 
   1814 /*
   1815  * Read an inode from disk and initialize this vnode / inode pair.
   1816  * Caller assures no other thread will try to load this inode.
   1817  */
   1818 int
   1819 lfs_loadvnode(struct mount *mp, struct vnode *vp,
   1820     const void *key, size_t key_len, const void **new_key)
   1821 {
   1822 	struct lfs *fs;
   1823 	union lfs_dinode *dip;
   1824 	struct inode *ip;
   1825 	struct buf *bp;
   1826 	IFILE *ifp;
   1827 	struct ulfsmount *ump;
   1828 	ino_t ino;
   1829 	daddr_t daddr;
   1830 	int error, retries;
   1831 	struct timespec ts;
   1832 
   1833 	KASSERT(key_len == sizeof(ino));
   1834 	memcpy(&ino, key, key_len);
   1835 
   1836 	memset(&ts, 0, sizeof ts);	/* XXX gcc */
   1837 
   1838 	ump = VFSTOULFS(mp);
   1839 	fs = ump->um_lfs;
   1840 
   1841 	/*
   1842 	 * If the filesystem is not completely mounted yet, suspend
   1843 	 * any access requests (wait for roll-forward to complete).
   1844 	 */
   1845 	mutex_enter(&lfs_lock);
   1846 	while ((fs->lfs_flags & LFS_NOTYET) && curproc->p_pid != fs->lfs_rfpid)
   1847 		mtsleep(&fs->lfs_flags, PRIBIO+1, "lfs_notyet", 0,
   1848 			&lfs_lock);
   1849 	mutex_exit(&lfs_lock);
   1850 
   1851 	KASSERTMSG(ino >= LFS_IFILE_INUM, "ino=%lld", (long long)ino);
   1852 	/* LFS_ASSERT_MAXINO(fs, ino); */
   1853 
   1854 	/* Translate the inode number to a disk address. */
   1855 	if (ino == LFS_IFILE_INUM)
   1856 		daddr = lfs_sb_getidaddr(fs);
   1857 	else {
   1858 		LFS_IENTRY(ifp, fs, ino, bp);
   1859 		daddr = lfs_if_getdaddr(fs, ifp);
   1860 		if (lfs_sb_getversion(fs) > 1) {
   1861 			ts.tv_sec = lfs_if_getatime_sec(fs, ifp);
   1862 			ts.tv_nsec = lfs_if_getatime_nsec(fs, ifp);
   1863 		}
   1864 		LFS_RELEASEIENTRY(ifp, fs, ino, bp);
   1865 
   1866 		if (DADDR_IS_BAD(daddr))
   1867 			return (ENOENT);
   1868 	}
   1869 
   1870 	/* Allocate/init new vnode/inode. */
   1871 	lfs_init_vnode(ump, ino, vp);
   1872 	ip = VTOI(vp);
   1873 
   1874 	/* If the cleaner supplied the inode, use it. */
   1875 	if (curlwp == fs->lfs_cleaner_thread && fs->lfs_cleaner_hint != NULL &&
   1876 	    fs->lfs_cleaner_hint->bi_lbn == LFS_UNUSED_LBN) {
   1877 		dip = fs->lfs_cleaner_hint->bi_bp;
   1878 		if (fs->lfs_is64) {
   1879 			error = copyin(dip, &ip->i_din->u_64,
   1880 				       sizeof(struct lfs64_dinode));
   1881 		} else {
   1882 			error = copyin(dip, &ip->i_din->u_32,
   1883 				       sizeof(struct lfs32_dinode));
   1884 		}
   1885 		if (error) {
   1886 			lfs_deinit_vnode(ump, vp);
   1887 			return error;
   1888 		}
   1889 		KASSERT(ip->i_number == ino);
   1890 		goto out;
   1891 	}
   1892 
   1893 	/* Read in the disk contents for the inode, copy into the inode. */
   1894 	retries = 0;
   1895 again:
   1896 	error = bread(fs->lfs_devvp, LFS_FSBTODB(fs, daddr),
   1897 		(lfs_sb_getversion(fs) == 1 ? lfs_sb_getbsize(fs) : lfs_sb_getibsize(fs)),
   1898 		0, &bp);
   1899 	if (error) {
   1900 		lfs_deinit_vnode(ump, vp);
   1901 		return error;
   1902 	}
   1903 
   1904 	dip = lfs_ifind(fs, ino, bp);
   1905 	if (dip == NULL) {
   1906 		/* Assume write has not completed yet; try again */
   1907 		brelse(bp, BC_INVAL);
   1908 		++retries;
   1909 		if (retries <= LFS_IFIND_RETRIES) {
   1910 			mutex_enter(&lfs_lock);
   1911 			if (fs->lfs_iocount) {
   1912 				DLOG((DLOG_VNODE,
   1913 				    "%s: dinode %d not found, retrying...\n",
   1914 				    __func__, ino));
   1915 				(void)mtsleep(&fs->lfs_iocount, PRIBIO + 1,
   1916 					      "lfs ifind", 1, &lfs_lock);
   1917 			} else
   1918 				retries = LFS_IFIND_RETRIES;
   1919 			mutex_exit(&lfs_lock);
   1920 			goto again;
   1921 		}
   1922 #ifdef DEBUG
   1923 		/* If the seglock is held look at the bpp to see
   1924 		   what is there anyway */
   1925 		mutex_enter(&lfs_lock);
   1926 		if (fs->lfs_seglock > 0) {
   1927 			struct buf **bpp;
   1928 			union lfs_dinode *dp;
   1929 			int i;
   1930 
   1931 			for (bpp = fs->lfs_sp->bpp;
   1932 			     bpp != fs->lfs_sp->cbpp; ++bpp) {
   1933 				if ((*bpp)->b_vp == fs->lfs_ivnode &&
   1934 				    bpp != fs->lfs_sp->bpp) {
   1935 					/* Inode block */
   1936 					printf("%s: block 0x%" PRIx64 ": ",
   1937 					       __func__, (*bpp)->b_blkno);
   1938 					for (i = 0; i < LFS_INOPB(fs); i++) {
   1939 						dp = DINO_IN_BLOCK(fs,
   1940 						    (*bpp)->b_data, i);
   1941 						if (lfs_dino_getinumber(fs, dp))
   1942 							printf("%ju ",
   1943 							    (uintmax_t)lfs_dino_getinumber(fs, dp));
   1944 					}
   1945 					printf("\n");
   1946 				}
   1947 			}
   1948 		}
   1949 		mutex_exit(&lfs_lock);
   1950 #endif /* DEBUG */
   1951 		panic("lfs_loadvnode: dinode not found");
   1952 	}
   1953 	lfs_copy_dinode(fs, ip->i_din, dip);
   1954 	brelse(bp, 0);
   1955 
   1956 out:
   1957 	if (lfs_sb_getversion(fs) > 1) {
   1958 		lfs_dino_setatime(fs, ip->i_din, ts.tv_sec);
   1959 		lfs_dino_setatimensec(fs, ip->i_din, ts.tv_nsec);
   1960 	}
   1961 
   1962 	lfs_vinit(mp, &vp);
   1963 
   1964 	*new_key = &ip->i_number;
   1965 	return 0;
   1966 }
   1967 
   1968 /*
   1969  * Create a new inode and initialize this vnode / inode pair.
   1970  */
   1971 int
   1972 lfs_newvnode(struct mount *mp, struct vnode *dvp, struct vnode *vp,
   1973     struct vattr *vap, kauth_cred_t cred, void *extra,
   1974     size_t *key_len, const void **new_key)
   1975 {
   1976 	ino_t ino;
   1977 	struct inode *ip;
   1978 	struct ulfsmount *ump;
   1979 	struct lfs *fs;
   1980 	int error, mode, gen;
   1981 
   1982 	ump = VFSTOULFS(mp);
   1983 	fs = ump->um_lfs;
   1984 
   1985 	KASSERT(dvp != NULL || vap->va_fileid > 0);
   1986 	KASSERT((fs->lfs_flags & LFS_NOTYET) ||
   1987 		(dvp != NULL && dvp->v_mount == mp));
   1988 	KASSERT(vap->va_type != VNON);
   1989 
   1990 	*key_len = sizeof(ino);
   1991 	mode = MAKEIMODE(vap->va_type, vap->va_mode);
   1992 
   1993 	/*
   1994 	 * Allocate fresh inode.  With "dvp == NULL" take the inode number
   1995 	 * and version from "vap".
   1996 	*/
   1997 	if (dvp == NULL) {
   1998 		ino = vap->va_fileid;
   1999 		gen = vap->va_gen;
   2000 		error = lfs_valloc_fixed(fs, ino, gen);
   2001 	} else {
   2002 		error = lfs_valloc(dvp, mode, cred, &ino, &gen);
   2003 	}
   2004 	if (error)
   2005 		return error;
   2006 
   2007 	/* Attach inode to vnode. */
   2008 	lfs_init_vnode(ump, ino, vp);
   2009 	ip = VTOI(vp);
   2010 
   2011 	mutex_enter(&lfs_lock);
   2012 	LFS_SET_UINO(ip, IN_CHANGE);
   2013 	mutex_exit(&lfs_lock);
   2014 
   2015 	/* Note no blocks yet */
   2016 	ip->i_lfs_hiblk = -1;
   2017 
   2018 	/* Set a new generation number for this inode. */
   2019 	ip->i_gen = gen;
   2020 	lfs_dino_setgen(fs, ip->i_din, gen);
   2021 
   2022 	memset(ip->i_lfs_fragsize, 0,
   2023 	    ULFS_NDADDR * sizeof(*ip->i_lfs_fragsize));
   2024 
   2025 	/* Set uid / gid. */
   2026 	if (cred == NOCRED || cred == FSCRED) {
   2027 		ip->i_gid = 0;
   2028 		ip->i_uid = 0;
   2029 	} else {
   2030 		ip->i_gid = VTOI(dvp)->i_gid;
   2031 		ip->i_uid = kauth_cred_geteuid(cred);
   2032 	}
   2033 	DIP_ASSIGN(ip, gid, ip->i_gid);
   2034 	DIP_ASSIGN(ip, uid, ip->i_uid);
   2035 
   2036 #if defined(LFS_QUOTA) || defined(LFS_QUOTA2)
   2037 	error = lfs_chkiq(ip, 1, cred, 0);
   2038 	if (error) {
   2039 		lfs_vfree(dvp, ino, mode);
   2040 		lfs_deinit_vnode(ump, vp);
   2041 
   2042 		return error;
   2043 	}
   2044 #endif
   2045 
   2046 	/* Set type and finalize. */
   2047 	ip->i_flags = 0;
   2048 	DIP_ASSIGN(ip, flags, 0);
   2049 	ip->i_mode = mode;
   2050 	DIP_ASSIGN(ip, mode, mode);
   2051 	if (vap->va_rdev != VNOVAL) {
   2052 		/*
   2053 		 * Want to be able to use this to make badblock
   2054 		 * inodes, so don't truncate the dev number.
   2055 		 */
   2056 		// XXX clean this up
   2057 		if (ump->um_fstype == ULFS1)
   2058 			ip->i_din->u_32.di_rdev = ulfs_rw32(vap->va_rdev,
   2059 			    ULFS_MPNEEDSWAP(fs));
   2060 		else
   2061 			ip->i_din->u_64.di_rdev = ulfs_rw64(vap->va_rdev,
   2062 			    ULFS_MPNEEDSWAP(fs));
   2063 	}
   2064 	lfs_vinit(mp, &vp);
   2065 
   2066 	*new_key = &ip->i_number;
   2067 	return 0;
   2068 }
   2069 
   2070 /*
   2071  * File handle to vnode
   2072  */
   2073 int
   2074 lfs_fhtovp(struct mount *mp, struct fid *fhp, int lktype, struct vnode **vpp)
   2075 {
   2076 	struct lfid lfh;
   2077 	struct lfs *fs;
   2078 
   2079 	if (fhp->fid_len != sizeof(struct lfid))
   2080 		return EINVAL;
   2081 
   2082 	memcpy(&lfh, fhp, sizeof(lfh));
   2083 	if (lfh.lfid_ino < LFS_IFILE_INUM)
   2084 		return ESTALE;
   2085 
   2086 	fs = VFSTOULFS(mp)->um_lfs;
   2087 	if (lfh.lfid_ident != lfs_sb_getident(fs))
   2088 		return ESTALE;
   2089 
   2090 	if (lfh.lfid_ino >
   2091 	    ((lfs_dino_getsize(fs, VTOI(fs->lfs_ivnode)->i_din) >> lfs_sb_getbshift(fs)) -
   2092 	     lfs_sb_getcleansz(fs) - lfs_sb_getsegtabsz(fs)) * lfs_sb_getifpb(fs))
   2093 		return ESTALE;
   2094 
   2095 	return (ulfs_fhtovp(mp, &lfh.lfid_ufid, lktype, vpp));
   2096 }
   2097 
   2098 /*
   2099  * Vnode pointer to File handle
   2100  */
   2101 /* ARGSUSED */
   2102 int
   2103 lfs_vptofh(struct vnode *vp, struct fid *fhp, size_t *fh_size)
   2104 {
   2105 	struct inode *ip;
   2106 	struct lfid lfh;
   2107 
   2108 	if (*fh_size < sizeof(struct lfid)) {
   2109 		*fh_size = sizeof(struct lfid);
   2110 		return E2BIG;
   2111 	}
   2112 	*fh_size = sizeof(struct lfid);
   2113 	ip = VTOI(vp);
   2114 	memset(&lfh, 0, sizeof(lfh));
   2115 	lfh.lfid_len = sizeof(struct lfid);
   2116 	lfh.lfid_ino = ip->i_number;
   2117 	lfh.lfid_gen = ip->i_gen;
   2118 	lfh.lfid_ident = lfs_sb_getident(ip->i_lfs);
   2119 	memcpy(fhp, &lfh, sizeof(lfh));
   2120 	return (0);
   2121 }
   2122 
   2123 /*
   2124  * ulfs_bmaparray callback function for writing.
   2125  *
   2126  * Since blocks will be written to the new segment anyway,
   2127  * we don't care about current daddr of them.
   2128  */
   2129 static bool
   2130 lfs_issequential_hole(const struct lfs *fs,
   2131     daddr_t daddr0, daddr_t daddr1)
   2132 {
   2133 	(void)fs; /* not used */
   2134 
   2135 	KASSERT(daddr0 == UNWRITTEN ||
   2136 	    (0 <= daddr0 && daddr0 <= LFS_MAX_DADDR(fs)));
   2137 	KASSERT(daddr1 == UNWRITTEN ||
   2138 	    (0 <= daddr1 && daddr1 <= LFS_MAX_DADDR(fs)));
   2139 
   2140 	/* NOTE: all we want to know here is 'hole or not'. */
   2141 	/* NOTE: UNASSIGNED is converted to 0 by ulfs_bmaparray. */
   2142 
   2143 	/*
   2144 	 * treat UNWRITTENs and all resident blocks as 'contiguous'
   2145 	 */
   2146 	if (daddr0 != 0 && daddr1 != 0)
   2147 		return true;
   2148 
   2149 	/*
   2150 	 * both are in hole?
   2151 	 */
   2152 	if (daddr0 == 0 && daddr1 == 0)
   2153 		return true; /* all holes are 'contiguous' for us. */
   2154 
   2155 	return false;
   2156 }
   2157 
   2158 /*
   2159  * lfs_gop_write functions exactly like genfs_gop_write, except that
   2160  * (1) it requires the seglock to be held by its caller, and sp->fip
   2161  *     to be properly initialized (it will return without re-initializing
   2162  *     sp->fip, and without calling lfs_writeseg).
   2163  * (2) it uses the remaining space in the segment, rather than VOP_BMAP,
   2164  *     to determine how large a block it can write at once (though it does
   2165  *     still use VOP_BMAP to find holes in the file);
   2166  * (3) it calls lfs_gatherblock instead of VOP_STRATEGY on its blocks
   2167  *     (leaving lfs_writeseg to deal with the cluster blocks, so we might
   2168  *     now have clusters of clusters, ick.)
   2169  */
   2170 static int
   2171 lfs_gop_write(struct vnode *vp, struct vm_page **pgs, int npages,
   2172     int flags)
   2173 {
   2174 	int i, error, run, haveeof = 0;
   2175 	int fs_bshift;
   2176 	vaddr_t kva;
   2177 	off_t eof, offset, startoffset = 0;
   2178 	size_t bytes, iobytes, skipbytes;
   2179 	bool async = (flags & PGO_SYNCIO) == 0;
   2180 	daddr_t lbn, blkno;
   2181 	struct vm_page *pg;
   2182 	struct buf *mbp, *bp;
   2183 	struct vnode *devvp = VTOI(vp)->i_devvp;
   2184 	struct inode *ip = VTOI(vp);
   2185 	struct lfs *fs = ip->i_lfs;
   2186 	struct segment *sp = fs->lfs_sp;
   2187 	SEGSUM *ssp;
   2188 	UVMHIST_FUNC("lfs_gop_write"); UVMHIST_CALLED(ubchist);
   2189 	const char * failreason = NULL;
   2190 
   2191 	ASSERT_SEGLOCK(fs);
   2192 
   2193 	/* The Ifile lives in the buffer cache */
   2194 	KASSERT(vp != fs->lfs_ivnode);
   2195 
   2196 	/*
   2197 	 * We don't want to fill the disk before the cleaner has a chance
   2198 	 * to make room for us.  If we're in danger of doing that, fail
   2199 	 * with EAGAIN.  The caller will have to notice this, unlock
   2200 	 * so the cleaner can run, relock and try again.
   2201 	 *
   2202 	 * We must write everything, however, if our vnode is being
   2203 	 * reclaimed.
   2204 	 */
   2205 	mutex_enter(vp->v_interlock);
   2206 	if (LFS_STARVED_FOR_SEGS(fs) && vdead_check(vp, VDEAD_NOWAIT) == 0) {
   2207 		mutex_exit(vp->v_interlock);
   2208 		failreason = "Starved for segs and not flushing vp";
   2209  		goto tryagain;
   2210 	}
   2211 	mutex_exit(vp->v_interlock);
   2212 
   2213 	/*
   2214 	 * Sometimes things slip past the filters in lfs_putpages,
   2215 	 * and the pagedaemon tries to write pages---problem is
   2216 	 * that the pagedaemon never acquires the segment lock.
   2217 	 *
   2218 	 * Alternatively, pages that were clean when we called
   2219 	 * genfs_putpages may have become dirty in the meantime.  In this
   2220 	 * case the segment header is not properly set up for blocks
   2221 	 * to be added to it.
   2222 	 *
   2223 	 * Unbusy and unclean the pages, and put them on the ACTIVE
   2224 	 * queue under the hypothesis that they couldn't have got here
   2225 	 * unless they were modified *quite* recently.
   2226 	 *
   2227 	 * XXXUBC that last statement is an oversimplification of course.
   2228 	 */
   2229 	if (!LFS_SEGLOCK_HELD(fs)) {
   2230 		failreason = "Seglock not held";
   2231 		goto tryagain;
   2232 	}
   2233 	if (ip->i_lfs_iflags & LFSI_NO_GOP_WRITE) {
   2234 		failreason = "Inode with no_gop_write";
   2235 		goto tryagain;
   2236 	}
   2237 	if ((pgs[0]->offset & lfs_sb_getbmask(fs)) != 0) {
   2238 		failreason = "Bad page offset";
   2239 		goto tryagain;
   2240 	}
   2241 
   2242 	UVMHIST_LOG(ubchist, "vp %#jx pgs %#jx npages %jd flags 0x%jx",
   2243 	    (uintptr_t)vp, (uintptr_t)pgs, npages, flags);
   2244 
   2245 	GOP_SIZE(vp, vp->v_size, &eof, 0);
   2246 	haveeof = 1;
   2247 
   2248 	if (vp->v_type == VREG)
   2249 		fs_bshift = vp->v_mount->mnt_fs_bshift;
   2250 	else
   2251 		fs_bshift = DEV_BSHIFT;
   2252 	error = 0;
   2253 	pg = pgs[0];
   2254 	startoffset = pg->offset;
   2255 	KASSERT(eof >= 0);
   2256 
   2257 	if (startoffset >= eof) {
   2258 		failreason = "Offset beyond EOF";
   2259 		goto tryagain;
   2260 	} else
   2261 		bytes = MIN(npages << PAGE_SHIFT, eof - startoffset);
   2262 	skipbytes = 0;
   2263 
   2264 	KASSERT(bytes != 0);
   2265 
   2266 	/* Swap PG_DELWRI for PG_PAGEOUT */
   2267 	for (i = 0; i < npages; i++) {
   2268 		if (pgs[i]->flags & PG_DELWRI) {
   2269 			KASSERT(!(pgs[i]->flags & PG_PAGEOUT));
   2270 			pgs[i]->flags &= ~PG_DELWRI;
   2271 			pgs[i]->flags |= PG_PAGEOUT;
   2272 			uvm_pageout_start(1);
   2273 			rw_enter(vp->v_uobj.vmobjlock, RW_WRITER);
   2274 			uvm_pagelock(pgs[i]);
   2275 			uvm_pageunwire(pgs[i]);
   2276 			uvm_pageunlock(pgs[i]);
   2277 			rw_exit(vp->v_uobj.vmobjlock);
   2278 		}
   2279 	}
   2280 
   2281 	/*
   2282 	 * Check to make sure we're starting on a block boundary.
   2283 	 * We'll check later to make sure we always write entire
   2284 	 * blocks (or fragments).
   2285 	 */
   2286 	if (startoffset & lfs_sb_getbmask(fs))
   2287 		printf("%" PRId64 " & %" PRIu64 " = %" PRId64 "\n",
   2288 		       startoffset, lfs_sb_getbmask(fs),
   2289 		       startoffset & lfs_sb_getbmask(fs));
   2290 	KASSERT((startoffset & lfs_sb_getbmask(fs)) == 0);
   2291 	if (bytes & lfs_sb_getffmask(fs)) {
   2292 		printf("lfs_gop_write: asked to write %ld bytes\n", (long)bytes);
   2293 		panic("lfs_gop_write: non-integer blocks");
   2294 	}
   2295 
   2296 	/*
   2297 	 * We could deadlock here on pager_map with UVMPAGER_MAPIN_WAITOK.
   2298 	 * If we would, write what we have and try again.  If we don't
   2299 	 * have anything to write, we'll have to sleep.
   2300 	 */
   2301 	ssp = (SEGSUM *)sp->segsum;
   2302 	if ((kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
   2303 				      (lfs_ss_getnfinfo(fs, ssp) < 1 ?
   2304 				       UVMPAGER_MAPIN_WAITOK : 0))) == 0x0) {
   2305 		DLOG((DLOG_PAGE, "lfs_gop_write: forcing write\n"));
   2306 		lfs_updatemeta(sp);
   2307 		lfs_release_finfo(fs);
   2308 		(void) lfs_writeseg(fs, sp);
   2309 
   2310 		lfs_acquire_finfo(fs, ip->i_number, ip->i_gen);
   2311 
   2312 		/*
   2313 		 * Having given up all of the pager_map we were holding,
   2314 		 * we can now wait for aiodoned to reclaim it for us
   2315 		 * without fear of deadlock.
   2316 		 */
   2317 		kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
   2318 				     UVMPAGER_MAPIN_WAITOK);
   2319 	}
   2320 
   2321 	mbp = getiobuf(NULL, true);
   2322 	UVMHIST_LOG(ubchist, "vp %#jx mbp %#jx num now %jd bytes 0x%jx",
   2323 	    (uintptr_t)vp, (uintptr_t)mbp, vp->v_numoutput, bytes);
   2324 	mbp->b_bufsize = npages << PAGE_SHIFT;
   2325 	mbp->b_data = (void *)kva;
   2326 	mbp->b_resid = mbp->b_bcount = bytes;
   2327 	mbp->b_cflags |= BC_BUSY|BC_AGE;
   2328 	mbp->b_iodone = uvm_aio_aiodone;
   2329 
   2330 	bp = NULL;
   2331 	for (offset = startoffset;
   2332 	    bytes > 0;
   2333 	    offset += iobytes, bytes -= iobytes) {
   2334 		lbn = offset >> fs_bshift;
   2335 		error = ulfs_bmaparray(vp, lbn, &blkno, NULL, NULL, &run,
   2336 		    lfs_issequential_hole);
   2337 		if (error) {
   2338 			UVMHIST_LOG(ubchist, "ulfs_bmaparray() -> %jd",
   2339 			    error,0,0,0);
   2340 			skipbytes += bytes;
   2341 			bytes = 0;
   2342 			break;
   2343 		}
   2344 
   2345 		iobytes = MIN((((off_t)lbn + 1 + run) << fs_bshift) - offset,
   2346 		    bytes);
   2347 		if (blkno == (daddr_t)-1) {
   2348 			skipbytes += iobytes;
   2349 			continue;
   2350 		}
   2351 
   2352 		/*
   2353 		 * Discover how much we can really pack into this buffer.
   2354 		 */
   2355 		/* If no room in the current segment, finish it up */
   2356 		if (sp->sum_bytes_left < sizeof(int32_t) ||
   2357 		    sp->seg_bytes_left < (1 << lfs_sb_getbshift(fs))) {
   2358 			int vers;
   2359 
   2360 			lfs_updatemeta(sp);
   2361 			vers = lfs_fi_getversion(fs, sp->fip);
   2362 			lfs_release_finfo(fs);
   2363 			(void) lfs_writeseg(fs, sp);
   2364 
   2365 			lfs_acquire_finfo(fs, ip->i_number, vers);
   2366 		}
   2367 		/* Check both for space in segment and space in segsum */
   2368 		iobytes = MIN(iobytes, (sp->seg_bytes_left >> fs_bshift)
   2369 					<< fs_bshift);
   2370 		iobytes = MIN(iobytes, (sp->sum_bytes_left / sizeof(int32_t))
   2371 				       << fs_bshift);
   2372 		KASSERT(iobytes > 0);
   2373 
   2374 		/* if it's really one i/o, don't make a second buf */
   2375 		if (offset == startoffset && iobytes == bytes) {
   2376 			bp = mbp;
   2377 			/*
   2378 			 * All the LFS output is done by the segwriter.  It
   2379 			 * will increment numoutput by one for all the bufs it
   2380 			 * receives.  However this buffer needs one extra to
   2381 			 * account for aiodone.
   2382 			 */
   2383 			mutex_enter(vp->v_interlock);
   2384 			vp->v_numoutput++;
   2385 			mutex_exit(vp->v_interlock);
   2386 		} else {
   2387 			bp = getiobuf(NULL, true);
   2388 			UVMHIST_LOG(ubchist, "vp %#jx bp %#jx num now %jd",
   2389 			    (uintptr_t)vp, (uintptr_t)bp, vp->v_numoutput, 0);
   2390 			nestiobuf_setup(mbp, bp, offset - pg->offset, iobytes);
   2391 			/*
   2392 			 * LFS doesn't like async I/O here, dies with
   2393 			 * an assert in lfs_bwrite().  Is that assert
   2394 			 * valid?  I retained non-async behaviour when
   2395 			 * converted this to use nestiobuf --pooka
   2396 			 */
   2397 			bp->b_flags &= ~B_ASYNC;
   2398 		}
   2399 
   2400 		/* XXX This is silly ... is this necessary? */
   2401 		mutex_enter(&bufcache_lock);
   2402 		mutex_enter(vp->v_interlock);
   2403 		bgetvp(vp, bp);
   2404 		mutex_exit(vp->v_interlock);
   2405 		mutex_exit(&bufcache_lock);
   2406 
   2407 		bp->b_lblkno = lfs_lblkno(fs, offset);
   2408 		bp->b_private = mbp;
   2409 		if (devvp->v_type == VBLK) {
   2410 			bp->b_dev = devvp->v_rdev;
   2411 		}
   2412 		VOP_BWRITE(bp->b_vp, bp);
   2413 		while (lfs_gatherblock(sp, bp, NULL))
   2414 			continue;
   2415 	}
   2416 
   2417 	nestiobuf_done(mbp, skipbytes, error);
   2418 	if (skipbytes) {
   2419 		UVMHIST_LOG(ubchist, "skipbytes %jd", skipbytes, 0,0,0);
   2420 	}
   2421 	UVMHIST_LOG(ubchist, "returning 0", 0,0,0,0);
   2422 
   2423 	if (!async) {
   2424 		/* Start a segment write. */
   2425 		UVMHIST_LOG(ubchist, "flushing", 0,0,0,0);
   2426 		mutex_enter(&lfs_lock);
   2427 		lfs_flush(fs, 0, 1);
   2428 		mutex_exit(&lfs_lock);
   2429 	}
   2430 
   2431 	if ((sp->seg_flags & SEGM_SINGLE) && lfs_sb_getcurseg(fs) != fs->lfs_startseg)
   2432 		return EAGAIN;
   2433 
   2434 	return (0);
   2435 
   2436     tryagain:
   2437 	/*
   2438 	 * We can't write the pages, for whatever reason.
   2439 	 * Clean up after ourselves, and make the caller try again.
   2440 	 */
   2441 
   2442 	/* Tell why we're here, if we know */
   2443 	if (failreason != NULL) {
   2444 		DLOG((DLOG_PAGE, "lfs_gop_write: %s\n", failreason));
   2445 	}
   2446 	if (haveeof && startoffset >= eof) {
   2447  		DLOG((DLOG_PAGE, "lfs_gop_write: ino %d start 0x%" PRIx64
   2448  		      " eof 0x%" PRIx64 " npages=%d\n", VTOI(vp)->i_number,
   2449  		      pgs[0]->offset, eof, npages));
   2450 	}
   2451 
   2452 	rw_enter(vp->v_uobj.vmobjlock, RW_WRITER);
   2453 	for (i = 0; i < npages; i++) {
   2454 		pg = pgs[i];
   2455 
   2456 		if (pg->flags & PG_PAGEOUT)
   2457 			uvm_pageout_done(1);
   2458 		uvm_pagelock(pg);
   2459 		if (pg->flags & PG_DELWRI) {
   2460 			uvm_pageunwire(pg);
   2461 		}
   2462 		uvm_pageactivate(pg);
   2463 		uvm_pageunlock(pg);
   2464 		pg->flags &= ~(PG_DELWRI|PG_PAGEOUT|PG_RELEASED);
   2465 		uvm_pagemarkdirty(pg, UVM_PAGE_STATUS_DIRTY);
   2466 		DLOG((DLOG_PAGE, "pg[%d] = %p (vp %p off %" PRIx64 ")\n", i, pg,
   2467 			vp, pg->offset));
   2468 		DLOG((DLOG_PAGE, "pg[%d]->flags = %x\n", i, pg->flags));
   2469 		DLOG((DLOG_PAGE, "pg[%d]->pqflags = %x\n", i, pg->pqflags));
   2470 		DLOG((DLOG_PAGE, "pg[%d]->uanon = %p\n", i, pg->uanon));
   2471 		DLOG((DLOG_PAGE, "pg[%d]->uobject = %p\n", i, pg->uobject));
   2472 		DLOG((DLOG_PAGE, "pg[%d]->wire_count = %d\n", i,
   2473 		      pg->wire_count));
   2474 		DLOG((DLOG_PAGE, "pg[%d]->loan_count = %d\n", i,
   2475 		      pg->loan_count));
   2476 	}
   2477 	uvm_page_unbusy(pgs, npages);
   2478 	rw_exit(vp->v_uobj.vmobjlock);
   2479 	return EAGAIN;
   2480 }
   2481 
   2482 /*
   2483  * finish vnode/inode initialization.
   2484  * used by lfs_vget.
   2485  */
   2486 void
   2487 lfs_vinit(struct mount *mp, struct vnode **vpp)
   2488 {
   2489 	struct vnode *vp = *vpp;
   2490 	struct inode *ip = VTOI(vp);
   2491 	struct ulfsmount *ump = VFSTOULFS(mp);
   2492 	struct lfs *fs = ump->um_lfs;
   2493 	int i;
   2494 
   2495 	ip->i_mode = lfs_dino_getmode(fs, ip->i_din);
   2496 	ip->i_nlink = lfs_dino_getnlink(fs, ip->i_din);
   2497 	ip->i_lfs_osize = ip->i_size = lfs_dino_getsize(fs, ip->i_din);
   2498 	ip->i_flags = lfs_dino_getflags(fs, ip->i_din);
   2499 	ip->i_gen = lfs_dino_getgen(fs, ip->i_din);
   2500 	ip->i_uid = lfs_dino_getuid(fs, ip->i_din);
   2501 	ip->i_gid = lfs_dino_getgid(fs, ip->i_din);
   2502 
   2503 	ip->i_lfs_effnblks = lfs_dino_getblocks(fs, ip->i_din);
   2504 	ip->i_lfs_odnlink = lfs_dino_getnlink(fs, ip->i_din);
   2505 
   2506 	/*
   2507 	 * Initialize the vnode from the inode, check for aliases.  In all
   2508 	 * cases re-init ip, the underlying vnode/inode may have changed.
   2509 	 */
   2510 	ulfs_vinit(mp, lfs_specop_p, lfs_fifoop_p, &vp);
   2511 	ip = VTOI(vp);
   2512 
   2513 	memset(ip->i_lfs_fragsize, 0, ULFS_NDADDR * sizeof(*ip->i_lfs_fragsize));
   2514 	if (vp->v_type != VLNK || ip->i_size >= ip->i_lfs->um_maxsymlinklen) {
   2515 #ifdef DEBUG
   2516 		for (i = (ip->i_size + lfs_sb_getbsize(fs) - 1) >> lfs_sb_getbshift(fs);
   2517 		    i < ULFS_NDADDR; i++) {
   2518 			if ((vp->v_type == VBLK || vp->v_type == VCHR) &&
   2519 			    i == 0)
   2520 				continue;
   2521 			if (lfs_dino_getdb(fs, ip->i_din, i) != 0) {
   2522 				lfs_dump_dinode(fs, ip->i_din);
   2523 				panic("inconsistent inode (direct)");
   2524 			}
   2525 		}
   2526 		for ( ; i < ULFS_NDADDR + ULFS_NIADDR; i++) {
   2527 			if (lfs_dino_getib(fs, ip->i_din, i - ULFS_NDADDR) != 0) {
   2528 				lfs_dump_dinode(fs, ip->i_din);
   2529 				panic("inconsistent inode (indirect)");
   2530 			}
   2531 		}
   2532 #endif /* DEBUG */
   2533 		for (i = 0; i < ULFS_NDADDR; i++)
   2534 			if (lfs_dino_getdb(fs, ip->i_din, i) != 0)
   2535 				ip->i_lfs_fragsize[i] = lfs_blksize(fs, ip, i);
   2536 	}
   2537 
   2538 	KASSERTMSG((vp->v_type != VNON),
   2539 	    "lfs_vinit: ino %llu is type VNON! (ifmt=%o)\n",
   2540 	    (unsigned long long)ip->i_number,
   2541 	    (ip->i_mode & LFS_IFMT) >> 12);
   2542 
   2543 	/*
   2544 	 * Finish inode initialization now that aliasing has been resolved.
   2545 	 */
   2546 
   2547 	ip->i_devvp = fs->lfs_devvp;
   2548 	vref(ip->i_devvp);
   2549 #if defined(LFS_QUOTA) || defined(LFS_QUOTA2)
   2550 	ulfsquota_init(ip);
   2551 #endif
   2552 	genfs_node_init(vp, &lfs_genfsops);
   2553 	uvm_vnp_setsize(vp, ip->i_size);
   2554 
   2555 	/* Initialize hiblk from file size */
   2556 	ip->i_lfs_hiblk = lfs_lblkno(ip->i_lfs, ip->i_size + lfs_sb_getbsize(ip->i_lfs) - 1) - 1;
   2557 
   2558 	*vpp = vp;
   2559 }
   2560 
   2561 /*
   2562  * Resize the filesystem to contain the specified number of segments.
   2563  */
   2564 int
   2565 lfs_resize_fs(struct lfs *fs, int newnsegs)
   2566 {
   2567 	SEGUSE *sup;
   2568 	CLEANERINFO *cip;
   2569 	struct buf *bp, *obp;
   2570 	daddr_t olast, nlast, ilast, noff, start, end, dirtysums;
   2571 	struct vnode *ivp;
   2572 	struct inode *ip;
   2573 	int error, badnews, inc, oldnsegs;
   2574 	int sbbytes, csbbytes, gain, cgain;
   2575 	int i, nexti;
   2576 
   2577 	/* Only support v2 and up */
   2578 	if (lfs_sb_getversion(fs) < 2)
   2579 		return EOPNOTSUPP;
   2580 
   2581 	/* If we're doing nothing, do it fast */
   2582 	oldnsegs = lfs_sb_getnseg(fs);
   2583 	if (newnsegs == oldnsegs)
   2584 		return 0;
   2585 
   2586 	/* We always have to have two superblocks */
   2587 	if (newnsegs <= lfs_dtosn(fs, lfs_sb_getsboff(fs, 1)))
   2588 		return EINVAL;
   2589 
   2590 	ivp = fs->lfs_ivnode;
   2591 	ip = VTOI(ivp);
   2592 	error = 0;
   2593 
   2594 	/* Take the segment lock */
   2595 	lfs_seglock(fs, SEGM_CKP);
   2596 
   2597 	/* If we're shrinking, clean out the upper segments */
   2598 	if (newnsegs < oldnsegs) {
   2599 		lfs_rewind(fs, newnsegs);
   2600 		for (i = newnsegs; i < oldnsegs; i++) {
   2601 			uint32_t bytes;
   2602 			LFS_SEGENTRY(sup, fs, i, bp);
   2603 			bytes = sup->su_nbytes;
   2604 			LFS_RELEASESEGENTRY(sup, fs, i, bp);
   2605 			if (bytes > 0) {
   2606 				if ((error = lfs_rewrite_segment(fs, i, NULL, NOCRED, curlwp)) != 0)
   2607 					goto out;
   2608 			}
   2609 
   2610 			lfs_invalidate(fs, i);
   2611 		}
   2612 	}
   2613 
   2614 	/*
   2615 	 * Make sure the segments we're going to be losing, if any,
   2616 	 * are in fact empty.  We hold the seglock, so their status
   2617 	 * cannot change underneath us.  Count the superblocks we lose,
   2618 	 * while we're at it.
   2619 	 */
   2620 	sbbytes = csbbytes = cgain = dirtysums = 0;
   2621 	for (i = newnsegs; i < oldnsegs; i++) {
   2622 		LFS_SEGENTRY(sup, fs, i, bp);
   2623 		badnews = sup->su_nbytes || !(sup->su_flags & SEGUSE_INVAL);
   2624 		if (sup->su_flags & SEGUSE_SUPERBLOCK)
   2625 			sbbytes += LFS_SBPAD;
   2626 		if (!(sup->su_flags & SEGUSE_DIRTY)) {
   2627 			++cgain;
   2628 			if (sup->su_flags & SEGUSE_SUPERBLOCK)
   2629 				csbbytes += LFS_SBPAD;
   2630 		} else
   2631 			dirtysums += sup->su_nsums;
   2632 		LFS_RELEASESEGENTRY(sup, fs, i, bp);
   2633 		if (badnews) {
   2634 			error = EBUSY;
   2635 			goto out;
   2636 		}
   2637 	}
   2638 
   2639 	/* Note old and new segment table endpoints, and old ifile size */
   2640 	olast = lfs_sb_getcleansz(fs) + lfs_sb_getsegtabsz(fs);
   2641 	nlast = howmany(newnsegs, lfs_sb_getsepb(fs)) + lfs_sb_getcleansz(fs);
   2642 	ilast = ivp->v_size >> lfs_sb_getbshift(fs);
   2643 	noff = nlast - olast;
   2644 
   2645 	/*
   2646 	 * Make sure no one can use the Ifile while we change it around.
   2647 	 * Even after taking the iflock we need to make sure no one still
   2648 	 * is holding Ifile buffers, so we get each one, to drain them.
   2649 	 * (XXX this could be done better.)
   2650 	 */
   2651 	for (i = 0; i < ilast; i++) {
   2652 		/* XXX what to do if bread fails? */
   2653 		bread(ivp, i, lfs_sb_getbsize(fs), 0, &bp);
   2654 		brelse(bp, 0);
   2655 	}
   2656 
   2657 	/* Allocate new Ifile blocks */
   2658 	for (i = ilast; i < ilast + noff; i++) {
   2659 		if (lfs_balloc(ivp, i * lfs_sb_getbsize(fs),
   2660 			       lfs_sb_getbsize(fs), NOCRED, 0,
   2661 			       &bp) != 0)
   2662 			panic("balloc extending ifile");
   2663 		memset(bp->b_data, 0, lfs_sb_getbsize(fs));
   2664 		VOP_BWRITE(bp->b_vp, bp);
   2665 	}
   2666 
   2667 	/*
   2668 	 * If we are expanding, increase the Ifile size now
   2669 	 * so we can allocate blocks.  If we are shrinking
   2670 	 * we need to wait until we have moved the data.
   2671 	 */
   2672 	if (noff > 0) {
   2673 		ip->i_size += noff * lfs_sb_getbsize(fs);
   2674 		lfs_dino_setsize(fs, ip->i_din, ip->i_size);
   2675 		uvm_vnp_setsize(ivp, ip->i_size);
   2676 	}
   2677 
   2678 	/* Copy the inode table to its new position */
   2679 	if (noff != 0) {
   2680 		if (noff < 0) {
   2681 			start = nlast;
   2682 			end = ilast + noff;
   2683 			inc = 1;
   2684 		} else {
   2685 			start = ilast + noff - 1;
   2686 			end = nlast - 1;
   2687 			inc = -1;
   2688 		}
   2689 		for (i = start; i != end; i += inc) {
   2690 			if (bread(ivp, i, lfs_sb_getbsize(fs),
   2691 			    B_MODIFY, &bp) != 0)
   2692 				panic("resize: bread dst blk failed");
   2693 			if (bread(ivp, i - noff, lfs_sb_getbsize(fs),
   2694 			    0, &obp))
   2695 				panic("resize: bread src blk failed");
   2696 			memcpy(bp->b_data, obp->b_data, lfs_sb_getbsize(fs));
   2697 			VOP_BWRITE(bp->b_vp, bp);
   2698 			brelse(obp, 0);
   2699 		}
   2700 	}
   2701 
   2702 	/* If we are expanding, write the new empty SEGUSE entries */
   2703 	for (i = oldnsegs, nexti = 0; i < newnsegs; i = nexti) {
   2704 		nexti = roundup(i + 1, lfs_sb_getsepb(fs));
   2705 		if (nexti > newnsegs)
   2706 			nexti = newnsegs;
   2707 
   2708 		if ((error = bread(ivp, i / lfs_sb_getsepb(fs) +
   2709 				   lfs_sb_getcleansz(fs),
   2710 				   lfs_sb_getbsize(fs),
   2711 				   (i > oldnsegs ? B_MODIFY : 0), &bp)) != 0)
   2712 			panic("lfs: ifile read: %d", error);
   2713 		sup = &((SEGUSE *)bp->b_data)[i % lfs_sb_getsepb(fs)];
   2714 		memset(sup, 0, (nexti - i) * sizeof(SEGUSE));
   2715 		VOP_BWRITE(bp->b_vp, bp);
   2716 	}
   2717 
   2718 	/* Zero out unused superblock offsets */
   2719 	for (i = 2; i < LFS_MAXNUMSB; i++)
   2720 		if (lfs_dtosn(fs, lfs_sb_getsboff(fs, i)) >= newnsegs)
   2721 			lfs_sb_setsboff(fs, i, 0x0);
   2722 
   2723 	/*
   2724 	 * Correct superblock entries that depend on fs size.
   2725 	 * The computations of these are as follows:
   2726 	 *
   2727 	 * size  = lfs_segtod(fs, nseg)
   2728 	 * dsize = lfs_segtod(fs, nseg - minfreeseg) - lfs_btofsb(#super * LFS_SBPAD)
   2729 	 * bfree = dsize - lfs_btofsb(fs, bsize * nseg / 2) - blocks_actually_used
   2730 	 * avail = lfs_segtod(fs, nclean) - lfs_btofsb(#clean_super * LFS_SBPAD)
   2731 	 *         + (lfs_segtod(fs, 1) - (offset - curseg))
   2732 	 *	   - lfs_segtod(fs, minfreeseg - (minfreeseg / 2))
   2733 	 *
   2734 	 * XXX - we should probably adjust minfreeseg as well.
   2735 	 */
   2736 	gain = (newnsegs - oldnsegs);
   2737 	lfs_sb_setnseg(fs, newnsegs);
   2738 	lfs_sb_setsegtabsz(fs, nlast - lfs_sb_getcleansz(fs));
   2739 	lfs_sb_addsize(fs, gain * lfs_btofsb(fs, lfs_sb_getssize(fs)));
   2740 	lfs_sb_adddsize(fs, gain * lfs_btofsb(fs, lfs_sb_getssize(fs))
   2741 			+ lfs_btofsb(fs, sbbytes));
   2742 	lfs_sb_addbfree(fs, gain * lfs_btofsb(fs, lfs_sb_getssize(fs))
   2743 			+ lfs_btofsb(fs, sbbytes)
   2744 #if 0 /* This doesn't match fsck_lfs */
   2745 			- gain * lfs_btofsb(fs, lfs_sb_getbsize(fs) / 2)
   2746 			+ dirtysums * lfs_btofsb(fs, lfs_sb_getsumsize(fs))
   2747 #endif /* 0 */
   2748 		);
   2749 	if (gain > 0) {
   2750 		lfs_sb_addnclean(fs, gain);
   2751 		lfs_sb_addavail(fs, gain * lfs_btofsb(fs, lfs_sb_getssize(fs)));
   2752 	} else {
   2753 		lfs_sb_subnclean(fs, cgain);
   2754 		lfs_sb_subavail(fs, cgain * lfs_btofsb(fs, lfs_sb_getssize(fs)) -
   2755 				 lfs_btofsb(fs, csbbytes));
   2756 	}
   2757 
   2758 	/* Truncate Ifile if necessary */
   2759 	if (noff < 0) {
   2760 		vn_lock(ivp, LK_EXCLUSIVE);
   2761 		lfs_truncate(ivp, ivp->v_size + (noff << lfs_sb_getbshift(fs)), 0,
   2762 		    NOCRED);
   2763 		VOP_UNLOCK(ivp);
   2764 	}
   2765 
   2766 	/* Update cleaner info so the cleaner can die */
   2767 	/* XXX what to do if bread fails? */
   2768 	bread(ivp, 0, lfs_sb_getbsize(fs), B_MODIFY, &bp);
   2769 	cip = bp->b_data;
   2770 	lfs_ci_setclean(fs, cip, lfs_sb_getnclean(fs));
   2771 	lfs_ci_setdirty(fs, cip, lfs_sb_getnseg(fs) - lfs_sb_getnclean(fs));
   2772 	VOP_BWRITE(bp->b_vp, bp);
   2773 
   2774     out:
   2775 	lfs_segunlock(fs);
   2776 	return error;
   2777 }
   2778 
   2779 /*
   2780  * Extended attribute dispatch
   2781  */
   2782 int
   2783 lfs_extattrctl(struct mount *mp, int cmd, struct vnode *vp,
   2784 	       int attrnamespace, const char *attrname)
   2785 {
   2786 #ifdef LFS_EXTATTR
   2787 	struct ulfsmount *ump;
   2788 
   2789 	ump = VFSTOULFS(mp);
   2790 	if (ump->um_fstype == ULFS1) {
   2791 		return ulfs_extattrctl(mp, cmd, vp, attrnamespace, attrname);
   2792 	}
   2793 #endif
   2794 	return vfs_stdextattrctl(mp, cmd, vp, attrnamespace, attrname);
   2795 }
   2796