xref: /netbsd-src/sys/ufs/lfs/lfs_vfsops.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: lfs_vfsops.c,v 1.190 2005/12/11 12:25:26 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1999, 2000, 2001, 2002, 2003 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Konrad E. Schroder <perseant@hhhh.org>.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the NetBSD
21  *	Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 /*-
39  * Copyright (c) 1989, 1991, 1993, 1994
40  *	The Regents of the University of California.  All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)lfs_vfsops.c	8.20 (Berkeley) 6/10/95
67  */
68 
69 #include <sys/cdefs.h>
70 __KERNEL_RCSID(0, "$NetBSD: lfs_vfsops.c,v 1.190 2005/12/11 12:25:26 christos Exp $");
71 
72 #if defined(_KERNEL_OPT)
73 #include "opt_quota.h"
74 #endif
75 
76 #include <sys/param.h>
77 #include <sys/systm.h>
78 #include <sys/namei.h>
79 #include <sys/proc.h>
80 #include <sys/kernel.h>
81 #include <sys/vnode.h>
82 #include <sys/mount.h>
83 #include <sys/kthread.h>
84 #include <sys/buf.h>
85 #include <sys/device.h>
86 #include <sys/mbuf.h>
87 #include <sys/file.h>
88 #include <sys/disklabel.h>
89 #include <sys/ioctl.h>
90 #include <sys/errno.h>
91 #include <sys/malloc.h>
92 #include <sys/pool.h>
93 #include <sys/socket.h>
94 #include <sys/syslog.h>
95 #include <uvm/uvm_extern.h>
96 #include <sys/sysctl.h>
97 #include <sys/conf.h>
98 
99 #include <miscfs/specfs/specdev.h>
100 
101 #include <ufs/ufs/quota.h>
102 #include <ufs/ufs/inode.h>
103 #include <ufs/ufs/ufsmount.h>
104 #include <ufs/ufs/ufs_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_extern.h>
113 
114 #include <miscfs/genfs/genfs.h>
115 #include <miscfs/genfs/genfs_node.h>
116 
117 static int lfs_gop_write(struct vnode *, struct vm_page **, int, int);
118 static boolean_t lfs_issequential_hole(const struct ufsmount *,
119     daddr_t, daddr_t);
120 
121 static int lfs_mountfs(struct vnode *, struct mount *, struct lwp *);
122 static void warn_ifile_size(struct lfs *);
123 static daddr_t check_segsum(struct lfs *, daddr_t, u_int64_t,
124     struct ucred *, int, int *, struct lwp *);
125 
126 extern const struct vnodeopv_desc lfs_vnodeop_opv_desc;
127 extern const struct vnodeopv_desc lfs_specop_opv_desc;
128 extern const struct vnodeopv_desc lfs_fifoop_opv_desc;
129 
130 pid_t lfs_writer_daemon = 0;
131 int lfs_do_flush = 0;
132 int lfs_do_rfw = 0;
133 
134 const struct vnodeopv_desc * const lfs_vnodeopv_descs[] = {
135 	&lfs_vnodeop_opv_desc,
136 	&lfs_specop_opv_desc,
137 	&lfs_fifoop_opv_desc,
138 	NULL,
139 };
140 
141 struct vfsops lfs_vfsops = {
142 	MOUNT_LFS,
143 	lfs_mount,
144 	ufs_start,
145 	lfs_unmount,
146 	ufs_root,
147 	ufs_quotactl,
148 	lfs_statvfs,
149 	lfs_sync,
150 	lfs_vget,
151 	lfs_fhtovp,
152 	lfs_vptofh,
153 	lfs_init,
154 	lfs_reinit,
155 	lfs_done,
156 	lfs_mountroot,
157 	(int (*)(struct mount *, struct vnode *, struct timespec *)) eopnotsupp,
158 	vfs_stdextattrctl,
159 	lfs_vnodeopv_descs,
160 };
161 VFS_ATTACH(lfs_vfsops);
162 
163 const struct genfs_ops lfs_genfsops = {
164 	.gop_size = lfs_gop_size,
165 	.gop_alloc = ufs_gop_alloc,
166 	.gop_write = lfs_gop_write,
167 	.gop_markupdate = ufs_gop_markupdate,
168 };
169 
170 static const struct ufs_ops lfs_ufsops = {
171 	.uo_itimes = NULL,
172 	.uo_update = lfs_update,
173 	.uo_truncate = lfs_truncate,
174 	.uo_valloc = lfs_valloc,
175 	.uo_vfree = lfs_vfree,
176 	.uo_balloc = lfs_balloc,
177 	.uo_blkatoff = lfs_blkatoff,
178 };
179 
180 /*
181  * XXX Same structure as FFS inodes?  Should we share a common pool?
182  */
183 POOL_INIT(lfs_inode_pool, sizeof(struct inode), 0, 0, 0, "lfsinopl",
184     &pool_allocator_nointr);
185 POOL_INIT(lfs_dinode_pool, sizeof(struct ufs1_dinode), 0, 0, 0, "lfsdinopl",
186     &pool_allocator_nointr);
187 POOL_INIT(lfs_inoext_pool, sizeof(struct lfs_inode_ext), 8, 0, 0, "lfsinoextpl",
188     &pool_allocator_nointr);
189 POOL_INIT(lfs_lbnentry_pool, sizeof(struct lbnentry), 0, 0, 0, "lfslbnpool",
190     &pool_allocator_nointr);
191 
192 /*
193  * The writer daemon.  UVM keeps track of how many dirty pages we are holding
194  * in lfs_subsys_pages; the daemon flushes the filesystem when this value
195  * crosses the (user-defined) threshhold LFS_MAX_PAGES.
196  */
197 static void
198 lfs_writerd(void *arg)
199 {
200 	struct mount *mp, *nmp;
201 	struct lfs *fs;
202 	int loopcount;
203 
204 	lfs_writer_daemon = curproc->p_pid;
205 
206 	simple_lock(&lfs_subsys_lock);
207 	for (;;) {
208 		ltsleep(&lfs_writer_daemon, PVM | PNORELOCK, "lfswriter", hz/10,
209 		    &lfs_subsys_lock);
210 
211 		/*
212 		 * Look through the list of LFSs to see if any of them
213 		 * have requested pageouts.
214 		 */
215 		simple_lock(&mountlist_slock);
216 		for (mp = CIRCLEQ_FIRST(&mountlist); mp != (void *)&mountlist;
217 		     mp = nmp) {
218 			if (vfs_busy(mp, LK_NOWAIT, &mountlist_slock)) {
219 				nmp = CIRCLEQ_NEXT(mp, mnt_list);
220 				continue;
221 			}
222 			if (strncmp(&mp->mnt_stat.f_fstypename[0], MOUNT_LFS,
223 				    MFSNAMELEN) == 0) {
224 				fs = VFSTOUFS(mp)->um_lfs;
225 				simple_lock(&fs->lfs_interlock);
226 				if (fs->lfs_pdflush ||
227 				    !TAILQ_EMPTY(&fs->lfs_pchainhd)) {
228 					DLOG((DLOG_FLUSH, "lfs_writerd: pdflush set\n"));
229 					fs->lfs_pdflush = 0;
230 					lfs_flush_fs(fs, 0);
231 				}
232 				simple_unlock(&fs->lfs_interlock);
233 			}
234 
235 			simple_lock(&mountlist_slock);
236 			nmp = CIRCLEQ_NEXT(mp, mnt_list);
237 			vfs_unbusy(mp);
238 		}
239 		simple_unlock(&mountlist_slock);
240 
241 		/*
242 		 * If global state wants a flush, flush everything.
243 		 */
244 		simple_lock(&lfs_subsys_lock);
245 		loopcount = 0;
246 		if (lfs_do_flush || locked_queue_count > LFS_MAX_BUFS ||
247 			locked_queue_bytes > LFS_MAX_BYTES ||
248 			lfs_subsys_pages > LFS_MAX_PAGES) {
249 
250 			if (lfs_do_flush)
251 				DLOG((DLOG_FLUSH, "daemon: lfs_do_flush\n"));
252 			if (locked_queue_count > LFS_MAX_BUFS)
253 				DLOG((DLOG_FLUSH, "daemon: lqc = %d, max %d\n",
254 				      locked_queue_count, LFS_MAX_BUFS));
255 			if (locked_queue_bytes > LFS_MAX_BYTES)
256 				DLOG((DLOG_FLUSH, "daemon: lqb = %ld, max %ld\n",
257 				      locked_queue_bytes, LFS_MAX_BYTES));
258 			if (lfs_subsys_pages > LFS_MAX_PAGES)
259 				DLOG((DLOG_FLUSH, "daemon: lssp = %d, max %d\n",
260 				      lfs_subsys_pages, LFS_MAX_PAGES));
261 
262 			lfs_flush(NULL, SEGM_WRITERD, 0);
263 			lfs_do_flush = 0;
264 		}
265 	}
266 	/* NOTREACHED */
267 }
268 
269 /*
270  * Initialize the filesystem, most work done by ufs_init.
271  */
272 void
273 lfs_init()
274 {
275 #ifdef _LKM
276 	malloc_type_attach(M_SEGMENT);
277 	pool_init(&lfs_inode_pool, sizeof(struct inode), 0, 0, 0,
278 	    "lfsinopl", &pool_allocator_nointr);
279 	pool_init(&lfs_dinode_pool, sizeof(struct ufs1_dinode), 0, 0, 0,
280 	    "lfsdinopl", &pool_allocator_nointr);
281 	pool_init(&lfs_inoext_pool, sizeof(struct lfs_inode_ext), 8, 0, 0,
282 	    "lfsinoextpl", &pool_allocator_nointr);
283 	pool_init(&lfs_lbnentry_pool, sizeof(struct lbnentry), 0, 0, 0,
284 	    "lfslbnpool", &pool_allocator_nointr);
285 #endif
286 	ufs_init();
287 
288 #ifdef DEBUG
289 	memset(lfs_log, 0, sizeof(lfs_log));
290 #endif
291 	simple_lock_init(&lfs_subsys_lock);
292 }
293 
294 void
295 lfs_reinit()
296 {
297 	ufs_reinit();
298 }
299 
300 void
301 lfs_done()
302 {
303 	ufs_done();
304 #ifdef _LKM
305 	pool_destroy(&lfs_inode_pool);
306 	pool_destroy(&lfs_dinode_pool);
307 	pool_destroy(&lfs_inoext_pool);
308 	pool_destroy(&lfs_lbnentry_pool);
309 	malloc_type_detach(M_SEGMENT);
310 #endif
311 }
312 
313 /*
314  * Called by main() when ufs is going to be mounted as root.
315  */
316 int
317 lfs_mountroot()
318 {
319 	extern struct vnode *rootvp;
320 	struct mount *mp;
321 	struct lwp *l = curlwp;	/* XXX */
322 	int error;
323 
324 	if (root_device->dv_class != DV_DISK)
325 		return (ENODEV);
326 
327 	if (rootdev == NODEV)
328 		return (ENODEV);
329 	if ((error = vfs_rootmountalloc(MOUNT_LFS, "root_device", &mp))) {
330 		vrele(rootvp);
331 		return (error);
332 	}
333 	if ((error = lfs_mountfs(rootvp, mp, l))) {
334 		mp->mnt_op->vfs_refcount--;
335 		vfs_unbusy(mp);
336 		free(mp, M_MOUNT);
337 		return (error);
338 	}
339 	simple_lock(&mountlist_slock);
340 	CIRCLEQ_INSERT_TAIL(&mountlist, mp, mnt_list);
341 	simple_unlock(&mountlist_slock);
342 	(void)lfs_statvfs(mp, &mp->mnt_stat, l);
343 	vfs_unbusy(mp);
344 	setrootfstime((time_t)(VFSTOUFS(mp)->um_lfs->lfs_tstamp));
345 	return (0);
346 }
347 
348 /*
349  * VFS Operations.
350  *
351  * mount system call
352  */
353 int
354 lfs_mount(struct mount *mp, const char *path, void *data, struct nameidata *ndp, struct lwp *l)
355 {
356 	struct vnode *devvp;
357 	struct ufs_args args;
358 	struct ufsmount *ump = NULL;
359 	struct lfs *fs = NULL;				/* LFS */
360 	struct proc *p;
361 	int error, update;
362 	mode_t accessmode;
363 
364 	p = l->l_proc;
365 	if (mp->mnt_flag & MNT_GETARGS) {
366 		ump = VFSTOUFS(mp);
367 		if (ump == NULL)
368 			return EIO;
369 		args.fspec = NULL;
370 		return copyout(&args, data, sizeof(args));
371 	}
372 	error = copyin(data, &args, sizeof (struct ufs_args));
373 	if (error)
374 		return (error);
375 
376 	update = mp->mnt_flag & MNT_UPDATE;
377 
378 	/* Check arguments */
379 	if (args.fspec != NULL) {
380 		/*
381 		 * Look up the name and verify that it's sane.
382 		 */
383 		NDINIT(ndp, LOOKUP, FOLLOW, UIO_USERSPACE, args.fspec, l);
384 		if ((error = namei(ndp)) != 0)
385 			return (error);
386 		devvp = ndp->ni_vp;
387 
388 		if (!update) {
389 			/*
390 			 * Be sure this is a valid block device
391 			 */
392 			if (devvp->v_type != VBLK)
393 				error = ENOTBLK;
394 			else if (bdevsw_lookup(devvp->v_rdev) == NULL)
395 				error = ENXIO;
396 		} else {
397 			/*
398 			 * Be sure we're still naming the same device
399 			 * used for our initial mount
400 			 */
401 			ump = VFSTOUFS(mp);
402 			if (devvp != ump->um_devvp)
403 				error = EINVAL;
404 		}
405 	} else {
406 		if (!update) {
407 			/* New mounts must have a filename for the device */
408 			return (EINVAL);
409 		} else {
410 			/* Use the extant mount */
411 			ump = VFSTOUFS(mp);
412 			devvp = ump->um_devvp;
413 			vref(devvp);
414 		}
415 	}
416 
417 
418 	/*
419 	 * If mount by non-root, then verify that user has necessary
420 	 * permissions on the device.
421 	 */
422 	if (error == 0 && p->p_ucred->cr_uid != 0) {
423 		accessmode = VREAD;
424 		if (update ?
425 		    (mp->mnt_iflag & IMNT_WANTRDWR) != 0 :
426 		    (mp->mnt_flag & MNT_RDONLY) == 0)
427 			accessmode |= VWRITE;
428 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
429 		error = VOP_ACCESS(devvp, accessmode, p->p_ucred, l);
430 		VOP_UNLOCK(devvp, 0);
431 	}
432 
433 	if (error) {
434 		vrele(devvp);
435 		return (error);
436 	}
437 
438 	if (!update) {
439 		int flags;
440 
441 		/*
442 		 * Disallow multiple mounts of the same device.
443 		 * Disallow mounting of a device that is currently in use
444 		 * (except for root, which might share swap device for
445 		 * miniroot).
446 		 */
447 		error = vfs_mountedon(devvp);
448 		if (error)
449 			goto fail;
450 		if (vcount(devvp) > 1 && devvp != rootvp) {
451 			error = EBUSY;
452 			goto fail;
453 		}
454 		if (mp->mnt_flag & MNT_RDONLY)
455 			flags = FREAD;
456 		else
457 			flags = FREAD|FWRITE;
458 		error = VOP_OPEN(devvp, flags, FSCRED, l);
459 		if (error)
460 			goto fail;
461 		error = lfs_mountfs(devvp, mp, l);		/* LFS */
462 		if (error) {
463 			vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
464 			(void)VOP_CLOSE(devvp, flags, NOCRED, l);
465 			VOP_UNLOCK(devvp, 0);
466 			goto fail;
467 		}
468 
469 		ump = VFSTOUFS(mp);
470 		fs = ump->um_lfs;
471 	} else {
472 		/*
473 		 * Update the mount.
474 		 */
475 
476 		/*
477 		 * The initial mount got a reference on this
478 		 * device, so drop the one obtained via
479 		 * namei(), above.
480 		 */
481 		vrele(devvp);
482 
483 		ump = VFSTOUFS(mp);
484 		fs = ump->um_lfs;
485 		if (fs->lfs_ronly && (mp->mnt_iflag & IMNT_WANTRDWR)) {
486 			/*
487 			 * Changing from read-only to read/write
488 			 */
489 			fs->lfs_ronly = 0;
490 		}
491 		if (args.fspec == NULL)
492 			return EINVAL;
493 	}
494 
495 	error = set_statvfs_info(path, UIO_USERSPACE, args.fspec,
496 	    UIO_USERSPACE, mp, l);
497 	if (error == 0)
498 		(void)strncpy(fs->lfs_fsmnt, mp->mnt_stat.f_mntonname,
499 			      sizeof(fs->lfs_fsmnt));
500 	return error;
501 
502 fail:
503 	vrele(devvp);
504 	return (error);
505 }
506 
507 /*
508  * Roll-forward code.
509  */
510 
511 /*
512  * Load the appropriate indirect block, and change the appropriate pointer.
513  * Mark the block dirty.  Do segment and avail accounting.
514  */
515 static int
516 update_meta(struct lfs *fs, ino_t ino, int vers, daddr_t lbn,
517 	    daddr_t ndaddr, size_t size, struct lwp *l)
518 {
519 	int error;
520 	struct vnode *vp;
521 	struct inode *ip;
522 #ifdef DEBUG
523 	daddr_t odaddr;
524 	struct indir a[NIADDR];
525 	int num;
526 	int i;
527 #endif /* DEBUG */
528 	struct buf *bp;
529 	SEGUSE *sup;
530 
531 	KASSERT(lbn >= 0);	/* no indirect blocks */
532 
533 	if ((error = lfs_rf_valloc(fs, ino, vers, l, &vp)) != 0) {
534 		DLOG((DLOG_RF, "update_meta: ino %d: lfs_rf_valloc"
535 		      " returned %d\n", ino, error));
536 		return error;
537 	}
538 
539 	if ((error = lfs_balloc(vp, (lbn << fs->lfs_bshift), size,
540 				NOCRED, 0, &bp)) != 0) {
541 		vput(vp);
542 		return (error);
543 	}
544 	/* No need to write, the block is already on disk */
545 	if (bp->b_flags & B_DELWRI) {
546 		LFS_UNLOCK_BUF(bp);
547 		fs->lfs_avail += btofsb(fs, bp->b_bcount);
548 	}
549 	bp->b_flags |= B_INVAL;
550 	brelse(bp);
551 
552 	/*
553 	 * Extend the file, if it is not large enough already.
554 	 * XXX this is not exactly right, we don't know how much of the
555 	 * XXX last block is actually used.  We hope that an inode will
556 	 * XXX appear later to give the correct size.
557 	 */
558 	ip = VTOI(vp);
559 	if (ip->i_size <= (lbn << fs->lfs_bshift)) {
560 		u_int64_t newsize;
561 
562 		if (lbn < NDADDR)
563 			newsize = ip->i_ffs1_size = (lbn << fs->lfs_bshift) +
564 				(size - fs->lfs_fsize) + 1;
565 		else
566 			newsize = ip->i_ffs1_size = (lbn << fs->lfs_bshift) + 1;
567 
568 		if (ip->i_size < newsize) {
569 			ip->i_size = newsize;
570 			/*
571 			 * tell vm our new size for the case the inode won't
572 			 * appear later.
573 			 */
574 			uvm_vnp_setsize(vp, newsize);
575 		}
576 	}
577 
578 	lfs_update_single(fs, NULL, vp, lbn, ndaddr, size);
579 
580 	LFS_SEGENTRY(sup, fs, dtosn(fs, ndaddr), bp);
581 	sup->su_nbytes += size;
582 	LFS_WRITESEGENTRY(sup, fs, dtosn(fs, ndaddr), bp);
583 
584 	/* differences here should be due to UNWRITTEN indirect blocks. */
585 	KASSERT((lblkno(fs, ip->i_size) > NDADDR &&
586 	    ip->i_lfs_effnblks == ip->i_ffs1_blocks) ||
587 	    ip->i_lfs_effnblks >= ip->i_ffs1_blocks);
588 
589 #ifdef DEBUG
590 	/* Now look again to make sure it worked */
591 	ufs_bmaparray(vp, lbn, &odaddr, &a[0], &num, NULL, NULL);
592 	for (i = num; i > 0; i--) {
593 		if (!a[i].in_exists)
594 			panic("update_meta: absent %d lv indirect block", i);
595 	}
596 	if (dbtofsb(fs, odaddr) != ndaddr)
597 		DLOG((DLOG_RF, "update_meta: failed setting ino %d lbn %"
598 		      PRId64 " to %" PRId64 "\n", ino, lbn, ndaddr));
599 #endif /* DEBUG */
600 	vput(vp);
601 	return 0;
602 }
603 
604 static int
605 update_inoblk(struct lfs *fs, daddr_t offset, struct ucred *cred,
606 	      struct lwp *l)
607 {
608 	struct vnode *devvp, *vp;
609 	struct inode *ip;
610 	struct ufs1_dinode *dip;
611 	struct buf *dbp, *ibp;
612 	int error;
613 	daddr_t daddr;
614 	IFILE *ifp;
615 	SEGUSE *sup;
616 
617 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
618 
619 	/*
620 	 * Get the inode, update times and perms.
621 	 * DO NOT update disk blocks, we do that separately.
622 	 */
623 	error = bread(devvp, fsbtodb(fs, offset), fs->lfs_ibsize, cred, &dbp);
624 	if (error) {
625 		DLOG((DLOG_RF, "update_inoblk: bread returned %d\n", error));
626 		return error;
627 	}
628 	dip = ((struct ufs1_dinode *)(dbp->b_data)) + INOPB(fs);
629 	while (--dip >= (struct ufs1_dinode *)dbp->b_data) {
630 		if (dip->di_inumber > LFS_IFILE_INUM) {
631 			error = lfs_rf_valloc(fs, dip->di_inumber, dip->di_gen,
632 					      l, &vp);
633 			if (error) {
634 				DLOG((DLOG_RF, "update_inoblk: lfs_rf_valloc"
635 				      " returned %d\n", error));
636 				continue;
637 			}
638 			ip = VTOI(vp);
639 			if (dip->di_size != ip->i_size)
640 				lfs_truncate(vp, dip->di_size, 0, NOCRED, l);
641 			/* Get mode, link count, size, and times */
642 			memcpy(ip->i_din.ffs1_din, dip,
643 			       offsetof(struct ufs1_dinode, di_db[0]));
644 
645 			/* Then the rest, except di_blocks */
646 			ip->i_flags = ip->i_ffs1_flags = dip->di_flags;
647 			ip->i_gen = ip->i_ffs1_gen = dip->di_gen;
648 			ip->i_uid = ip->i_ffs1_uid = dip->di_uid;
649 			ip->i_gid = ip->i_ffs1_gid = dip->di_gid;
650 
651 			ip->i_mode = ip->i_ffs1_mode;
652 			ip->i_nlink = ip->i_ffs_effnlink = ip->i_ffs1_nlink;
653 			ip->i_size = ip->i_ffs1_size;
654 
655 			LFS_SET_UINO(ip, IN_CHANGE | IN_UPDATE);
656 
657 			/* Re-initialize to get type right */
658 			ufs_vinit(vp->v_mount, lfs_specop_p, lfs_fifoop_p,
659 				  &vp);
660 			vput(vp);
661 
662 			/* Record change in location */
663 			LFS_IENTRY(ifp, fs, dip->di_inumber, ibp);
664 			daddr = ifp->if_daddr;
665 			ifp->if_daddr = dbtofsb(fs, dbp->b_blkno);
666 			error = LFS_BWRITE_LOG(ibp); /* Ifile */
667 			/* And do segment accounting */
668 			if (dtosn(fs, daddr) != dtosn(fs, dbtofsb(fs, dbp->b_blkno))) {
669 				if (daddr > 0) {
670 					LFS_SEGENTRY(sup, fs, dtosn(fs, daddr),
671 						     ibp);
672 					sup->su_nbytes -= sizeof (struct ufs1_dinode);
673 					LFS_WRITESEGENTRY(sup, fs,
674 							  dtosn(fs, daddr),
675 							  ibp);
676 				}
677 				LFS_SEGENTRY(sup, fs, dtosn(fs, dbtofsb(fs, dbp->b_blkno)),
678 					     ibp);
679 				sup->su_nbytes += sizeof (struct ufs1_dinode);
680 				LFS_WRITESEGENTRY(sup, fs,
681 						  dtosn(fs, dbtofsb(fs, dbp->b_blkno)),
682 						  ibp);
683 			}
684 		}
685 	}
686 	dbp->b_flags |= B_AGE;
687 	brelse(dbp);
688 
689 	return 0;
690 }
691 
692 #define CHECK_CKSUM   0x0001  /* Check the checksum to make sure it's valid */
693 #define CHECK_UPDATE  0x0002  /* Update Ifile for new data blocks / inodes */
694 
695 static daddr_t
696 check_segsum(struct lfs *fs, daddr_t offset, u_int64_t nextserial,
697 	     struct ucred *cred, int flags, int *pseg_flags, struct lwp *l)
698 {
699 	struct vnode *devvp;
700 	struct buf *bp, *dbp;
701 	int error, nblocks = 0, ninos, i, j; /* XXX: gcc */
702 	SEGSUM *ssp;
703 	u_long *dp = NULL, *datap = NULL; /* XXX u_int32_t */
704 	daddr_t oldoffset;
705 	int32_t *iaddr;	/* XXX ondisk32 */
706 	FINFO *fip;
707 	SEGUSE *sup;
708 	size_t size;
709 
710 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
711 	/*
712 	 * If the segment has a superblock and we're at the top
713 	 * of the segment, skip the superblock.
714 	 */
715 	if (sntod(fs, dtosn(fs, offset)) == offset) {
716 		LFS_SEGENTRY(sup, fs, dtosn(fs, offset), bp);
717 		if (sup->su_flags & SEGUSE_SUPERBLOCK)
718 			offset += btofsb(fs, LFS_SBPAD);
719 		brelse(bp);
720 	}
721 
722 	/* Read in the segment summary */
723 	error = bread(devvp, fsbtodb(fs, offset), fs->lfs_sumsize, cred, &bp);
724 	if (error)
725 		return -1;
726 
727 	/* Check summary checksum */
728 	ssp = (SEGSUM *)bp->b_data;
729 	if (flags & CHECK_CKSUM) {
730 		if (ssp->ss_sumsum != cksum(&ssp->ss_datasum,
731 					   fs->lfs_sumsize -
732 					   sizeof(ssp->ss_sumsum))) {
733 			DLOG((DLOG_RF, "Sumsum error at 0x%" PRIx64 "\n", offset));
734 			offset = -1;
735 			goto err1;
736 		}
737 		if (ssp->ss_nfinfo == 0 && ssp->ss_ninos == 0) {
738 			DLOG((DLOG_RF, "Empty pseg at 0x%" PRIx64 "\n", offset));
739 			offset = -1;
740 			goto err1;
741 		}
742 		if (ssp->ss_create < fs->lfs_tstamp) {
743 			DLOG((DLOG_RF, "Old data at 0x%" PRIx64 "\n", offset));
744 			offset = -1;
745 			goto err1;
746 		}
747 	}
748 	if (fs->lfs_version > 1) {
749 		if (ssp->ss_serial != nextserial) {
750 			DLOG((DLOG_RF, "Unexpected serial number at 0x%" PRIx64
751 			      "\n", offset));
752 			offset = -1;
753 			goto err1;
754 		}
755 		if (ssp->ss_ident != fs->lfs_ident) {
756 			DLOG((DLOG_RF, "Incorrect fsid (0x%x vs 0x%x) at 0x%"
757 			      PRIx64 "\n", ssp->ss_ident, fs->lfs_ident, offset));
758 			offset = -1;
759 			goto err1;
760 		}
761 	}
762 	if (pseg_flags)
763 		*pseg_flags = ssp->ss_flags;
764 	oldoffset = offset;
765 	offset += btofsb(fs, fs->lfs_sumsize);
766 
767 	ninos = howmany(ssp->ss_ninos, INOPB(fs));
768 	/* XXX ondisk32 */
769 	iaddr = (int32_t *)(bp->b_data + fs->lfs_sumsize - sizeof(int32_t));
770 	if (flags & CHECK_CKSUM) {
771 		/* Count blocks */
772 		nblocks = 0;
773 		fip = (FINFO *)(bp->b_data + SEGSUM_SIZE(fs));
774 		for (i = 0; i < ssp->ss_nfinfo; ++i) {
775 			nblocks += fip->fi_nblocks;
776 			if (fip->fi_nblocks <= 0)
777 				break;
778 			/* XXX ondisk32 */
779 			fip = (FINFO *)(((char *)fip) + FINFOSIZE +
780 					(fip->fi_nblocks * sizeof(int32_t)));
781 		}
782 		nblocks += ninos;
783 		/* Create the sum array */
784 		datap = dp = (u_long *)malloc(nblocks * sizeof(u_long),
785 					      M_SEGMENT, M_WAITOK);
786 	}
787 
788 	/* Handle individual blocks */
789 	fip = (FINFO *)(bp->b_data + SEGSUM_SIZE(fs));
790 	for (i = 0; i < ssp->ss_nfinfo || ninos; ++i) {
791 		/* Inode block? */
792 		if (ninos && *iaddr == offset) {
793 			if (flags & CHECK_CKSUM) {
794 				/* Read in the head and add to the buffer */
795 				error = bread(devvp, fsbtodb(fs, offset), fs->lfs_bsize,
796 					      cred, &dbp);
797 				if (error) {
798 					offset = -1;
799 					goto err2;
800 				}
801 				(*dp++) = ((u_long *)(dbp->b_data))[0];
802 				dbp->b_flags |= B_AGE;
803 				brelse(dbp);
804 			}
805 			if (flags & CHECK_UPDATE) {
806 				if ((error = update_inoblk(fs, offset, cred, l))
807 				    != 0) {
808 					offset = -1;
809 					goto err2;
810 				}
811 			}
812 			offset += btofsb(fs, fs->lfs_ibsize);
813 			--iaddr;
814 			--ninos;
815 			--i; /* compensate */
816 			continue;
817 		}
818 		size = fs->lfs_bsize;
819 		for (j = 0; j < fip->fi_nblocks; ++j) {
820 			if (j == fip->fi_nblocks - 1)
821 				size = fip->fi_lastlength;
822 			if (flags & CHECK_CKSUM) {
823 				error = bread(devvp, fsbtodb(fs, offset), size, cred, &dbp);
824 				if (error) {
825 					offset = -1;
826 					goto err2;
827 				}
828 				(*dp++) = ((u_long *)(dbp->b_data))[0];
829 				dbp->b_flags |= B_AGE;
830 				brelse(dbp);
831 			}
832 			/* Account for and update any direct blocks */
833 			if ((flags & CHECK_UPDATE) &&
834 			   fip->fi_ino > LFS_IFILE_INUM &&
835 			   fip->fi_blocks[j] >= 0) {
836 				update_meta(fs, fip->fi_ino, fip->fi_version,
837 					    fip->fi_blocks[j], offset, size, l);
838 			}
839 			offset += btofsb(fs, size);
840 		}
841 		/* XXX ondisk32 */
842 		fip = (FINFO *)(((char *)fip) + FINFOSIZE
843 				+ fip->fi_nblocks * sizeof(int32_t));
844 	}
845 	/* Checksum the array, compare */
846 	if ((flags & CHECK_CKSUM) &&
847 	   ssp->ss_datasum != cksum(datap, nblocks * sizeof(u_long)))
848 	{
849 		DLOG((DLOG_RF, "Datasum error at 0x%" PRIx64
850 		      " (wanted %x got %x)\n",
851 		      offset, ssp->ss_datasum, cksum(datap, nblocks *
852 						     sizeof(u_long))));
853 		offset = -1;
854 		goto err2;
855 	}
856 
857 	/* If we're at the end of the segment, move to the next */
858 	if (dtosn(fs, offset + btofsb(fs, fs->lfs_sumsize + fs->lfs_bsize)) !=
859 	   dtosn(fs, offset)) {
860 		if (dtosn(fs, offset) == dtosn(fs, ssp->ss_next)) {
861 			offset = -1;
862 			goto err2;
863 		}
864 		offset = ssp->ss_next;
865 		DLOG((DLOG_RF, "LFS roll forward: moving to offset 0x%" PRIx64
866 		       " -> segment %d\n", offset, dtosn(fs,offset)));
867 	}
868 
869 	if (flags & CHECK_UPDATE) {
870 		fs->lfs_avail -= (offset - oldoffset);
871 		/* Don't clog the buffer queue */
872 		simple_lock(&lfs_subsys_lock);
873 		if (locked_queue_count > LFS_MAX_BUFS ||
874 		    locked_queue_bytes > LFS_MAX_BYTES) {
875 			lfs_flush(fs, SEGM_CKP, 0);
876 		}
877 		simple_unlock(&lfs_subsys_lock);
878 	}
879 
880     err2:
881 	if (flags & CHECK_CKSUM)
882 		free(datap, M_SEGMENT);
883     err1:
884 	bp->b_flags |= B_AGE;
885 	brelse(bp);
886 
887 	/* XXX should we update the serial number even for bad psegs? */
888 	if ((flags & CHECK_UPDATE) && offset > 0 && fs->lfs_version > 1)
889 		fs->lfs_serial = nextserial;
890 	return offset;
891 }
892 
893 /*
894  * Common code for mount and mountroot
895  * LFS specific
896  */
897 int
898 lfs_mountfs(struct vnode *devvp, struct mount *mp, struct lwp *l)
899 {
900 	struct dlfs *tdfs, *dfs, *adfs;
901 	struct lfs *fs;
902 	struct ufsmount *ump;
903 	struct vnode *vp;
904 	struct buf *bp, *abp;
905 	struct partinfo dpart;
906 	struct proc *p;
907 	dev_t dev;
908 	int error, i, ronly, secsize, fsbsize;
909 	struct ucred *cred;
910 	CLEANERINFO *cip;
911 	SEGUSE *sup;
912 	int flags, dirty, do_rollforward;
913 	daddr_t offset, oldoffset, lastgoodpseg, sb_addr;
914 	int sn, curseg;
915 
916 	p = l ? l->l_proc : NULL;
917 	cred = p ? p->p_ucred : NOCRED;
918 
919 	/*
920 	 * Flush out any old buffers remaining from a previous use.
921 	 */
922 	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
923 	error = vinvalbuf(devvp, V_SAVE, cred, l, 0, 0);
924 	VOP_UNLOCK(devvp, 0);
925 	if (error)
926 		return (error);
927 
928 	ronly = (mp->mnt_flag & MNT_RDONLY) != 0;
929 	if (VOP_IOCTL(devvp, DIOCGPART, &dpart, FREAD, cred, l) != 0)
930 		secsize = DEV_BSIZE;
931 	else
932 		secsize = dpart.disklab->d_secsize;
933 
934 	/* Don't free random space on error. */
935 	bp = NULL;
936 	abp = NULL;
937 	ump = NULL;
938 
939 	sb_addr = LFS_LABELPAD / secsize;
940 	while (1) {
941 		/* Read in the superblock. */
942 		error = bread(devvp, sb_addr, LFS_SBPAD, cred, &bp);
943 		if (error)
944 			goto out;
945 		dfs = (struct dlfs *)bp->b_data;
946 
947 		/* Check the basics. */
948 		if (dfs->dlfs_magic != LFS_MAGIC || dfs->dlfs_bsize > MAXBSIZE ||
949 		    dfs->dlfs_version > LFS_VERSION ||
950 		    dfs->dlfs_bsize < sizeof(struct dlfs)) {
951 			DLOG((DLOG_MOUNT, "lfs_mountfs: primary superblock sanity failed\n"));
952 			error = EINVAL;		/* XXX needs translation */
953 			goto out;
954 		}
955 		if (dfs->dlfs_inodefmt > LFS_MAXINODEFMT) {
956 			DLOG((DLOG_MOUNT, "lfs_mountfs: unknown inode format %d\n",
957 			       dfs->dlfs_inodefmt));
958 			error = EINVAL;
959 			goto out;
960 		}
961 
962 		if (dfs->dlfs_version == 1)
963 			fsbsize = secsize;
964 		else {
965 			fsbsize = 1 << (dfs->dlfs_bshift - dfs->dlfs_blktodb +
966 				dfs->dlfs_fsbtodb);
967 			/*
968 			 * Could be, if the frag size is large enough, that we
969 			 * don't have the "real" primary superblock.  If that's
970 			 * the case, get the real one, and try again.
971 			 */
972 			if (sb_addr != dfs->dlfs_sboffs[0] <<
973 				       dfs->dlfs_fsbtodb) {
974 				DLOG((DLOG_MOUNT, "lfs_mountfs: sb daddr"
975 				      " 0x%llx is not right, trying 0x%llx\n",
976 				      (long long)sb_addr,
977 				      (long long)(dfs->dlfs_sboffs[0] <<
978 						  dfs->dlfs_fsbtodb)));
979 				sb_addr = dfs->dlfs_sboffs[0] <<
980 					  dfs->dlfs_fsbtodb;
981 				brelse(bp);
982 				continue;
983 			}
984 		}
985 		break;
986 	}
987 
988 	/*
989 	 * Check the second superblock to see which is newer; then mount
990 	 * using the older of the two.	This is necessary to ensure that
991 	 * the filesystem is valid if it was not unmounted cleanly.
992 	 */
993 
994 	if (dfs->dlfs_sboffs[1] &&
995 	    dfs->dlfs_sboffs[1] - LFS_LABELPAD / fsbsize > LFS_SBPAD / fsbsize)
996 	{
997 		error = bread(devvp, dfs->dlfs_sboffs[1] * (fsbsize / secsize),
998 			LFS_SBPAD, cred, &abp);
999 		if (error)
1000 			goto out;
1001 		adfs = (struct dlfs *)abp->b_data;
1002 
1003 		if (dfs->dlfs_version == 1) {
1004 			/* 1s resolution comparison */
1005 			if (adfs->dlfs_tstamp < dfs->dlfs_tstamp)
1006 				tdfs = adfs;
1007 			else
1008 				tdfs = dfs;
1009 		} else {
1010 			/* monotonic infinite-resolution comparison */
1011 			if (adfs->dlfs_serial < dfs->dlfs_serial)
1012 				tdfs = adfs;
1013 			else
1014 				tdfs = dfs;
1015 		}
1016 
1017 		/* Check the basics. */
1018 		if (tdfs->dlfs_magic != LFS_MAGIC ||
1019 		    tdfs->dlfs_bsize > MAXBSIZE ||
1020 		    tdfs->dlfs_version > LFS_VERSION ||
1021 		    tdfs->dlfs_bsize < sizeof(struct dlfs)) {
1022 			DLOG((DLOG_MOUNT, "lfs_mountfs: alt superblock"
1023 			      " sanity failed\n"));
1024 			error = EINVAL;		/* XXX needs translation */
1025 			goto out;
1026 		}
1027 	} else {
1028 		DLOG((DLOG_MOUNT, "lfs_mountfs: invalid alt superblock"
1029 		      " daddr=0x%x\n", dfs->dlfs_sboffs[1]));
1030 		error = EINVAL;
1031 		goto out;
1032 	}
1033 
1034 	/* Allocate the mount structure, copy the superblock into it. */
1035 	fs = malloc(sizeof(struct lfs), M_UFSMNT, M_WAITOK | M_ZERO);
1036 	memcpy(&fs->lfs_dlfs, tdfs, sizeof(struct dlfs));
1037 
1038 	/* Compatibility */
1039 	if (fs->lfs_version < 2) {
1040 		fs->lfs_sumsize = LFS_V1_SUMMARY_SIZE;
1041 		fs->lfs_ibsize = fs->lfs_bsize;
1042 		fs->lfs_start = fs->lfs_sboffs[0];
1043 		fs->lfs_tstamp = fs->lfs_otstamp;
1044 		fs->lfs_fsbtodb = 0;
1045 	}
1046 
1047 	/*
1048 	 * If we aren't going to be able to write meaningfully to this
1049 	 * filesystem, and were not mounted readonly, bomb out now.
1050 	 */
1051 	if (fsbtob(fs, LFS_NRESERVE(fs)) > LFS_MAX_BYTES && !ronly) {
1052 		DLOG((DLOG_MOUNT, "lfs_mount: to mount this filesystem read/write,"
1053 		      " we need BUFPAGES >= %lld\n",
1054 		      (long long)((bufmem_hiwater / bufmem_lowater) *
1055 				  LFS_INVERSE_MAX_BYTES(
1056 					  fsbtob(fs, LFS_NRESERVE(fs))) >> PAGE_SHIFT)));
1057 		free(fs, M_UFSMNT);
1058 		error = EFBIG; /* XXX needs translation */
1059 		goto out;
1060 	}
1061 
1062 	/* Before rolling forward, lock so vget will sleep for other procs */
1063 	fs->lfs_flags = LFS_NOTYET;
1064 	fs->lfs_rfpid = p->p_pid;
1065 
1066 	ump = malloc(sizeof *ump, M_UFSMNT, M_WAITOK | M_ZERO);
1067 	ump->um_lfs = fs;
1068 	ump->um_ops = &lfs_ufsops;
1069 	ump->um_fstype = UFS1;
1070 	if (sizeof(struct lfs) < LFS_SBPAD) {			/* XXX why? */
1071 		bp->b_flags |= B_INVAL;
1072 		abp->b_flags |= B_INVAL;
1073 	}
1074 	brelse(bp);
1075 	bp = NULL;
1076 	brelse(abp);
1077 	abp = NULL;
1078 
1079 	/* Set up the I/O information */
1080 	fs->lfs_devbsize = secsize;
1081 	fs->lfs_iocount = 0;
1082 	fs->lfs_diropwait = 0;
1083 	fs->lfs_activesb = 0;
1084 	fs->lfs_uinodes = 0;
1085 	fs->lfs_ravail = 0;
1086 	fs->lfs_favail = 0;
1087 	fs->lfs_sbactive = 0;
1088 
1089 	/* Set up the ifile and lock aflags */
1090 	fs->lfs_doifile = 0;
1091 	fs->lfs_writer = 0;
1092 	fs->lfs_dirops = 0;
1093 	fs->lfs_nadirop = 0;
1094 	fs->lfs_seglock = 0;
1095 	fs->lfs_pdflush = 0;
1096 	fs->lfs_sleepers = 0;
1097 	fs->lfs_pages = 0;
1098 	simple_lock_init(&fs->lfs_interlock);
1099 	lockinit(&fs->lfs_fraglock, PINOD, "lfs_fraglock", 0, 0);
1100 	lockinit(&fs->lfs_iflock, PINOD, "lfs_iflock", 0, 0);
1101 
1102 	/* Set the file system readonly/modify bits. */
1103 	fs->lfs_ronly = ronly;
1104 	if (ronly == 0)
1105 		fs->lfs_fmod = 1;
1106 
1107 	/* Initialize the mount structure. */
1108 	dev = devvp->v_rdev;
1109 	mp->mnt_data = ump;
1110 	mp->mnt_stat.f_fsidx.__fsid_val[0] = (long)dev;
1111 	mp->mnt_stat.f_fsidx.__fsid_val[1] = makefstype(MOUNT_LFS);
1112 	mp->mnt_stat.f_fsid = mp->mnt_stat.f_fsidx.__fsid_val[0];
1113 	mp->mnt_stat.f_namemax = LFS_MAXNAMLEN;
1114 	mp->mnt_stat.f_iosize = fs->lfs_bsize;
1115 	mp->mnt_flag |= MNT_LOCAL;
1116 	mp->mnt_fs_bshift = fs->lfs_bshift;
1117 	ump->um_flags = 0;
1118 	ump->um_mountp = mp;
1119 	ump->um_dev = dev;
1120 	ump->um_devvp = devvp;
1121 	ump->um_bptrtodb = fs->lfs_fsbtodb;
1122 	ump->um_seqinc = fragstofsb(fs, fs->lfs_frag);
1123 	ump->um_nindir = fs->lfs_nindir;
1124 	ump->um_lognindir = ffs(fs->lfs_nindir) - 1;
1125 	for (i = 0; i < MAXQUOTAS; i++)
1126 		ump->um_quotas[i] = NULLVP;
1127 	ump->um_maxsymlinklen = fs->lfs_maxsymlinklen;
1128 	ump->um_dirblksiz = DIRBLKSIZ;
1129 	ump->um_maxfilesize = fs->lfs_maxfilesize;
1130 	if (ump->um_maxsymlinklen > 0)
1131 		mp->mnt_iflag |= IMNT_DTYPE;
1132 	devvp->v_specmountpoint = mp;
1133 
1134 	/* Set up reserved memory for pageout */
1135 	lfs_setup_resblks(fs);
1136 	/* Set up vdirop tailq */
1137 	TAILQ_INIT(&fs->lfs_dchainhd);
1138 	/* and paging tailq */
1139 	TAILQ_INIT(&fs->lfs_pchainhd);
1140 
1141 	/*
1142 	 * We use the ifile vnode for almost every operation.  Instead of
1143 	 * retrieving it from the hash table each time we retrieve it here,
1144 	 * artificially increment the reference count and keep a pointer
1145 	 * to it in the incore copy of the superblock.
1146 	 */
1147 	if ((error = VFS_VGET(mp, LFS_IFILE_INUM, &vp)) != 0) {
1148 		DLOG((DLOG_MOUNT, "lfs_mountfs: ifile vget failed, error=%d\n", error));
1149 		goto out;
1150 	}
1151 	fs->lfs_ivnode = vp;
1152 	VREF(vp);
1153 
1154 	/* Set up segment usage flags for the autocleaner. */
1155 	fs->lfs_nactive = 0;
1156 	fs->lfs_suflags = (u_int32_t **)malloc(2 * sizeof(u_int32_t *),
1157 						M_SEGMENT, M_WAITOK);
1158 	fs->lfs_suflags[0] = (u_int32_t *)malloc(fs->lfs_nseg * sizeof(u_int32_t),
1159 						 M_SEGMENT, M_WAITOK);
1160 	fs->lfs_suflags[1] = (u_int32_t *)malloc(fs->lfs_nseg * sizeof(u_int32_t),
1161 						 M_SEGMENT, M_WAITOK);
1162 	memset(fs->lfs_suflags[1], 0, fs->lfs_nseg * sizeof(u_int32_t));
1163 	for (i = 0; i < fs->lfs_nseg; i++) {
1164 		int changed;
1165 
1166 		LFS_SEGENTRY(sup, fs, i, bp);
1167 		changed = 0;
1168 		if (!ronly) {
1169 			if (sup->su_nbytes == 0 &&
1170 			    !(sup->su_flags & SEGUSE_EMPTY)) {
1171 				sup->su_flags |= SEGUSE_EMPTY;
1172 				++changed;
1173 			} else if (!(sup->su_nbytes == 0) &&
1174 				   (sup->su_flags & SEGUSE_EMPTY)) {
1175 				sup->su_flags &= ~SEGUSE_EMPTY;
1176 				++changed;
1177 			}
1178 			if (sup->su_flags & (SEGUSE_ACTIVE|SEGUSE_INVAL)) {
1179 				sup->su_flags &= ~(SEGUSE_ACTIVE|SEGUSE_INVAL);
1180 				++changed;
1181 			}
1182 		}
1183 		fs->lfs_suflags[0][i] = sup->su_flags;
1184 		if (changed)
1185 			LFS_WRITESEGENTRY(sup, fs, i, bp);
1186 		else
1187 			brelse(bp);
1188 	}
1189 
1190 	/*
1191 	 * Roll forward.
1192 	 *
1193 	 * We don't roll forward for v1 filesystems, because
1194 	 * of the danger that the clock was turned back between the last
1195 	 * checkpoint and crash.  This would roll forward garbage.
1196 	 *
1197 	 * v2 filesystems don't have this problem because they use a
1198 	 * monotonically increasing serial number instead of a timestamp.
1199 	 */
1200 	do_rollforward = (!(fs->lfs_pflags & LFS_PF_CLEAN) &&
1201 			  lfs_do_rfw && fs->lfs_version > 1);
1202 	if (do_rollforward) {
1203 		u_int64_t nextserial;
1204 		/*
1205 		 * Phase I: Find the address of the last good partial
1206 		 * segment that was written after the checkpoint.  Mark
1207 		 * the segments in question dirty, so they won't be
1208 		 * reallocated.
1209 		 */
1210 		lastgoodpseg = oldoffset = offset = fs->lfs_offset;
1211 		flags = 0x0;
1212 		DLOG((DLOG_RF, "LFS roll forward phase 1: start at offset 0x%"
1213 		      PRIx64 "\n", offset));
1214 		LFS_SEGENTRY(sup, fs, dtosn(fs, offset), bp);
1215 		if (!(sup->su_flags & SEGUSE_DIRTY))
1216 			--fs->lfs_nclean;
1217 		sup->su_flags |= SEGUSE_DIRTY;
1218 		LFS_WRITESEGENTRY(sup, fs, dtosn(fs, offset), bp);
1219 		nextserial = fs->lfs_serial + 1;
1220 		while ((offset = check_segsum(fs, offset, nextserial,
1221 		    cred, CHECK_CKSUM, &flags, l)) > 0) {
1222 			nextserial++;
1223 			if (sntod(fs, oldoffset) != sntod(fs, offset)) {
1224 				LFS_SEGENTRY(sup, fs, dtosn(fs, oldoffset),
1225 					     bp);
1226 				if (!(sup->su_flags & SEGUSE_DIRTY))
1227 					--fs->lfs_nclean;
1228 				sup->su_flags |= SEGUSE_DIRTY;
1229 				LFS_WRITESEGENTRY(sup, fs, dtosn(fs, oldoffset),
1230 					     bp);
1231 			}
1232 
1233 			DLOG((DLOG_RF, "LFS roll forward phase 1: offset=0x%"
1234 			      PRIx64 "\n", offset));
1235 			if (flags & SS_DIROP) {
1236 				DLOG((DLOG_RF, "lfs_mountfs: dirops at 0x%"
1237 				      PRIx64 "\n", oldoffset));
1238 				if (!(flags & SS_CONT))
1239 				     DLOG((DLOG_RF, "lfs_mountfs: dirops end "
1240 					   "at 0x%" PRIx64 "\n", oldoffset));
1241 			}
1242 			if (!(flags & SS_CONT))
1243 				lastgoodpseg = offset;
1244 			oldoffset = offset;
1245 		}
1246 		if (flags & SS_CONT) {
1247 			DLOG((DLOG_RF, "LFS roll forward: warning: incomplete "
1248 			      "dirops discarded\n"));
1249 		}
1250 		DLOG((DLOG_RF, "LFS roll forward phase 1: completed: "
1251 		      "lastgoodpseg=0x%" PRIx64 "\n", lastgoodpseg));
1252 		oldoffset = fs->lfs_offset;
1253 		if (fs->lfs_offset != lastgoodpseg) {
1254 			/* Don't overwrite what we're trying to preserve */
1255 			offset = fs->lfs_offset;
1256 			fs->lfs_offset = lastgoodpseg;
1257 			fs->lfs_curseg = sntod(fs, dtosn(fs, fs->lfs_offset));
1258 			for (sn = curseg = dtosn(fs, fs->lfs_curseg);;) {
1259 				sn = (sn + 1) % fs->lfs_nseg;
1260 				if (sn == curseg)
1261 					panic("lfs_mountfs: no clean segments");
1262 				LFS_SEGENTRY(sup, fs, sn, bp);
1263 				dirty = (sup->su_flags & SEGUSE_DIRTY);
1264 				brelse(bp);
1265 				if (!dirty)
1266 					break;
1267 			}
1268 			fs->lfs_nextseg = sntod(fs, sn);
1269 
1270 			/*
1271 			 * Phase II: Roll forward from the first superblock.
1272 			 */
1273 			while (offset != lastgoodpseg) {
1274 				DLOG((DLOG_RF, "LFS roll forward phase 2: 0x%"
1275 				      PRIx64 "\n", offset));
1276 				offset = check_segsum(fs, offset,
1277 				    fs->lfs_serial + 1, cred, CHECK_UPDATE,
1278 				    NULL, l);
1279 			}
1280 
1281 			/*
1282 			 * Finish: flush our changes to disk.
1283 			 */
1284 			lfs_segwrite(mp, SEGM_CKP | SEGM_SYNC);
1285 			DLOG((DLOG_RF, "lfs_mountfs: roll forward ",
1286 			      "recovered %lld blocks\n",
1287 			      (long long)(lastgoodpseg - oldoffset)));
1288 		}
1289 		DLOG((DLOG_RF, "LFS roll forward complete\n"));
1290 	}
1291 	/* If writing, sb is not clean; record in case of immediate crash */
1292 	if (!fs->lfs_ronly) {
1293 		fs->lfs_pflags &= ~LFS_PF_CLEAN;
1294 		lfs_writesuper(fs, fs->lfs_sboffs[0]);
1295 		lfs_writesuper(fs, fs->lfs_sboffs[1]);
1296 	}
1297 
1298 	/* Allow vget now that roll-forward is complete */
1299 	fs->lfs_flags &= ~(LFS_NOTYET);
1300 	wakeup(&fs->lfs_flags);
1301 
1302 	/*
1303 	 * Initialize the ifile cleaner info with information from
1304 	 * the superblock.
1305 	 */
1306 	LFS_CLEANERINFO(cip, fs, bp);
1307 	cip->clean = fs->lfs_nclean;
1308 	cip->dirty = fs->lfs_nseg - fs->lfs_nclean;
1309 	cip->avail = fs->lfs_avail;
1310 	cip->bfree = fs->lfs_bfree;
1311 	(void) LFS_BWRITE_LOG(bp); /* Ifile */
1312 
1313 	/*
1314 	 * Mark the current segment as ACTIVE, since we're going to
1315 	 * be writing to it.
1316 	 */
1317 	LFS_SEGENTRY(sup, fs, dtosn(fs, fs->lfs_offset), bp);
1318 	sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
1319 	fs->lfs_nactive++;
1320 	LFS_WRITESEGENTRY(sup, fs, dtosn(fs, fs->lfs_offset), bp);  /* Ifile */
1321 
1322 	/* Now that roll-forward is done, unlock the Ifile */
1323 	vput(vp);
1324 
1325 	/* Comment on ifile size if it is too large */
1326 	warn_ifile_size(fs);
1327 
1328 	/* Start the pagedaemon-anticipating daemon */
1329 	if (lfs_writer_daemon == 0 &&
1330 	    kthread_create1(lfs_writerd, NULL, NULL, "lfs_writer") != 0)
1331 		panic("fork lfs_writer");
1332 
1333 	return (0);
1334 
1335 out:
1336 	if (bp)
1337 		brelse(bp);
1338 	if (abp)
1339 		brelse(abp);
1340 	if (ump) {
1341 		free(ump->um_lfs, M_UFSMNT);
1342 		free(ump, M_UFSMNT);
1343 		mp->mnt_data = NULL;
1344 	}
1345 
1346 	return (error);
1347 }
1348 
1349 /*
1350  * unmount system call
1351  */
1352 int
1353 lfs_unmount(struct mount *mp, int mntflags, struct lwp *l)
1354 {
1355 	struct ufsmount *ump;
1356 	struct lfs *fs;
1357 	int error, flags, ronly;
1358 	int s;
1359 
1360 	flags = 0;
1361 	if (mntflags & MNT_FORCE)
1362 		flags |= FORCECLOSE;
1363 
1364 	ump = VFSTOUFS(mp);
1365 	fs = ump->um_lfs;
1366 
1367 	/* wake up the cleaner so it can die */
1368 	wakeup(&fs->lfs_nextseg);
1369 	wakeup(&lfs_allclean_wakeup);
1370 	simple_lock(&fs->lfs_interlock);
1371 	while (fs->lfs_sleepers)
1372 		ltsleep(&fs->lfs_sleepers, PRIBIO + 1, "lfs_sleepers", 0,
1373 			&fs->lfs_interlock);
1374 	simple_unlock(&fs->lfs_interlock);
1375 
1376 #ifdef QUOTA
1377 	if (mp->mnt_flag & MNT_QUOTA) {
1378 		int i;
1379 		error = vflush(mp, fs->lfs_ivnode, SKIPSYSTEM|flags);
1380 		if (error)
1381 			return (error);
1382 		for (i = 0; i < MAXQUOTAS; i++) {
1383 			if (ump->um_quotas[i] == NULLVP)
1384 				continue;
1385 			quotaoff(l, mp, i);
1386 		}
1387 		/*
1388 		 * Here we fall through to vflush again to ensure
1389 		 * that we have gotten rid of all the system vnodes.
1390 		 */
1391 	}
1392 #endif
1393 	if ((error = vflush(mp, fs->lfs_ivnode, flags)) != 0)
1394 		return (error);
1395 	if ((error = VFS_SYNC(mp, 1, l->l_proc->p_ucred, l)) != 0)
1396 		return (error);
1397 	s = splbio();
1398 	if (LIST_FIRST(&fs->lfs_ivnode->v_dirtyblkhd))
1399 		panic("lfs_unmount: still dirty blocks on ifile vnode");
1400 	splx(s);
1401 
1402 	/* Comment on ifile size if it has become too large */
1403 	if (!(fs->lfs_flags & LFS_WARNED))
1404 		warn_ifile_size(fs);
1405 
1406 	/* Explicitly write the superblock, to update serial and pflags */
1407 	fs->lfs_pflags |= LFS_PF_CLEAN;
1408 	lfs_writesuper(fs, fs->lfs_sboffs[0]);
1409 	lfs_writesuper(fs, fs->lfs_sboffs[1]);
1410 	simple_lock(&fs->lfs_interlock);
1411 	while (fs->lfs_iocount)
1412 		ltsleep(&fs->lfs_iocount, PRIBIO + 1, "lfs_umount", 0,
1413 			&fs->lfs_interlock);
1414 	simple_unlock(&fs->lfs_interlock);
1415 
1416 	/* Finish with the Ifile, now that we're done with it */
1417 	vrele(fs->lfs_ivnode);
1418 	vgone(fs->lfs_ivnode);
1419 
1420 	ronly = !fs->lfs_ronly;
1421 	if (ump->um_devvp->v_type != VBAD)
1422 		ump->um_devvp->v_specmountpoint = NULL;
1423 	vn_lock(ump->um_devvp, LK_EXCLUSIVE | LK_RETRY);
1424 	error = VOP_CLOSE(ump->um_devvp,
1425 	    ronly ? FREAD : FREAD|FWRITE, NOCRED, l);
1426 	vput(ump->um_devvp);
1427 
1428 	/* Complain about page leakage */
1429 	if (fs->lfs_pages > 0)
1430 		printf("lfs_unmount: still claim %d pages (%d in subsystem)\n",
1431 			fs->lfs_pages, lfs_subsys_pages);
1432 
1433 	/* Free per-mount data structures */
1434 	free(fs->lfs_suflags[0], M_SEGMENT);
1435 	free(fs->lfs_suflags[1], M_SEGMENT);
1436 	free(fs->lfs_suflags, M_SEGMENT);
1437 	lfs_free_resblks(fs);
1438 	free(fs, M_UFSMNT);
1439 	free(ump, M_UFSMNT);
1440 
1441 	mp->mnt_data = NULL;
1442 	mp->mnt_flag &= ~MNT_LOCAL;
1443 	return (error);
1444 }
1445 
1446 /*
1447  * Get file system statistics.
1448  *
1449  * NB: We don't lock to access the superblock here, because it's not
1450  * really that important if we get it wrong.
1451  */
1452 int
1453 lfs_statvfs(struct mount *mp, struct statvfs *sbp, struct lwp *l)
1454 {
1455 	struct lfs *fs;
1456 	struct ufsmount *ump;
1457 
1458 	ump = VFSTOUFS(mp);
1459 	fs = ump->um_lfs;
1460 	if (fs->lfs_magic != LFS_MAGIC)
1461 		panic("lfs_statvfs: magic");
1462 
1463 	sbp->f_bsize = fs->lfs_bsize;
1464 	sbp->f_frsize = fs->lfs_fsize;
1465 	sbp->f_iosize = fs->lfs_bsize;
1466 	sbp->f_blocks = fsbtofrags(fs, LFS_EST_NONMETA(fs));
1467 
1468 	sbp->f_bfree = fsbtofrags(fs, LFS_EST_BFREE(fs));
1469 	KASSERT(sbp->f_bfree <= fs->lfs_dsize);
1470 	if (sbp->f_bfree < 0)
1471 		sbp->f_bfree = 0;
1472 
1473 	sbp->f_bresvd = fsbtofrags(fs, LFS_EST_RSVD(fs));
1474 	if (sbp->f_bfree > sbp->f_bresvd)
1475 		sbp->f_bavail = sbp->f_bfree - sbp->f_bresvd;
1476 	else
1477 		sbp->f_bavail = 0;
1478 
1479 	sbp->f_files = fs->lfs_bfree / btofsb(fs, fs->lfs_ibsize) * INOPB(fs);
1480 	sbp->f_ffree = sbp->f_files - fs->lfs_nfiles;
1481 	sbp->f_favail = sbp->f_ffree;
1482 	sbp->f_fresvd = 0;
1483 	copy_statvfs_info(sbp, mp);
1484 	return (0);
1485 }
1486 
1487 /*
1488  * Go through the disk queues to initiate sandbagged IO;
1489  * go through the inodes to write those that have been modified;
1490  * initiate the writing of the super block if it has been modified.
1491  *
1492  * Note: we are always called with the filesystem marked `MPBUSY'.
1493  */
1494 int
1495 lfs_sync(struct mount *mp, int waitfor, struct ucred *cred, struct lwp *l)
1496 {
1497 	int error;
1498 	struct lfs *fs;
1499 
1500 	fs = VFSTOUFS(mp)->um_lfs;
1501 	if (fs->lfs_ronly)
1502 		return 0;
1503 	lfs_writer_enter(fs, "lfs_dirops");
1504 
1505 	/* All syncs must be checkpoints until roll-forward is implemented. */
1506 	error = lfs_segwrite(mp, SEGM_CKP | (waitfor ? SEGM_SYNC : 0));
1507 	lfs_writer_leave(fs);
1508 #ifdef QUOTA
1509 	qsync(mp);
1510 #endif
1511 	return (error);
1512 }
1513 
1514 extern struct lock ufs_hashlock;
1515 
1516 /*
1517  * Look up an LFS dinode number to find its incore vnode.  If not already
1518  * in core, read it in from the specified device.  Return the inode locked.
1519  * Detection and handling of mount points must be done by the calling routine.
1520  */
1521 int
1522 lfs_vget(struct mount *mp, ino_t ino, struct vnode **vpp)
1523 {
1524 	struct lfs *fs;
1525 	struct ufs1_dinode *dip;
1526 	struct inode *ip;
1527 	struct buf *bp;
1528 	struct ifile *ifp;
1529 	struct vnode *vp;
1530 	struct ufsmount *ump;
1531 	daddr_t daddr;
1532 	dev_t dev;
1533 	int error, retries;
1534 	struct timespec ts;
1535 
1536 	ump = VFSTOUFS(mp);
1537 	dev = ump->um_dev;
1538 	fs = ump->um_lfs;
1539 
1540 	/*
1541 	 * If the filesystem is not completely mounted yet, suspend
1542 	 * any access requests (wait for roll-forward to complete).
1543 	 */
1544 	simple_lock(&fs->lfs_interlock);
1545 	while ((fs->lfs_flags & LFS_NOTYET) && curproc->p_pid != fs->lfs_rfpid)
1546 		ltsleep(&fs->lfs_flags, PRIBIO+1, "lfs_notyet", 0,
1547 			&fs->lfs_interlock);
1548 	simple_unlock(&fs->lfs_interlock);
1549 
1550 	if ((*vpp = ufs_ihashget(dev, ino, LK_EXCLUSIVE)) != NULL)
1551 		return (0);
1552 
1553 	if ((error = getnewvnode(VT_LFS, mp, lfs_vnodeop_p, &vp)) != 0) {
1554 		*vpp = NULL;
1555 		 return (error);
1556 	}
1557 
1558 	do {
1559 		if ((*vpp = ufs_ihashget(dev, ino, LK_EXCLUSIVE)) != NULL) {
1560 			ungetnewvnode(vp);
1561 			return (0);
1562 		}
1563 	} while (lockmgr(&ufs_hashlock, LK_EXCLUSIVE|LK_SLEEPFAIL, 0));
1564 
1565 	/* Translate the inode number to a disk address. */
1566 	if (ino == LFS_IFILE_INUM)
1567 		daddr = fs->lfs_idaddr;
1568 	else {
1569 		/* XXX bounds-check this too */
1570 		LFS_IENTRY(ifp, fs, ino, bp);
1571 		daddr = ifp->if_daddr;
1572 		if (fs->lfs_version > 1) {
1573 			ts.tv_sec = ifp->if_atime_sec;
1574 			ts.tv_nsec = ifp->if_atime_nsec;
1575 		}
1576 
1577 		brelse(bp);
1578 		if (daddr == LFS_UNUSED_DADDR) {
1579 			*vpp = NULLVP;
1580 			ungetnewvnode(vp);
1581 			lockmgr(&ufs_hashlock, LK_RELEASE, 0);
1582 			return (ENOENT);
1583 		}
1584 	}
1585 
1586 	/* Allocate/init new vnode/inode. */
1587 	lfs_vcreate(mp, ino, vp);
1588 
1589 	/*
1590 	 * Put it onto its hash chain and lock it so that other requests for
1591 	 * this inode will block if they arrive while we are sleeping waiting
1592 	 * for old data structures to be purged or for the contents of the
1593 	 * disk portion of this inode to be read.
1594 	 */
1595 	ip = VTOI(vp);
1596 	ufs_ihashins(ip);
1597 	lockmgr(&ufs_hashlock, LK_RELEASE, 0);
1598 
1599 	/*
1600 	 * XXX
1601 	 * This may not need to be here, logically it should go down with
1602 	 * the i_devvp initialization.
1603 	 * Ask Kirk.
1604 	 */
1605 	ip->i_lfs = ump->um_lfs;
1606 
1607 	/* Read in the disk contents for the inode, copy into the inode. */
1608 	retries = 0;
1609     again:
1610 	error = bread(ump->um_devvp, fsbtodb(fs, daddr),
1611 		(fs->lfs_version == 1 ? fs->lfs_bsize : fs->lfs_ibsize),
1612 		NOCRED, &bp);
1613 	if (error) {
1614 		/*
1615 		 * The inode does not contain anything useful, so it would
1616 		 * be misleading to leave it on its hash chain. With mode
1617 		 * still zero, it will be unlinked and returned to the free
1618 		 * list by vput().
1619 		 */
1620 		vput(vp);
1621 		brelse(bp);
1622 		*vpp = NULL;
1623 		return (error);
1624 	}
1625 
1626 	dip = lfs_ifind(fs, ino, bp);
1627 	if (dip == NULL) {
1628 		/* Assume write has not completed yet; try again */
1629 		bp->b_flags |= B_INVAL;
1630 		brelse(bp);
1631 		++retries;
1632 		if (retries > LFS_IFIND_RETRIES) {
1633 #ifdef DEBUG
1634 			/* If the seglock is held look at the bpp to see
1635 			   what is there anyway */
1636 			simple_lock(&fs->lfs_interlock);
1637 			if (fs->lfs_seglock > 0) {
1638 				struct buf **bpp;
1639 				struct ufs1_dinode *dp;
1640 				int i;
1641 
1642 				for (bpp = fs->lfs_sp->bpp;
1643 				     bpp != fs->lfs_sp->cbpp; ++bpp) {
1644 					if ((*bpp)->b_vp == fs->lfs_ivnode &&
1645 					    bpp != fs->lfs_sp->bpp) {
1646 						/* Inode block */
1647 						printf("lfs_vget: block 0x%" PRIx64 ": ",
1648 						       (*bpp)->b_blkno);
1649 						dp = (struct ufs1_dinode *)(*bpp)->b_data;
1650 						for (i = 0; i < INOPB(fs); i++)
1651 							if (dp[i].di_u.inumber)
1652 								printf("%d ", dp[i].di_u.inumber);
1653 						printf("\n");
1654 					}
1655 				}
1656 			}
1657 			simple_unlock(&fs->lfs_interlock);
1658 #endif /* DEBUG */
1659 			panic("lfs_vget: dinode not found");
1660 		}
1661 		simple_lock(&fs->lfs_interlock);
1662 		if (fs->lfs_iocount) {
1663 			DLOG((DLOG_VNODE, "lfs_vget: dinode %d not found, retrying...\n", ino));
1664 			(void)ltsleep(&fs->lfs_iocount, PRIBIO + 1,
1665 				      "lfs ifind", 1, &fs->lfs_interlock);
1666 		} else
1667 			retries = LFS_IFIND_RETRIES;
1668 		simple_unlock(&fs->lfs_interlock);
1669 		goto again;
1670 	}
1671 	*ip->i_din.ffs1_din = *dip;
1672 	brelse(bp);
1673 
1674 	if (fs->lfs_version > 1) {
1675 		ip->i_ffs1_atime = ts.tv_sec;
1676 		ip->i_ffs1_atimensec = ts.tv_nsec;
1677 	}
1678 
1679 	lfs_vinit(mp, &vp);
1680 
1681 	*vpp = vp;
1682 
1683 	KASSERT(VOP_ISLOCKED(vp));
1684 
1685 	return (0);
1686 }
1687 
1688 /*
1689  * File handle to vnode
1690  */
1691 int
1692 lfs_fhtovp(struct mount *mp, struct fid *fhp, struct vnode **vpp)
1693 {
1694 	struct lfid *lfhp;
1695 	struct buf *bp;
1696 	IFILE *ifp;
1697 	int32_t daddr;
1698 	struct lfs *fs;
1699 
1700 	lfhp = (struct lfid *)fhp;
1701 	if (lfhp->lfid_ino < LFS_IFILE_INUM)
1702 		return ESTALE;
1703 
1704 	fs = VFSTOUFS(mp)->um_lfs;
1705 	if (lfhp->lfid_ident != fs->lfs_ident)
1706 		return ESTALE;
1707 
1708 	if (lfhp->lfid_ino >
1709 	    ((VTOI(fs->lfs_ivnode)->i_ffs1_size >> fs->lfs_bshift) -
1710 	     fs->lfs_cleansz - fs->lfs_segtabsz) * fs->lfs_ifpb)
1711 		return ESTALE;
1712 
1713 	if (ufs_ihashlookup(VFSTOUFS(mp)->um_dev, lfhp->lfid_ino) == NULLVP) {
1714 		LFS_IENTRY(ifp, fs, lfhp->lfid_ino, bp);
1715 		daddr = ifp->if_daddr;
1716 		brelse(bp);
1717 		if (daddr == LFS_UNUSED_DADDR)
1718 			return ESTALE;
1719 	}
1720 
1721 	return (ufs_fhtovp(mp, &lfhp->lfid_ufid, vpp));
1722 }
1723 
1724 /*
1725  * Vnode pointer to File handle
1726  */
1727 /* ARGSUSED */
1728 int
1729 lfs_vptofh(struct vnode *vp, struct fid *fhp)
1730 {
1731 	struct inode *ip;
1732 	struct lfid *lfhp;
1733 
1734 	ip = VTOI(vp);
1735 	lfhp = (struct lfid *)fhp;
1736 	lfhp->lfid_len = sizeof(struct lfid);
1737 	lfhp->lfid_ino = ip->i_number;
1738 	lfhp->lfid_gen = ip->i_gen;
1739 	lfhp->lfid_ident = ip->i_lfs->lfs_ident;
1740 	return (0);
1741 }
1742 
1743 static int
1744 sysctl_lfs_dostats(SYSCTLFN_ARGS)
1745 {
1746 	extern struct lfs_stats lfs_stats;
1747 	extern int lfs_dostats;
1748 	int error;
1749 
1750 	error = sysctl_lookup(SYSCTLFN_CALL(rnode));
1751 	if (error || newp == NULL)
1752 		return (error);
1753 
1754 	if (lfs_dostats == 0)
1755 		memset(&lfs_stats, 0, sizeof(lfs_stats));
1756 
1757 	return (0);
1758 }
1759 
1760 struct shortlong {
1761 	const char *sname;
1762 	const char *lname;
1763 };
1764 
1765 SYSCTL_SETUP(sysctl_vfs_lfs_setup, "sysctl vfs.lfs subtree setup")
1766 {
1767 	int i;
1768 	extern int lfs_writeindir, lfs_dostats, lfs_clean_vnhead,
1769 		   lfs_fs_pagetrip;
1770 #ifdef DEBUG
1771 	extern int lfs_debug_log_subsys[DLOG_MAX];
1772 	struct shortlong dlog_names[DLOG_MAX] = { /* Must match lfs.h ! */
1773 		{ "rollforward", "Debug roll-forward code" },
1774 		{ "alloc",	"Debug inode allocation and free list" },
1775 		{ "avail",	"Debug space-available-now accounting" },
1776 		{ "flush",	"Debug flush triggers" },
1777 		{ "lockedlist",	"Debug locked list accounting" },
1778 		{ "vnode_verbose", "Verbose per-vnode-written debugging" },
1779 		{ "vnode",	"Debug vnode use during segment write" },
1780 		{ "segment",	"Debug segment writing" },
1781 		{ "seguse",	"Debug segment used-bytes accounting" },
1782 		{ "cleaner",	"Debug cleaning routines" },
1783 		{ "mount",	"Debug mount/unmount routines" },
1784 		{ "pagecache",	"Debug UBC interactions" },
1785 		{ "dirop",	"Debug directory-operation accounting" },
1786 		{ "malloc",	"Debug private malloc accounting" },
1787 	};
1788 #endif /* DEBUG */
1789 	struct shortlong stat_names[] = { /* Must match lfs.h! */
1790 		{ "segsused",	    "Number of new segments allocated" },
1791 		{ "psegwrites",	    "Number of partial-segment writes" },
1792 		{ "psyncwrites",    "Number of synchronous partial-segment"
1793 				    " writes" },
1794 		{ "pcleanwrites",   "Number of partial-segment writes by the"
1795 				    " cleaner" },
1796 		{ "blocktot",       "Number of blocks written" },
1797 		{ "cleanblocks",    "Number of blocks written by the cleaner" },
1798 		{ "ncheckpoints",   "Number of checkpoints made" },
1799 		{ "nwrites",        "Number of whole writes" },
1800 		{ "nsync_writes",   "Number of synchronous writes" },
1801 		{ "wait_exceeded",  "Number of times writer waited for"
1802 				    " cleaner" },
1803 		{ "write_exceeded", "Number of times writer invoked flush" },
1804 		{ "flush_invoked",  "Number of times flush was invoked" },
1805 		{ "vflush_invoked", "Number of time vflush was called" },
1806 		{ "clean_inlocked", "Number of vnodes skipped for VXLOCK" },
1807 		{ "clean_vnlocked", "Number of vnodes skipped for vget failure" },
1808 		{ "segs_reclaimed", "Number of segments reclaimed" },
1809 	};
1810 
1811 	sysctl_createv(clog, 0, NULL, NULL,
1812 		       CTLFLAG_PERMANENT,
1813 		       CTLTYPE_NODE, "vfs", NULL,
1814 		       NULL, 0, NULL, 0,
1815 		       CTL_VFS, CTL_EOL);
1816 	sysctl_createv(clog, 0, NULL, NULL,
1817 		       CTLFLAG_PERMANENT,
1818 		       CTLTYPE_NODE, "lfs",
1819 		       SYSCTL_DESCR("Log-structured file system"),
1820 		       NULL, 0, NULL, 0,
1821 		       CTL_VFS, 5, CTL_EOL);
1822 	/*
1823 	 * XXX the "5" above could be dynamic, thereby eliminating one
1824 	 * more instance of the "number to vfs" mapping problem, but
1825 	 * "5" is the order as taken from sys/mount.h
1826 	 */
1827 
1828 	sysctl_createv(clog, 0, NULL, NULL,
1829 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1830 		       CTLTYPE_INT, "flushindir", NULL,
1831 		       NULL, 0, &lfs_writeindir, 0,
1832 		       CTL_VFS, 5, LFS_WRITEINDIR, CTL_EOL);
1833 	sysctl_createv(clog, 0, NULL, NULL,
1834 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1835 		       CTLTYPE_INT, "clean_vnhead", NULL,
1836 		       NULL, 0, &lfs_clean_vnhead, 0,
1837 		       CTL_VFS, 5, LFS_CLEAN_VNHEAD, CTL_EOL);
1838 	sysctl_createv(clog, 0, NULL, NULL,
1839 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1840 		       CTLTYPE_INT, "dostats",
1841 		       SYSCTL_DESCR("Maintain statistics on LFS operations"),
1842 		       sysctl_lfs_dostats, 0, &lfs_dostats, 0,
1843 		       CTL_VFS, 5, LFS_DOSTATS, CTL_EOL);
1844 	sysctl_createv(clog, 0, NULL, NULL,
1845 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1846 		       CTLTYPE_INT, "pagetrip",
1847 		       SYSCTL_DESCR("How many dirty pages in fs triggers"
1848 				    " a flush"),
1849 		       NULL, 0, &lfs_fs_pagetrip, 0,
1850 		       CTL_VFS, 5, LFS_FS_PAGETRIP, CTL_EOL);
1851 	sysctl_createv(clog, 0, NULL, NULL,
1852 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1853 		       CTLTYPE_INT, "rfw",
1854 		       SYSCTL_DESCR("Use in-kernel roll-forward on mount"),
1855 		       NULL, 0, &lfs_do_rfw, 0,
1856 		       CTL_VFS, 5, LFS_DO_RFW, CTL_EOL);
1857 
1858 	sysctl_createv(clog, 0, NULL, NULL,
1859 		       CTLFLAG_PERMANENT,
1860 		       CTLTYPE_NODE, "stats",
1861 		       SYSCTL_DESCR("Debugging options"),
1862 		       NULL, 0, NULL, 0,
1863 		       CTL_VFS, 5, LFS_STATS, CTL_EOL);
1864 	for (i = 0; i < sizeof(struct lfs_stats) / sizeof(u_int); i++) {
1865 		sysctl_createv(clog, 0, NULL, NULL,
1866 			       CTLFLAG_PERMANENT|CTLFLAG_READONLY,
1867 			       CTLTYPE_INT, stat_names[i].sname,
1868 			       SYSCTL_DESCR(stat_names[i].lname),
1869 			       NULL, 0, &(((u_int *)&lfs_stats.segsused)[i]),
1870 			       0, CTL_VFS, 5, LFS_STATS, i, CTL_EOL);
1871 	}
1872 
1873 #ifdef DEBUG
1874 	sysctl_createv(clog, 0, NULL, NULL,
1875 		       CTLFLAG_PERMANENT,
1876 		       CTLTYPE_NODE, "debug",
1877 		       SYSCTL_DESCR("Debugging options"),
1878 		       NULL, 0, NULL, 0,
1879 		       CTL_VFS, 5, LFS_DEBUGLOG, CTL_EOL);
1880 	for (i = 0; i < DLOG_MAX; i++) {
1881 		sysctl_createv(clog, 0, NULL, NULL,
1882 			       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1883 			       CTLTYPE_INT, dlog_names[i].sname,
1884 			       SYSCTL_DESCR(dlog_names[i].lname),
1885 			       NULL, 0, &(lfs_debug_log_subsys[i]), 0,
1886 			       CTL_VFS, 5, LFS_DEBUGLOG, i, CTL_EOL);
1887 	}
1888 #endif
1889 }
1890 
1891 /*
1892  * ufs_bmaparray callback function for writing.
1893  *
1894  * Since blocks will be written to the new segment anyway,
1895  * we don't care about current daddr of them.
1896  */
1897 static boolean_t
1898 lfs_issequential_hole(const struct ufsmount *ump,
1899     daddr_t daddr0, daddr_t daddr1)
1900 {
1901 	daddr0 = (daddr_t)((int32_t)daddr0); /* XXX ondisk32 */
1902 	daddr1 = (daddr_t)((int32_t)daddr1); /* XXX ondisk32 */
1903 
1904 	KASSERT(daddr0 == UNWRITTEN ||
1905 	    (0 <= daddr0 && daddr0 <= LFS_MAX_DADDR));
1906 	KASSERT(daddr1 == UNWRITTEN ||
1907 	    (0 <= daddr1 && daddr1 <= LFS_MAX_DADDR));
1908 
1909 	/* NOTE: all we want to know here is 'hole or not'. */
1910 	/* NOTE: UNASSIGNED is converted to 0 by ufs_bmaparray. */
1911 
1912 	/*
1913 	 * treat UNWRITTENs and all resident blocks as 'contiguous'
1914 	 */
1915 	if (daddr0 != 0 && daddr1 != 0)
1916 		return TRUE;
1917 
1918 	/*
1919 	 * both are in hole?
1920 	 */
1921 	if (daddr0 == 0 && daddr1 == 0)
1922 		return TRUE; /* all holes are 'contiguous' for us. */
1923 
1924 	return FALSE;
1925 }
1926 
1927 /*
1928  * lfs_gop_write functions exactly like genfs_gop_write, except that
1929  * (1) it requires the seglock to be held by its caller, and sp->fip
1930  *     to be properly initialized (it will return without re-initializing
1931  *     sp->fip, and without calling lfs_writeseg).
1932  * (2) it uses the remaining space in the segment, rather than VOP_BMAP,
1933  *     to determine how large a block it can write at once (though it does
1934  *     still use VOP_BMAP to find holes in the file);
1935  * (3) it calls lfs_gatherblock instead of VOP_STRATEGY on its blocks
1936  *     (leaving lfs_writeseg to deal with the cluster blocks, so we might
1937  *     now have clusters of clusters, ick.)
1938  */
1939 static int
1940 lfs_gop_write(struct vnode *vp, struct vm_page **pgs, int npages, int flags)
1941 {
1942 	int i, s, error, run;
1943 	int fs_bshift;
1944 	vaddr_t kva;
1945 	off_t eof, offset, startoffset = 0;
1946 	size_t bytes, iobytes, skipbytes;
1947 	daddr_t lbn, blkno;
1948 	struct vm_page *pg;
1949 	struct buf *mbp, *bp;
1950 	struct vnode *devvp = VTOI(vp)->i_devvp;
1951 	struct inode *ip = VTOI(vp);
1952 	struct lfs *fs = ip->i_lfs;
1953 	struct segment *sp = fs->lfs_sp;
1954 	UVMHIST_FUNC("lfs_gop_write"); UVMHIST_CALLED(ubchist);
1955 
1956 	ASSERT_SEGLOCK(fs);
1957 
1958 	/* The Ifile lives in the buffer cache */
1959 	KASSERT(vp != fs->lfs_ivnode);
1960 
1961 	/*
1962 	 * Sometimes things slip past the filters in lfs_putpages,
1963 	 * and the pagedaemon tries to write pages---problem is
1964 	 * that the pagedaemon never acquires the segment lock.
1965 	 *
1966 	 * Alternatively, pages that were clean when we called
1967 	 * genfs_putpages may have become dirty in the meantime.  In this
1968 	 * case the segment header is not properly set up for blocks
1969 	 * to be added to it.
1970 	 *
1971 	 * Unbusy and unclean the pages, and put them on the ACTIVE
1972 	 * queue under the hypothesis that they couldn't have got here
1973 	 * unless they were modified *quite* recently.
1974 	 *
1975 	 * XXXUBC that last statement is an oversimplification of course.
1976 	 */
1977 	if (!LFS_SEGLOCK_HELD(fs) ||
1978 	    (ip->i_lfs_iflags & LFSI_NO_GOP_WRITE) ||
1979 	    (pgs[0]->offset & fs->lfs_bmask) != 0) {
1980 		goto tryagain;
1981 	}
1982 
1983 	UVMHIST_LOG(ubchist, "vp %p pgs %p npages %d flags 0x%x",
1984 	    vp, pgs, npages, flags);
1985 
1986 	GOP_SIZE(vp, vp->v_size, &eof, GOP_SIZE_WRITE);
1987 
1988 	if (vp->v_type == VREG)
1989 		fs_bshift = vp->v_mount->mnt_fs_bshift;
1990 	else
1991 		fs_bshift = DEV_BSHIFT;
1992 	error = 0;
1993 	pg = pgs[0];
1994 	startoffset = pg->offset;
1995 	if (startoffset >= eof) {
1996 		goto tryagain;
1997 	} else
1998 		bytes = MIN(npages << PAGE_SHIFT, eof - startoffset);
1999 	skipbytes = 0;
2000 
2001 	KASSERT(bytes != 0);
2002 
2003 	/* Swap PG_DELWRI for PG_PAGEOUT */
2004 	for (i = 0; i < npages; i++)
2005 		if (pgs[i]->flags & PG_DELWRI) {
2006 			KASSERT(!(pgs[i]->flags & PG_PAGEOUT));
2007 			pgs[i]->flags &= ~PG_DELWRI;
2008 			pgs[i]->flags |= PG_PAGEOUT;
2009 			uvmexp.paging++;
2010 			uvm_lock_pageq();
2011 			uvm_pageunwire(pgs[i]);
2012 			uvm_unlock_pageq();
2013 		}
2014 
2015 	/*
2016 	 * Check to make sure we're starting on a block boundary.
2017 	 * We'll check later to make sure we always write entire
2018 	 * blocks (or fragments).
2019 	 */
2020 	if (startoffset & fs->lfs_bmask)
2021 		printf("%" PRId64 " & %" PRId64 " = %" PRId64 "\n",
2022 		       startoffset, fs->lfs_bmask,
2023 		       startoffset & fs->lfs_bmask);
2024 	KASSERT((startoffset & fs->lfs_bmask) == 0);
2025 	if (bytes & fs->lfs_ffmask) {
2026 		printf("lfs_gop_write: asked to write %ld bytes\n", (long)bytes);
2027 		panic("lfs_gop_write: non-integer blocks");
2028 	}
2029 
2030 	/*
2031 	 * We could deadlock here on pager_map with UVMPAGER_MAPIN_WAITOK.
2032 	 * If we would, write what we have and try again.  If we don't
2033 	 * have anything to write, we'll have to sleep.
2034 	 */
2035 	if ((kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
2036 				      (((SEGSUM *)(sp->segsum))->ss_nfinfo < 1 ?
2037 				       UVMPAGER_MAPIN_WAITOK : 0))) == 0x0) {
2038 		int vers;
2039 
2040 		DLOG((DLOG_PAGE, "lfs_gop_write: forcing write\n"));
2041 #if 0
2042 		      " with nfinfo=%d at offset 0x%x\n",
2043 		      (int)((SEGSUM *)(sp->segsum))->ss_nfinfo,
2044 		      (unsigned)fs->lfs_offset));
2045 #endif
2046 		if (sp->fip->fi_nblocks == 0) {
2047 			/* Don't write zero-length finfos */
2048 			--((SEGSUM *)(sp->segsum))->ss_nfinfo;
2049 			sp->sum_bytes_left += FINFOSIZE;
2050 		} else
2051 			lfs_updatemeta(sp);
2052 
2053 		vers = sp->fip->fi_version;
2054 		(void) lfs_writeseg(fs, sp);
2055 
2056 		sp->fip->fi_version = vers;
2057 		sp->fip->fi_ino = ip->i_number;
2058 		/* Add the current file to the segment summary. */
2059 		++((SEGSUM *)(sp->segsum))->ss_nfinfo;
2060 		sp->sum_bytes_left -= FINFOSIZE;
2061 
2062 		/*
2063 		 * Having given up all of the pager_map we were holding,
2064 		 * we can now wait for aiodoned to reclaim it for us
2065 		 * without fear of deadlock.
2066 		 */
2067 		kva = uvm_pagermapin(pgs, npages, UVMPAGER_MAPIN_WRITE |
2068 				     UVMPAGER_MAPIN_WAITOK);
2069 	}
2070 
2071 	s = splbio();
2072 	simple_lock(&global_v_numoutput_slock);
2073 	vp->v_numoutput += 2; /* one for biodone, one for aiodone */
2074 	simple_unlock(&global_v_numoutput_slock);
2075 	mbp = pool_get(&bufpool, PR_WAITOK);
2076 	splx(s);
2077 
2078 	memset(mbp, 0, sizeof(*bp));
2079 	BUF_INIT(mbp);
2080 	UVMHIST_LOG(ubchist, "vp %p mbp %p num now %d bytes 0x%x",
2081 	    vp, mbp, vp->v_numoutput, bytes);
2082 	mbp->b_bufsize = npages << PAGE_SHIFT;
2083 	mbp->b_data = (void *)kva;
2084 	mbp->b_resid = mbp->b_bcount = bytes;
2085 	mbp->b_flags = B_BUSY|B_WRITE|B_AGE|B_CALL;
2086 	mbp->b_iodone = uvm_aio_biodone;
2087 	mbp->b_vp = vp;
2088 
2089 	bp = NULL;
2090 	for (offset = startoffset;
2091 	    bytes > 0;
2092 	    offset += iobytes, bytes -= iobytes) {
2093 		lbn = offset >> fs_bshift;
2094 		error = ufs_bmaparray(vp, lbn, &blkno, NULL, NULL, &run,
2095 		    lfs_issequential_hole);
2096 		if (error) {
2097 			UVMHIST_LOG(ubchist, "ufs_bmaparray() -> %d",
2098 			    error,0,0,0);
2099 			skipbytes += bytes;
2100 			bytes = 0;
2101 			break;
2102 		}
2103 
2104 		iobytes = MIN((((off_t)lbn + 1 + run) << fs_bshift) - offset,
2105 		    bytes);
2106 		if (blkno == (daddr_t)-1) {
2107 			skipbytes += iobytes;
2108 			continue;
2109 		}
2110 
2111 		/*
2112 		 * Discover how much we can really pack into this buffer.
2113 		 */
2114 		/* If no room in the current segment, finish it up */
2115 		if (sp->sum_bytes_left < sizeof(int32_t) ||
2116 		    sp->seg_bytes_left < (1 << fs->lfs_bshift)) {
2117 			int vers;
2118 
2119 			lfs_updatemeta(sp);
2120 
2121 			vers = sp->fip->fi_version;
2122 			(void) lfs_writeseg(fs, sp);
2123 
2124 			sp->fip->fi_version = vers;
2125 			sp->fip->fi_ino = ip->i_number;
2126 			/* Add the current file to the segment summary. */
2127 			++((SEGSUM *)(sp->segsum))->ss_nfinfo;
2128 			sp->sum_bytes_left -= FINFOSIZE;
2129 		}
2130 		/* Check both for space in segment and space in segsum */
2131 		iobytes = MIN(iobytes, (sp->seg_bytes_left >> fs_bshift)
2132 					<< fs_bshift);
2133 		iobytes = MIN(iobytes, (sp->sum_bytes_left / sizeof(int32_t))
2134 				       << fs_bshift);
2135 		KASSERT(iobytes > 0);
2136 
2137 		/* if it's really one i/o, don't make a second buf */
2138 		if (offset == startoffset && iobytes == bytes) {
2139 			bp = mbp;
2140 			/* correct overcount if there is no second buffer */
2141 			s = splbio();
2142 			simple_lock(&global_v_numoutput_slock);
2143 			--vp->v_numoutput;
2144 			simple_unlock(&global_v_numoutput_slock);
2145 			splx(s);
2146 		} else {
2147 			s = splbio();
2148 			bp = pool_get(&bufpool, PR_WAITOK);
2149 			UVMHIST_LOG(ubchist, "vp %p bp %p num now %d",
2150 			    vp, bp, vp->v_numoutput, 0);
2151 			splx(s);
2152 			memset(bp, 0, sizeof(*bp));
2153 			BUF_INIT(bp);
2154 			bp->b_data = (char *)kva +
2155 			    (vaddr_t)(offset - pg->offset);
2156 			bp->b_resid = bp->b_bcount = iobytes;
2157 			bp->b_flags = B_BUSY|B_WRITE|B_CALL;
2158 			bp->b_iodone = uvm_aio_biodone1;
2159 		}
2160 
2161 		/* XXX This is silly ... is this necessary? */
2162 		bp->b_vp = NULL;
2163 		s = splbio();
2164 		bgetvp(vp, bp);
2165 		splx(s);
2166 
2167 		bp->b_lblkno = lblkno(fs, offset);
2168 		bp->b_private = mbp;
2169 		if (devvp->v_type == VBLK) {
2170 			bp->b_dev = devvp->v_rdev;
2171 		}
2172 		VOP_BWRITE(bp);
2173 		while (lfs_gatherblock(sp, bp, NULL))
2174 			continue;
2175 	}
2176 
2177 	if (skipbytes) {
2178 		UVMHIST_LOG(ubchist, "skipbytes %d", skipbytes, 0,0,0);
2179 		s = splbio();
2180 		if (error) {
2181 			mbp->b_flags |= B_ERROR;
2182 			mbp->b_error = error;
2183 		}
2184 		mbp->b_resid -= skipbytes;
2185 		if (mbp->b_resid == 0) {
2186 			biodone(mbp);
2187 		}
2188 		splx(s);
2189 	}
2190 	UVMHIST_LOG(ubchist, "returning 0", 0,0,0,0);
2191 	return (0);
2192 
2193     tryagain:
2194 	/*
2195 	 * We can't write the pages, for whatever reason.
2196 	 * Clean up after ourselves, and make the caller try again.
2197 	 */
2198 	simple_lock(&vp->v_interlock);
2199 
2200 	/* Tell why we're here, if we know */
2201 	if (ip->i_lfs_iflags & LFSI_NO_GOP_WRITE)
2202 		DLOG((DLOG_PAGE, "lfs_gop_write: clean pages dirtied\n"));
2203 	else if ((pgs[0]->offset & fs->lfs_bmask) != 0)
2204 		DLOG((DLOG_PAGE, "lfs_gop_write: not on block boundary\n"));
2205 	else if (startoffset >= eof)
2206 		DLOG((DLOG_PAGE, "lfs_gop_write: ino %d start 0x%" PRIx64
2207 		      " eof 0x%" PRIx64 " npages=%d\n", VTOI(vp)->i_number,
2208 		      pgs[0]->offset, eof, npages));
2209 	else
2210 		DLOG((DLOG_PAGE, "lfs_gop_write: seglock not held\n"));
2211 
2212 	uvm_lock_pageq();
2213 	for (i = 0; i < npages; i++) {
2214 		pg = pgs[i];
2215 
2216 		if (pg->flags & PG_PAGEOUT)
2217 			uvmexp.paging--;
2218 		if (pg->flags & PG_DELWRI) {
2219 			uvm_pageunwire(pg);
2220 		}
2221 		uvm_pageactivate(pg);
2222 		pg->flags &= ~(PG_CLEAN|PG_DELWRI|PG_PAGEOUT|PG_RELEASED);
2223 		DLOG((DLOG_PAGE, "pg[%d] = %p\n", i, pg));
2224 		DLOG((DLOG_PAGE, "pg[%d]->flags = %x\n", i, pg->flags));
2225 		DLOG((DLOG_PAGE, "pg[%d]->pqflags = %x\n", i, pg->pqflags));
2226 		DLOG((DLOG_PAGE, "pg[%d]->uanon = %p\n", i, pg->uanon));
2227 		DLOG((DLOG_PAGE, "pg[%d]->uobject = %p\n", i, pg->uobject));
2228 		DLOG((DLOG_PAGE, "pg[%d]->wire_count = %d\n", i,
2229 		      pg->wire_count));
2230 		DLOG((DLOG_PAGE, "pg[%d]->loan_count = %d\n", i,
2231 		      pg->loan_count));
2232 	}
2233 	/* uvm_pageunbusy takes care of PG_BUSY, PG_WANTED */
2234 	uvm_page_unbusy(pgs, npages);
2235 	uvm_unlock_pageq();
2236 	simple_unlock(&vp->v_interlock);
2237 	return EAGAIN;
2238 }
2239 
2240 /*
2241  * finish vnode/inode initialization.
2242  * used by lfs_vget and lfs_fastvget.
2243  */
2244 void
2245 lfs_vinit(struct mount *mp, struct vnode **vpp)
2246 {
2247 	struct vnode *vp = *vpp;
2248 	struct inode *ip = VTOI(vp);
2249 	struct ufsmount *ump = VFSTOUFS(mp);
2250 	int i;
2251 
2252 	ip->i_mode = ip->i_ffs1_mode;
2253 	ip->i_ffs_effnlink = ip->i_nlink = ip->i_ffs1_nlink;
2254 	ip->i_lfs_osize = ip->i_size = ip->i_ffs1_size;
2255 	ip->i_flags = ip->i_ffs1_flags;
2256 	ip->i_gen = ip->i_ffs1_gen;
2257 	ip->i_uid = ip->i_ffs1_uid;
2258 	ip->i_gid = ip->i_ffs1_gid;
2259 
2260 	ip->i_lfs_effnblks = ip->i_ffs1_blocks;
2261 
2262 	/*
2263 	 * Initialize the vnode from the inode, check for aliases.  In all
2264 	 * cases re-init ip, the underlying vnode/inode may have changed.
2265 	 */
2266 	ufs_vinit(mp, lfs_specop_p, lfs_fifoop_p, &vp);
2267 	ip = VTOI(vp);
2268 
2269 	memset(ip->i_lfs_fragsize, 0, NDADDR * sizeof(*ip->i_lfs_fragsize));
2270 	if (vp->v_type != VLNK || ip->i_size >= ip->i_ump->um_maxsymlinklen) {
2271 		struct lfs *fs = ump->um_lfs;
2272 #ifdef DEBUG
2273 		for (i = (ip->i_size + fs->lfs_bsize - 1) >> fs->lfs_bshift;
2274 		    i < NDADDR; i++) {
2275 			if ((vp->v_type == VBLK || vp->v_type == VCHR) &&
2276 			    i == 0)
2277 				continue;
2278 			if (ip->i_ffs1_db[i] != 0) {
2279 inconsistent:
2280 				lfs_dump_dinode(ip->i_din.ffs1_din);
2281 				panic("inconsistent inode");
2282 			}
2283 		}
2284 		for ( ; i < NDADDR + NIADDR; i++) {
2285 			if (ip->i_ffs1_ib[i - NDADDR] != 0) {
2286 				goto inconsistent;
2287 			}
2288 		}
2289 #endif /* DEBUG */
2290 		for (i = 0; i < NDADDR; i++)
2291 			if (ip->i_ffs1_db[i] != 0)
2292 				ip->i_lfs_fragsize[i] = blksize(fs, ip, i);
2293 	}
2294 
2295 #ifdef DIAGNOSTIC
2296 	if (vp->v_type == VNON) {
2297 # ifdef DEBUG
2298 		lfs_dump_dinode(ip->i_din.ffs1_din);
2299 # endif
2300 		panic("lfs_vinit: ino %llu is type VNON! (ifmt=%o)\n",
2301 		      (unsigned long long)ip->i_number,
2302 		      (ip->i_mode & IFMT) >> 12);
2303 	}
2304 #endif /* DIAGNOSTIC */
2305 
2306 	/*
2307 	 * Finish inode initialization now that aliasing has been resolved.
2308 	 */
2309 
2310 	ip->i_devvp = ump->um_devvp;
2311 	VREF(ip->i_devvp);
2312 	genfs_node_init(vp, &lfs_genfsops);
2313 	uvm_vnp_setsize(vp, ip->i_size);
2314 
2315 	/* Initialize hiblk from file size */
2316 	ip->i_lfs_hiblk = lblkno(ip->i_lfs, ip->i_size + ip->i_lfs->lfs_bsize - 1) - 1;
2317 
2318 	*vpp = vp;
2319 }
2320 
2321 /*
2322  * Warn if the inode portion of the Ifile is too large to be contained
2323  * in the buffer cache, according to LFS_MAX_BUFS / LFS_MAX_BYTES.
2324  * XXX the estimates don't take multiple LFSs into account.
2325  */
2326 static void
2327 warn_ifile_size(struct lfs *fs)
2328 {
2329 	KASSERT(LFS_MAX_BUFS > 0);
2330 	KASSERT(LFS_MAX_BYTES > 0);
2331 	if (((fs->lfs_ivnode->v_size >> fs->lfs_bshift) - fs->lfs_segtabsz) >
2332 	    LFS_MAX_BUFS) {
2333 		simple_lock(&fs->lfs_interlock);
2334 		fs->lfs_flags |= LFS_WARNED;
2335 		simple_unlock(&fs->lfs_interlock);
2336 		log(LOG_WARNING, "lfs_mountfs: inode part of ifile of length %"
2337 				 PRId64 " cannot fit in %d buffers\n",
2338 				 fs->lfs_ivnode->v_size -
2339 				 (fs->lfs_segtabsz << fs->lfs_bshift),
2340 				 LFS_MAX_BUFS);
2341 		log(LOG_WARNING, "lfs_mountfs: please consider increasing NBUF"
2342 				 " to at least %" PRId64 "\n",
2343 				 LFS_INVERSE_MAX_BUFS((fs->lfs_ivnode->v_size >>
2344 						       fs->lfs_bshift) -
2345 						      fs->lfs_segtabsz));
2346 	} else if ((fs->lfs_ivnode->v_size >> fs->lfs_bshift) > LFS_MAX_BUFS) {
2347 		/* Same thing but LOG_NOTICE */
2348 		simple_lock(&fs->lfs_interlock);
2349 		fs->lfs_flags |= LFS_WARNED;
2350 		simple_unlock(&fs->lfs_interlock);
2351 		log(LOG_NOTICE, "lfs_mountfs: entire ifile of length %"
2352 				PRId64 " cannot fit in %d buffers\n",
2353 				fs->lfs_ivnode->v_size, LFS_MAX_BUFS);
2354 		log(LOG_NOTICE, "lfs_mountfs: please consider increasing NBUF"
2355 				" to at least %" PRId64 "\n",
2356 				LFS_INVERSE_MAX_BUFS(fs->lfs_ivnode->v_size >>
2357 						     fs->lfs_bshift));
2358 	}
2359 
2360 	if (fs->lfs_ivnode->v_size - (fs->lfs_segtabsz << fs->lfs_bshift) >
2361 	    LFS_MAX_BYTES) {
2362 		simple_lock(&fs->lfs_interlock);
2363 		fs->lfs_flags |= LFS_WARNED;
2364 		simple_unlock(&fs->lfs_interlock);
2365 		log(LOG_WARNING, "lfs_mountfs: inode part of ifile of length %"
2366 				 PRId64 " cannot fit in %lu bytes\n",
2367 				 fs->lfs_ivnode->v_size - (fs->lfs_segtabsz <<
2368 							   fs->lfs_bshift),
2369 				 LFS_MAX_BYTES);
2370 		log(LOG_WARNING, "lfs_mountfs: please consider increasing"
2371 				 " BUFPAGES to at least %" PRId64 "\n",
2372 				 LFS_INVERSE_MAX_BYTES(fs->lfs_ivnode->v_size -
2373 						       (fs->lfs_segtabsz <<
2374 							fs->lfs_bshift)) >>
2375 				 PAGE_SHIFT);
2376 	} else if(fs->lfs_ivnode->v_size > LFS_MAX_BYTES) {
2377 		simple_lock(&fs->lfs_interlock);
2378 		fs->lfs_flags |= LFS_WARNED;
2379 		simple_unlock(&fs->lfs_interlock);
2380 		log(LOG_NOTICE, "lfs_mountfs: entire ifile of length %" PRId64
2381 				" cannot fit in %lu buffer bytes\n",
2382 				fs->lfs_ivnode->v_size, LFS_MAX_BYTES);
2383 		log(LOG_NOTICE, "lfs_mountfs: please consider increasing"
2384 				" BUFPAGES to at least %" PRId64 "\n",
2385 				LFS_INVERSE_MAX_BYTES(fs->lfs_ivnode->v_size -
2386 						      (fs->lfs_segtabsz <<
2387 						       fs->lfs_bshift)) >>
2388 				PAGE_SHIFT);
2389 	}
2390 }
2391 
2392 /*
2393  * Resize the filesystem to contain the specified number of segments.
2394  */
2395 int
2396 lfs_resize_fs(struct lfs *fs, int newnsegs)
2397 {
2398 	SEGUSE *sup;
2399 	struct buf *bp, *obp;
2400 	daddr_t olast, nlast, ilast, noff, start, end;
2401 	struct vnode *ivp;
2402 	struct inode *ip;
2403 	int error, badnews, inc, oldnsegs;
2404 	int sbbytes, csbbytes, gain, cgain;
2405 	int i;
2406 
2407 	/* Only support v2 and up */
2408 	if (fs->lfs_version < 2)
2409 		return EOPNOTSUPP;
2410 
2411 	/* If we're doing nothing, do it fast */
2412 	oldnsegs = fs->lfs_nseg;
2413 	if (newnsegs == oldnsegs)
2414 		return 0;
2415 
2416 	/* We always have to have two superblocks */
2417 	if (newnsegs <= dtosn(fs, fs->lfs_sboffs[1]))
2418 		return EFBIG;
2419 
2420 	ivp = fs->lfs_ivnode;
2421 	ip = VTOI(ivp);
2422 	error = 0;
2423 
2424 	/* Take the segment lock so no one else calls lfs_newseg() */
2425 	lfs_seglock(fs, SEGM_PROT);
2426 
2427 	/*
2428 	 * Make sure the segments we're going to be losing, if any,
2429 	 * are in fact empty.  We hold the seglock, so their status
2430 	 * cannot change underneath us.  Count the superblocks we lose,
2431 	 * while we're at it.
2432 	 */
2433 	sbbytes = csbbytes = 0;
2434 	cgain = 0;
2435 	for (i = newnsegs; i < oldnsegs; i++) {
2436 		LFS_SEGENTRY(sup, fs, i, bp);
2437 		badnews = sup->su_nbytes || !(sup->su_flags & SEGUSE_INVAL);
2438 		if (sup->su_flags & SEGUSE_SUPERBLOCK)
2439 			sbbytes += LFS_SBPAD;
2440 		if (!(sup->su_flags & SEGUSE_DIRTY)) {
2441 			++cgain;
2442 			if (sup->su_flags & SEGUSE_SUPERBLOCK)
2443 				csbbytes += LFS_SBPAD;
2444 		}
2445 		brelse(bp);
2446 		if (badnews) {
2447 			error = EBUSY;
2448 			goto out;
2449 		}
2450 	}
2451 
2452 	/* Note old and new segment table endpoints, and old ifile size */
2453 	olast = fs->lfs_cleansz + fs->lfs_segtabsz;
2454 	nlast = howmany(newnsegs, fs->lfs_sepb) + fs->lfs_cleansz;
2455 	ilast = ivp->v_size >> fs->lfs_bshift;
2456 	noff = nlast - olast;
2457 
2458 	/*
2459 	 * Make sure no one can use the Ifile while we change it around.
2460 	 * Even after taking the iflock we need to make sure no one still
2461 	 * is holding Ifile buffers, so we get each one, to drain them.
2462 	 * (XXX this could be done better.)
2463 	 */
2464 	simple_lock(&fs->lfs_interlock);
2465 	lockmgr(&fs->lfs_iflock, LK_EXCLUSIVE, &fs->lfs_interlock);
2466 	simple_unlock(&fs->lfs_interlock);
2467 	vn_lock(ivp, LK_EXCLUSIVE | LK_RETRY);
2468 	for (i = 0; i < ilast; i++) {
2469 		bread(ivp, i, fs->lfs_bsize, NOCRED, &bp);
2470 		brelse(bp);
2471 	}
2472 
2473 	/* Allocate new Ifile blocks */
2474 	for (i = ilast; i < ilast + noff; i++) {
2475 		if (lfs_balloc(ivp, i * fs->lfs_bsize, fs->lfs_bsize, NOCRED, 0,
2476 			       &bp) != 0)
2477 			panic("balloc extending ifile");
2478 		memset(bp->b_data, 0, fs->lfs_bsize);
2479 		VOP_BWRITE(bp);
2480 	}
2481 
2482 	/* Register new ifile size */
2483 	ip->i_size += noff * fs->lfs_bsize;
2484 	ip->i_ffs1_size = ip->i_size;
2485 	uvm_vnp_setsize(ivp, ip->i_size);
2486 
2487 	/* Copy the inode table to its new position */
2488 	if (noff != 0) {
2489 		if (noff < 0) {
2490 			start = nlast;
2491 			end = ilast + noff;
2492 			inc = 1;
2493 		} else {
2494 			start = ilast + noff - 1;
2495 			end = nlast - 1;
2496 			inc = -1;
2497 		}
2498 		for (i = start; i != end; i += inc) {
2499 			if (bread(ivp, i, fs->lfs_bsize, NOCRED, &bp) != 0)
2500 				panic("resize: bread dst blk failed");
2501 			if (bread(ivp, i - noff, fs->lfs_bsize, NOCRED, &obp))
2502 				panic("resize: bread src blk failed");
2503 			memcpy(bp->b_data, obp->b_data, fs->lfs_bsize);
2504 			VOP_BWRITE(bp);
2505 			brelse(obp);
2506 		}
2507 	}
2508 
2509 	/* If we are expanding, write the new empty SEGUSE entries */
2510 	if (newnsegs > oldnsegs) {
2511 		for (i = oldnsegs; i < newnsegs; i++) {
2512 			if ((error = bread(ivp, i / fs->lfs_sepb +
2513 					   fs->lfs_cleansz,
2514 					   fs->lfs_bsize, NOCRED, &bp)) != 0)
2515 				panic("lfs: ifile read: %d", error);
2516 			while ((i + 1) % fs->lfs_sepb && i < newnsegs) {
2517 				sup = &((SEGUSE *)bp->b_data)[i % fs->lfs_sepb];
2518 				memset(sup, 0, sizeof(*sup));
2519 				i++;
2520 			}
2521 			VOP_BWRITE(bp);
2522 		}
2523 	}
2524 
2525 	/* Zero out unused superblock offsets */
2526 	for (i = 2; i < LFS_MAXNUMSB; i++)
2527 		if (dtosn(fs, fs->lfs_sboffs[i]) >= newnsegs)
2528 			fs->lfs_sboffs[i] = 0x0;
2529 
2530 	/*
2531 	 * Correct superblock entries that depend on fs size.
2532 	 * The computations of these are as follows:
2533 	 *
2534 	 * size  = segtod(fs, nseg)
2535 	 * dsize = segtod(fs, nseg - minfreeseg) - btofsb(#super * LFS_SBPAD)
2536 	 * bfree = dsize - btofsb(fs, bsize * nseg / 2) - blocks_actually_used
2537 	 * avail = segtod(fs, nclean) - btofsb(#clean_super * LFS_SBPAD)
2538 	 *         + (segtod(fs, 1) - (offset - curseg))
2539 	 *	   - segtod(fs, minfreeseg - (minfreeseg / 2))
2540 	 *
2541 	 * XXX - we should probably adjust minfreeseg as well.
2542 	 */
2543 	gain = (newnsegs - oldnsegs);
2544 	fs->lfs_nseg = newnsegs;
2545 	fs->lfs_segtabsz = nlast - fs->lfs_cleansz;
2546 	fs->lfs_size += gain * btofsb(fs, fs->lfs_ssize);
2547 	fs->lfs_dsize += gain * btofsb(fs, fs->lfs_ssize) - btofsb(fs, sbbytes);
2548 	fs->lfs_bfree += gain * btofsb(fs, fs->lfs_ssize) - btofsb(fs, sbbytes)
2549 		       - gain * btofsb(fs, fs->lfs_bsize / 2);
2550 	if (gain > 0) {
2551 		fs->lfs_nclean += gain;
2552 		fs->lfs_avail += gain * btofsb(fs, fs->lfs_ssize);
2553 	} else {
2554 		fs->lfs_nclean -= cgain;
2555 		fs->lfs_avail -= cgain * btofsb(fs, fs->lfs_ssize) -
2556 				 btofsb(fs, csbbytes);
2557 	}
2558 
2559 	/* Resize segment flag cache */
2560 	fs->lfs_suflags[0] = (u_int32_t *)realloc(fs->lfs_suflags[0],
2561 						  fs->lfs_nseg * sizeof(u_int32_t),
2562 						  M_SEGMENT, M_WAITOK);
2563 	fs->lfs_suflags[1] = (u_int32_t *)realloc(fs->lfs_suflags[0],
2564 						  fs->lfs_nseg * sizeof(u_int32_t),
2565 						  M_SEGMENT, M_WAITOK);
2566 	for (i = oldnsegs; i < newnsegs; i++)
2567 		fs->lfs_suflags[0][i] = fs->lfs_suflags[1][i] = 0x0;
2568 
2569 	/* Truncate Ifile if necessary */
2570 	if (noff < 0)
2571 		lfs_truncate(ivp, ivp->v_size + (noff << fs->lfs_bshift), 0,
2572 			     NOCRED, curlwp);
2573 
2574 	/* Update cleaner info so the cleaner can die */
2575 	bread(ivp, 0, fs->lfs_bsize, NOCRED, &bp);
2576 	((CLEANERINFO *)bp->b_data)->clean = fs->lfs_nclean;
2577 	((CLEANERINFO *)bp->b_data)->dirty = fs->lfs_nseg - fs->lfs_nclean;
2578 	VOP_BWRITE(bp);
2579 
2580 	/* Let Ifile accesses proceed */
2581 	VOP_UNLOCK(ivp, 0);
2582 	simple_lock(&fs->lfs_interlock);
2583 	lockmgr(&fs->lfs_iflock, LK_RELEASE, &fs->lfs_interlock);
2584 	simple_unlock(&fs->lfs_interlock);
2585 
2586     out:
2587 	lfs_segunlock(fs);
2588 	return error;
2589 }
2590