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