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