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