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