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