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