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