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