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