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