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