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