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