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