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