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