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