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