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