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