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