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