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