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