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