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