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