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