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