Home | History | Annotate | Line # | Download | only in lfs
lfs_segment.c revision 1.189
      1 /*	$NetBSD: lfs_segment.c,v 1.189 2006/09/01 19:41:28 perseant 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 (at) 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) 1991, 1993
     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_segment.c	8.10 (Berkeley) 6/10/95
     67  */
     68 
     69 #include <sys/cdefs.h>
     70 __KERNEL_RCSID(0, "$NetBSD: lfs_segment.c,v 1.189 2006/09/01 19:41:28 perseant Exp $");
     71 
     72 #ifdef DEBUG
     73 # define vndebug(vp, str) do {						\
     74 	if (VTOI(vp)->i_flag & IN_CLEANING)				\
     75 		DLOG((DLOG_WVNODE, "not writing ino %d because %s (op %d)\n", \
     76 		     VTOI(vp)->i_number, (str), op));			\
     77 } while(0)
     78 #else
     79 # define vndebug(vp, str)
     80 #endif
     81 #define ivndebug(vp, str) \
     82 	DLOG((DLOG_WVNODE, "ino %d: %s\n", VTOI(vp)->i_number, (str)))
     83 
     84 #if defined(_KERNEL_OPT)
     85 #include "opt_ddb.h"
     86 #endif
     87 
     88 #include <sys/param.h>
     89 #include <sys/systm.h>
     90 #include <sys/namei.h>
     91 #include <sys/kernel.h>
     92 #include <sys/resourcevar.h>
     93 #include <sys/file.h>
     94 #include <sys/stat.h>
     95 #include <sys/buf.h>
     96 #include <sys/proc.h>
     97 #include <sys/vnode.h>
     98 #include <sys/mount.h>
     99 #include <sys/kauth.h>
    100 #include <sys/syslog.h>
    101 
    102 #include <miscfs/specfs/specdev.h>
    103 #include <miscfs/fifofs/fifo.h>
    104 
    105 #include <ufs/ufs/inode.h>
    106 #include <ufs/ufs/dir.h>
    107 #include <ufs/ufs/ufsmount.h>
    108 #include <ufs/ufs/ufs_extern.h>
    109 
    110 #include <ufs/lfs/lfs.h>
    111 #include <ufs/lfs/lfs_extern.h>
    112 
    113 #include <uvm/uvm.h>
    114 #include <uvm/uvm_extern.h>
    115 
    116 MALLOC_DEFINE(M_SEGMENT, "LFS segment", "Segment for LFS");
    117 
    118 extern int count_lock_queue(void);
    119 extern struct simplelock vnode_free_list_slock;		/* XXX */
    120 extern struct simplelock bqueue_slock;			/* XXX */
    121 
    122 static void lfs_generic_callback(struct buf *, void (*)(struct buf *));
    123 static void lfs_free_aiodone(struct buf *);
    124 static void lfs_super_aiodone(struct buf *);
    125 static void lfs_cluster_aiodone(struct buf *);
    126 static void lfs_cluster_callback(struct buf *);
    127 
    128 /*
    129  * Determine if it's OK to start a partial in this segment, or if we need
    130  * to go on to a new segment.
    131  */
    132 #define	LFS_PARTIAL_FITS(fs) \
    133 	((fs)->lfs_fsbpseg - ((fs)->lfs_offset - (fs)->lfs_curseg) > \
    134 	fragstofsb((fs), (fs)->lfs_frag))
    135 
    136 /*
    137  * Figure out whether we should do a checkpoint write or go ahead with
    138  * an ordinary write.
    139  */
    140 #define LFS_SHOULD_CHECKPOINT(fs, flags) \
    141         ((flags & SEGM_CLEAN) == 0 &&					\
    142 	  ((fs->lfs_nactive > LFS_MAX_ACTIVE ||				\
    143 	    (flags & SEGM_CKP) ||					\
    144 	    fs->lfs_nclean < LFS_MAX_ACTIVE)))
    145 
    146 int	 lfs_match_fake(struct lfs *, struct buf *);
    147 void	 lfs_newseg(struct lfs *);
    148 /* XXX ondisk32 */
    149 void	 lfs_shellsort(struct buf **, int32_t *, int, int);
    150 void	 lfs_supercallback(struct buf *);
    151 void	 lfs_updatemeta(struct segment *);
    152 void	 lfs_writesuper(struct lfs *, daddr_t);
    153 int	 lfs_writevnodes(struct lfs *fs, struct mount *mp,
    154 	    struct segment *sp, int dirops);
    155 
    156 int	lfs_allclean_wakeup;		/* Cleaner wakeup address. */
    157 int	lfs_writeindir = 1;		/* whether to flush indir on non-ckp */
    158 int	lfs_clean_vnhead = 0;		/* Allow freeing to head of vn list */
    159 int	lfs_dirvcount = 0;		/* # active dirops */
    160 
    161 /* Statistics Counters */
    162 int lfs_dostats = 1;
    163 struct lfs_stats lfs_stats;
    164 
    165 /* op values to lfs_writevnodes */
    166 #define	VN_REG		0
    167 #define	VN_DIROP	1
    168 #define	VN_EMPTY	2
    169 #define VN_CLEAN	3
    170 
    171 /*
    172  * XXX KS - Set modification time on the Ifile, so the cleaner can
    173  * read the fs mod time off of it.  We don't set IN_UPDATE here,
    174  * since we don't really need this to be flushed to disk (and in any
    175  * case that wouldn't happen to the Ifile until we checkpoint).
    176  */
    177 void
    178 lfs_imtime(struct lfs *fs)
    179 {
    180 	struct timespec ts;
    181 	struct inode *ip;
    182 
    183 	ASSERT_MAYBE_SEGLOCK(fs);
    184 	vfs_timestamp(&ts);
    185 	ip = VTOI(fs->lfs_ivnode);
    186 	ip->i_ffs1_mtime = ts.tv_sec;
    187 	ip->i_ffs1_mtimensec = ts.tv_nsec;
    188 }
    189 
    190 /*
    191  * Ifile and meta data blocks are not marked busy, so segment writes MUST be
    192  * single threaded.  Currently, there are two paths into lfs_segwrite, sync()
    193  * and getnewbuf().  They both mark the file system busy.  Lfs_vflush()
    194  * explicitly marks the file system busy.  So lfs_segwrite is safe.  I think.
    195  */
    196 
    197 #define IS_FLUSHING(fs,vp)  ((fs)->lfs_flushvp == (vp))
    198 
    199 int
    200 lfs_vflush(struct vnode *vp)
    201 {
    202 	struct inode *ip;
    203 	struct lfs *fs;
    204 	struct segment *sp;
    205 	struct buf *bp, *nbp, *tbp, *tnbp;
    206 	int error, s;
    207 	int flushed;
    208 	int relock;
    209 	int loopcount;
    210 
    211 	ip = VTOI(vp);
    212 	fs = VFSTOUFS(vp->v_mount)->um_lfs;
    213 	relock = 0;
    214 
    215     top:
    216 	ASSERT_NO_SEGLOCK(fs);
    217 	if (ip->i_flag & IN_CLEANING) {
    218 		ivndebug(vp,"vflush/in_cleaning");
    219 		LFS_CLR_UINO(ip, IN_CLEANING);
    220 		LFS_SET_UINO(ip, IN_MODIFIED);
    221 
    222 		/*
    223 		 * Toss any cleaning buffers that have real counterparts
    224 		 * to avoid losing new data.
    225 		 */
    226 		s = splbio();
    227 		for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
    228 			nbp = LIST_NEXT(bp, b_vnbufs);
    229 			if (!LFS_IS_MALLOC_BUF(bp))
    230 				continue;
    231 			/*
    232 			 * Look for pages matching the range covered
    233 			 * by cleaning blocks.  It's okay if more dirty
    234 			 * pages appear, so long as none disappear out
    235 			 * from under us.
    236 			 */
    237 			if (bp->b_lblkno > 0 && vp->v_type == VREG &&
    238 			    vp != fs->lfs_ivnode) {
    239 				struct vm_page *pg;
    240 				voff_t off;
    241 
    242 				simple_lock(&vp->v_interlock);
    243 				for (off = lblktosize(fs, bp->b_lblkno);
    244 				     off < lblktosize(fs, bp->b_lblkno + 1);
    245 				     off += PAGE_SIZE) {
    246 					pg = uvm_pagelookup(&vp->v_uobj, off);
    247 					if (pg == NULL)
    248 						continue;
    249 					if ((pg->flags & PG_CLEAN) == 0 ||
    250 					    pmap_is_modified(pg)) {
    251 						fs->lfs_avail += btofsb(fs,
    252 							bp->b_bcount);
    253 						wakeup(&fs->lfs_avail);
    254 						lfs_freebuf(fs, bp);
    255 						bp = NULL;
    256 						simple_unlock(&vp->v_interlock);
    257 						goto nextbp;
    258 					}
    259 				}
    260 				simple_unlock(&vp->v_interlock);
    261 			}
    262 			for (tbp = LIST_FIRST(&vp->v_dirtyblkhd); tbp;
    263 			    tbp = tnbp)
    264 			{
    265 				tnbp = LIST_NEXT(tbp, b_vnbufs);
    266 				if (tbp->b_vp == bp->b_vp
    267 				   && tbp->b_lblkno == bp->b_lblkno
    268 				   && tbp != bp)
    269 				{
    270 					fs->lfs_avail += btofsb(fs,
    271 						bp->b_bcount);
    272 					wakeup(&fs->lfs_avail);
    273 					lfs_freebuf(fs, bp);
    274 					bp = NULL;
    275 					break;
    276 				}
    277 			}
    278 		    nextbp:
    279 			;
    280 		}
    281 		splx(s);
    282 	}
    283 
    284 	/* If the node is being written, wait until that is done */
    285 	simple_lock(&vp->v_interlock);
    286 	s = splbio();
    287 	if (WRITEINPROG(vp)) {
    288 		ivndebug(vp,"vflush/writeinprog");
    289 		ltsleep(vp, (PRIBIO+1), "lfs_vw", 0, &vp->v_interlock);
    290 	}
    291 	splx(s);
    292 	simple_unlock(&vp->v_interlock);
    293 
    294 	/* Protect against VXLOCK deadlock in vinvalbuf() */
    295 	lfs_seglock(fs, SEGM_SYNC);
    296 
    297 	/* If we're supposed to flush a freed inode, just toss it */
    298 	if (ip->i_lfs_iflags & LFSI_DELETED) {
    299 		DLOG((DLOG_VNODE, "lfs_vflush: ino %d freed, not flushing\n",
    300 		      ip->i_number));
    301 		s = splbio();
    302 		/* Drain v_numoutput */
    303 		simple_lock(&global_v_numoutput_slock);
    304 		while (vp->v_numoutput > 0) {
    305 			vp->v_flag |= VBWAIT;
    306 			ltsleep(&vp->v_numoutput, PRIBIO + 1, "lfs_vf4", 0,
    307 				&global_v_numoutput_slock);
    308 		}
    309 		simple_unlock(&global_v_numoutput_slock);
    310 		KASSERT(vp->v_numoutput == 0);
    311 
    312 		for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
    313 			nbp = LIST_NEXT(bp, b_vnbufs);
    314 
    315 			KASSERT((bp->b_flags & B_GATHERED) == 0);
    316 			if (bp->b_flags & B_DELWRI) { /* XXX always true? */
    317 				fs->lfs_avail += btofsb(fs, bp->b_bcount);
    318 				wakeup(&fs->lfs_avail);
    319 			}
    320 			/* Copied from lfs_writeseg */
    321 			if (bp->b_flags & B_CALL) {
    322 				biodone(bp);
    323 			} else {
    324 				bremfree(bp);
    325 				LFS_UNLOCK_BUF(bp);
    326 				bp->b_flags &= ~(B_ERROR | B_READ | B_DELWRI |
    327 					 B_GATHERED);
    328 				bp->b_flags |= B_DONE;
    329 				reassignbuf(bp, vp);
    330 				brelse(bp);
    331 			}
    332 		}
    333 		splx(s);
    334 		LFS_CLR_UINO(ip, IN_CLEANING);
    335 		LFS_CLR_UINO(ip, IN_MODIFIED | IN_ACCESSED);
    336 		ip->i_flag &= ~IN_ALLMOD;
    337 		DLOG((DLOG_VNODE, "lfs_vflush: done not flushing ino %d\n",
    338 		      ip->i_number));
    339 		lfs_segunlock(fs);
    340 
    341 		KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
    342 
    343 		return 0;
    344 	}
    345 
    346 	fs->lfs_flushvp = vp;
    347 	if (LFS_SHOULD_CHECKPOINT(fs, fs->lfs_sp->seg_flags)) {
    348 		error = lfs_segwrite(vp->v_mount, SEGM_CKP | SEGM_SYNC);
    349 		fs->lfs_flushvp = NULL;
    350 		KASSERT(fs->lfs_flushvp_fakevref == 0);
    351 		lfs_segunlock(fs);
    352 
    353 		/* Make sure that any pending buffers get written */
    354 		s = splbio();
    355 		simple_lock(&global_v_numoutput_slock);
    356 		while (vp->v_numoutput > 0) {
    357 			vp->v_flag |= VBWAIT;
    358 			ltsleep(&vp->v_numoutput, PRIBIO + 1, "lfs_vf3", 0,
    359 				&global_v_numoutput_slock);
    360 		}
    361 		simple_unlock(&global_v_numoutput_slock);
    362 		splx(s);
    363 
    364 		KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
    365 		KASSERT(vp->v_numoutput == 0);
    366 
    367 		return error;
    368 	}
    369 	sp = fs->lfs_sp;
    370 
    371 	flushed = 0;
    372 	if (VPISEMPTY(vp)) {
    373 		lfs_writevnodes(fs, vp->v_mount, sp, VN_EMPTY);
    374 		++flushed;
    375 	} else if ((ip->i_flag & IN_CLEANING) &&
    376 		  (fs->lfs_sp->seg_flags & SEGM_CLEAN)) {
    377 		ivndebug(vp,"vflush/clean");
    378 		lfs_writevnodes(fs, vp->v_mount, sp, VN_CLEAN);
    379 		++flushed;
    380 	} else if (lfs_dostats) {
    381 		if (!VPISEMPTY(vp) || (VTOI(vp)->i_flag & IN_ALLMOD))
    382 			++lfs_stats.vflush_invoked;
    383 		ivndebug(vp,"vflush");
    384 	}
    385 
    386 #ifdef DIAGNOSTIC
    387 	if (vp->v_flag & VDIROP) {
    388 		DLOG((DLOG_VNODE, "lfs_vflush: flushing VDIROP\n"));
    389 		/* panic("lfs_vflush: VDIROP being flushed...this can\'t happen"); */
    390 	}
    391 	if (vp->v_usecount < 0) {
    392 		printf("usecount=%ld\n", (long)vp->v_usecount);
    393 		panic("lfs_vflush: usecount<0");
    394 	}
    395 #endif
    396 
    397 	do {
    398 		loopcount = 0;
    399 		do {
    400 			if (LIST_FIRST(&vp->v_dirtyblkhd) != NULL) {
    401 				relock = lfs_writefile(fs, sp, vp);
    402 				if (relock) {
    403 					/*
    404 					 * Might have to wait for the
    405 					 * cleaner to run; but we're
    406 					 * still not done with this vnode.
    407 					 */
    408 					KDASSERT(ip->i_number != LFS_IFILE_INUM);
    409 					lfs_writeinode(fs, sp, ip);
    410 					LFS_SET_UINO(ip, IN_MODIFIED);
    411 					lfs_writeseg(fs, sp);
    412 					lfs_segunlock(fs);
    413 					lfs_segunlock_relock(fs);
    414 					goto top;
    415 				}
    416 			}
    417 			/*
    418 			 * If we begin a new segment in the middle of writing
    419 			 * the Ifile, it creates an inconsistent checkpoint,
    420 			 * since the Ifile information for the new segment
    421 			 * is not up-to-date.  Take care of this here by
    422 			 * sending the Ifile through again in case there
    423 			 * are newly dirtied blocks.  But wait, there's more!
    424 			 * This second Ifile write could *also* cross a segment
    425 			 * boundary, if the first one was large.  The second
    426 			 * one is guaranteed to be no more than 8 blocks,
    427 			 * though (two segment blocks and supporting indirects)
    428 			 * so the third write *will not* cross the boundary.
    429 			 */
    430 			if (vp == fs->lfs_ivnode) {
    431 				lfs_writefile(fs, sp, vp);
    432 				lfs_writefile(fs, sp, vp);
    433 			}
    434 #ifdef DEBUG
    435 			if (++loopcount > 1)
    436 				printf("lfs_vflush: loopcount=%d\n", loopcount);
    437 #endif
    438 		} while (lfs_writeinode(fs, sp, ip));
    439 	} while (lfs_writeseg(fs, sp) && ip->i_number == LFS_IFILE_INUM);
    440 
    441 	if (lfs_dostats) {
    442 		++lfs_stats.nwrites;
    443 		if (sp->seg_flags & SEGM_SYNC)
    444 			++lfs_stats.nsync_writes;
    445 		if (sp->seg_flags & SEGM_CKP)
    446 			++lfs_stats.ncheckpoints;
    447 	}
    448 	/*
    449 	 * If we were called from somewhere that has already held the seglock
    450 	 * (e.g., lfs_markv()), the lfs_segunlock will not wait for
    451 	 * the write to complete because we are still locked.
    452 	 * Since lfs_vflush() must return the vnode with no dirty buffers,
    453 	 * we must explicitly wait, if that is the case.
    454 	 *
    455 	 * We compare the iocount against 1, not 0, because it is
    456 	 * artificially incremented by lfs_seglock().
    457 	 */
    458 	simple_lock(&fs->lfs_interlock);
    459 	if (fs->lfs_seglock > 1) {
    460 		while (fs->lfs_iocount > 1)
    461 			(void)ltsleep(&fs->lfs_iocount, PRIBIO + 1,
    462 				     "lfs_vflush", 0, &fs->lfs_interlock);
    463 	}
    464 	simple_unlock(&fs->lfs_interlock);
    465 
    466 	lfs_segunlock(fs);
    467 
    468 	/* Wait for these buffers to be recovered by aiodoned */
    469 	s = splbio();
    470 	simple_lock(&global_v_numoutput_slock);
    471 	while (vp->v_numoutput > 0) {
    472 		vp->v_flag |= VBWAIT;
    473 		ltsleep(&vp->v_numoutput, PRIBIO + 1, "lfs_vf2", 0,
    474 			&global_v_numoutput_slock);
    475 	}
    476 	simple_unlock(&global_v_numoutput_slock);
    477 	splx(s);
    478 
    479 	KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
    480 	KASSERT(vp->v_numoutput == 0);
    481 
    482 	fs->lfs_flushvp = NULL;
    483 	KASSERT(fs->lfs_flushvp_fakevref == 0);
    484 
    485 	return (0);
    486 }
    487 
    488 int
    489 lfs_writevnodes(struct lfs *fs, struct mount *mp, struct segment *sp, int op)
    490 {
    491 	struct inode *ip;
    492 	struct vnode *vp, *nvp;
    493 	int inodes_written = 0, only_cleaning;
    494 	int error = 0;
    495 
    496 	ASSERT_SEGLOCK(fs);
    497 #ifndef LFS_NO_BACKVP_HACK
    498 	/* BEGIN HACK */
    499 #define	VN_OFFSET	\
    500 	(((caddr_t)&LIST_NEXT(vp, v_mntvnodes)) - (caddr_t)vp)
    501 #define	BACK_VP(VP)	\
    502 	((struct vnode *)(((caddr_t)(VP)->v_mntvnodes.le_prev) - VN_OFFSET))
    503 #define	BEG_OF_VLIST	\
    504 	((struct vnode *)(((caddr_t)&LIST_FIRST(&mp->mnt_vnodelist)) \
    505 	- VN_OFFSET))
    506 
    507 	/* Find last vnode. */
    508  loop:	for (vp = LIST_FIRST(&mp->mnt_vnodelist);
    509 	     vp && LIST_NEXT(vp, v_mntvnodes) != NULL;
    510 	     vp = LIST_NEXT(vp, v_mntvnodes));
    511 	for (; vp && vp != BEG_OF_VLIST; vp = nvp) {
    512 		nvp = BACK_VP(vp);
    513 #else
    514 	loop:
    515 	for (vp = LIST_FIRST(&mp->mnt_vnodelist); vp; vp = nvp) {
    516 		nvp = LIST_NEXT(vp, v_mntvnodes);
    517 #endif
    518 		/*
    519 		 * If the vnode that we are about to sync is no longer
    520 		 * associated with this mount point, start over.
    521 		 */
    522 		if (vp->v_mount != mp) {
    523 			DLOG((DLOG_VNODE, "lfs_writevnodes: starting over\n"));
    524 			/*
    525 			 * After this, pages might be busy
    526 			 * due to our own previous putpages.
    527 			 * Start actual segment write here to avoid deadlock.
    528 			 */
    529 			(void)lfs_writeseg(fs, sp);
    530 			goto loop;
    531 		}
    532 
    533 		if (vp->v_type == VNON) {
    534 			continue;
    535 		}
    536 
    537 		ip = VTOI(vp);
    538 		if ((op == VN_DIROP && !(vp->v_flag & VDIROP)) ||
    539 		    (op != VN_DIROP && op != VN_CLEAN &&
    540 		    (vp->v_flag & VDIROP))) {
    541 			vndebug(vp,"dirop");
    542 			continue;
    543 		}
    544 
    545 		if (op == VN_EMPTY && !VPISEMPTY(vp)) {
    546 			vndebug(vp,"empty");
    547 			continue;
    548 		}
    549 
    550 		if (op == VN_CLEAN && ip->i_number != LFS_IFILE_INUM
    551 		   && vp != fs->lfs_flushvp
    552 		   && !(ip->i_flag & IN_CLEANING)) {
    553 			vndebug(vp,"cleaning");
    554 			continue;
    555 		}
    556 
    557 		if (lfs_vref(vp)) {
    558 			vndebug(vp,"vref");
    559 			continue;
    560 		}
    561 
    562 		only_cleaning = 0;
    563 		/*
    564 		 * Write the inode/file if dirty and it's not the IFILE.
    565 		 */
    566 		if ((ip->i_flag & IN_ALLMOD) || !VPISEMPTY(vp)) {
    567 			only_cleaning =
    568 			    ((ip->i_flag & IN_ALLMOD) == IN_CLEANING);
    569 
    570 			if (ip->i_number != LFS_IFILE_INUM) {
    571 				error = lfs_writefile(fs, sp, vp);
    572 				if (error) {
    573 					lfs_vunref(vp);
    574 					if (error == EAGAIN) {
    575 						/*
    576 						 * This error from lfs_putpages
    577 						 * indicates we need to drop
    578 						 * the segment lock and start
    579 						 * over after the cleaner has
    580 						 * had a chance to run.
    581 						 */
    582 						lfs_writeinode(fs, sp, ip);
    583 						lfs_writeseg(fs, sp);
    584 						if (!VPISEMPTY(vp) &&
    585 						    !WRITEINPROG(vp) &&
    586 						    !(ip->i_flag & IN_ALLMOD))
    587 							LFS_SET_UINO(ip, IN_MODIFIED);
    588 						break;
    589 					}
    590 					error = 0; /* XXX not quite right */
    591 					continue;
    592 				}
    593 
    594 				if (!VPISEMPTY(vp)) {
    595 					if (WRITEINPROG(vp)) {
    596 						ivndebug(vp,"writevnodes/write2");
    597 					} else if (!(ip->i_flag & IN_ALLMOD)) {
    598 						LFS_SET_UINO(ip, IN_MODIFIED);
    599 					}
    600 				}
    601 				(void) lfs_writeinode(fs, sp, ip);
    602 				inodes_written++;
    603 			}
    604 		}
    605 
    606 		if (lfs_clean_vnhead && only_cleaning)
    607 			lfs_vunref_head(vp);
    608 		else
    609 			lfs_vunref(vp);
    610 	}
    611 	return error;
    612 }
    613 
    614 /*
    615  * Do a checkpoint.
    616  */
    617 int
    618 lfs_segwrite(struct mount *mp, int flags)
    619 {
    620 	struct buf *bp;
    621 	struct inode *ip;
    622 	struct lfs *fs;
    623 	struct segment *sp;
    624 	struct vnode *vp;
    625 	SEGUSE *segusep;
    626 	int do_ckp, did_ckp, error, s;
    627 	unsigned n, segleft, maxseg, sn, i, curseg;
    628 	int writer_set = 0;
    629 	int dirty;
    630 	int redo;
    631 	int um_error;
    632 	int loopcount;
    633 
    634 	fs = VFSTOUFS(mp)->um_lfs;
    635 	ASSERT_MAYBE_SEGLOCK(fs);
    636 
    637 	if (fs->lfs_ronly)
    638 		return EROFS;
    639 
    640 	lfs_imtime(fs);
    641 
    642 	/*
    643 	 * Allocate a segment structure and enough space to hold pointers to
    644 	 * the maximum possible number of buffers which can be described in a
    645 	 * single summary block.
    646 	 */
    647 	do_ckp = LFS_SHOULD_CHECKPOINT(fs, flags);
    648 
    649 	lfs_seglock(fs, flags | (do_ckp ? SEGM_CKP : 0));
    650 	sp = fs->lfs_sp;
    651 	if (sp->seg_flags & (SEGM_CLEAN | SEGM_CKP))
    652 		do_ckp = 1;
    653 
    654 	/*
    655 	 * If lfs_flushvp is non-NULL, we are called from lfs_vflush,
    656 	 * in which case we have to flush *all* buffers off of this vnode.
    657 	 * We don't care about other nodes, but write any non-dirop nodes
    658 	 * anyway in anticipation of another getnewvnode().
    659 	 *
    660 	 * If we're cleaning we only write cleaning and ifile blocks, and
    661 	 * no dirops, since otherwise we'd risk corruption in a crash.
    662 	 */
    663 	if (sp->seg_flags & SEGM_CLEAN)
    664 		lfs_writevnodes(fs, mp, sp, VN_CLEAN);
    665 	else if (!(sp->seg_flags & SEGM_FORCE_CKP)) {
    666 		do {
    667 			um_error = lfs_writevnodes(fs, mp, sp, VN_REG);
    668 			if (!fs->lfs_dirops || !fs->lfs_flushvp) {
    669 				if (!writer_set) {
    670 					lfs_writer_enter(fs, "lfs writer");
    671 					writer_set = 1;
    672 				}
    673 				error = lfs_writevnodes(fs, mp, sp, VN_DIROP);
    674 				if (um_error == 0)
    675 					um_error = error;
    676 				/* In case writevnodes errored out */
    677 				lfs_flush_dirops(fs);
    678 				((SEGSUM *)(sp->segsum))->ss_flags &= ~(SS_CONT);
    679 				lfs_finalize_fs_seguse(fs);
    680 			}
    681 			if (do_ckp && um_error) {
    682 				lfs_segunlock_relock(fs);
    683 				sp = fs->lfs_sp;
    684 			}
    685 		} while (do_ckp && um_error != 0);
    686 	}
    687 
    688 	/*
    689 	 * If we are doing a checkpoint, mark everything since the
    690 	 * last checkpoint as no longer ACTIVE.
    691 	 */
    692 	if (do_ckp || fs->lfs_doifile) {
    693 		segleft = fs->lfs_nseg;
    694 		curseg = 0;
    695 		for (n = 0; n < fs->lfs_segtabsz; n++) {
    696 			dirty = 0;
    697 			if (bread(fs->lfs_ivnode,
    698 			    fs->lfs_cleansz + n, fs->lfs_bsize, NOCRED, &bp))
    699 				panic("lfs_segwrite: ifile read");
    700 			segusep = (SEGUSE *)bp->b_data;
    701 			maxseg = min(segleft, fs->lfs_sepb);
    702 			for (i = 0; i < maxseg; i++) {
    703 				sn = curseg + i;
    704 				if (sn != dtosn(fs, fs->lfs_curseg) &&
    705 				    segusep->su_flags & SEGUSE_ACTIVE) {
    706 					segusep->su_flags &= ~SEGUSE_ACTIVE;
    707 					--fs->lfs_nactive;
    708 					++dirty;
    709 				}
    710 				fs->lfs_suflags[fs->lfs_activesb][sn] =
    711 					segusep->su_flags;
    712 				if (fs->lfs_version > 1)
    713 					++segusep;
    714 				else
    715 					segusep = (SEGUSE *)
    716 						((SEGUSE_V1 *)segusep + 1);
    717 			}
    718 
    719 			if (dirty)
    720 				error = LFS_BWRITE_LOG(bp); /* Ifile */
    721 			else
    722 				brelse(bp);
    723 			segleft -= fs->lfs_sepb;
    724 			curseg += fs->lfs_sepb;
    725 		}
    726 	}
    727 
    728 	LOCK_ASSERT(LFS_SEGLOCK_HELD(fs));
    729 
    730 	did_ckp = 0;
    731 	if (do_ckp || fs->lfs_doifile) {
    732 		vp = fs->lfs_ivnode;
    733 		vn_lock(vp, LK_EXCLUSIVE);
    734 		loopcount = 0;
    735 		do {
    736 #ifdef DEBUG
    737 			LFS_ENTER_LOG("pretend", __FILE__, __LINE__, 0, 0, curproc->p_pid);
    738 #endif
    739 			simple_lock(&fs->lfs_interlock);
    740 			fs->lfs_flags &= ~LFS_IFDIRTY;
    741 			simple_unlock(&fs->lfs_interlock);
    742 
    743 			ip = VTOI(vp);
    744 
    745 			if (LIST_FIRST(&vp->v_dirtyblkhd) != NULL) {
    746 				/*
    747 				 * Ifile has no pages, so we don't need
    748 				 * to check error return here.
    749 				 */
    750 				lfs_writefile(fs, sp, vp);
    751 				/*
    752 				 * Ensure the Ifile takes the current segment
    753 				 * into account.  See comment in lfs_vflush.
    754 				 */
    755 				lfs_writefile(fs, sp, vp);
    756 				lfs_writefile(fs, sp, vp);
    757 			}
    758 
    759 			if (ip->i_flag & IN_ALLMOD)
    760 				++did_ckp;
    761 #if 0
    762 			redo = (do_ckp ? lfs_writeinode(fs, sp, ip) : 0);
    763 #else
    764 			redo = lfs_writeinode(fs, sp, ip);
    765 #endif
    766 			redo += lfs_writeseg(fs, sp);
    767 			simple_lock(&fs->lfs_interlock);
    768 			redo += (fs->lfs_flags & LFS_IFDIRTY);
    769 			simple_unlock(&fs->lfs_interlock);
    770 #ifdef DEBUG
    771 			if (++loopcount > 1)
    772 				printf("lfs_segwrite: loopcount=%d\n",
    773 					loopcount);
    774 #endif
    775 		} while (redo && do_ckp);
    776 
    777 		/*
    778 		 * Unless we are unmounting, the Ifile may continue to have
    779 		 * dirty blocks even after a checkpoint, due to changes to
    780 		 * inodes' atime.  If we're checkpointing, it's "impossible"
    781 		 * for other parts of the Ifile to be dirty after the loop
    782 		 * above, since we hold the segment lock.
    783 		 */
    784 		s = splbio();
    785 		if (LIST_EMPTY(&vp->v_dirtyblkhd)) {
    786 			LFS_CLR_UINO(ip, IN_ALLMOD);
    787 		}
    788 #ifdef DIAGNOSTIC
    789 		else if (do_ckp) {
    790 			int do_panic = 0;
    791 			LIST_FOREACH(bp, &vp->v_dirtyblkhd, b_vnbufs) {
    792 				if (bp->b_lblkno < fs->lfs_cleansz +
    793 				    fs->lfs_segtabsz &&
    794 				    !(bp->b_flags & B_GATHERED)) {
    795 					printf("ifile lbn %ld still dirty (flags %lx)\n",
    796 						(long)bp->b_lblkno,
    797 						(long)bp->b_flags);
    798 					++do_panic;
    799 				}
    800 			}
    801 			if (do_panic)
    802 				panic("dirty blocks");
    803 		}
    804 #endif
    805 		splx(s);
    806 		VOP_UNLOCK(vp, 0);
    807 	} else {
    808 		(void) lfs_writeseg(fs, sp);
    809 	}
    810 
    811 	/* Note Ifile no longer needs to be written */
    812 	fs->lfs_doifile = 0;
    813 	if (writer_set)
    814 		lfs_writer_leave(fs);
    815 
    816 	/*
    817 	 * If we didn't write the Ifile, we didn't really do anything.
    818 	 * That means that (1) there is a checkpoint on disk and (2)
    819 	 * nothing has changed since it was written.
    820 	 *
    821 	 * Take the flags off of the segment so that lfs_segunlock
    822 	 * doesn't have to write the superblock either.
    823 	 */
    824 	if (do_ckp && !did_ckp) {
    825 		sp->seg_flags &= ~SEGM_CKP;
    826 	}
    827 
    828 	if (lfs_dostats) {
    829 		++lfs_stats.nwrites;
    830 		if (sp->seg_flags & SEGM_SYNC)
    831 			++lfs_stats.nsync_writes;
    832 		if (sp->seg_flags & SEGM_CKP)
    833 			++lfs_stats.ncheckpoints;
    834 	}
    835 	lfs_segunlock(fs);
    836 	return (0);
    837 }
    838 
    839 /*
    840  * Write the dirty blocks associated with a vnode.
    841  */
    842 int
    843 lfs_writefile(struct lfs *fs, struct segment *sp, struct vnode *vp)
    844 {
    845 	struct finfo *fip;
    846 	struct inode *ip;
    847 	int i, frag;
    848 	int error;
    849 
    850 	ASSERT_SEGLOCK(fs);
    851 	error = 0;
    852 	ip = VTOI(vp);
    853 
    854 	fip = sp->fip;
    855 	lfs_acquire_finfo(fs, ip->i_number, ip->i_gen);
    856 
    857 	if (vp->v_flag & VDIROP)
    858 		((SEGSUM *)(sp->segsum))->ss_flags |= (SS_DIROP|SS_CONT);
    859 
    860 	if (sp->seg_flags & SEGM_CLEAN) {
    861 		lfs_gather(fs, sp, vp, lfs_match_fake);
    862 		/*
    863 		 * For a file being flushed, we need to write *all* blocks.
    864 		 * This means writing the cleaning blocks first, and then
    865 		 * immediately following with any non-cleaning blocks.
    866 		 * The same is true of the Ifile since checkpoints assume
    867 		 * that all valid Ifile blocks are written.
    868 		 */
    869 		if (IS_FLUSHING(fs, vp) || vp == fs->lfs_ivnode) {
    870 			lfs_gather(fs, sp, vp, lfs_match_data);
    871 			/*
    872 			 * Don't call VOP_PUTPAGES: if we're flushing,
    873 			 * we've already done it, and the Ifile doesn't
    874 			 * use the page cache.
    875 			 */
    876 		}
    877 	} else {
    878 		lfs_gather(fs, sp, vp, lfs_match_data);
    879 		/*
    880 		 * If we're flushing, we've already called VOP_PUTPAGES
    881 		 * so don't do it again.  Otherwise, we want to write
    882 		 * everything we've got.
    883 		 */
    884 		if (!IS_FLUSHING(fs, vp)) {
    885 			simple_lock(&vp->v_interlock);
    886 			error = VOP_PUTPAGES(vp, 0, 0,
    887 				PGO_CLEANIT | PGO_ALLPAGES | PGO_LOCKED);
    888 		}
    889 	}
    890 
    891 	/*
    892 	 * It may not be necessary to write the meta-data blocks at this point,
    893 	 * as the roll-forward recovery code should be able to reconstruct the
    894 	 * list.
    895 	 *
    896 	 * We have to write them anyway, though, under two conditions: (1) the
    897 	 * vnode is being flushed (for reuse by vinvalbuf); or (2) we are
    898 	 * checkpointing.
    899 	 *
    900 	 * BUT if we are cleaning, we might have indirect blocks that refer to
    901 	 * new blocks not being written yet, in addition to fragments being
    902 	 * moved out of a cleaned segment.  If that is the case, don't
    903 	 * write the indirect blocks, or the finfo will have a small block
    904 	 * in the middle of it!
    905 	 * XXX in this case isn't the inode size wrong too?
    906 	 */
    907 	frag = 0;
    908 	if (sp->seg_flags & SEGM_CLEAN) {
    909 		for (i = 0; i < NDADDR; i++)
    910 			if (ip->i_lfs_fragsize[i] > 0 &&
    911 			    ip->i_lfs_fragsize[i] < fs->lfs_bsize)
    912 				++frag;
    913 	}
    914 #ifdef DIAGNOSTIC
    915 	if (frag > 1)
    916 		panic("lfs_writefile: more than one fragment!");
    917 #endif
    918 	if (IS_FLUSHING(fs, vp) ||
    919 	    (frag == 0 && (lfs_writeindir || (sp->seg_flags & SEGM_CKP)))) {
    920 		lfs_gather(fs, sp, vp, lfs_match_indir);
    921 		lfs_gather(fs, sp, vp, lfs_match_dindir);
    922 		lfs_gather(fs, sp, vp, lfs_match_tindir);
    923 	}
    924 	fip = sp->fip;
    925 	lfs_release_finfo(fs);
    926 
    927 	return error;
    928 }
    929 
    930 /*
    931  * Update segment accounting to reflect this inode's change of address.
    932  */
    933 static int
    934 lfs_update_iaddr(struct lfs *fs, struct segment *sp, struct inode *ip, daddr_t ndaddr)
    935 {
    936 	struct buf *bp;
    937 	daddr_t daddr;
    938 	IFILE *ifp;
    939 	SEGUSE *sup;
    940 	ino_t ino;
    941 	int redo_ifile, error;
    942 	u_int32_t sn;
    943 
    944 	redo_ifile = 0;
    945 
    946 	/*
    947 	 * If updating the ifile, update the super-block.  Update the disk
    948 	 * address and access times for this inode in the ifile.
    949 	 */
    950 	ino = ip->i_number;
    951 	if (ino == LFS_IFILE_INUM) {
    952 		daddr = fs->lfs_idaddr;
    953 		fs->lfs_idaddr = dbtofsb(fs, ndaddr);
    954 	} else {
    955 		LFS_IENTRY(ifp, fs, ino, bp);
    956 		daddr = ifp->if_daddr;
    957 		ifp->if_daddr = dbtofsb(fs, ndaddr);
    958 		error = LFS_BWRITE_LOG(bp); /* Ifile */
    959 	}
    960 
    961 	/*
    962 	 * If this is the Ifile and lfs_offset is set to the first block
    963 	 * in the segment, dirty the new segment's accounting block
    964 	 * (XXX should already be dirty?) and tell the caller to do it again.
    965 	 */
    966 	if (ip->i_number == LFS_IFILE_INUM) {
    967 		sn = dtosn(fs, fs->lfs_offset);
    968 		if (sntod(fs, sn) + btofsb(fs, fs->lfs_sumsize) ==
    969 		    fs->lfs_offset) {
    970 			LFS_SEGENTRY(sup, fs, sn, bp);
    971 			KASSERT(bp->b_flags & B_DELWRI);
    972 			LFS_WRITESEGENTRY(sup, fs, sn, bp);
    973 			/* fs->lfs_flags |= LFS_IFDIRTY; */
    974 			redo_ifile |= 1;
    975 		}
    976 	}
    977 
    978 	/*
    979 	 * The inode's last address should not be in the current partial
    980 	 * segment, except under exceptional circumstances (lfs_writevnodes
    981 	 * had to start over, and in the meantime more blocks were written
    982 	 * to a vnode).	 Both inodes will be accounted to this segment
    983 	 * in lfs_writeseg so we need to subtract the earlier version
    984 	 * here anyway.	 The segment count can temporarily dip below
    985 	 * zero here; keep track of how many duplicates we have in
    986 	 * "dupino" so we don't panic below.
    987 	 */
    988 	if (daddr >= fs->lfs_lastpseg && daddr <= fs->lfs_offset) {
    989 		++sp->ndupino;
    990 		DLOG((DLOG_SEG, "lfs_writeinode: last inode addr in current pseg "
    991 		      "(ino %d daddr 0x%llx) ndupino=%d\n", ino,
    992 		      (long long)daddr, sp->ndupino));
    993 	}
    994 	/*
    995 	 * Account the inode: it no longer belongs to its former segment,
    996 	 * though it will not belong to the new segment until that segment
    997 	 * is actually written.
    998 	 */
    999 	if (daddr != LFS_UNUSED_DADDR) {
   1000 		u_int32_t oldsn = dtosn(fs, daddr);
   1001 #ifdef DIAGNOSTIC
   1002 		int ndupino = (sp->seg_number == oldsn) ? sp->ndupino : 0;
   1003 #endif
   1004 		LFS_SEGENTRY(sup, fs, oldsn, bp);
   1005 #ifdef DIAGNOSTIC
   1006 		if (sup->su_nbytes +
   1007 		    sizeof (struct ufs1_dinode) * ndupino
   1008 		      < sizeof (struct ufs1_dinode)) {
   1009 			printf("lfs_writeinode: negative bytes "
   1010 			       "(segment %" PRIu32 " short by %d, "
   1011 			       "oldsn=%" PRIu32 ", cursn=%" PRIu32
   1012 			       ", daddr=%" PRId64 ", su_nbytes=%u, "
   1013 			       "ndupino=%d)\n",
   1014 			       dtosn(fs, daddr),
   1015 			       (int)sizeof (struct ufs1_dinode) *
   1016 				   (1 - sp->ndupino) - sup->su_nbytes,
   1017 			       oldsn, sp->seg_number, daddr,
   1018 			       (unsigned int)sup->su_nbytes,
   1019 			       sp->ndupino);
   1020 			panic("lfs_writeinode: negative bytes");
   1021 			sup->su_nbytes = sizeof (struct ufs1_dinode);
   1022 		}
   1023 #endif
   1024 		DLOG((DLOG_SU, "seg %d -= %d for ino %d inode\n",
   1025 		      dtosn(fs, daddr), sizeof (struct ufs1_dinode), ino));
   1026 		sup->su_nbytes -= sizeof (struct ufs1_dinode);
   1027 		redo_ifile |=
   1028 			(ino == LFS_IFILE_INUM && !(bp->b_flags & B_GATHERED));
   1029 		if (redo_ifile) {
   1030 			simple_lock(&fs->lfs_interlock);
   1031 			fs->lfs_flags |= LFS_IFDIRTY;
   1032 			simple_unlock(&fs->lfs_interlock);
   1033 			/* Don't double-account */
   1034 			fs->lfs_idaddr = 0x0;
   1035 		}
   1036 		LFS_WRITESEGENTRY(sup, fs, oldsn, bp); /* Ifile */
   1037 	}
   1038 
   1039 	return redo_ifile;
   1040 }
   1041 
   1042 int
   1043 lfs_writeinode(struct lfs *fs, struct segment *sp, struct inode *ip)
   1044 {
   1045 	struct buf *bp;
   1046 	struct ufs1_dinode *cdp;
   1047 	daddr_t daddr;
   1048 	int32_t *daddrp;	/* XXX ondisk32 */
   1049 	int i, ndx;
   1050 	int redo_ifile = 0;
   1051 	int gotblk = 0;
   1052 	int count;
   1053 
   1054 	ASSERT_SEGLOCK(fs);
   1055 	if (!(ip->i_flag & IN_ALLMOD))
   1056 		return (0);
   1057 
   1058 	/* Can't write ifile when writer is not set */
   1059 	KASSERT(ip->i_number != LFS_IFILE_INUM || fs->lfs_writer > 0 ||
   1060 		(sp->seg_flags & SEGM_CLEAN));
   1061 
   1062 	/*
   1063 	 * If this is the Ifile, see if writing it here will generate a
   1064 	 * temporary misaccounting.  If it will, do the accounting and write
   1065 	 * the blocks, postponing the inode write until the accounting is
   1066 	 * solid.
   1067 	 */
   1068 	count = 0;
   1069 	while (ip->i_number == LFS_IFILE_INUM) {
   1070 		int redo = 0;
   1071 
   1072 		if (sp->idp == NULL && sp->ibp == NULL &&
   1073 		    (sp->seg_bytes_left < fs->lfs_ibsize ||
   1074 		     sp->sum_bytes_left < sizeof(int32_t))) {
   1075 			(void) lfs_writeseg(fs, sp);
   1076 			continue;
   1077 		}
   1078 
   1079 		/* Look for dirty Ifile blocks */
   1080 		LIST_FOREACH(bp, &fs->lfs_ivnode->v_dirtyblkhd, b_vnbufs) {
   1081 			if (!(bp->b_flags & B_GATHERED)) {
   1082 				redo = 1;
   1083 				break;
   1084 			}
   1085 		}
   1086 
   1087 		if (redo == 0)
   1088 			redo = lfs_update_iaddr(fs, sp, ip, 0x0);
   1089 		if (redo == 0)
   1090 			break;
   1091 
   1092 		if (sp->idp) {
   1093 			sp->idp->di_inumber = 0;
   1094 			sp->idp = NULL;
   1095 		}
   1096 		++count;
   1097 		if (count > 1)
   1098 			printf("lfs_writeinode: looping count=%d\n", count);
   1099 		lfs_writefile(fs, sp, fs->lfs_ivnode);
   1100 	}
   1101 
   1102 	/* Allocate a new inode block if necessary. */
   1103 	if ((ip->i_number != LFS_IFILE_INUM || sp->idp == NULL) &&
   1104 	    sp->ibp == NULL) {
   1105 		/* Allocate a new segment if necessary. */
   1106 		if (sp->seg_bytes_left < fs->lfs_ibsize ||
   1107 		    sp->sum_bytes_left < sizeof(int32_t))
   1108 			(void) lfs_writeseg(fs, sp);
   1109 
   1110 		/* Get next inode block. */
   1111 		daddr = fs->lfs_offset;
   1112 		fs->lfs_offset += btofsb(fs, fs->lfs_ibsize);
   1113 		sp->ibp = *sp->cbpp++ =
   1114 			getblk(VTOI(fs->lfs_ivnode)->i_devvp,
   1115 			    fsbtodb(fs, daddr), fs->lfs_ibsize, 0, 0);
   1116 		gotblk++;
   1117 
   1118 		/* Zero out inode numbers */
   1119 		for (i = 0; i < INOPB(fs); ++i)
   1120 			((struct ufs1_dinode *)sp->ibp->b_data)[i].di_inumber =
   1121 			    0;
   1122 
   1123 		++sp->start_bpp;
   1124 		fs->lfs_avail -= btofsb(fs, fs->lfs_ibsize);
   1125 		/* Set remaining space counters. */
   1126 		sp->seg_bytes_left -= fs->lfs_ibsize;
   1127 		sp->sum_bytes_left -= sizeof(int32_t);
   1128 		ndx = fs->lfs_sumsize / sizeof(int32_t) -
   1129 			sp->ninodes / INOPB(fs) - 1;
   1130 		((int32_t *)(sp->segsum))[ndx] = daddr;
   1131 	}
   1132 
   1133 	/* Check VDIROP in case there is a new file with no data blocks */
   1134 	if (ITOV(ip)->v_flag & VDIROP)
   1135 		((SEGSUM *)(sp->segsum))->ss_flags |= (SS_DIROP|SS_CONT);
   1136 
   1137 	/* Update the inode times and copy the inode onto the inode page. */
   1138 	/* XXX kludge --- don't redirty the ifile just to put times on it */
   1139 	if (ip->i_number != LFS_IFILE_INUM)
   1140 		LFS_ITIMES(ip, NULL, NULL, NULL);
   1141 
   1142 	/*
   1143 	 * If this is the Ifile, and we've already written the Ifile in this
   1144 	 * partial segment, just overwrite it (it's not on disk yet) and
   1145 	 * continue.
   1146 	 *
   1147 	 * XXX we know that the bp that we get the second time around has
   1148 	 * already been gathered.
   1149 	 */
   1150 	if (ip->i_number == LFS_IFILE_INUM && sp->idp) {
   1151 		*(sp->idp) = *ip->i_din.ffs1_din;
   1152 		ip->i_lfs_osize = ip->i_size;
   1153 		return 0;
   1154 	}
   1155 
   1156 	bp = sp->ibp;
   1157 	cdp = ((struct ufs1_dinode *)bp->b_data) + (sp->ninodes % INOPB(fs));
   1158 	*cdp = *ip->i_din.ffs1_din;
   1159 
   1160 	/*
   1161 	 * If cleaning, link counts and directory file sizes cannot change,
   1162 	 * since those would be directory operations---even if the file
   1163 	 * we are writing is marked VDIROP we should write the old values.
   1164 	 * If we're not cleaning, of course, update the values so we get
   1165 	 * current values the next time we clean.
   1166 	 */
   1167 	if (sp->seg_flags & SEGM_CLEAN) {
   1168 		if (ITOV(ip)->v_flag & VDIROP) {
   1169 			cdp->di_nlink = ip->i_lfs_odnlink;
   1170 			/* if (ITOV(ip)->v_type == VDIR) */
   1171 			cdp->di_size = ip->i_lfs_osize;
   1172 		}
   1173 	} else {
   1174 		ip->i_lfs_odnlink = cdp->di_nlink;
   1175 		ip->i_lfs_osize = ip->i_size;
   1176 	}
   1177 
   1178 
   1179 	/* We can finish the segment accounting for truncations now */
   1180 	lfs_finalize_ino_seguse(fs, ip);
   1181 
   1182 	/*
   1183 	 * If we are cleaning, ensure that we don't write UNWRITTEN disk
   1184 	 * addresses to disk; possibly change the on-disk record of
   1185 	 * the inode size, either by reverting to the previous size
   1186 	 * (in the case of cleaning) or by verifying the inode's block
   1187 	 * holdings (in the case of files being allocated as they are being
   1188 	 * written).
   1189 	 * XXX By not writing UNWRITTEN blocks, we are making the lfs_avail
   1190 	 * XXX count on disk wrong by the same amount.	We should be
   1191 	 * XXX able to "borrow" from lfs_avail and return it after the
   1192 	 * XXX Ifile is written.  See also in lfs_writeseg.
   1193 	 */
   1194 
   1195 	/* Check file size based on highest allocated block */
   1196 	if (((ip->i_ffs1_mode & IFMT) == IFREG ||
   1197 	     (ip->i_ffs1_mode & IFMT) == IFDIR) &&
   1198 	    ip->i_size > ((ip->i_lfs_hiblk + 1) << fs->lfs_bshift)) {
   1199 		cdp->di_size = (ip->i_lfs_hiblk + 1) << fs->lfs_bshift;
   1200 		DLOG((DLOG_SEG, "lfs_writeinode: ino %d size %" PRId64 " -> %"
   1201 		      PRId64 "\n", (int)ip->i_number, ip->i_size, cdp->di_size));
   1202 	}
   1203 	if (ip->i_lfs_effnblks != ip->i_ffs1_blocks) {
   1204 		DLOG((DLOG_SEG, "lfs_writeinode: cleansing ino %d eff %d != nblk %d)"
   1205 		      " at %x\n", ip->i_number, ip->i_lfs_effnblks,
   1206 		      ip->i_ffs1_blocks, fs->lfs_offset));
   1207 		for (daddrp = cdp->di_db; daddrp < cdp->di_ib + NIADDR;
   1208 		     daddrp++) {
   1209 			if (*daddrp == UNWRITTEN) {
   1210 				DLOG((DLOG_SEG, "lfs_writeinode: wiping UNWRITTEN\n"));
   1211 				*daddrp = 0;
   1212 			}
   1213 		}
   1214 	}
   1215 
   1216 #ifdef DIAGNOSTIC
   1217 	/*
   1218 	 * Check dinode held blocks against dinode size.
   1219 	 * This should be identical to the check in lfs_vget().
   1220 	 */
   1221 	for (i = (cdp->di_size + fs->lfs_bsize - 1) >> fs->lfs_bshift;
   1222 	     i < NDADDR; i++) {
   1223 		KASSERT(i >= 0);
   1224 		if ((cdp->di_mode & IFMT) == IFLNK)
   1225 			continue;
   1226 		if (((cdp->di_mode & IFMT) == IFBLK ||
   1227 		     (cdp->di_mode & IFMT) == IFCHR) && i == 0)
   1228 			continue;
   1229 		if (cdp->di_db[i] != 0) {
   1230 # ifdef DEBUG
   1231 			lfs_dump_dinode(cdp);
   1232 # endif
   1233 			panic("writing inconsistent inode");
   1234 		}
   1235 	}
   1236 #endif /* DIAGNOSTIC */
   1237 
   1238 	if (ip->i_flag & IN_CLEANING)
   1239 		LFS_CLR_UINO(ip, IN_CLEANING);
   1240 	else {
   1241 		/* XXX IN_ALLMOD */
   1242 		LFS_CLR_UINO(ip, IN_ACCESSED | IN_ACCESS | IN_CHANGE |
   1243 			     IN_UPDATE | IN_MODIFY);
   1244 		if (ip->i_lfs_effnblks == ip->i_ffs1_blocks)
   1245 			LFS_CLR_UINO(ip, IN_MODIFIED);
   1246 		else
   1247 			DLOG((DLOG_VNODE, "lfs_writeinode: ino %d: real blks=%d, "
   1248 			      "eff=%d\n", ip->i_number, ip->i_ffs1_blocks,
   1249 			      ip->i_lfs_effnblks));
   1250 	}
   1251 
   1252 	if (ip->i_number == LFS_IFILE_INUM) {
   1253 		/* We know sp->idp == NULL */
   1254 		sp->idp = ((struct ufs1_dinode *)bp->b_data) +
   1255 			(sp->ninodes % INOPB(fs));
   1256 
   1257 		/* Not dirty any more */
   1258 		simple_lock(&fs->lfs_interlock);
   1259 		fs->lfs_flags &= ~LFS_IFDIRTY;
   1260 		simple_unlock(&fs->lfs_interlock);
   1261 	}
   1262 
   1263 	if (gotblk) {
   1264 		LFS_LOCK_BUF(bp);
   1265 		brelse(bp);
   1266 	}
   1267 
   1268 	/* Increment inode count in segment summary block. */
   1269 	++((SEGSUM *)(sp->segsum))->ss_ninos;
   1270 
   1271 	/* If this page is full, set flag to allocate a new page. */
   1272 	if (++sp->ninodes % INOPB(fs) == 0)
   1273 		sp->ibp = NULL;
   1274 
   1275 	redo_ifile = lfs_update_iaddr(fs, sp, ip, bp->b_blkno);
   1276 
   1277 	KASSERT(redo_ifile == 0);
   1278 	return (redo_ifile);
   1279 }
   1280 
   1281 int
   1282 lfs_gatherblock(struct segment *sp, struct buf *bp, int *sptr)
   1283 {
   1284 	struct lfs *fs;
   1285 	int vers;
   1286 	int j, blksinblk;
   1287 
   1288 	ASSERT_SEGLOCK(sp->fs);
   1289 	/*
   1290 	 * If full, finish this segment.  We may be doing I/O, so
   1291 	 * release and reacquire the splbio().
   1292 	 */
   1293 #ifdef DIAGNOSTIC
   1294 	if (sp->vp == NULL)
   1295 		panic ("lfs_gatherblock: Null vp in segment");
   1296 #endif
   1297 	fs = sp->fs;
   1298 	blksinblk = howmany(bp->b_bcount, fs->lfs_bsize);
   1299 	if (sp->sum_bytes_left < sizeof(int32_t) * blksinblk ||
   1300 	    sp->seg_bytes_left < bp->b_bcount) {
   1301 		if (sptr)
   1302 			splx(*sptr);
   1303 		lfs_updatemeta(sp);
   1304 
   1305 		vers = sp->fip->fi_version;
   1306 		(void) lfs_writeseg(fs, sp);
   1307 
   1308 		/* Add the current file to the segment summary. */
   1309 		lfs_acquire_finfo(fs, VTOI(sp->vp)->i_number, vers);
   1310 
   1311 		if (sptr)
   1312 			*sptr = splbio();
   1313 		return (1);
   1314 	}
   1315 
   1316 	if (bp->b_flags & B_GATHERED) {
   1317 		DLOG((DLOG_SEG, "lfs_gatherblock: already gathered! Ino %d,"
   1318 		      " lbn %" PRId64 "\n",
   1319 		      sp->fip->fi_ino, bp->b_lblkno));
   1320 		return (0);
   1321 	}
   1322 
   1323 	/* Insert into the buffer list, update the FINFO block. */
   1324 	bp->b_flags |= B_GATHERED;
   1325 
   1326 	*sp->cbpp++ = bp;
   1327 	for (j = 0; j < blksinblk; j++) {
   1328 		sp->fip->fi_blocks[sp->fip->fi_nblocks++] = bp->b_lblkno + j;
   1329 		/* This block's accounting moves from lfs_favail to lfs_avail */
   1330 		lfs_deregister_block(sp->vp, bp->b_lblkno + j);
   1331 	}
   1332 
   1333 	sp->sum_bytes_left -= sizeof(int32_t) * blksinblk;
   1334 	sp->seg_bytes_left -= bp->b_bcount;
   1335 	return (0);
   1336 }
   1337 
   1338 int
   1339 lfs_gather(struct lfs *fs, struct segment *sp, struct vnode *vp,
   1340     int (*match)(struct lfs *, struct buf *))
   1341 {
   1342 	struct buf *bp, *nbp;
   1343 	int s, count = 0;
   1344 
   1345 	ASSERT_SEGLOCK(fs);
   1346 	if (vp->v_type == VBLK)
   1347 		return 0;
   1348 	KASSERT(sp->vp == NULL);
   1349 	sp->vp = vp;
   1350 	s = splbio();
   1351 
   1352 #ifndef LFS_NO_BACKBUF_HACK
   1353 /* This is a hack to see if ordering the blocks in LFS makes a difference. */
   1354 # define	BUF_OFFSET	\
   1355 	(((caddr_t)&LIST_NEXT(bp, b_vnbufs)) - (caddr_t)bp)
   1356 # define	BACK_BUF(BP)	\
   1357 	((struct buf *)(((caddr_t)(BP)->b_vnbufs.le_prev) - BUF_OFFSET))
   1358 # define	BEG_OF_LIST	\
   1359 	((struct buf *)(((caddr_t)&LIST_FIRST(&vp->v_dirtyblkhd)) - BUF_OFFSET))
   1360 
   1361 loop:
   1362 	/* Find last buffer. */
   1363 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd);
   1364 	     bp && LIST_NEXT(bp, b_vnbufs) != NULL;
   1365 	     bp = LIST_NEXT(bp, b_vnbufs))
   1366 		/* nothing */;
   1367 	for (; bp && bp != BEG_OF_LIST; bp = nbp) {
   1368 		nbp = BACK_BUF(bp);
   1369 #else /* LFS_NO_BACKBUF_HACK */
   1370 loop:
   1371 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
   1372 		nbp = LIST_NEXT(bp, b_vnbufs);
   1373 #endif /* LFS_NO_BACKBUF_HACK */
   1374 		if ((bp->b_flags & (B_BUSY|B_GATHERED)) || !match(fs, bp)) {
   1375 #ifdef DEBUG
   1376 			if (vp == fs->lfs_ivnode &&
   1377 			    (bp->b_flags & (B_BUSY|B_GATHERED)) == B_BUSY)
   1378 				log(LOG_NOTICE, "lfs_gather: ifile lbn %"
   1379 				      PRId64 " busy (%x) at 0x%x",
   1380 				      bp->b_lblkno, bp->b_flags,
   1381 				      (unsigned)fs->lfs_offset);
   1382 #endif
   1383 			continue;
   1384 		}
   1385 #ifdef DIAGNOSTIC
   1386 # ifdef LFS_USE_B_INVAL
   1387 		if ((bp->b_flags & (B_CALL|B_INVAL)) == B_INVAL) {
   1388 			DLOG((DLOG_SEG, "lfs_gather: lbn %" PRId64
   1389 			      " is B_INVAL\n", bp->b_lblkno));
   1390 			VOP_PRINT(bp->b_vp);
   1391 		}
   1392 # endif /* LFS_USE_B_INVAL */
   1393 		if (!(bp->b_flags & B_DELWRI))
   1394 			panic("lfs_gather: bp not B_DELWRI");
   1395 		if (!(bp->b_flags & B_LOCKED)) {
   1396 			DLOG((DLOG_SEG, "lfs_gather: lbn %" PRId64
   1397 			      " blk %" PRId64 " not B_LOCKED\n",
   1398 			      bp->b_lblkno,
   1399 			      dbtofsb(fs, bp->b_blkno)));
   1400 			VOP_PRINT(bp->b_vp);
   1401 			panic("lfs_gather: bp not B_LOCKED");
   1402 		}
   1403 #endif
   1404 		if (lfs_gatherblock(sp, bp, &s)) {
   1405 			goto loop;
   1406 		}
   1407 		count++;
   1408 	}
   1409 	splx(s);
   1410 	lfs_updatemeta(sp);
   1411 	KASSERT(sp->vp == vp);
   1412 	sp->vp = NULL;
   1413 	return count;
   1414 }
   1415 
   1416 #if DEBUG
   1417 # define DEBUG_OOFF(n) do {						\
   1418 	if (ooff == 0) {						\
   1419 		DLOG((DLOG_SEG, "lfs_updatemeta[%d]: warning: writing " \
   1420 			"ino %d lbn %" PRId64 " at 0x%" PRIx32		\
   1421 			", was 0x0 (or %" PRId64 ")\n",			\
   1422 			(n), ip->i_number, lbn, ndaddr, daddr));	\
   1423 	}								\
   1424 } while (0)
   1425 #else
   1426 # define DEBUG_OOFF(n)
   1427 #endif
   1428 
   1429 /*
   1430  * Change the given block's address to ndaddr, finding its previous
   1431  * location using ufs_bmaparray().
   1432  *
   1433  * Account for this change in the segment table.
   1434  *
   1435  * called with sp == NULL by roll-forwarding code.
   1436  */
   1437 void
   1438 lfs_update_single(struct lfs *fs, struct segment *sp, struct vnode *vp,
   1439     daddr_t lbn, int32_t ndaddr, int size)
   1440 {
   1441 	SEGUSE *sup;
   1442 	struct buf *bp;
   1443 	struct indir a[NIADDR + 2], *ap;
   1444 	struct inode *ip;
   1445 	daddr_t daddr, ooff;
   1446 	int num, error;
   1447 	int bb, osize, obb;
   1448 
   1449 	ASSERT_SEGLOCK(fs);
   1450 	KASSERT(sp == NULL || sp->vp == vp);
   1451 	ip = VTOI(vp);
   1452 
   1453 	error = ufs_bmaparray(vp, lbn, &daddr, a, &num, NULL, NULL);
   1454 	if (error)
   1455 		panic("lfs_updatemeta: ufs_bmaparray returned %d", error);
   1456 
   1457 	daddr = (daddr_t)((int32_t)daddr); /* XXX ondisk32 */
   1458 	KASSERT(daddr <= LFS_MAX_DADDR);
   1459 	if (daddr > 0)
   1460 		daddr = dbtofsb(fs, daddr);
   1461 
   1462 	bb = fragstofsb(fs, numfrags(fs, size));
   1463 	switch (num) {
   1464 	    case 0:
   1465 		    ooff = ip->i_ffs1_db[lbn];
   1466 		    DEBUG_OOFF(0);
   1467 		    if (ooff == UNWRITTEN)
   1468 			    ip->i_ffs1_blocks += bb;
   1469 		    else {
   1470 			    /* possible fragment truncation or extension */
   1471 			    obb = btofsb(fs, ip->i_lfs_fragsize[lbn]);
   1472 			    ip->i_ffs1_blocks += (bb - obb);
   1473 		    }
   1474 		    ip->i_ffs1_db[lbn] = ndaddr;
   1475 		    break;
   1476 	    case 1:
   1477 		    ooff = ip->i_ffs1_ib[a[0].in_off];
   1478 		    DEBUG_OOFF(1);
   1479 		    if (ooff == UNWRITTEN)
   1480 			    ip->i_ffs1_blocks += bb;
   1481 		    ip->i_ffs1_ib[a[0].in_off] = ndaddr;
   1482 		    break;
   1483 	    default:
   1484 		    ap = &a[num - 1];
   1485 		    if (bread(vp, ap->in_lbn, fs->lfs_bsize, NOCRED, &bp))
   1486 			    panic("lfs_updatemeta: bread bno %" PRId64,
   1487 				  ap->in_lbn);
   1488 
   1489 		    /* XXX ondisk32 */
   1490 		    ooff = ((int32_t *)bp->b_data)[ap->in_off];
   1491 		    DEBUG_OOFF(num);
   1492 		    if (ooff == UNWRITTEN)
   1493 			    ip->i_ffs1_blocks += bb;
   1494 		    /* XXX ondisk32 */
   1495 		    ((int32_t *)bp->b_data)[ap->in_off] = ndaddr;
   1496 		    (void) VOP_BWRITE(bp);
   1497 	}
   1498 
   1499 	KASSERT(ooff == 0 || ooff == UNWRITTEN || ooff == daddr);
   1500 
   1501 	/* Update hiblk when extending the file */
   1502 	if (lbn > ip->i_lfs_hiblk)
   1503 		ip->i_lfs_hiblk = lbn;
   1504 
   1505 	/*
   1506 	 * Though we'd rather it couldn't, this *can* happen right now
   1507 	 * if cleaning blocks and regular blocks coexist.
   1508 	 */
   1509 	/* KASSERT(daddr < fs->lfs_lastpseg || daddr > ndaddr); */
   1510 
   1511 	/*
   1512 	 * Update segment usage information, based on old size
   1513 	 * and location.
   1514 	 */
   1515 	if (daddr > 0) {
   1516 		u_int32_t oldsn = dtosn(fs, daddr);
   1517 #ifdef DIAGNOSTIC
   1518 		int ndupino;
   1519 
   1520 		if (sp && sp->seg_number == oldsn) {
   1521 			ndupino = sp->ndupino;
   1522 		} else {
   1523 			ndupino = 0;
   1524 		}
   1525 #endif
   1526 		KASSERT(oldsn >= 0 && oldsn < fs->lfs_nseg);
   1527 		if (lbn >= 0 && lbn < NDADDR)
   1528 			osize = ip->i_lfs_fragsize[lbn];
   1529 		else
   1530 			osize = fs->lfs_bsize;
   1531 		LFS_SEGENTRY(sup, fs, oldsn, bp);
   1532 #ifdef DIAGNOSTIC
   1533 		if (sup->su_nbytes + sizeof (struct ufs1_dinode) * ndupino
   1534 		    < osize) {
   1535 			printf("lfs_updatemeta: negative bytes "
   1536 			       "(segment %" PRIu32 " short by %" PRId64
   1537 			       ")\n", dtosn(fs, daddr),
   1538 			       (int64_t)osize -
   1539 			       (sizeof (struct ufs1_dinode) * ndupino +
   1540 				sup->su_nbytes));
   1541 			printf("lfs_updatemeta: ino %llu, lbn %" PRId64
   1542 			       ", addr = 0x%" PRIx64 "\n",
   1543 			       (unsigned long long)ip->i_number, lbn, daddr);
   1544 			printf("lfs_updatemeta: ndupino=%d\n", ndupino);
   1545 			panic("lfs_updatemeta: negative bytes");
   1546 			sup->su_nbytes = osize -
   1547 			    sizeof (struct ufs1_dinode) * ndupino;
   1548 		}
   1549 #endif
   1550 		DLOG((DLOG_SU, "seg %" PRIu32 " -= %d for ino %d lbn %" PRId64
   1551 		      " db 0x%" PRIx64 "\n",
   1552 		      dtosn(fs, daddr), osize,
   1553 		      ip->i_number, lbn, daddr));
   1554 		sup->su_nbytes -= osize;
   1555 		if (!(bp->b_flags & B_GATHERED)) {
   1556 			simple_lock(&fs->lfs_interlock);
   1557 			fs->lfs_flags |= LFS_IFDIRTY;
   1558 			simple_unlock(&fs->lfs_interlock);
   1559 		}
   1560 		LFS_WRITESEGENTRY(sup, fs, oldsn, bp);
   1561 	}
   1562 	/*
   1563 	 * Now that this block has a new address, and its old
   1564 	 * segment no longer owns it, we can forget about its
   1565 	 * old size.
   1566 	 */
   1567 	if (lbn >= 0 && lbn < NDADDR)
   1568 		ip->i_lfs_fragsize[lbn] = size;
   1569 }
   1570 
   1571 /*
   1572  * Update the metadata that points to the blocks listed in the FINFO
   1573  * array.
   1574  */
   1575 void
   1576 lfs_updatemeta(struct segment *sp)
   1577 {
   1578 	struct buf *sbp;
   1579 	struct lfs *fs;
   1580 	struct vnode *vp;
   1581 	daddr_t lbn;
   1582 	int i, nblocks, num;
   1583 	int bb;
   1584 	int bytesleft, size;
   1585 
   1586 	ASSERT_SEGLOCK(sp->fs);
   1587 	vp = sp->vp;
   1588 	nblocks = &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp;
   1589 	KASSERT(nblocks >= 0);
   1590 	KASSERT(vp != NULL);
   1591 	if (nblocks == 0)
   1592 		return;
   1593 
   1594 	/*
   1595 	 * This count may be high due to oversize blocks from lfs_gop_write.
   1596 	 * Correct for this. (XXX we should be able to keep track of these.)
   1597 	 */
   1598 	fs = sp->fs;
   1599 	for (i = 0; i < nblocks; i++) {
   1600 		if (sp->start_bpp[i] == NULL) {
   1601 			DLOG((DLOG_SEG, "lfs_updatemeta: nblocks = %d, not %d\n", i, nblocks));
   1602 			nblocks = i;
   1603 			break;
   1604 		}
   1605 		num = howmany(sp->start_bpp[i]->b_bcount, fs->lfs_bsize);
   1606 		KASSERT(sp->start_bpp[i]->b_lblkno >= 0 || num == 1);
   1607 		nblocks -= num - 1;
   1608 	}
   1609 
   1610 	KASSERT(vp->v_type == VREG ||
   1611 	   nblocks == &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp);
   1612 	KASSERT(nblocks == sp->cbpp - sp->start_bpp);
   1613 
   1614 	/*
   1615 	 * Sort the blocks.
   1616 	 *
   1617 	 * We have to sort even if the blocks come from the
   1618 	 * cleaner, because there might be other pending blocks on the
   1619 	 * same inode...and if we don't sort, and there are fragments
   1620 	 * present, blocks may be written in the wrong place.
   1621 	 */
   1622 	lfs_shellsort(sp->start_bpp, sp->start_lbp, nblocks, fs->lfs_bsize);
   1623 
   1624 	/*
   1625 	 * Record the length of the last block in case it's a fragment.
   1626 	 * If there are indirect blocks present, they sort last.  An
   1627 	 * indirect block will be lfs_bsize and its presence indicates
   1628 	 * that you cannot have fragments.
   1629 	 *
   1630 	 * XXX This last is a lie.  A cleaned fragment can coexist with
   1631 	 * XXX a later indirect block.	This will continue to be
   1632 	 * XXX true until lfs_markv is fixed to do everything with
   1633 	 * XXX fake blocks (including fake inodes and fake indirect blocks).
   1634 	 */
   1635 	sp->fip->fi_lastlength = ((sp->start_bpp[nblocks - 1]->b_bcount - 1) &
   1636 		fs->lfs_bmask) + 1;
   1637 
   1638 	/*
   1639 	 * Assign disk addresses, and update references to the logical
   1640 	 * block and the segment usage information.
   1641 	 */
   1642 	for (i = nblocks; i--; ++sp->start_bpp) {
   1643 		sbp = *sp->start_bpp;
   1644 		lbn = *sp->start_lbp;
   1645 		KASSERT(sbp->b_lblkno == lbn);
   1646 
   1647 		sbp->b_blkno = fsbtodb(fs, fs->lfs_offset);
   1648 
   1649 		/*
   1650 		 * If we write a frag in the wrong place, the cleaner won't
   1651 		 * be able to correctly identify its size later, and the
   1652 		 * segment will be uncleanable.	 (Even worse, it will assume
   1653 		 * that the indirect block that actually ends the list
   1654 		 * is of a smaller size!)
   1655 		 */
   1656 		if ((sbp->b_bcount & fs->lfs_bmask) && i != 0)
   1657 			panic("lfs_updatemeta: fragment is not last block");
   1658 
   1659 		/*
   1660 		 * For each subblock in this possibly oversized block,
   1661 		 * update its address on disk.
   1662 		 */
   1663 		KASSERT(lbn >= 0 || sbp->b_bcount == fs->lfs_bsize);
   1664 		KASSERT(vp == sbp->b_vp);
   1665 		for (bytesleft = sbp->b_bcount; bytesleft > 0;
   1666 		     bytesleft -= fs->lfs_bsize) {
   1667 			size = MIN(bytesleft, fs->lfs_bsize);
   1668 			bb = fragstofsb(fs, numfrags(fs, size));
   1669 			lbn = *sp->start_lbp++;
   1670 			lfs_update_single(fs, sp, sp->vp, lbn, fs->lfs_offset,
   1671 			    size);
   1672 			fs->lfs_offset += bb;
   1673 		}
   1674 
   1675 	}
   1676 }
   1677 
   1678 /*
   1679  * Move lfs_offset to a segment earlier than sn.
   1680  */
   1681 int
   1682 lfs_rewind(struct lfs *fs, int newsn)
   1683 {
   1684 	int sn, osn, isdirty;
   1685 	struct buf *bp;
   1686 	SEGUSE *sup;
   1687 
   1688 	ASSERT_SEGLOCK(fs);
   1689 
   1690 	osn = dtosn(fs, fs->lfs_offset);
   1691 	if (osn < newsn)
   1692 		return 0;
   1693 
   1694 	/* lfs_avail eats the remaining space in this segment */
   1695 	fs->lfs_avail -= fs->lfs_fsbpseg - (fs->lfs_offset - fs->lfs_curseg);
   1696 
   1697 	/* Find a low-numbered segment */
   1698 	for (sn = 0; sn < fs->lfs_nseg; ++sn) {
   1699 		LFS_SEGENTRY(sup, fs, sn, bp);
   1700 		isdirty = sup->su_flags & SEGUSE_DIRTY;
   1701 		brelse(bp);
   1702 
   1703 		if (!isdirty)
   1704 			break;
   1705 	}
   1706 	if (sn == fs->lfs_nseg)
   1707 		panic("lfs_rewind: no clean segments");
   1708 	if (newsn >= 0 && sn >= newsn)
   1709 		return ENOENT;
   1710 	fs->lfs_nextseg = sn;
   1711 	lfs_newseg(fs);
   1712 	fs->lfs_offset = fs->lfs_curseg;
   1713 
   1714 	return 0;
   1715 }
   1716 
   1717 /*
   1718  * Start a new partial segment.
   1719  *
   1720  * Return 1 when we entered to a new segment.
   1721  * Otherwise, return 0.
   1722  */
   1723 int
   1724 lfs_initseg(struct lfs *fs)
   1725 {
   1726 	struct segment *sp = fs->lfs_sp;
   1727 	SEGSUM *ssp;
   1728 	struct buf *sbp;	/* buffer for SEGSUM */
   1729 	int repeat = 0;		/* return value */
   1730 
   1731 	ASSERT_SEGLOCK(fs);
   1732 	/* Advance to the next segment. */
   1733 	if (!LFS_PARTIAL_FITS(fs)) {
   1734 		SEGUSE *sup;
   1735 		struct buf *bp;
   1736 
   1737 		/* lfs_avail eats the remaining space */
   1738 		fs->lfs_avail -= fs->lfs_fsbpseg - (fs->lfs_offset -
   1739 						   fs->lfs_curseg);
   1740 		/* Wake up any cleaning procs waiting on this file system. */
   1741 		lfs_wakeup_cleaner(fs);
   1742 		lfs_newseg(fs);
   1743 		repeat = 1;
   1744 		fs->lfs_offset = fs->lfs_curseg;
   1745 
   1746 		sp->seg_number = dtosn(fs, fs->lfs_curseg);
   1747 		sp->seg_bytes_left = fsbtob(fs, fs->lfs_fsbpseg);
   1748 
   1749 		/*
   1750 		 * If the segment contains a superblock, update the offset
   1751 		 * and summary address to skip over it.
   1752 		 */
   1753 		LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
   1754 		if (sup->su_flags & SEGUSE_SUPERBLOCK) {
   1755 			fs->lfs_offset += btofsb(fs, LFS_SBPAD);
   1756 			sp->seg_bytes_left -= LFS_SBPAD;
   1757 		}
   1758 		brelse(bp);
   1759 		/* Segment zero could also contain the labelpad */
   1760 		if (fs->lfs_version > 1 && sp->seg_number == 0 &&
   1761 		    fs->lfs_start < btofsb(fs, LFS_LABELPAD)) {
   1762 			fs->lfs_offset +=
   1763 			    btofsb(fs, LFS_LABELPAD) - fs->lfs_start;
   1764 			sp->seg_bytes_left -=
   1765 			    LFS_LABELPAD - fsbtob(fs, fs->lfs_start);
   1766 		}
   1767 	} else {
   1768 		sp->seg_number = dtosn(fs, fs->lfs_curseg);
   1769 		sp->seg_bytes_left = fsbtob(fs, fs->lfs_fsbpseg -
   1770 				      (fs->lfs_offset - fs->lfs_curseg));
   1771 	}
   1772 	fs->lfs_lastpseg = fs->lfs_offset;
   1773 
   1774 	/* Record first address of this partial segment */
   1775 	if (sp->seg_flags & SEGM_CLEAN) {
   1776 		fs->lfs_cleanint[fs->lfs_cleanind] = fs->lfs_offset;
   1777 		if (++fs->lfs_cleanind >= LFS_MAX_CLEANIND) {
   1778 			/* "1" is the artificial inc in lfs_seglock */
   1779 			simple_lock(&fs->lfs_interlock);
   1780 			while (fs->lfs_iocount > 1) {
   1781 				ltsleep(&fs->lfs_iocount, PRIBIO + 1,
   1782 				    "lfs_initseg", 0, &fs->lfs_interlock);
   1783 			}
   1784 			simple_unlock(&fs->lfs_interlock);
   1785 			fs->lfs_cleanind = 0;
   1786 		}
   1787 	}
   1788 
   1789 	sp->fs = fs;
   1790 	sp->ibp = NULL;
   1791 	sp->idp = NULL;
   1792 	sp->ninodes = 0;
   1793 	sp->ndupino = 0;
   1794 
   1795 	sp->cbpp = sp->bpp;
   1796 
   1797 	/* Get a new buffer for SEGSUM */
   1798 	sbp = lfs_newbuf(fs, VTOI(fs->lfs_ivnode)->i_devvp,
   1799 	    fsbtodb(fs, fs->lfs_offset), fs->lfs_sumsize, LFS_NB_SUMMARY);
   1800 
   1801 	/* ... and enter it into the buffer list. */
   1802 	*sp->cbpp = sbp;
   1803 	sp->cbpp++;
   1804 	fs->lfs_offset += btofsb(fs, fs->lfs_sumsize);
   1805 
   1806 	sp->start_bpp = sp->cbpp;
   1807 
   1808 	/* Set point to SEGSUM, initialize it. */
   1809 	ssp = sp->segsum = sbp->b_data;
   1810 	memset(ssp, 0, fs->lfs_sumsize);
   1811 	ssp->ss_next = fs->lfs_nextseg;
   1812 	ssp->ss_nfinfo = ssp->ss_ninos = 0;
   1813 	ssp->ss_magic = SS_MAGIC;
   1814 
   1815 	/* Set pointer to first FINFO, initialize it. */
   1816 	sp->fip = (struct finfo *)((caddr_t)sp->segsum + SEGSUM_SIZE(fs));
   1817 	sp->fip->fi_nblocks = 0;
   1818 	sp->start_lbp = &sp->fip->fi_blocks[0];
   1819 	sp->fip->fi_lastlength = 0;
   1820 
   1821 	sp->seg_bytes_left -= fs->lfs_sumsize;
   1822 	sp->sum_bytes_left = fs->lfs_sumsize - SEGSUM_SIZE(fs);
   1823 
   1824 	return (repeat);
   1825 }
   1826 
   1827 /*
   1828  * Remove SEGUSE_INVAL from all segments.
   1829  */
   1830 void
   1831 lfs_unset_inval_all(struct lfs *fs)
   1832 {
   1833 	SEGUSE *sup;
   1834 	struct buf *bp;
   1835 	int i;
   1836 
   1837 	for (i = 0; i < fs->lfs_nseg; i++) {
   1838 		LFS_SEGENTRY(sup, fs, i, bp);
   1839 		if (sup->su_flags & SEGUSE_INVAL) {
   1840 			sup->su_flags &= ~SEGUSE_INVAL;
   1841 			LFS_WRITESEGENTRY(sup, fs, i, bp);
   1842 		} else
   1843 			brelse(bp);
   1844 	}
   1845 }
   1846 
   1847 /*
   1848  * Return the next segment to write.
   1849  */
   1850 void
   1851 lfs_newseg(struct lfs *fs)
   1852 {
   1853 	CLEANERINFO *cip;
   1854 	SEGUSE *sup;
   1855 	struct buf *bp;
   1856 	int curseg, isdirty, sn, skip_inval;
   1857 
   1858 	ASSERT_SEGLOCK(fs);
   1859 
   1860 	/* Honor LFCNWRAPSTOP */
   1861 	simple_lock(&fs->lfs_interlock);
   1862 	while (fs->lfs_nextseg < fs->lfs_curseg && fs->lfs_nowrap) {
   1863 		if (fs->lfs_wrappass) {
   1864 			log(LOG_NOTICE, "%s: wrappass=%d\n",
   1865 				fs->lfs_fsmnt, fs->lfs_wrappass);
   1866 			fs->lfs_wrappass = 0;
   1867 			break;
   1868 		}
   1869 		fs->lfs_wrapstatus = LFS_WRAP_WAITING;
   1870 		wakeup(&fs->lfs_nowrap);
   1871 		log(LOG_NOTICE, "%s: waiting at log wrap\n", fs->lfs_fsmnt);
   1872 		ltsleep(&fs->lfs_wrappass, PVFS, "newseg", 10 * hz,
   1873 			&fs->lfs_interlock);
   1874 	}
   1875 	fs->lfs_wrapstatus = LFS_WRAP_GOING;
   1876 	simple_unlock(&fs->lfs_interlock);
   1877 
   1878 	LFS_SEGENTRY(sup, fs, dtosn(fs, fs->lfs_nextseg), bp);
   1879 	DLOG((DLOG_SU, "lfs_newseg: seg %d := 0 in newseg\n",
   1880 	      dtosn(fs, fs->lfs_nextseg)));
   1881 	sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
   1882 	sup->su_nbytes = 0;
   1883 	sup->su_nsums = 0;
   1884 	sup->su_ninos = 0;
   1885 	LFS_WRITESEGENTRY(sup, fs, dtosn(fs, fs->lfs_nextseg), bp);
   1886 
   1887 	LFS_CLEANERINFO(cip, fs, bp);
   1888 	--cip->clean;
   1889 	++cip->dirty;
   1890 	fs->lfs_nclean = cip->clean;
   1891 	LFS_SYNC_CLEANERINFO(cip, fs, bp, 1);
   1892 
   1893 	fs->lfs_lastseg = fs->lfs_curseg;
   1894 	fs->lfs_curseg = fs->lfs_nextseg;
   1895 	skip_inval = 1;
   1896 	for (sn = curseg = dtosn(fs, fs->lfs_curseg) + fs->lfs_interleave;;) {
   1897 		sn = (sn + 1) % fs->lfs_nseg;
   1898 
   1899 		if (sn == curseg) {
   1900 			if (skip_inval)
   1901 				skip_inval = 0;
   1902 			else
   1903 				panic("lfs_nextseg: no clean segments");
   1904 		}
   1905 		LFS_SEGENTRY(sup, fs, sn, bp);
   1906 		isdirty = sup->su_flags & (SEGUSE_DIRTY | (skip_inval ? SEGUSE_INVAL : 0));
   1907 		/* Check SEGUSE_EMPTY as we go along */
   1908 		if (isdirty && sup->su_nbytes == 0 &&
   1909 		    !(sup->su_flags & SEGUSE_EMPTY))
   1910 			LFS_WRITESEGENTRY(sup, fs, sn, bp);
   1911 		else
   1912 			brelse(bp);
   1913 
   1914 		if (!isdirty)
   1915 			break;
   1916 	}
   1917 	if (skip_inval == 0)
   1918 		lfs_unset_inval_all(fs);
   1919 
   1920 	++fs->lfs_nactive;
   1921 	fs->lfs_nextseg = sntod(fs, sn);
   1922 	if (lfs_dostats) {
   1923 		++lfs_stats.segsused;
   1924 	}
   1925 }
   1926 
   1927 static struct buf *
   1928 lfs_newclusterbuf(struct lfs *fs, struct vnode *vp, daddr_t addr, int n)
   1929 {
   1930 	struct lfs_cluster *cl;
   1931 	struct buf **bpp, *bp;
   1932 
   1933 	ASSERT_SEGLOCK(fs);
   1934 	cl = (struct lfs_cluster *)pool_get(&fs->lfs_clpool, PR_WAITOK);
   1935 	bpp = (struct buf **)pool_get(&fs->lfs_bpppool, PR_WAITOK);
   1936 	memset(cl, 0, sizeof(*cl));
   1937 	cl->fs = fs;
   1938 	cl->bpp = bpp;
   1939 	cl->bufcount = 0;
   1940 	cl->bufsize = 0;
   1941 
   1942 	/* If this segment is being written synchronously, note that */
   1943 	if (fs->lfs_sp->seg_flags & SEGM_SYNC) {
   1944 		cl->flags |= LFS_CL_SYNC;
   1945 		cl->seg = fs->lfs_sp;
   1946 		++cl->seg->seg_iocount;
   1947 	}
   1948 
   1949 	/* Get an empty buffer header, or maybe one with something on it */
   1950 	bp = getiobuf();
   1951 	bp->b_flags = B_BUSY | B_CALL;
   1952 	bp->b_dev = NODEV;
   1953 	bp->b_blkno = bp->b_lblkno = addr;
   1954 	bp->b_iodone = lfs_cluster_callback;
   1955 	bp->b_private = cl;
   1956 	bp->b_vp = vp;
   1957 
   1958 	return bp;
   1959 }
   1960 
   1961 int
   1962 lfs_writeseg(struct lfs *fs, struct segment *sp)
   1963 {
   1964 	struct buf **bpp, *bp, *cbp, *newbp;
   1965 	SEGUSE *sup;
   1966 	SEGSUM *ssp;
   1967 	int i, s;
   1968 	int do_again, nblocks, byteoffset;
   1969 	size_t el_size;
   1970 	struct lfs_cluster *cl;
   1971 	u_short ninos;
   1972 	struct vnode *devvp;
   1973 	char *p = NULL;
   1974 	struct vnode *vp;
   1975 	int32_t *daddrp;	/* XXX ondisk32 */
   1976 	int changed;
   1977 	u_int32_t sum;
   1978 #ifdef DEBUG
   1979 	FINFO *fip;
   1980 	int findex;
   1981 #endif
   1982 
   1983 	ASSERT_SEGLOCK(fs);
   1984 
   1985 	ssp = (SEGSUM *)sp->segsum;
   1986 
   1987 	/*
   1988 	 * If there are no buffers other than the segment summary to write,
   1989 	 * don't do anything.  If we are the end of a dirop sequence, however,
   1990 	 * write the empty segment summary anyway, to help out the
   1991 	 * roll-forward agent.
   1992 	 */
   1993 	if ((nblocks = sp->cbpp - sp->bpp) == 1) {
   1994 		if ((ssp->ss_flags & (SS_DIROP | SS_CONT)) != SS_DIROP)
   1995 			return 0;
   1996 	}
   1997 
   1998 	/* Note if partial segment is being written by the cleaner */
   1999 	if (sp->seg_flags & SEGM_CLEAN)
   2000 		ssp->ss_flags |= SS_CLEAN;
   2001 
   2002 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
   2003 
   2004 	/* Update the segment usage information. */
   2005 	LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
   2006 
   2007 	/* Loop through all blocks, except the segment summary. */
   2008 	for (bpp = sp->bpp; ++bpp < sp->cbpp; ) {
   2009 		if ((*bpp)->b_vp != devvp) {
   2010 			sup->su_nbytes += (*bpp)->b_bcount;
   2011 			DLOG((DLOG_SU, "seg %" PRIu32 " += %ld for ino %d"
   2012 			      " lbn %" PRId64 " db 0x%" PRIx64 "\n",
   2013 			      sp->seg_number, (*bpp)->b_bcount,
   2014 			      VTOI((*bpp)->b_vp)->i_number, (*bpp)->b_lblkno,
   2015 			      (*bpp)->b_blkno));
   2016 		}
   2017 	}
   2018 
   2019 #ifdef DEBUG
   2020 	/* Check for zero-length and zero-version FINFO entries. */
   2021 	fip = (struct finfo *)((caddr_t)ssp + SEGSUM_SIZE(fs));
   2022 	for (findex = 0; findex < ssp->ss_nfinfo; findex++) {
   2023 		KDASSERT(fip->fi_nblocks > 0);
   2024 		KDASSERT(fip->fi_version > 0);
   2025 		fip = (FINFO *)((caddr_t)fip + FINFOSIZE +
   2026 			sizeof(int32_t) * fip->fi_nblocks);
   2027 	}
   2028 #endif /* DEBUG */
   2029 
   2030 	ninos = (ssp->ss_ninos + INOPB(fs) - 1) / INOPB(fs);
   2031 	DLOG((DLOG_SU, "seg %d += %d for %d inodes\n",
   2032 	      sp->seg_number, ssp->ss_ninos * sizeof (struct ufs1_dinode),
   2033 	      ssp->ss_ninos));
   2034 	sup->su_nbytes += ssp->ss_ninos * sizeof (struct ufs1_dinode);
   2035 	/* sup->su_nbytes += fs->lfs_sumsize; */
   2036 	if (fs->lfs_version == 1)
   2037 		sup->su_olastmod = time_second;
   2038 	else
   2039 		sup->su_lastmod = time_second;
   2040 	sup->su_ninos += ninos;
   2041 	++sup->su_nsums;
   2042 	fs->lfs_avail -= btofsb(fs, fs->lfs_sumsize);
   2043 
   2044 	do_again = !(bp->b_flags & B_GATHERED);
   2045 	LFS_WRITESEGENTRY(sup, fs, sp->seg_number, bp); /* Ifile */
   2046 
   2047 	/*
   2048 	 * Mark blocks B_BUSY, to prevent then from being changed between
   2049 	 * the checksum computation and the actual write.
   2050 	 *
   2051 	 * If we are cleaning, check indirect blocks for UNWRITTEN, and if
   2052 	 * there are any, replace them with copies that have UNASSIGNED
   2053 	 * instead.
   2054 	 */
   2055 	for (bpp = sp->bpp, i = nblocks - 1; i--;) {
   2056 		++bpp;
   2057 		bp = *bpp;
   2058 		if (bp->b_flags & B_CALL) { /* UBC or malloced buffer */
   2059 			bp->b_flags |= B_BUSY;
   2060 			continue;
   2061 		}
   2062 
   2063 		simple_lock(&bp->b_interlock);
   2064 		s = splbio();
   2065 		while (bp->b_flags & B_BUSY) {
   2066 			DLOG((DLOG_SEG, "lfs_writeseg: avoiding potential"
   2067 			      " data summary corruption for ino %d, lbn %"
   2068 			      PRId64 "\n",
   2069 			      VTOI(bp->b_vp)->i_number, bp->b_lblkno));
   2070 			bp->b_flags |= B_WANTED;
   2071 			ltsleep(bp, (PRIBIO + 1), "lfs_writeseg", 0,
   2072 				&bp->b_interlock);
   2073 			splx(s);
   2074 			s = splbio();
   2075 		}
   2076 		bp->b_flags |= B_BUSY;
   2077 		splx(s);
   2078 		simple_unlock(&bp->b_interlock);
   2079 
   2080 		/*
   2081 		 * Check and replace indirect block UNWRITTEN bogosity.
   2082 		 * XXX See comment in lfs_writefile.
   2083 		 */
   2084 		if (bp->b_lblkno < 0 && bp->b_vp != devvp && bp->b_vp &&
   2085 		   VTOI(bp->b_vp)->i_ffs1_blocks !=
   2086 		   VTOI(bp->b_vp)->i_lfs_effnblks) {
   2087 			DLOG((DLOG_VNODE, "lfs_writeseg: cleansing ino %d (%d != %d)\n",
   2088 			      VTOI(bp->b_vp)->i_number,
   2089 			      VTOI(bp->b_vp)->i_lfs_effnblks,
   2090 			      VTOI(bp->b_vp)->i_ffs1_blocks));
   2091 			/* Make a copy we'll make changes to */
   2092 			newbp = lfs_newbuf(fs, bp->b_vp, bp->b_lblkno,
   2093 					   bp->b_bcount, LFS_NB_IBLOCK);
   2094 			newbp->b_blkno = bp->b_blkno;
   2095 			memcpy(newbp->b_data, bp->b_data,
   2096 			       newbp->b_bcount);
   2097 
   2098 			changed = 0;
   2099 			/* XXX ondisk32 */
   2100 			for (daddrp = (int32_t *)(newbp->b_data);
   2101 			     daddrp < (int32_t *)(newbp->b_data +
   2102 						  newbp->b_bcount); daddrp++) {
   2103 				if (*daddrp == UNWRITTEN) {
   2104 					++changed;
   2105 					*daddrp = 0;
   2106 				}
   2107 			}
   2108 			/*
   2109 			 * Get rid of the old buffer.  Don't mark it clean,
   2110 			 * though, if it still has dirty data on it.
   2111 			 */
   2112 			if (changed) {
   2113 				DLOG((DLOG_SEG, "lfs_writeseg: replacing UNWRITTEN(%d):"
   2114 				      " bp = %p newbp = %p\n", changed, bp,
   2115 				      newbp));
   2116 				*bpp = newbp;
   2117 				bp->b_flags &= ~(B_ERROR | B_GATHERED);
   2118 				if (bp->b_flags & B_CALL) {
   2119 					DLOG((DLOG_SEG, "lfs_writeseg: "
   2120 					      "indir bp should not be B_CALL\n"));
   2121 					s = splbio();
   2122 					biodone(bp);
   2123 					splx(s);
   2124 					bp = NULL;
   2125 				} else {
   2126 					/* Still on free list, leave it there */
   2127 					s = splbio();
   2128 					bp->b_flags &= ~B_BUSY;
   2129 					if (bp->b_flags & B_WANTED)
   2130 						wakeup(bp);
   2131 					splx(s);
   2132 					/*
   2133 					 * We have to re-decrement lfs_avail
   2134 					 * since this block is going to come
   2135 					 * back around to us in the next
   2136 					 * segment.
   2137 					 */
   2138 					fs->lfs_avail -=
   2139 					    btofsb(fs, bp->b_bcount);
   2140 				}
   2141 			} else {
   2142 				lfs_freebuf(fs, newbp);
   2143 			}
   2144 		}
   2145 	}
   2146 	/*
   2147 	 * Compute checksum across data and then across summary; the first
   2148 	 * block (the summary block) is skipped.  Set the create time here
   2149 	 * so that it's guaranteed to be later than the inode mod times.
   2150 	 */
   2151 	sum = 0;
   2152 	if (fs->lfs_version == 1)
   2153 		el_size = sizeof(u_long);
   2154 	else
   2155 		el_size = sizeof(u_int32_t);
   2156 	for (bpp = sp->bpp, i = nblocks - 1; i--; ) {
   2157 		++bpp;
   2158 		/* Loop through gop_write cluster blocks */
   2159 		for (byteoffset = 0; byteoffset < (*bpp)->b_bcount;
   2160 		     byteoffset += fs->lfs_bsize) {
   2161 #ifdef LFS_USE_B_INVAL
   2162 			if (((*bpp)->b_flags & (B_CALL | B_INVAL)) ==
   2163 			    (B_CALL | B_INVAL)) {
   2164 				if (copyin((caddr_t)(*bpp)->b_saveaddr +
   2165 					   byteoffset, dp, el_size)) {
   2166 					panic("lfs_writeseg: copyin failed [1]:"
   2167 						" ino %d blk %" PRId64,
   2168 						VTOI((*bpp)->b_vp)->i_number,
   2169 						(*bpp)->b_lblkno);
   2170 				}
   2171 			} else
   2172 #endif /* LFS_USE_B_INVAL */
   2173 			{
   2174 				sum = lfs_cksum_part(
   2175 				    (*bpp)->b_data + byteoffset, el_size, sum);
   2176 			}
   2177 		}
   2178 	}
   2179 	if (fs->lfs_version == 1)
   2180 		ssp->ss_ocreate = time_second;
   2181 	else {
   2182 		ssp->ss_create = time_second;
   2183 		ssp->ss_serial = ++fs->lfs_serial;
   2184 		ssp->ss_ident  = fs->lfs_ident;
   2185 	}
   2186 	ssp->ss_datasum = lfs_cksum_fold(sum);
   2187 	ssp->ss_sumsum = cksum(&ssp->ss_datasum,
   2188 	    fs->lfs_sumsize - sizeof(ssp->ss_sumsum));
   2189 
   2190 	simple_lock(&fs->lfs_interlock);
   2191 	fs->lfs_bfree -= (btofsb(fs, ninos * fs->lfs_ibsize) +
   2192 			  btofsb(fs, fs->lfs_sumsize));
   2193 	fs->lfs_dmeta += (btofsb(fs, ninos * fs->lfs_ibsize) +
   2194 			  btofsb(fs, fs->lfs_sumsize));
   2195 	simple_unlock(&fs->lfs_interlock);
   2196 
   2197 	/*
   2198 	 * When we simply write the blocks we lose a rotation for every block
   2199 	 * written.  To avoid this problem, we cluster the buffers into a
   2200 	 * chunk and write the chunk.  MAXPHYS is the largest size I/O
   2201 	 * devices can handle, use that for the size of the chunks.
   2202 	 *
   2203 	 * Blocks that are already clusters (from GOP_WRITE), however, we
   2204 	 * don't bother to copy into other clusters.
   2205 	 */
   2206 
   2207 #define CHUNKSIZE MAXPHYS
   2208 
   2209 	if (devvp == NULL)
   2210 		panic("devvp is NULL");
   2211 	for (bpp = sp->bpp, i = nblocks; i;) {
   2212 		cbp = lfs_newclusterbuf(fs, devvp, (*bpp)->b_blkno, i);
   2213 		cl = cbp->b_private;
   2214 
   2215 		cbp->b_flags |= B_ASYNC | B_BUSY;
   2216 		cbp->b_bcount = 0;
   2217 
   2218 #if defined(DEBUG) && defined(DIAGNOSTIC)
   2219 		if (bpp - sp->bpp > (fs->lfs_sumsize - SEGSUM_SIZE(fs))
   2220 		    / sizeof(int32_t)) {
   2221 			panic("lfs_writeseg: real bpp overwrite");
   2222 		}
   2223 		if (bpp - sp->bpp > segsize(fs) / fs->lfs_fsize) {
   2224 			panic("lfs_writeseg: theoretical bpp overwrite");
   2225 		}
   2226 #endif
   2227 
   2228 		/*
   2229 		 * Construct the cluster.
   2230 		 */
   2231 		simple_lock(&fs->lfs_interlock);
   2232 		++fs->lfs_iocount;
   2233 		simple_unlock(&fs->lfs_interlock);
   2234 		while (i && cbp->b_bcount < CHUNKSIZE) {
   2235 			bp = *bpp;
   2236 
   2237 			if (bp->b_bcount > (CHUNKSIZE - cbp->b_bcount))
   2238 				break;
   2239 			if (cbp->b_bcount > 0 && !(cl->flags & LFS_CL_MALLOC))
   2240 				break;
   2241 
   2242 			/* Clusters from GOP_WRITE are expedited */
   2243 			if (bp->b_bcount > fs->lfs_bsize) {
   2244 				if (cbp->b_bcount > 0)
   2245 					/* Put in its own buffer */
   2246 					break;
   2247 				else {
   2248 					cbp->b_data = bp->b_data;
   2249 				}
   2250 			} else if (cbp->b_bcount == 0) {
   2251 				p = cbp->b_data = lfs_malloc(fs, CHUNKSIZE,
   2252 							     LFS_NB_CLUSTER);
   2253 				cl->flags |= LFS_CL_MALLOC;
   2254 			}
   2255 #ifdef DIAGNOSTIC
   2256 			if (dtosn(fs, dbtofsb(fs, bp->b_blkno +
   2257 					      btodb(bp->b_bcount - 1))) !=
   2258 			    sp->seg_number) {
   2259 				printf("blk size %d daddr %" PRIx64
   2260 				    " not in seg %d\n",
   2261 				    bp->b_bcount, bp->b_blkno,
   2262 				    sp->seg_number);
   2263 				panic("segment overwrite");
   2264 			}
   2265 #endif
   2266 
   2267 #ifdef LFS_USE_B_INVAL
   2268 			/*
   2269 			 * Fake buffers from the cleaner are marked as B_INVAL.
   2270 			 * We need to copy the data from user space rather than
   2271 			 * from the buffer indicated.
   2272 			 * XXX == what do I do on an error?
   2273 			 */
   2274 			if ((bp->b_flags & (B_CALL|B_INVAL)) ==
   2275 			    (B_CALL|B_INVAL)) {
   2276 				if (copyin(bp->b_saveaddr, p, bp->b_bcount))
   2277 					panic("lfs_writeseg: "
   2278 					    "copyin failed [2]");
   2279 			} else
   2280 #endif /* LFS_USE_B_INVAL */
   2281 			if (cl->flags & LFS_CL_MALLOC) {
   2282 				/* copy data into our cluster. */
   2283 				memcpy(p, bp->b_data, bp->b_bcount);
   2284 				p += bp->b_bcount;
   2285 			}
   2286 
   2287 			cbp->b_bcount += bp->b_bcount;
   2288 			cl->bufsize += bp->b_bcount;
   2289 
   2290 			bp->b_flags &= ~(B_ERROR | B_READ | B_DELWRI | B_DONE);
   2291 			cl->bpp[cl->bufcount++] = bp;
   2292 			vp = bp->b_vp;
   2293 			s = splbio();
   2294 			reassignbuf(bp, vp);
   2295 			V_INCR_NUMOUTPUT(vp);
   2296 			splx(s);
   2297 
   2298 			bpp++;
   2299 			i--;
   2300 		}
   2301 		if (fs->lfs_sp->seg_flags & SEGM_SYNC)
   2302 			BIO_SETPRIO(cbp, BPRIO_TIMECRITICAL);
   2303 		else
   2304 			BIO_SETPRIO(cbp, BPRIO_TIMELIMITED);
   2305 		s = splbio();
   2306 		V_INCR_NUMOUTPUT(devvp);
   2307 		splx(s);
   2308 		VOP_STRATEGY(devvp, cbp);
   2309 		curproc->p_stats->p_ru.ru_oublock++;
   2310 	}
   2311 
   2312 	if (lfs_dostats) {
   2313 		++lfs_stats.psegwrites;
   2314 		lfs_stats.blocktot += nblocks - 1;
   2315 		if (fs->lfs_sp->seg_flags & SEGM_SYNC)
   2316 			++lfs_stats.psyncwrites;
   2317 		if (fs->lfs_sp->seg_flags & SEGM_CLEAN) {
   2318 			++lfs_stats.pcleanwrites;
   2319 			lfs_stats.cleanblocks += nblocks - 1;
   2320 		}
   2321 	}
   2322 	return (lfs_initseg(fs) || do_again);
   2323 }
   2324 
   2325 void
   2326 lfs_writesuper(struct lfs *fs, daddr_t daddr)
   2327 {
   2328 	struct buf *bp;
   2329 	int s;
   2330 	struct vnode *devvp = VTOI(fs->lfs_ivnode)->i_devvp;
   2331 
   2332 	ASSERT_MAYBE_SEGLOCK(fs);
   2333 #ifdef DIAGNOSTIC
   2334 	KASSERT(fs->lfs_magic == LFS_MAGIC);
   2335 #endif
   2336 	/*
   2337 	 * If we can write one superblock while another is in
   2338 	 * progress, we risk not having a complete checkpoint if we crash.
   2339 	 * So, block here if a superblock write is in progress.
   2340 	 */
   2341 	simple_lock(&fs->lfs_interlock);
   2342 	s = splbio();
   2343 	while (fs->lfs_sbactive) {
   2344 		ltsleep(&fs->lfs_sbactive, PRIBIO+1, "lfs sb", 0,
   2345 			&fs->lfs_interlock);
   2346 	}
   2347 	fs->lfs_sbactive = daddr;
   2348 	splx(s);
   2349 	simple_unlock(&fs->lfs_interlock);
   2350 
   2351 	/* Set timestamp of this version of the superblock */
   2352 	if (fs->lfs_version == 1)
   2353 		fs->lfs_otstamp = time_second;
   2354 	fs->lfs_tstamp = time_second;
   2355 
   2356 	/* Checksum the superblock and copy it into a buffer. */
   2357 	fs->lfs_cksum = lfs_sb_cksum(&(fs->lfs_dlfs));
   2358 	bp = lfs_newbuf(fs, devvp,
   2359 	    fsbtodb(fs, daddr), LFS_SBPAD, LFS_NB_SBLOCK);
   2360 	memset(bp->b_data + sizeof(struct dlfs), 0,
   2361 	    LFS_SBPAD - sizeof(struct dlfs));
   2362 	*(struct dlfs *)bp->b_data = fs->lfs_dlfs;
   2363 
   2364 	bp->b_flags |= B_BUSY | B_CALL | B_ASYNC;
   2365 	bp->b_flags &= ~(B_DONE | B_ERROR | B_READ | B_DELWRI);
   2366 	bp->b_iodone = lfs_supercallback;
   2367 
   2368 	if (fs->lfs_sp != NULL && fs->lfs_sp->seg_flags & SEGM_SYNC)
   2369 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
   2370 	else
   2371 		BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
   2372 	curproc->p_stats->p_ru.ru_oublock++;
   2373 	s = splbio();
   2374 	V_INCR_NUMOUTPUT(bp->b_vp);
   2375 	splx(s);
   2376 	simple_lock(&fs->lfs_interlock);
   2377 	++fs->lfs_iocount;
   2378 	simple_unlock(&fs->lfs_interlock);
   2379 	VOP_STRATEGY(devvp, bp);
   2380 }
   2381 
   2382 /*
   2383  * Logical block number match routines used when traversing the dirty block
   2384  * chain.
   2385  */
   2386 int
   2387 lfs_match_fake(struct lfs *fs, struct buf *bp)
   2388 {
   2389 
   2390 	ASSERT_SEGLOCK(fs);
   2391 	return LFS_IS_MALLOC_BUF(bp);
   2392 }
   2393 
   2394 #if 0
   2395 int
   2396 lfs_match_real(struct lfs *fs, struct buf *bp)
   2397 {
   2398 
   2399 	ASSERT_SEGLOCK(fs);
   2400 	return (lfs_match_data(fs, bp) && !lfs_match_fake(fs, bp));
   2401 }
   2402 #endif
   2403 
   2404 int
   2405 lfs_match_data(struct lfs *fs, struct buf *bp)
   2406 {
   2407 
   2408 	ASSERT_SEGLOCK(fs);
   2409 	return (bp->b_lblkno >= 0);
   2410 }
   2411 
   2412 int
   2413 lfs_match_indir(struct lfs *fs, struct buf *bp)
   2414 {
   2415 	daddr_t lbn;
   2416 
   2417 	ASSERT_SEGLOCK(fs);
   2418 	lbn = bp->b_lblkno;
   2419 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 0);
   2420 }
   2421 
   2422 int
   2423 lfs_match_dindir(struct lfs *fs, struct buf *bp)
   2424 {
   2425 	daddr_t lbn;
   2426 
   2427 	ASSERT_SEGLOCK(fs);
   2428 	lbn = bp->b_lblkno;
   2429 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 1);
   2430 }
   2431 
   2432 int
   2433 lfs_match_tindir(struct lfs *fs, struct buf *bp)
   2434 {
   2435 	daddr_t lbn;
   2436 
   2437 	ASSERT_SEGLOCK(fs);
   2438 	lbn = bp->b_lblkno;
   2439 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 2);
   2440 }
   2441 
   2442 static void
   2443 lfs_free_aiodone(struct buf *bp)
   2444 {
   2445 	struct lfs *fs;
   2446 
   2447 	fs = bp->b_private;
   2448 	ASSERT_NO_SEGLOCK(fs);
   2449 	lfs_freebuf(fs, bp);
   2450 }
   2451 
   2452 static void
   2453 lfs_super_aiodone(struct buf *bp)
   2454 {
   2455 	struct lfs *fs;
   2456 
   2457 	fs = bp->b_private;
   2458 	ASSERT_NO_SEGLOCK(fs);
   2459 	simple_lock(&fs->lfs_interlock);
   2460 	fs->lfs_sbactive = 0;
   2461 	if (--fs->lfs_iocount <= 1)
   2462 		wakeup(&fs->lfs_iocount);
   2463 	simple_unlock(&fs->lfs_interlock);
   2464 	wakeup(&fs->lfs_sbactive);
   2465 	lfs_freebuf(fs, bp);
   2466 }
   2467 
   2468 static void
   2469 lfs_cluster_aiodone(struct buf *bp)
   2470 {
   2471 	struct lfs_cluster *cl;
   2472 	struct lfs *fs;
   2473 	struct buf *tbp, *fbp;
   2474 	struct vnode *vp, *devvp;
   2475 	struct inode *ip;
   2476 	int s, error=0;
   2477 
   2478 	if (bp->b_flags & B_ERROR)
   2479 		error = bp->b_error;
   2480 
   2481 	cl = bp->b_private;
   2482 	fs = cl->fs;
   2483 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
   2484 	ASSERT_NO_SEGLOCK(fs);
   2485 
   2486 	/* Put the pages back, and release the buffer */
   2487 	while (cl->bufcount--) {
   2488 		tbp = cl->bpp[cl->bufcount];
   2489 		KASSERT(tbp->b_flags & B_BUSY);
   2490 		if (error) {
   2491 			tbp->b_flags |= B_ERROR;
   2492 			tbp->b_error = error;
   2493 		}
   2494 
   2495 		/*
   2496 		 * We're done with tbp.	 If it has not been re-dirtied since
   2497 		 * the cluster was written, free it.  Otherwise, keep it on
   2498 		 * the locked list to be written again.
   2499 		 */
   2500 		vp = tbp->b_vp;
   2501 
   2502 		tbp->b_flags &= ~B_GATHERED;
   2503 
   2504 		LFS_BCLEAN_LOG(fs, tbp);
   2505 
   2506 		if (!(tbp->b_flags & B_CALL)) {
   2507 			KASSERT(tbp->b_flags & B_LOCKED);
   2508 			s = splbio();
   2509 			simple_lock(&bqueue_slock);
   2510 			bremfree(tbp);
   2511 			simple_unlock(&bqueue_slock);
   2512 			if (vp)
   2513 				reassignbuf(tbp, vp);
   2514 			splx(s);
   2515 			tbp->b_flags |= B_ASYNC; /* for biodone */
   2516 		}
   2517 
   2518 		if ((tbp->b_flags & (B_LOCKED | B_DELWRI)) == B_LOCKED)
   2519 			LFS_UNLOCK_BUF(tbp);
   2520 
   2521 		if (tbp->b_flags & B_DONE) {
   2522 			DLOG((DLOG_SEG, "blk %d biodone already (flags %lx)\n",
   2523 				cl->bufcount, (long)tbp->b_flags));
   2524 		}
   2525 
   2526 		if ((tbp->b_flags & B_CALL) && !LFS_IS_MALLOC_BUF(tbp)) {
   2527 			/*
   2528 			 * A buffer from the page daemon.
   2529 			 * We use the same iodone as it does,
   2530 			 * so we must manually disassociate its
   2531 			 * buffers from the vp.
   2532 			 */
   2533 			if (tbp->b_vp) {
   2534 				/* This is just silly */
   2535 				s = splbio();
   2536 				brelvp(tbp);
   2537 				tbp->b_vp = vp;
   2538 				splx(s);
   2539 			}
   2540 			/* Put it back the way it was */
   2541 			tbp->b_flags |= B_ASYNC;
   2542 			/* Master buffers have B_AGE */
   2543 			if (tbp->b_private == tbp)
   2544 				tbp->b_flags |= B_AGE;
   2545 		}
   2546 		s = splbio();
   2547 		biodone(tbp);
   2548 
   2549 		/*
   2550 		 * If this is the last block for this vnode, but
   2551 		 * there are other blocks on its dirty list,
   2552 		 * set IN_MODIFIED/IN_CLEANING depending on what
   2553 		 * sort of block.  Only do this for our mount point,
   2554 		 * not for, e.g., inode blocks that are attached to
   2555 		 * the devvp.
   2556 		 * XXX KS - Shouldn't we set *both* if both types
   2557 		 * of blocks are present (traverse the dirty list?)
   2558 		 */
   2559 		simple_lock(&global_v_numoutput_slock);
   2560 		if (vp != devvp && vp->v_numoutput == 0 &&
   2561 		    (fbp = LIST_FIRST(&vp->v_dirtyblkhd)) != NULL) {
   2562 			ip = VTOI(vp);
   2563 			DLOG((DLOG_SEG, "lfs_cluster_aiodone: mark ino %d\n",
   2564 			       ip->i_number));
   2565 			if (LFS_IS_MALLOC_BUF(fbp))
   2566 				LFS_SET_UINO(ip, IN_CLEANING);
   2567 			else
   2568 				LFS_SET_UINO(ip, IN_MODIFIED);
   2569 		}
   2570 		simple_unlock(&global_v_numoutput_slock);
   2571 		splx(s);
   2572 		wakeup(vp);
   2573 	}
   2574 
   2575 	/* Fix up the cluster buffer, and release it */
   2576 	if (cl->flags & LFS_CL_MALLOC)
   2577 		lfs_free(fs, bp->b_data, LFS_NB_CLUSTER);
   2578 	putiobuf(bp);
   2579 
   2580 	/* Note i/o done */
   2581 	if (cl->flags & LFS_CL_SYNC) {
   2582 		if (--cl->seg->seg_iocount == 0)
   2583 			wakeup(&cl->seg->seg_iocount);
   2584 	}
   2585 	simple_lock(&fs->lfs_interlock);
   2586 #ifdef DIAGNOSTIC
   2587 	if (fs->lfs_iocount == 0)
   2588 		panic("lfs_cluster_aiodone: zero iocount");
   2589 #endif
   2590 	if (--fs->lfs_iocount <= 1)
   2591 		wakeup(&fs->lfs_iocount);
   2592 	simple_unlock(&fs->lfs_interlock);
   2593 
   2594 	pool_put(&fs->lfs_bpppool, cl->bpp);
   2595 	cl->bpp = NULL;
   2596 	pool_put(&fs->lfs_clpool, cl);
   2597 }
   2598 
   2599 static void
   2600 lfs_generic_callback(struct buf *bp, void (*aiodone)(struct buf *))
   2601 {
   2602 	/* reset b_iodone for when this is a single-buf i/o. */
   2603 	bp->b_iodone = aiodone;
   2604 
   2605 	simple_lock(&uvm.aiodoned_lock);	/* locks uvm.aio_done */
   2606 	TAILQ_INSERT_TAIL(&uvm.aio_done, bp, b_freelist);
   2607 	wakeup(&uvm.aiodoned);
   2608 	simple_unlock(&uvm.aiodoned_lock);
   2609 }
   2610 
   2611 static void
   2612 lfs_cluster_callback(struct buf *bp)
   2613 {
   2614 
   2615 	lfs_generic_callback(bp, lfs_cluster_aiodone);
   2616 }
   2617 
   2618 void
   2619 lfs_supercallback(struct buf *bp)
   2620 {
   2621 
   2622 	lfs_generic_callback(bp, lfs_super_aiodone);
   2623 }
   2624 
   2625 /*
   2626  * The only buffers that are going to hit these functions are the
   2627  * segment write blocks, or the segment summaries, or the superblocks.
   2628  *
   2629  * All of the above are created by lfs_newbuf, and so do not need to be
   2630  * released via brelse.
   2631  */
   2632 void
   2633 lfs_callback(struct buf *bp)
   2634 {
   2635 
   2636 	lfs_generic_callback(bp, lfs_free_aiodone);
   2637 }
   2638 
   2639 /*
   2640  * Shellsort (diminishing increment sort) from Data Structures and
   2641  * Algorithms, Aho, Hopcraft and Ullman, 1983 Edition, page 290;
   2642  * see also Knuth Vol. 3, page 84.  The increments are selected from
   2643  * formula (8), page 95.  Roughly O(N^3/2).
   2644  */
   2645 /*
   2646  * This is our own private copy of shellsort because we want to sort
   2647  * two parallel arrays (the array of buffer pointers and the array of
   2648  * logical block numbers) simultaneously.  Note that we cast the array
   2649  * of logical block numbers to a unsigned in this routine so that the
   2650  * negative block numbers (meta data blocks) sort AFTER the data blocks.
   2651  */
   2652 
   2653 void
   2654 lfs_shellsort(struct buf **bp_array, int32_t *lb_array, int nmemb, int size)
   2655 {
   2656 	static int __rsshell_increments[] = { 4, 1, 0 };
   2657 	int incr, *incrp, t1, t2;
   2658 	struct buf *bp_temp;
   2659 
   2660 #ifdef DEBUG
   2661 	incr = 0;
   2662 	for (t1 = 0; t1 < nmemb; t1++) {
   2663 		for (t2 = 0; t2 * size < bp_array[t1]->b_bcount; t2++) {
   2664 			if (lb_array[incr++] != bp_array[t1]->b_lblkno + t2) {
   2665 				/* dump before panic */
   2666 				printf("lfs_shellsort: nmemb=%d, size=%d\n",
   2667 				    nmemb, size);
   2668 				incr = 0;
   2669 				for (t1 = 0; t1 < nmemb; t1++) {
   2670 					const struct buf *bp = bp_array[t1];
   2671 
   2672 					printf("bp[%d]: lbn=%" PRIu64 ", size=%"
   2673 					    PRIu64 "\n", t1,
   2674 					    (uint64_t)bp->b_bcount,
   2675 					    (uint64_t)bp->b_lblkno);
   2676 					printf("lbns:");
   2677 					for (t2 = 0; t2 * size < bp->b_bcount;
   2678 					    t2++) {
   2679 						printf(" %" PRId32,
   2680 						    lb_array[incr++]);
   2681 					}
   2682 					printf("\n");
   2683 				}
   2684 				panic("lfs_shellsort: inconsistent input");
   2685 			}
   2686 		}
   2687 	}
   2688 #endif
   2689 
   2690 	for (incrp = __rsshell_increments; (incr = *incrp++) != 0;)
   2691 		for (t1 = incr; t1 < nmemb; ++t1)
   2692 			for (t2 = t1 - incr; t2 >= 0;)
   2693 				if ((u_int32_t)bp_array[t2]->b_lblkno >
   2694 				    (u_int32_t)bp_array[t2 + incr]->b_lblkno) {
   2695 					bp_temp = bp_array[t2];
   2696 					bp_array[t2] = bp_array[t2 + incr];
   2697 					bp_array[t2 + incr] = bp_temp;
   2698 					t2 -= incr;
   2699 				} else
   2700 					break;
   2701 
   2702 	/* Reform the list of logical blocks */
   2703 	incr = 0;
   2704 	for (t1 = 0; t1 < nmemb; t1++) {
   2705 		for (t2 = 0; t2 * size < bp_array[t1]->b_bcount; t2++) {
   2706 			lb_array[incr++] = bp_array[t1]->b_lblkno + t2;
   2707 		}
   2708 	}
   2709 }
   2710 
   2711 /*
   2712  * Call vget with LK_NOWAIT.  If we are the one who holds VXLOCK/VFREEING,
   2713  * however, we must press on.  Just fake success in that case.
   2714  */
   2715 int
   2716 lfs_vref(struct vnode *vp)
   2717 {
   2718 	int error;
   2719 	struct lfs *fs;
   2720 
   2721 	fs = VTOI(vp)->i_lfs;
   2722 
   2723 	ASSERT_MAYBE_SEGLOCK(fs);
   2724 
   2725 	/*
   2726 	 * If we return 1 here during a flush, we risk vinvalbuf() not
   2727 	 * being able to flush all of the pages from this vnode, which
   2728 	 * will cause it to panic.  So, return 0 if a flush is in progress.
   2729 	 */
   2730 	error = vget(vp, LK_NOWAIT);
   2731 	if (error == EBUSY && IS_FLUSHING(VTOI(vp)->i_lfs, vp)) {
   2732 		++fs->lfs_flushvp_fakevref;
   2733 		return 0;
   2734 	}
   2735 	return error;
   2736 }
   2737 
   2738 /*
   2739  * This is vrele except that we do not want to VOP_INACTIVE this vnode. We
   2740  * inline vrele here to avoid the vn_lock and VOP_INACTIVE call at the end.
   2741  */
   2742 void
   2743 lfs_vunref(struct vnode *vp)
   2744 {
   2745 	struct lfs *fs;
   2746 
   2747 	fs = VTOI(vp)->i_lfs;
   2748 	ASSERT_MAYBE_SEGLOCK(fs);
   2749 
   2750 	/*
   2751 	 * Analogous to lfs_vref, if the node is flushing, fake it.
   2752 	 */
   2753 	if (IS_FLUSHING(fs, vp) && fs->lfs_flushvp_fakevref) {
   2754 		--fs->lfs_flushvp_fakevref;
   2755 		return;
   2756 	}
   2757 
   2758 	simple_lock(&vp->v_interlock);
   2759 #ifdef DIAGNOSTIC
   2760 	if (vp->v_usecount <= 0) {
   2761 		printf("lfs_vunref: inum is %llu\n", (unsigned long long)
   2762 		    VTOI(vp)->i_number);
   2763 		printf("lfs_vunref: flags are 0x%lx\n", (u_long)vp->v_flag);
   2764 		printf("lfs_vunref: usecount = %ld\n", (long)vp->v_usecount);
   2765 		panic("lfs_vunref: v_usecount < 0");
   2766 	}
   2767 #endif
   2768 	vp->v_usecount--;
   2769 	if (vp->v_usecount > 0) {
   2770 		simple_unlock(&vp->v_interlock);
   2771 		return;
   2772 	}
   2773 	/*
   2774 	 * insert at tail of LRU list
   2775 	 */
   2776 	simple_lock(&vnode_free_list_slock);
   2777 	if (vp->v_holdcnt > 0)
   2778 		TAILQ_INSERT_TAIL(&vnode_hold_list, vp, v_freelist);
   2779 	else
   2780 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
   2781 	simple_unlock(&vnode_free_list_slock);
   2782 	simple_unlock(&vp->v_interlock);
   2783 }
   2784 
   2785 /*
   2786  * We use this when we have vnodes that were loaded in solely for cleaning.
   2787  * There is no reason to believe that these vnodes will be referenced again
   2788  * soon, since the cleaning process is unrelated to normal filesystem
   2789  * activity.  Putting cleaned vnodes at the tail of the list has the effect
   2790  * of flushing the vnode LRU.  So, put vnodes that were loaded only for
   2791  * cleaning at the head of the list, instead.
   2792  */
   2793 void
   2794 lfs_vunref_head(struct vnode *vp)
   2795 {
   2796 
   2797 	ASSERT_SEGLOCK(VTOI(vp)->i_lfs);
   2798 	simple_lock(&vp->v_interlock);
   2799 #ifdef DIAGNOSTIC
   2800 	if (vp->v_usecount == 0) {
   2801 		panic("lfs_vunref: v_usecount<0");
   2802 	}
   2803 #endif
   2804 	vp->v_usecount--;
   2805 	if (vp->v_usecount > 0) {
   2806 		simple_unlock(&vp->v_interlock);
   2807 		return;
   2808 	}
   2809 	/*
   2810 	 * insert at head of LRU list
   2811 	 */
   2812 	simple_lock(&vnode_free_list_slock);
   2813 	if (vp->v_holdcnt > 0)
   2814 		TAILQ_INSERT_TAIL(&vnode_hold_list, vp, v_freelist);
   2815 	else
   2816 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
   2817 	simple_unlock(&vnode_free_list_slock);
   2818 	simple_unlock(&vp->v_interlock);
   2819 }
   2820 
   2821 
   2822 /*
   2823  * Set up an FINFO entry for a new file.  The fip pointer is assumed to
   2824  * point at uninitialized space.
   2825  */
   2826 void
   2827 lfs_acquire_finfo(struct lfs *fs, ino_t ino, int vers)
   2828 {
   2829 	struct segment *sp = fs->lfs_sp;
   2830 
   2831 	KASSERT(vers > 0);
   2832 
   2833 	if (sp->seg_bytes_left < fs->lfs_bsize ||
   2834 	    sp->sum_bytes_left < sizeof(struct finfo))
   2835 		(void) lfs_writeseg(fs, fs->lfs_sp);
   2836 
   2837 	sp->sum_bytes_left -= FINFOSIZE;
   2838 	++((SEGSUM *)(sp->segsum))->ss_nfinfo;
   2839 	sp->fip->fi_nblocks = 0;
   2840 	sp->fip->fi_ino = ino;
   2841 	sp->fip->fi_version = vers;
   2842 }
   2843 
   2844 /*
   2845  * Release the FINFO entry, either clearing out an unused entry or
   2846  * advancing us to the next available entry.
   2847  */
   2848 void
   2849 lfs_release_finfo(struct lfs *fs)
   2850 {
   2851 	struct segment *sp = fs->lfs_sp;
   2852 
   2853 	if (sp->fip->fi_nblocks != 0) {
   2854 		sp->fip = (FINFO*)((caddr_t)sp->fip + FINFOSIZE +
   2855 			sizeof(int32_t) * sp->fip->fi_nblocks);
   2856 		sp->start_lbp = &sp->fip->fi_blocks[0];
   2857 	} else {
   2858 		sp->sum_bytes_left += FINFOSIZE;
   2859 		--((SEGSUM *)(sp->segsum))->ss_nfinfo;
   2860 	}
   2861 }
   2862