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