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