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