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