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