Home | History | Annotate | Line # | Download | only in lfs
lfs_segment.c revision 1.256
      1 /*	$NetBSD: lfs_segment.c,v 1.256 2015/08/12 18:28:01 dholland 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  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 /*
     32  * Copyright (c) 1991, 1993
     33  *	The Regents of the University of California.  All rights reserved.
     34  *
     35  * Redistribution and use in source and binary forms, with or without
     36  * modification, are permitted provided that the following conditions
     37  * are met:
     38  * 1. Redistributions of source code must retain the above copyright
     39  *    notice, this list of conditions and the following disclaimer.
     40  * 2. Redistributions in binary form must reproduce the above copyright
     41  *    notice, this list of conditions and the following disclaimer in the
     42  *    documentation and/or other materials provided with the distribution.
     43  * 3. Neither the name of the University nor the names of its contributors
     44  *    may be used to endorse or promote products derived from this software
     45  *    without specific prior written permission.
     46  *
     47  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     48  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     49  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     50  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     51  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     52  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     53  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     54  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     55  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     56  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     57  * SUCH DAMAGE.
     58  *
     59  *	@(#)lfs_segment.c	8.10 (Berkeley) 6/10/95
     60  */
     61 
     62 #include <sys/cdefs.h>
     63 __KERNEL_RCSID(0, "$NetBSD: lfs_segment.c,v 1.256 2015/08/12 18:28:01 dholland Exp $");
     64 
     65 #define _VFS_VNODE_PRIVATE	/* XXX: check for VI_MARKER, this has to go */
     66 
     67 #ifdef DEBUG
     68 # define vndebug(vp, str) do {						\
     69 	if (VTOI(vp)->i_flag & IN_CLEANING)				\
     70 		DLOG((DLOG_WVNODE, "not writing ino %d because %s (op %d)\n", \
     71 		     VTOI(vp)->i_number, (str), op));			\
     72 } while(0)
     73 #else
     74 # define vndebug(vp, str)
     75 #endif
     76 #define ivndebug(vp, str) \
     77 	DLOG((DLOG_WVNODE, "ino %d: %s\n", VTOI(vp)->i_number, (str)))
     78 
     79 #if defined(_KERNEL_OPT)
     80 #include "opt_ddb.h"
     81 #endif
     82 
     83 #include <sys/param.h>
     84 #include <sys/systm.h>
     85 #include <sys/namei.h>
     86 #include <sys/kernel.h>
     87 #include <sys/resourcevar.h>
     88 #include <sys/file.h>
     89 #include <sys/stat.h>
     90 #include <sys/buf.h>
     91 #include <sys/proc.h>
     92 #include <sys/vnode.h>
     93 #include <sys/mount.h>
     94 #include <sys/kauth.h>
     95 #include <sys/syslog.h>
     96 
     97 #include <miscfs/specfs/specdev.h>
     98 #include <miscfs/fifofs/fifo.h>
     99 
    100 #include <ufs/lfs/ulfs_inode.h>
    101 #include <ufs/lfs/ulfsmount.h>
    102 #include <ufs/lfs/ulfs_extern.h>
    103 
    104 #include <ufs/lfs/lfs.h>
    105 #include <ufs/lfs/lfs_accessors.h>
    106 #include <ufs/lfs/lfs_kernel.h>
    107 #include <ufs/lfs/lfs_extern.h>
    108 
    109 #include <uvm/uvm.h>
    110 #include <uvm/uvm_extern.h>
    111 
    112 MALLOC_JUSTDEFINE(M_SEGMENT, "LFS segment", "Segment for LFS");
    113 
    114 static void lfs_generic_callback(struct buf *, void (*)(struct buf *));
    115 static void lfs_free_aiodone(struct buf *);
    116 static void lfs_super_aiodone(struct buf *);
    117 static void lfs_cluster_aiodone(struct buf *);
    118 static void lfs_cluster_callback(struct buf *);
    119 
    120 /*
    121  * Determine if it's OK to start a partial in this segment, or if we need
    122  * to go on to a new segment.
    123  */
    124 #define	LFS_PARTIAL_FITS(fs) \
    125 	(lfs_sb_getfsbpseg(fs) - \
    126 	    (lfs_sb_getoffset(fs) - lfs_sb_getcurseg(fs)) > \
    127 	lfs_sb_getfrag(fs))
    128 
    129 /*
    130  * Figure out whether we should do a checkpoint write or go ahead with
    131  * an ordinary write.
    132  */
    133 #define LFS_SHOULD_CHECKPOINT(fs, flags) \
    134         ((flags & SEGM_CLEAN) == 0 &&					\
    135 	  ((fs->lfs_nactive > LFS_MAX_ACTIVE ||				\
    136 	    (flags & SEGM_CKP) ||					\
    137 	    lfs_sb_getnclean(fs) < LFS_MAX_ACTIVE)))
    138 
    139 int	 lfs_match_fake(struct lfs *, struct buf *);
    140 void	 lfs_newseg(struct lfs *);
    141 void	 lfs_supercallback(struct buf *);
    142 void	 lfs_updatemeta(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 static void lfs_shellsort(struct lfs *, struct buf **, union lfs_blocks *,
    148 			  int, int);
    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 /*
    166  * XXX KS - Set modification time on the Ifile, so the cleaner can
    167  * read the fs mod time off of it.  We don't set IN_UPDATE here,
    168  * since we don't really need this to be flushed to disk (and in any
    169  * case that wouldn't happen to the Ifile until we checkpoint).
    170  */
    171 void
    172 lfs_imtime(struct lfs *fs)
    173 {
    174 	struct timespec ts;
    175 	struct inode *ip;
    176 
    177 	ASSERT_MAYBE_SEGLOCK(fs);
    178 	vfs_timestamp(&ts);
    179 	ip = VTOI(fs->lfs_ivnode);
    180 	ip->i_ffs1_mtime = ts.tv_sec;
    181 	ip->i_ffs1_mtimensec = ts.tv_nsec;
    182 }
    183 
    184 /*
    185  * Ifile and meta data blocks are not marked busy, so segment writes MUST be
    186  * single threaded.  Currently, there are two paths into lfs_segwrite, sync()
    187  * and getnewbuf().  They both mark the file system busy.  Lfs_vflush()
    188  * explicitly marks the file system busy.  So lfs_segwrite is safe.  I think.
    189  */
    190 
    191 #define IS_FLUSHING(fs,vp)  ((fs)->lfs_flushvp == (vp))
    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;
    201 	int flushed;
    202 	int relock;
    203 
    204 	ip = VTOI(vp);
    205 	fs = VFSTOULFS(vp->v_mount)->um_lfs;
    206 	relock = 0;
    207 
    208     top:
    209 	KASSERT(mutex_owned(vp->v_interlock) == false);
    210 	KASSERT(mutex_owned(&lfs_lock) == false);
    211 	KASSERT(mutex_owned(&bufcache_lock) == false);
    212 	ASSERT_NO_SEGLOCK(fs);
    213 	if (ip->i_flag & IN_CLEANING) {
    214 		ivndebug(vp,"vflush/in_cleaning");
    215 		mutex_enter(&lfs_lock);
    216 		LFS_CLR_UINO(ip, IN_CLEANING);
    217 		LFS_SET_UINO(ip, IN_MODIFIED);
    218 		mutex_exit(&lfs_lock);
    219 
    220 		/*
    221 		 * Toss any cleaning buffers that have real counterparts
    222 		 * to avoid losing new data.
    223 		 */
    224 		mutex_enter(vp->v_interlock);
    225 		for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
    226 			nbp = LIST_NEXT(bp, b_vnbufs);
    227 			if (!LFS_IS_MALLOC_BUF(bp))
    228 				continue;
    229 			/*
    230 			 * Look for pages matching the range covered
    231 			 * by cleaning blocks.  It's okay if more dirty
    232 			 * pages appear, so long as none disappear out
    233 			 * from under us.
    234 			 */
    235 			if (bp->b_lblkno > 0 && vp->v_type == VREG &&
    236 			    vp != fs->lfs_ivnode) {
    237 				struct vm_page *pg;
    238 				voff_t off;
    239 
    240 				for (off = lfs_lblktosize(fs, bp->b_lblkno);
    241 				     off < lfs_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 						lfs_sb_addavail(fs,
    249 							lfs_btofsb(fs,
    250 								bp->b_bcount));
    251 						wakeup(&fs->lfs_availsleep);
    252 						mutex_exit(vp->v_interlock);
    253 						lfs_freebuf(fs, bp);
    254 						mutex_enter(vp->v_interlock);
    255 						bp = NULL;
    256 						break;
    257 					}
    258 				}
    259 			}
    260 			for (tbp = LIST_FIRST(&vp->v_dirtyblkhd); tbp;
    261 			    tbp = tnbp)
    262 			{
    263 				tnbp = LIST_NEXT(tbp, b_vnbufs);
    264 				if (tbp->b_vp == bp->b_vp
    265 				   && tbp->b_lblkno == bp->b_lblkno
    266 				   && tbp != bp)
    267 				{
    268 					lfs_sb_addavail(fs, lfs_btofsb(fs,
    269 						bp->b_bcount));
    270 					wakeup(&fs->lfs_availsleep);
    271 					mutex_exit(vp->v_interlock);
    272 					lfs_freebuf(fs, bp);
    273 					mutex_enter(vp->v_interlock);
    274 					bp = NULL;
    275 					break;
    276 				}
    277 			}
    278 		}
    279 	} else {
    280 		mutex_enter(vp->v_interlock);
    281 	}
    282 
    283 	/* If the node is being written, wait until that is done */
    284 	while (WRITEINPROG(vp)) {
    285 		ivndebug(vp,"vflush/writeinprog");
    286 		cv_wait(&vp->v_cv, vp->v_interlock);
    287 	}
    288 	error = vdead_check(vp, VDEAD_NOWAIT);
    289 	mutex_exit(vp->v_interlock);
    290 
    291 	/* Protect against deadlock in vinvalbuf() */
    292 	lfs_seglock(fs, SEGM_SYNC | ((error != 0) ? SEGM_RECLAIM : 0));
    293 	if (error != 0) {
    294 		fs->lfs_reclino = ip->i_number;
    295 	}
    296 
    297 	/* If we're supposed to flush a freed inode, just toss it */
    298 	if (ip->i_lfs_iflags & LFSI_DELETED) {
    299 		DLOG((DLOG_VNODE, "lfs_vflush: ino %d freed, not flushing\n",
    300 		      ip->i_number));
    301 		/* Drain v_numoutput */
    302 		mutex_enter(vp->v_interlock);
    303 		while (vp->v_numoutput > 0) {
    304 			cv_wait(&vp->v_cv, vp->v_interlock);
    305 		}
    306 		KASSERT(vp->v_numoutput == 0);
    307 		mutex_exit(vp->v_interlock);
    308 
    309 		mutex_enter(&bufcache_lock);
    310 		for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
    311 			nbp = LIST_NEXT(bp, b_vnbufs);
    312 
    313 			KASSERT((bp->b_flags & B_GATHERED) == 0);
    314 			if (bp->b_oflags & BO_DELWRI) { /* XXX always true? */
    315 				lfs_sb_addavail(fs, lfs_btofsb(fs, bp->b_bcount));
    316 				wakeup(&fs->lfs_availsleep);
    317 			}
    318 			/* Copied from lfs_writeseg */
    319 			if (bp->b_iodone != NULL) {
    320 				mutex_exit(&bufcache_lock);
    321 				biodone(bp);
    322 				mutex_enter(&bufcache_lock);
    323 			} else {
    324 				bremfree(bp);
    325 				LFS_UNLOCK_BUF(bp);
    326 				mutex_enter(vp->v_interlock);
    327 				bp->b_flags &= ~(B_READ | B_GATHERED);
    328 				bp->b_oflags = (bp->b_oflags & ~BO_DELWRI) | BO_DONE;
    329 				bp->b_error = 0;
    330 				reassignbuf(bp, vp);
    331 				mutex_exit(vp->v_interlock);
    332 				brelse(bp, 0);
    333 			}
    334 		}
    335 		mutex_exit(&bufcache_lock);
    336 		LFS_CLR_UINO(ip, IN_CLEANING);
    337 		LFS_CLR_UINO(ip, IN_MODIFIED | IN_ACCESSED);
    338 		ip->i_flag &= ~IN_ALLMOD;
    339 		DLOG((DLOG_VNODE, "lfs_vflush: done not flushing ino %d\n",
    340 		      ip->i_number));
    341 		lfs_segunlock(fs);
    342 
    343 		KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
    344 
    345 		return 0;
    346 	}
    347 
    348 	fs->lfs_flushvp = vp;
    349 	if (LFS_SHOULD_CHECKPOINT(fs, fs->lfs_sp->seg_flags)) {
    350 		error = lfs_segwrite(vp->v_mount, SEGM_CKP | SEGM_SYNC);
    351 		fs->lfs_flushvp = NULL;
    352 		KASSERT(fs->lfs_flushvp_fakevref == 0);
    353 		lfs_segunlock(fs);
    354 
    355 		/* Make sure that any pending buffers get written */
    356 		mutex_enter(vp->v_interlock);
    357 		while (vp->v_numoutput > 0) {
    358 			cv_wait(&vp->v_cv, vp->v_interlock);
    359 		}
    360 		KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
    361 		KASSERT(vp->v_numoutput == 0);
    362 		mutex_exit(vp->v_interlock);
    363 
    364 		return error;
    365 	}
    366 	sp = fs->lfs_sp;
    367 
    368 	flushed = 0;
    369 	if (VPISEMPTY(vp)) {
    370 		lfs_writevnodes(fs, vp->v_mount, sp, VN_EMPTY);
    371 		++flushed;
    372 	} else if ((ip->i_flag & IN_CLEANING) &&
    373 		  (fs->lfs_sp->seg_flags & SEGM_CLEAN)) {
    374 		ivndebug(vp,"vflush/clean");
    375 		lfs_writevnodes(fs, vp->v_mount, sp, VN_CLEAN);
    376 		++flushed;
    377 	} else if (lfs_dostats) {
    378 		if (!VPISEMPTY(vp) || (VTOI(vp)->i_flag & IN_ALLMOD))
    379 			++lfs_stats.vflush_invoked;
    380 		ivndebug(vp,"vflush");
    381 	}
    382 
    383 #ifdef DIAGNOSTIC
    384 	if (vp->v_uflag & VU_DIROP) {
    385 		DLOG((DLOG_VNODE, "lfs_vflush: flushing VU_DIROP\n"));
    386 		/* panic("lfs_vflush: VU_DIROP being flushed...this can\'t happen"); */
    387 	}
    388 #endif
    389 
    390 	do {
    391 #ifdef DEBUG
    392 		int loopcount = 0;
    393 #endif
    394 		do {
    395 			if (LIST_FIRST(&vp->v_dirtyblkhd) != NULL) {
    396 				relock = lfs_writefile(fs, sp, vp);
    397 				if (relock && vp != fs->lfs_ivnode) {
    398 					/*
    399 					 * Might have to wait for the
    400 					 * cleaner to run; but we're
    401 					 * still not done with this vnode.
    402 					 * XXX we can do better than this.
    403 					 */
    404 					KDASSERT(ip->i_number != LFS_IFILE_INUM);
    405 					lfs_writeinode(fs, sp, ip);
    406 					mutex_enter(&lfs_lock);
    407 					LFS_SET_UINO(ip, IN_MODIFIED);
    408 					mutex_exit(&lfs_lock);
    409 					lfs_writeseg(fs, sp);
    410 					lfs_segunlock(fs);
    411 					lfs_segunlock_relock(fs);
    412 					goto top;
    413 				}
    414 			}
    415 			/*
    416 			 * If we begin a new segment in the middle of writing
    417 			 * the Ifile, it creates an inconsistent checkpoint,
    418 			 * since the Ifile information for the new segment
    419 			 * is not up-to-date.  Take care of this here by
    420 			 * sending the Ifile through again in case there
    421 			 * are newly dirtied blocks.  But wait, there's more!
    422 			 * This second Ifile write could *also* cross a segment
    423 			 * boundary, if the first one was large.  The second
    424 			 * one is guaranteed to be no more than 8 blocks,
    425 			 * though (two segment blocks and supporting indirects)
    426 			 * so the third write *will not* cross the boundary.
    427 			 */
    428 			if (vp == fs->lfs_ivnode) {
    429 				lfs_writefile(fs, sp, vp);
    430 				lfs_writefile(fs, sp, vp);
    431 			}
    432 #ifdef DEBUG
    433 			if (++loopcount > 2)
    434 				log(LOG_NOTICE, "lfs_vflush: looping count=%d\n", loopcount);
    435 #endif
    436 		} while (lfs_writeinode(fs, sp, ip));
    437 	} while (lfs_writeseg(fs, sp) && ip->i_number == LFS_IFILE_INUM);
    438 
    439 	if (lfs_dostats) {
    440 		++lfs_stats.nwrites;
    441 		if (sp->seg_flags & SEGM_SYNC)
    442 			++lfs_stats.nsync_writes;
    443 		if (sp->seg_flags & SEGM_CKP)
    444 			++lfs_stats.ncheckpoints;
    445 	}
    446 	/*
    447 	 * If we were called from somewhere that has already held the seglock
    448 	 * (e.g., lfs_markv()), the lfs_segunlock will not wait for
    449 	 * the write to complete because we are still locked.
    450 	 * Since lfs_vflush() must return the vnode with no dirty buffers,
    451 	 * we must explicitly wait, if that is the case.
    452 	 *
    453 	 * We compare the iocount against 1, not 0, because it is
    454 	 * artificially incremented by lfs_seglock().
    455 	 */
    456 	mutex_enter(&lfs_lock);
    457 	if (fs->lfs_seglock > 1) {
    458 		while (fs->lfs_iocount > 1)
    459 			(void)mtsleep(&fs->lfs_iocount, PRIBIO + 1,
    460 				     "lfs_vflush", 0, &lfs_lock);
    461 	}
    462 	mutex_exit(&lfs_lock);
    463 
    464 	lfs_segunlock(fs);
    465 
    466 	/* Wait for these buffers to be recovered by aiodoned */
    467 	mutex_enter(vp->v_interlock);
    468 	while (vp->v_numoutput > 0) {
    469 		cv_wait(&vp->v_cv, vp->v_interlock);
    470 	}
    471 	KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
    472 	KASSERT(vp->v_numoutput == 0);
    473 	mutex_exit(vp->v_interlock);
    474 
    475 	fs->lfs_flushvp = NULL;
    476 	KASSERT(fs->lfs_flushvp_fakevref == 0);
    477 
    478 	return (0);
    479 }
    480 
    481 int
    482 lfs_writevnodes(struct lfs *fs, struct mount *mp, struct segment *sp, int op)
    483 {
    484 	struct inode *ip;
    485 	struct vnode *vp;
    486 	int inodes_written = 0;
    487 	int error = 0;
    488 
    489 	ASSERT_SEGLOCK(fs);
    490  loop:
    491 	/* start at last (newest) vnode. */
    492 	mutex_enter(&mntvnode_lock);
    493 	TAILQ_FOREACH_REVERSE(vp, &mp->mnt_vnodelist, vnodelst, v_mntvnodes) {
    494 		/*
    495 		 * If the vnode that we are about to sync is no longer
    496 		 * associated with this mount point, start over.
    497 		 */
    498 		if (vp->v_mount != mp) {
    499 			DLOG((DLOG_VNODE, "lfs_writevnodes: starting over\n"));
    500 			/*
    501 			 * After this, pages might be busy
    502 			 * due to our own previous putpages.
    503 			 * Start actual segment write here to avoid deadlock.
    504 			 * If we were just writing one segment and we've done
    505 			 * that, break out.
    506 			 */
    507 			mutex_exit(&mntvnode_lock);
    508 			if (lfs_writeseg(fs, sp) &&
    509 			    (sp->seg_flags & SEGM_SINGLE) &&
    510 			    lfs_sb_getcurseg(fs) != fs->lfs_startseg) {
    511 				DLOG((DLOG_VNODE, "lfs_writevnodes: breaking out of segment write at daddr 0x%jx\n", (uintmax_t)lfs_sb_getoffset(fs)));
    512 				break;
    513 			}
    514 			goto loop;
    515 		}
    516 
    517 		mutex_enter(vp->v_interlock);
    518 		if (vp->v_type == VNON || (vp->v_iflag & VI_MARKER) ||
    519 		    vdead_check(vp, VDEAD_NOWAIT) != 0) {
    520 			mutex_exit(vp->v_interlock);
    521 			continue;
    522 		}
    523 
    524 		ip = VTOI(vp);
    525 		if ((op == VN_DIROP && !(vp->v_uflag & VU_DIROP)) ||
    526 		    (op != VN_DIROP && op != VN_CLEAN &&
    527 		    (vp->v_uflag & VU_DIROP))) {
    528 			mutex_exit(vp->v_interlock);
    529 			vndebug(vp,"dirop");
    530 			continue;
    531 		}
    532 
    533 		if (op == VN_EMPTY && !VPISEMPTY(vp)) {
    534 			mutex_exit(vp->v_interlock);
    535 			vndebug(vp,"empty");
    536 			continue;
    537 		}
    538 
    539 		if (op == VN_CLEAN && ip->i_number != LFS_IFILE_INUM
    540 		   && vp != fs->lfs_flushvp
    541 		   && !(ip->i_flag & IN_CLEANING)) {
    542 			mutex_exit(vp->v_interlock);
    543 			vndebug(vp,"cleaning");
    544 			continue;
    545 		}
    546 
    547 		mutex_exit(&mntvnode_lock);
    548 		if (vget(vp, LK_NOWAIT, false /* !wait */)) {
    549 			vndebug(vp,"vget");
    550 			mutex_enter(&mntvnode_lock);
    551 			continue;
    552 		}
    553 
    554 		/*
    555 		 * Write the inode/file if dirty and it's not the IFILE.
    556 		 */
    557 		if ((ip->i_flag & IN_ALLMOD) || !VPISEMPTY(vp)) {
    558 			if (ip->i_number != LFS_IFILE_INUM) {
    559 				error = lfs_writefile(fs, sp, vp);
    560 				if (error) {
    561 					vrele(vp);
    562 					if (error == EAGAIN) {
    563 						/*
    564 						 * This error from lfs_putpages
    565 						 * indicates we need to drop
    566 						 * the segment lock and start
    567 						 * over after the cleaner has
    568 						 * had a chance to run.
    569 						 */
    570 						lfs_writeinode(fs, sp, ip);
    571 						lfs_writeseg(fs, sp);
    572 						if (!VPISEMPTY(vp) &&
    573 						    !WRITEINPROG(vp) &&
    574 						    !(ip->i_flag & IN_ALLMOD)) {
    575 							mutex_enter(&lfs_lock);
    576 							LFS_SET_UINO(ip, IN_MODIFIED);
    577 							mutex_exit(&lfs_lock);
    578 						}
    579 						mutex_enter(&mntvnode_lock);
    580 						break;
    581 					}
    582 					error = 0; /* XXX not quite right */
    583 					mutex_enter(&mntvnode_lock);
    584 					continue;
    585 				}
    586 
    587 				if (!VPISEMPTY(vp)) {
    588 					if (WRITEINPROG(vp)) {
    589 						ivndebug(vp,"writevnodes/write2");
    590 					} else if (!(ip->i_flag & IN_ALLMOD)) {
    591 						mutex_enter(&lfs_lock);
    592 						LFS_SET_UINO(ip, IN_MODIFIED);
    593 						mutex_exit(&lfs_lock);
    594 					}
    595 				}
    596 				(void) lfs_writeinode(fs, sp, ip);
    597 				inodes_written++;
    598 			}
    599 		}
    600 
    601 		vrele(vp);
    602 
    603 		mutex_enter(&mntvnode_lock);
    604 	}
    605 	mutex_exit(&mntvnode_lock);
    606 	return error;
    607 }
    608 
    609 /*
    610  * Do a checkpoint.
    611  */
    612 int
    613 lfs_segwrite(struct mount *mp, int flags)
    614 {
    615 	struct buf *bp;
    616 	struct inode *ip;
    617 	struct lfs *fs;
    618 	struct segment *sp;
    619 	struct vnode *vp;
    620 	SEGUSE *segusep;
    621 	int do_ckp, did_ckp, error;
    622 	unsigned n, segleft, maxseg, sn, i, curseg;
    623 	int writer_set = 0;
    624 	int dirty;
    625 	int redo;
    626 	SEGSUM *ssp;
    627 	int um_error;
    628 
    629 	fs = VFSTOULFS(mp)->um_lfs;
    630 	ASSERT_MAYBE_SEGLOCK(fs);
    631 
    632 	if (fs->lfs_ronly)
    633 		return EROFS;
    634 
    635 	lfs_imtime(fs);
    636 
    637 	/*
    638 	 * Allocate a segment structure and enough space to hold pointers to
    639 	 * the maximum possible number of buffers which can be described in a
    640 	 * single summary block.
    641 	 */
    642 	do_ckp = LFS_SHOULD_CHECKPOINT(fs, flags);
    643 
    644 	/* We can't do a partial write and checkpoint at the same time. */
    645 	if (do_ckp)
    646 		flags &= ~SEGM_SINGLE;
    647 
    648 	lfs_seglock(fs, flags | (do_ckp ? SEGM_CKP : 0));
    649 	sp = fs->lfs_sp;
    650 	if (sp->seg_flags & (SEGM_CLEAN | SEGM_CKP))
    651 		do_ckp = 1;
    652 
    653 	/*
    654 	 * If lfs_flushvp is non-NULL, we are called from lfs_vflush,
    655 	 * in which case we have to flush *all* buffers off of this vnode.
    656 	 * We don't care about other nodes, but write any non-dirop nodes
    657 	 * anyway in anticipation of another getnewvnode().
    658 	 *
    659 	 * If we're cleaning we only write cleaning and ifile blocks, and
    660 	 * no dirops, since otherwise we'd risk corruption in a crash.
    661 	 */
    662 	if (sp->seg_flags & SEGM_CLEAN)
    663 		lfs_writevnodes(fs, mp, sp, VN_CLEAN);
    664 	else if (!(sp->seg_flags & SEGM_FORCE_CKP)) {
    665 		do {
    666 			um_error = lfs_writevnodes(fs, mp, sp, VN_REG);
    667 			if ((sp->seg_flags & SEGM_SINGLE) &&
    668 			    lfs_sb_getcurseg(fs) != fs->lfs_startseg) {
    669 				DLOG((DLOG_SEG, "lfs_segwrite: breaking out of segment write at daddr 0x%jx\n", (uintmax_t)lfs_sb_getoffset(fs)));
    670 				break;
    671 			}
    672 
    673 			if (do_ckp || fs->lfs_dirops == 0) {
    674 				if (!writer_set) {
    675 					lfs_writer_enter(fs, "lfs writer");
    676 					writer_set = 1;
    677 				}
    678 				error = lfs_writevnodes(fs, mp, sp, VN_DIROP);
    679 				if (um_error == 0)
    680 					um_error = error;
    681 				/* In case writevnodes errored out */
    682 				lfs_flush_dirops(fs);
    683 				ssp = (SEGSUM *)(sp->segsum);
    684 				lfs_ss_setflags(fs, ssp,
    685 						lfs_ss_getflags(fs, ssp) & ~(SS_CONT));
    686 				lfs_finalize_fs_seguse(fs);
    687 			}
    688 			if (do_ckp && um_error) {
    689 				lfs_segunlock_relock(fs);
    690 				sp = fs->lfs_sp;
    691 			}
    692 		} while (do_ckp && um_error != 0);
    693 	}
    694 
    695 	/*
    696 	 * If we are doing a checkpoint, mark everything since the
    697 	 * last checkpoint as no longer ACTIVE.
    698 	 */
    699 	if (do_ckp || fs->lfs_doifile) {
    700 		segleft = lfs_sb_getnseg(fs);
    701 		curseg = 0;
    702 		for (n = 0; n < lfs_sb_getsegtabsz(fs); n++) {
    703 			dirty = 0;
    704 			if (bread(fs->lfs_ivnode, lfs_sb_getcleansz(fs) + n,
    705 			    lfs_sb_getbsize(fs), B_MODIFY, &bp))
    706 				panic("lfs_segwrite: ifile read");
    707 			segusep = (SEGUSE *)bp->b_data;
    708 			maxseg = min(segleft, lfs_sb_getsepb(fs));
    709 			for (i = 0; i < maxseg; i++) {
    710 				sn = curseg + i;
    711 				if (sn != lfs_dtosn(fs, lfs_sb_getcurseg(fs)) &&
    712 				    segusep->su_flags & SEGUSE_ACTIVE) {
    713 					segusep->su_flags &= ~SEGUSE_ACTIVE;
    714 					--fs->lfs_nactive;
    715 					++dirty;
    716 				}
    717 				fs->lfs_suflags[fs->lfs_activesb][sn] =
    718 					segusep->su_flags;
    719 				if (lfs_sb_getversion(fs) > 1)
    720 					++segusep;
    721 				else
    722 					segusep = (SEGUSE *)
    723 						((SEGUSE_V1 *)segusep + 1);
    724 			}
    725 
    726 			if (dirty)
    727 				error = LFS_BWRITE_LOG(bp); /* Ifile */
    728 			else
    729 				brelse(bp, 0);
    730 			segleft -= lfs_sb_getsepb(fs);
    731 			curseg += lfs_sb_getsepb(fs);
    732 		}
    733 	}
    734 
    735 	KASSERT(LFS_SEGLOCK_HELD(fs));
    736 
    737 	did_ckp = 0;
    738 	if (do_ckp || fs->lfs_doifile) {
    739 		vp = fs->lfs_ivnode;
    740 #ifdef DEBUG
    741 		int loopcount = 0;
    742 #endif
    743 		do {
    744 #ifdef DEBUG
    745 			LFS_ENTER_LOG("pretend", __FILE__, __LINE__, 0, 0, curproc->p_pid);
    746 #endif
    747 			mutex_enter(&lfs_lock);
    748 			fs->lfs_flags &= ~LFS_IFDIRTY;
    749 			mutex_exit(&lfs_lock);
    750 
    751 			ip = VTOI(vp);
    752 
    753 			if (LIST_FIRST(&vp->v_dirtyblkhd) != NULL) {
    754 				/*
    755 				 * Ifile has no pages, so we don't need
    756 				 * to check error return here.
    757 				 */
    758 				lfs_writefile(fs, sp, vp);
    759 				/*
    760 				 * Ensure the Ifile takes the current segment
    761 				 * into account.  See comment in lfs_vflush.
    762 				 */
    763 				lfs_writefile(fs, sp, vp);
    764 				lfs_writefile(fs, sp, vp);
    765 			}
    766 
    767 			if (ip->i_flag & IN_ALLMOD)
    768 				++did_ckp;
    769 #if 0
    770 			redo = (do_ckp ? lfs_writeinode(fs, sp, ip) : 0);
    771 #else
    772 			redo = lfs_writeinode(fs, sp, ip);
    773 #endif
    774 			redo += lfs_writeseg(fs, sp);
    775 			mutex_enter(&lfs_lock);
    776 			redo += (fs->lfs_flags & LFS_IFDIRTY);
    777 			mutex_exit(&lfs_lock);
    778 #ifdef DEBUG
    779 			if (++loopcount > 2)
    780 				log(LOG_NOTICE, "lfs_segwrite: looping count=%d\n",
    781 					loopcount);
    782 #endif
    783 		} while (redo && do_ckp);
    784 
    785 		/*
    786 		 * Unless we are unmounting, the Ifile may continue to have
    787 		 * dirty blocks even after a checkpoint, due to changes to
    788 		 * inodes' atime.  If we're checkpointing, it's "impossible"
    789 		 * for other parts of the Ifile to be dirty after the loop
    790 		 * above, since we hold the segment lock.
    791 		 */
    792 		mutex_enter(vp->v_interlock);
    793 		if (LIST_EMPTY(&vp->v_dirtyblkhd)) {
    794 			LFS_CLR_UINO(ip, IN_ALLMOD);
    795 		}
    796 #ifdef DIAGNOSTIC
    797 		else if (do_ckp) {
    798 			int do_panic = 0;
    799 			LIST_FOREACH(bp, &vp->v_dirtyblkhd, b_vnbufs) {
    800 				if (bp->b_lblkno < lfs_sb_getcleansz(fs) +
    801 				    lfs_sb_getsegtabsz(fs) &&
    802 				    !(bp->b_flags & B_GATHERED)) {
    803 					printf("ifile lbn %ld still dirty (flags %lx)\n",
    804 						(long)bp->b_lblkno,
    805 						(long)bp->b_flags);
    806 					++do_panic;
    807 				}
    808 			}
    809 			if (do_panic)
    810 				panic("dirty blocks");
    811 		}
    812 #endif
    813 		mutex_exit(vp->v_interlock);
    814 	} else {
    815 		(void) lfs_writeseg(fs, sp);
    816 	}
    817 
    818 	/* Note Ifile no longer needs to be written */
    819 	fs->lfs_doifile = 0;
    820 	if (writer_set)
    821 		lfs_writer_leave(fs);
    822 
    823 	/*
    824 	 * If we didn't write the Ifile, we didn't really do anything.
    825 	 * That means that (1) there is a checkpoint on disk and (2)
    826 	 * nothing has changed since it was written.
    827 	 *
    828 	 * Take the flags off of the segment so that lfs_segunlock
    829 	 * doesn't have to write the superblock either.
    830 	 */
    831 	if (do_ckp && !did_ckp) {
    832 		sp->seg_flags &= ~SEGM_CKP;
    833 	}
    834 
    835 	if (lfs_dostats) {
    836 		++lfs_stats.nwrites;
    837 		if (sp->seg_flags & SEGM_SYNC)
    838 			++lfs_stats.nsync_writes;
    839 		if (sp->seg_flags & SEGM_CKP)
    840 			++lfs_stats.ncheckpoints;
    841 	}
    842 	lfs_segunlock(fs);
    843 	return (0);
    844 }
    845 
    846 /*
    847  * Write the dirty blocks associated with a vnode.
    848  */
    849 int
    850 lfs_writefile(struct lfs *fs, struct segment *sp, struct vnode *vp)
    851 {
    852 	struct inode *ip;
    853 	int i, frag;
    854 	SEGSUM *ssp;
    855 	int error;
    856 
    857 	ASSERT_SEGLOCK(fs);
    858 	error = 0;
    859 	ip = VTOI(vp);
    860 
    861 	lfs_acquire_finfo(fs, ip->i_number, ip->i_gen);
    862 
    863 	if (vp->v_uflag & VU_DIROP) {
    864 		ssp = (SEGSUM *)sp->segsum;
    865 		lfs_ss_setflags(fs, ssp,
    866 				lfs_ss_getflags(fs, ssp) | (SS_DIROP|SS_CONT));
    867 	}
    868 
    869 	if (sp->seg_flags & SEGM_CLEAN) {
    870 		lfs_gather(fs, sp, vp, lfs_match_fake);
    871 		/*
    872 		 * For a file being flushed, we need to write *all* blocks.
    873 		 * This means writing the cleaning blocks first, and then
    874 		 * immediately following with any non-cleaning blocks.
    875 		 * The same is true of the Ifile since checkpoints assume
    876 		 * that all valid Ifile blocks are written.
    877 		 */
    878 		if (IS_FLUSHING(fs, vp) || vp == fs->lfs_ivnode) {
    879 			lfs_gather(fs, sp, vp, lfs_match_data);
    880 			/*
    881 			 * Don't call VOP_PUTPAGES: if we're flushing,
    882 			 * we've already done it, and the Ifile doesn't
    883 			 * use the page cache.
    884 			 */
    885 		}
    886 	} else {
    887 		lfs_gather(fs, sp, vp, lfs_match_data);
    888 		/*
    889 		 * If we're flushing, we've already called VOP_PUTPAGES
    890 		 * so don't do it again.  Otherwise, we want to write
    891 		 * everything we've got.
    892 		 */
    893 		if (!IS_FLUSHING(fs, vp)) {
    894 			mutex_enter(vp->v_interlock);
    895 			error = VOP_PUTPAGES(vp, 0, 0,
    896 				PGO_CLEANIT | PGO_ALLPAGES | PGO_LOCKED);
    897 		}
    898 	}
    899 
    900 	/*
    901 	 * It may not be necessary to write the meta-data blocks at this point,
    902 	 * as the roll-forward recovery code should be able to reconstruct the
    903 	 * list.
    904 	 *
    905 	 * We have to write them anyway, though, under two conditions: (1) the
    906 	 * vnode is being flushed (for reuse by vinvalbuf); or (2) we are
    907 	 * checkpointing.
    908 	 *
    909 	 * BUT if we are cleaning, we might have indirect blocks that refer to
    910 	 * new blocks not being written yet, in addition to fragments being
    911 	 * moved out of a cleaned segment.  If that is the case, don't
    912 	 * write the indirect blocks, or the finfo will have a small block
    913 	 * in the middle of it!
    914 	 * XXX in this case isn't the inode size wrong too?
    915 	 */
    916 	frag = 0;
    917 	if (sp->seg_flags & SEGM_CLEAN) {
    918 		for (i = 0; i < ULFS_NDADDR; i++)
    919 			if (ip->i_lfs_fragsize[i] > 0 &&
    920 			    ip->i_lfs_fragsize[i] < lfs_sb_getbsize(fs))
    921 				++frag;
    922 	}
    923 #ifdef DIAGNOSTIC
    924 	if (frag > 1)
    925 		panic("lfs_writefile: more than one fragment!");
    926 #endif
    927 	if (IS_FLUSHING(fs, vp) ||
    928 	    (frag == 0 && (lfs_writeindir || (sp->seg_flags & SEGM_CKP)))) {
    929 		lfs_gather(fs, sp, vp, lfs_match_indir);
    930 		lfs_gather(fs, sp, vp, lfs_match_dindir);
    931 		lfs_gather(fs, sp, vp, lfs_match_tindir);
    932 	}
    933 	lfs_release_finfo(fs);
    934 
    935 	return error;
    936 }
    937 
    938 /*
    939  * Update segment accounting to reflect this inode's change of address.
    940  */
    941 static int
    942 lfs_update_iaddr(struct lfs *fs, struct segment *sp, struct inode *ip, daddr_t ndaddr)
    943 {
    944 	struct buf *bp;
    945 	daddr_t daddr;
    946 	IFILE *ifp;
    947 	SEGUSE *sup;
    948 	ino_t ino;
    949 	int redo_ifile;
    950 	u_int32_t sn;
    951 
    952 	redo_ifile = 0;
    953 
    954 	/*
    955 	 * If updating the ifile, update the super-block.  Update the disk
    956 	 * address and access times for this inode in the ifile.
    957 	 */
    958 	ino = ip->i_number;
    959 	if (ino == LFS_IFILE_INUM) {
    960 		daddr = lfs_sb_getidaddr(fs);
    961 		lfs_sb_setidaddr(fs, LFS_DBTOFSB(fs, ndaddr));
    962 	} else {
    963 		LFS_IENTRY(ifp, fs, ino, bp);
    964 		daddr = lfs_if_getdaddr(fs, ifp);
    965 		lfs_if_setdaddr(fs, ifp, LFS_DBTOFSB(fs, ndaddr));
    966 		(void)LFS_BWRITE_LOG(bp); /* Ifile */
    967 	}
    968 
    969 	/*
    970 	 * If this is the Ifile and lfs_offset is set to the first block
    971 	 * in the segment, dirty the new segment's accounting block
    972 	 * (XXX should already be dirty?) and tell the caller to do it again.
    973 	 */
    974 	if (ip->i_number == LFS_IFILE_INUM) {
    975 		sn = lfs_dtosn(fs, lfs_sb_getoffset(fs));
    976 		if (lfs_sntod(fs, sn) + lfs_btofsb(fs, lfs_sb_getsumsize(fs)) ==
    977 		    lfs_sb_getoffset(fs)) {
    978 			LFS_SEGENTRY(sup, fs, sn, bp);
    979 			KASSERT(bp->b_oflags & BO_DELWRI);
    980 			LFS_WRITESEGENTRY(sup, fs, sn, bp);
    981 			/* fs->lfs_flags |= LFS_IFDIRTY; */
    982 			redo_ifile |= 1;
    983 		}
    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 >= lfs_sb_getlastpseg(fs) && daddr <= lfs_sb_getoffset(fs)) {
    997 		++sp->ndupino;
    998 		DLOG((DLOG_SEG, "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 = lfs_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 + DINOSIZE(fs) * ndupino < DINOSIZE(fs)) {
   1015 			printf("lfs_writeinode: negative bytes "
   1016 			       "(segment %" PRIu32 " short by %d, "
   1017 			       "oldsn=%" PRIu32 ", cursn=%" PRIu32
   1018 			       ", daddr=%" PRId64 ", su_nbytes=%u, "
   1019 			       "ndupino=%d)\n",
   1020 			       lfs_dtosn(fs, daddr),
   1021 			       (int)DINOSIZE(fs) *
   1022 				   (1 - sp->ndupino) - sup->su_nbytes,
   1023 			       oldsn, sp->seg_number, daddr,
   1024 			       (unsigned int)sup->su_nbytes,
   1025 			       sp->ndupino);
   1026 			panic("lfs_writeinode: negative bytes");
   1027 			sup->su_nbytes = DINOSIZE(fs);
   1028 		}
   1029 #endif
   1030 		DLOG((DLOG_SU, "seg %d -= %d for ino %d inode\n",
   1031 		      lfs_dtosn(fs, daddr), DINOSIZE(fs), ino));
   1032 		sup->su_nbytes -= DINOSIZE(fs);
   1033 		redo_ifile |=
   1034 			(ino == LFS_IFILE_INUM && !(bp->b_flags & B_GATHERED));
   1035 		if (redo_ifile) {
   1036 			mutex_enter(&lfs_lock);
   1037 			fs->lfs_flags |= LFS_IFDIRTY;
   1038 			mutex_exit(&lfs_lock);
   1039 			/* Don't double-account */
   1040 			lfs_sb_setidaddr(fs, 0x0);
   1041 		}
   1042 		LFS_WRITESEGENTRY(sup, fs, oldsn, bp); /* Ifile */
   1043 	}
   1044 
   1045 	return redo_ifile;
   1046 }
   1047 
   1048 int
   1049 lfs_writeinode(struct lfs *fs, struct segment *sp, struct inode *ip)
   1050 {
   1051 	struct buf *bp;
   1052 	union lfs_dinode *cdp;
   1053 	struct vnode *vp = ITOV(ip);
   1054 	daddr_t daddr;
   1055 	int i, ndx;
   1056 	int redo_ifile = 0;
   1057 	int gotblk = 0;
   1058 	int count;
   1059 	SEGSUM *ssp;
   1060 
   1061 	ASSERT_SEGLOCK(fs);
   1062 	if (!(ip->i_flag & IN_ALLMOD) && !(vp->v_uflag & VU_DIROP))
   1063 		return (0);
   1064 
   1065 	/* Can't write ifile when writer is not set */
   1066 	KASSERT(ip->i_number != LFS_IFILE_INUM || fs->lfs_writer > 0 ||
   1067 		(sp->seg_flags & SEGM_CLEAN));
   1068 
   1069 	/*
   1070 	 * If this is the Ifile, see if writing it here will generate a
   1071 	 * temporary misaccounting.  If it will, do the accounting and write
   1072 	 * the blocks, postponing the inode write until the accounting is
   1073 	 * solid.
   1074 	 */
   1075 	count = 0;
   1076 	while (vp == fs->lfs_ivnode) {
   1077 		int redo = 0;
   1078 
   1079 		if (sp->idp == NULL && sp->ibp == NULL &&
   1080 		    (sp->seg_bytes_left < lfs_sb_getibsize(fs) ||
   1081 		     sp->sum_bytes_left < sizeof(int32_t))) {
   1082 			(void) lfs_writeseg(fs, sp);
   1083 			continue;
   1084 		}
   1085 
   1086 		/* Look for dirty Ifile blocks */
   1087 		LIST_FOREACH(bp, &fs->lfs_ivnode->v_dirtyblkhd, b_vnbufs) {
   1088 			if (!(bp->b_flags & B_GATHERED)) {
   1089 				redo = 1;
   1090 				break;
   1091 			}
   1092 		}
   1093 
   1094 		if (redo == 0)
   1095 			redo = lfs_update_iaddr(fs, sp, ip, 0x0);
   1096 		if (redo == 0)
   1097 			break;
   1098 
   1099 		if (sp->idp) {
   1100 			lfs_dino_setinumber(fs, sp->idp, 0);
   1101 			sp->idp = NULL;
   1102 		}
   1103 		++count;
   1104 		if (count > 2)
   1105 			log(LOG_NOTICE, "lfs_writeinode: looping count=%d\n", count);
   1106 		lfs_writefile(fs, sp, fs->lfs_ivnode);
   1107 	}
   1108 
   1109 	/* Allocate a new inode block if necessary. */
   1110 	if ((ip->i_number != LFS_IFILE_INUM || sp->idp == NULL) &&
   1111 	    sp->ibp == NULL) {
   1112 		/* Allocate a new segment if necessary. */
   1113 		if (sp->seg_bytes_left < lfs_sb_getibsize(fs) ||
   1114 		    sp->sum_bytes_left < sizeof(int32_t))
   1115 			(void) lfs_writeseg(fs, sp);
   1116 
   1117 		/* Get next inode block. */
   1118 		daddr = lfs_sb_getoffset(fs);
   1119 		lfs_sb_addoffset(fs, lfs_btofsb(fs, lfs_sb_getibsize(fs)));
   1120 		sp->ibp = *sp->cbpp++ =
   1121 			getblk(VTOI(fs->lfs_ivnode)->i_devvp,
   1122 			    LFS_FSBTODB(fs, daddr), lfs_sb_getibsize(fs), 0, 0);
   1123 		gotblk++;
   1124 
   1125 		/* Zero out inode numbers */
   1126 		for (i = 0; i < LFS_INOPB(fs); ++i) {
   1127 			union lfs_dinode *tmpdi;
   1128 
   1129 			tmpdi = (union lfs_dinode *)((char *)sp->ibp->b_data +
   1130 						     DINOSIZE(fs) * i);
   1131 			lfs_dino_setinumber(fs, tmpdi, 0);
   1132 		}
   1133 
   1134 		++sp->start_bpp;
   1135 		lfs_sb_subavail(fs, lfs_btofsb(fs, lfs_sb_getibsize(fs)));
   1136 		/* Set remaining space counters. */
   1137 		sp->seg_bytes_left -= lfs_sb_getibsize(fs);
   1138 		sp->sum_bytes_left -= sizeof(int32_t);
   1139 		ndx = lfs_sb_getsumsize(fs) / sizeof(int32_t) -
   1140 			sp->ninodes / LFS_INOPB(fs) - 1;
   1141 		/* XXX ondisk32 */
   1142 		((int32_t *)(sp->segsum))[ndx] = daddr;
   1143 	}
   1144 
   1145 	/* Check VU_DIROP in case there is a new file with no data blocks */
   1146 	if (vp->v_uflag & VU_DIROP) {
   1147 		ssp = (SEGSUM *)sp->segsum;
   1148 		lfs_ss_setflags(fs, ssp,
   1149 				lfs_ss_getflags(fs, ssp) | (SS_DIROP|SS_CONT));
   1150 	}
   1151 
   1152 	/* Update the inode times and copy the inode onto the inode page. */
   1153 	/* XXX kludge --- don't redirty the ifile just to put times on it */
   1154 	if (ip->i_number != LFS_IFILE_INUM)
   1155 		LFS_ITIMES(ip, NULL, NULL, NULL);
   1156 
   1157 	/*
   1158 	 * If this is the Ifile, and we've already written the Ifile in this
   1159 	 * partial segment, just overwrite it (it's not on disk yet) and
   1160 	 * continue.
   1161 	 *
   1162 	 * XXX we know that the bp that we get the second time around has
   1163 	 * already been gathered.
   1164 	 */
   1165 	if (ip->i_number == LFS_IFILE_INUM && sp->idp) {
   1166 		if (fs->lfs_is64) {
   1167 			sp->idp->u_64 = *ip->i_din.ffs2_din;
   1168 		} else {
   1169 			sp->idp->u_32 = *ip->i_din.ffs1_din;
   1170 		}
   1171 		ip->i_lfs_osize = ip->i_size;
   1172 		return 0;
   1173 	}
   1174 
   1175 	bp = sp->ibp;
   1176 	cdp = (union lfs_dinode *)((char *)bp->b_data + DINOSIZE(fs) * (sp->ninodes % LFS_INOPB(fs)));
   1177 	if (fs->lfs_is64) {
   1178 		cdp->u_64 = *ip->i_din.ffs2_din;
   1179 	} else {
   1180 		cdp->u_32 = *ip->i_din.ffs1_din;
   1181 	}
   1182 
   1183 	/*
   1184 	 * This inode is on its way to disk; clear its VU_DIROP status when
   1185 	 * the write is complete.
   1186 	 */
   1187 	if (vp->v_uflag & VU_DIROP) {
   1188 		if (!(sp->seg_flags & SEGM_CLEAN))
   1189 			ip->i_flag |= IN_CDIROP;
   1190 		else {
   1191 			DLOG((DLOG_DIROP, "lfs_writeinode: not clearing dirop for cleaned ino %d\n", (int)ip->i_number));
   1192 		}
   1193 	}
   1194 
   1195 	/*
   1196 	 * If cleaning, link counts and directory file sizes cannot change,
   1197 	 * since those would be directory operations---even if the file
   1198 	 * we are writing is marked VU_DIROP we should write the old values.
   1199 	 * If we're not cleaning, of course, update the values so we get
   1200 	 * current values the next time we clean.
   1201 	 */
   1202 	if (sp->seg_flags & SEGM_CLEAN) {
   1203 		if (vp->v_uflag & VU_DIROP) {
   1204 			lfs_dino_setnlink(fs, cdp, ip->i_lfs_odnlink);
   1205 			/* if (vp->v_type == VDIR) */
   1206 			lfs_dino_setsize(fs, cdp, ip->i_lfs_osize);
   1207 		}
   1208 	} else {
   1209 		ip->i_lfs_odnlink = lfs_dino_getnlink(fs, cdp);
   1210 		ip->i_lfs_osize = ip->i_size;
   1211 	}
   1212 
   1213 
   1214 	/* We can finish the segment accounting for truncations now */
   1215 	lfs_finalize_ino_seguse(fs, ip);
   1216 
   1217 	/*
   1218 	 * If we are cleaning, ensure that we don't write UNWRITTEN disk
   1219 	 * addresses to disk; possibly change the on-disk record of
   1220 	 * the inode size, either by reverting to the previous size
   1221 	 * (in the case of cleaning) or by verifying the inode's block
   1222 	 * holdings (in the case of files being allocated as they are being
   1223 	 * written).
   1224 	 * XXX By not writing UNWRITTEN blocks, we are making the lfs_avail
   1225 	 * XXX count on disk wrong by the same amount.	We should be
   1226 	 * XXX able to "borrow" from lfs_avail and return it after the
   1227 	 * XXX Ifile is written.  See also in lfs_writeseg.
   1228 	 */
   1229 
   1230 	/* Check file size based on highest allocated block */
   1231 	if (((ip->i_ffs1_mode & LFS_IFMT) == LFS_IFREG ||
   1232 	     (ip->i_ffs1_mode & LFS_IFMT) == LFS_IFDIR) &&
   1233 	    ip->i_size > ((ip->i_lfs_hiblk + 1) << lfs_sb_getbshift(fs))) {
   1234 		lfs_dino_setsize(fs, cdp, (ip->i_lfs_hiblk + 1) << lfs_sb_getbshift(fs));
   1235 		DLOG((DLOG_SEG, "lfs_writeinode: ino %d size %" PRId64 " -> %"
   1236 		      PRId64 "\n", (int)ip->i_number, ip->i_size, lfs_dino_getsize(fs, cdp)));
   1237 	}
   1238 	if (ip->i_lfs_effnblks != ip->i_ffs1_blocks) {
   1239 		DLOG((DLOG_SEG, "lfs_writeinode: cleansing ino %d eff %jd != nblk %d)"
   1240 		      " at %jx\n", ip->i_number, (intmax_t)ip->i_lfs_effnblks,
   1241 		      ip->i_ffs1_blocks, (uintmax_t)lfs_sb_getoffset(fs)));
   1242 		for (i=0; i<ULFS_NDADDR; i++) {
   1243 			if (lfs_dino_getdb(fs, cdp, i) == UNWRITTEN) {
   1244 				DLOG((DLOG_SEG, "lfs_writeinode: wiping UNWRITTEN\n"));
   1245 				lfs_dino_setdb(fs, cdp, i, 0);
   1246 			}
   1247 		}
   1248 		for (i=0; i<ULFS_NIADDR; i++) {
   1249 			if (lfs_dino_getib(fs, cdp, i) == UNWRITTEN) {
   1250 				DLOG((DLOG_SEG, "lfs_writeinode: wiping UNWRITTEN\n"));
   1251 				lfs_dino_setib(fs, cdp, i, 0);
   1252 			}
   1253 		}
   1254 	}
   1255 
   1256 #ifdef DIAGNOSTIC
   1257 	/*
   1258 	 * Check dinode held blocks against dinode size.
   1259 	 * This should be identical to the check in lfs_vget().
   1260 	 */
   1261 	for (i = (lfs_dino_getsize(fs, cdp) + lfs_sb_getbsize(fs) - 1) >> lfs_sb_getbshift(fs);
   1262 	     i < ULFS_NDADDR; i++) {
   1263 		KASSERT(i >= 0);
   1264 		if ((lfs_dino_getmode(fs, cdp) & LFS_IFMT) == LFS_IFLNK)
   1265 			continue;
   1266 		if (((lfs_dino_getmode(fs, cdp) & LFS_IFMT) == LFS_IFBLK ||
   1267 		     (lfs_dino_getmode(fs, cdp) & LFS_IFMT) == LFS_IFCHR) && i == 0)
   1268 			continue;
   1269 		if (lfs_dino_getdb(fs, cdp, i) != 0) {
   1270 # ifdef DEBUG
   1271 			lfs_dump_dinode(fs, cdp);
   1272 # endif
   1273 			panic("writing inconsistent inode");
   1274 		}
   1275 	}
   1276 #endif /* DIAGNOSTIC */
   1277 
   1278 	if (ip->i_flag & IN_CLEANING)
   1279 		LFS_CLR_UINO(ip, IN_CLEANING);
   1280 	else {
   1281 		/* XXX IN_ALLMOD */
   1282 		LFS_CLR_UINO(ip, IN_ACCESSED | IN_ACCESS | IN_CHANGE |
   1283 			     IN_UPDATE | IN_MODIFY);
   1284 		if (ip->i_lfs_effnblks == ip->i_ffs1_blocks)
   1285 			LFS_CLR_UINO(ip, IN_MODIFIED);
   1286 		else {
   1287 			DLOG((DLOG_VNODE, "lfs_writeinode: ino %d: real "
   1288 			    "blks=%d, eff=%jd\n", ip->i_number,
   1289 			    ip->i_ffs1_blocks, (intmax_t)ip->i_lfs_effnblks));
   1290 		}
   1291 	}
   1292 
   1293 	if (ip->i_number == LFS_IFILE_INUM) {
   1294 		/* We know sp->idp == NULL */
   1295 		sp->idp = DINO_IN_BLOCK(fs, bp, sp->ninodes % LFS_INOPB(fs));
   1296 
   1297 		/* Not dirty any more */
   1298 		mutex_enter(&lfs_lock);
   1299 		fs->lfs_flags &= ~LFS_IFDIRTY;
   1300 		mutex_exit(&lfs_lock);
   1301 	}
   1302 
   1303 	if (gotblk) {
   1304 		mutex_enter(&bufcache_lock);
   1305 		LFS_LOCK_BUF(bp);
   1306 		brelsel(bp, 0);
   1307 		mutex_exit(&bufcache_lock);
   1308 	}
   1309 
   1310 	/* Increment inode count in segment summary block. */
   1311 
   1312 	ssp = (SEGSUM *)sp->segsum;
   1313 	lfs_ss_setninos(fs, ssp, lfs_ss_getninos(fs, ssp) + 1);
   1314 
   1315 	/* If this page is full, set flag to allocate a new page. */
   1316 	if (++sp->ninodes % LFS_INOPB(fs) == 0)
   1317 		sp->ibp = NULL;
   1318 
   1319 	redo_ifile = lfs_update_iaddr(fs, sp, ip, bp->b_blkno);
   1320 
   1321 	KASSERT(redo_ifile == 0);
   1322 	return (redo_ifile);
   1323 }
   1324 
   1325 int
   1326 lfs_gatherblock(struct segment *sp, struct buf *bp, kmutex_t *mptr)
   1327 {
   1328 	struct lfs *fs;
   1329 	int vers;
   1330 	int j, blksinblk;
   1331 
   1332 	ASSERT_SEGLOCK(sp->fs);
   1333 	/*
   1334 	 * If full, finish this segment.  We may be doing I/O, so
   1335 	 * release and reacquire the splbio().
   1336 	 */
   1337 #ifdef DIAGNOSTIC
   1338 	if (sp->vp == NULL)
   1339 		panic ("lfs_gatherblock: Null vp in segment");
   1340 #endif
   1341 	fs = sp->fs;
   1342 	blksinblk = howmany(bp->b_bcount, lfs_sb_getbsize(fs));
   1343 	if (sp->sum_bytes_left < sizeof(int32_t) * blksinblk ||
   1344 	    sp->seg_bytes_left < bp->b_bcount) {
   1345 		if (mptr)
   1346 			mutex_exit(mptr);
   1347 		lfs_updatemeta(sp);
   1348 
   1349 		vers = lfs_fi_getversion(fs, sp->fip);
   1350 		(void) lfs_writeseg(fs, sp);
   1351 
   1352 		/* Add the current file to the segment summary. */
   1353 		lfs_acquire_finfo(fs, VTOI(sp->vp)->i_number, vers);
   1354 
   1355 		if (mptr)
   1356 			mutex_enter(mptr);
   1357 		return (1);
   1358 	}
   1359 
   1360 	if (bp->b_flags & B_GATHERED) {
   1361 		DLOG((DLOG_SEG, "lfs_gatherblock: already gathered! Ino %ju,"
   1362 		      " lbn %" PRId64 "\n",
   1363 		      (uintmax_t)lfs_fi_getino(fs, sp->fip), bp->b_lblkno));
   1364 		return (0);
   1365 	}
   1366 
   1367 	/* Insert into the buffer list, update the FINFO block. */
   1368 	bp->b_flags |= B_GATHERED;
   1369 
   1370 	*sp->cbpp++ = bp;
   1371 	for (j = 0; j < blksinblk; j++) {
   1372 		unsigned bn;
   1373 
   1374 		bn = lfs_fi_getnblocks(fs, sp->fip);
   1375 		lfs_fi_setnblocks(fs, sp->fip, bn+1);
   1376 		lfs_fi_setblock(fs, sp->fip, bn, bp->b_lblkno + j);
   1377 		/* This block's accounting moves from lfs_favail to lfs_avail */
   1378 		lfs_deregister_block(sp->vp, bp->b_lblkno + j);
   1379 	}
   1380 
   1381 	sp->sum_bytes_left -= sizeof(int32_t) * blksinblk;
   1382 	sp->seg_bytes_left -= bp->b_bcount;
   1383 	return (0);
   1384 }
   1385 
   1386 int
   1387 lfs_gather(struct lfs *fs, struct segment *sp, struct vnode *vp,
   1388     int (*match)(struct lfs *, struct buf *))
   1389 {
   1390 	struct buf *bp, *nbp;
   1391 	int count = 0;
   1392 
   1393 	ASSERT_SEGLOCK(fs);
   1394 	if (vp->v_type == VBLK)
   1395 		return 0;
   1396 	KASSERT(sp->vp == NULL);
   1397 	sp->vp = vp;
   1398 	mutex_enter(&bufcache_lock);
   1399 
   1400 #ifndef LFS_NO_BACKBUF_HACK
   1401 /* This is a hack to see if ordering the blocks in LFS makes a difference. */
   1402 # define	BUF_OFFSET	\
   1403 	(((char *)&LIST_NEXT(bp, b_vnbufs)) - (char *)bp)
   1404 # define	BACK_BUF(BP)	\
   1405 	((struct buf *)(((char *)(BP)->b_vnbufs.le_prev) - BUF_OFFSET))
   1406 # define	BEG_OF_LIST	\
   1407 	((struct buf *)(((char *)&LIST_FIRST(&vp->v_dirtyblkhd)) - BUF_OFFSET))
   1408 
   1409 loop:
   1410 	/* Find last buffer. */
   1411 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd);
   1412 	     bp && LIST_NEXT(bp, b_vnbufs) != NULL;
   1413 	     bp = LIST_NEXT(bp, b_vnbufs))
   1414 		/* nothing */;
   1415 	for (; bp && bp != BEG_OF_LIST; bp = nbp) {
   1416 		nbp = BACK_BUF(bp);
   1417 #else /* LFS_NO_BACKBUF_HACK */
   1418 loop:
   1419 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
   1420 		nbp = LIST_NEXT(bp, b_vnbufs);
   1421 #endif /* LFS_NO_BACKBUF_HACK */
   1422 		if ((bp->b_cflags & BC_BUSY) != 0 ||
   1423 		    (bp->b_flags & B_GATHERED) != 0 || !match(fs, bp)) {
   1424 #ifdef DEBUG
   1425 			if (vp == fs->lfs_ivnode &&
   1426 			    (bp->b_cflags & BC_BUSY) != 0 &&
   1427 			    (bp->b_flags & B_GATHERED) == 0)
   1428 				log(LOG_NOTICE, "lfs_gather: ifile lbn %"
   1429 				      PRId64 " busy (%x) at 0x%jx",
   1430 				      bp->b_lblkno, bp->b_flags,
   1431 				      (uintmax_t)lfs_sb_getoffset(fs));
   1432 #endif
   1433 			continue;
   1434 		}
   1435 #ifdef DIAGNOSTIC
   1436 # ifdef LFS_USE_B_INVAL
   1437 		if ((bp->b_flags & BC_INVAL) != 0 && bp->b_iodone == NULL) {
   1438 			DLOG((DLOG_SEG, "lfs_gather: lbn %" PRId64
   1439 			      " is BC_INVAL\n", bp->b_lblkno));
   1440 			VOP_PRINT(bp->b_vp);
   1441 		}
   1442 # endif /* LFS_USE_B_INVAL */
   1443 		if (!(bp->b_oflags & BO_DELWRI))
   1444 			panic("lfs_gather: bp not BO_DELWRI");
   1445 		if (!(bp->b_flags & B_LOCKED)) {
   1446 			DLOG((DLOG_SEG, "lfs_gather: lbn %" PRId64
   1447 			      " blk %" PRId64 " not B_LOCKED\n",
   1448 			      bp->b_lblkno,
   1449 			      LFS_DBTOFSB(fs, bp->b_blkno)));
   1450 			VOP_PRINT(bp->b_vp);
   1451 			panic("lfs_gather: bp not B_LOCKED");
   1452 		}
   1453 #endif
   1454 		if (lfs_gatherblock(sp, bp, &bufcache_lock)) {
   1455 			goto loop;
   1456 		}
   1457 		count++;
   1458 	}
   1459 	mutex_exit(&bufcache_lock);
   1460 	lfs_updatemeta(sp);
   1461 	KASSERT(sp->vp == vp);
   1462 	sp->vp = NULL;
   1463 	return count;
   1464 }
   1465 
   1466 #if DEBUG
   1467 # define DEBUG_OOFF(n) do {						\
   1468 	if (ooff == 0) {						\
   1469 		DLOG((DLOG_SEG, "lfs_updatemeta[%d]: warning: writing " \
   1470 			"ino %d lbn %" PRId64 " at 0x%" PRIx32		\
   1471 			", was 0x0 (or %" PRId64 ")\n",			\
   1472 			(n), ip->i_number, lbn, ndaddr, daddr));	\
   1473 	}								\
   1474 } while (0)
   1475 #else
   1476 # define DEBUG_OOFF(n)
   1477 #endif
   1478 
   1479 /*
   1480  * Change the given block's address to ndaddr, finding its previous
   1481  * location using ulfs_bmaparray().
   1482  *
   1483  * Account for this change in the segment table.
   1484  *
   1485  * called with sp == NULL by roll-forwarding code.
   1486  */
   1487 void
   1488 lfs_update_single(struct lfs *fs, struct segment *sp,
   1489     struct vnode *vp, daddr_t lbn, daddr_t ndaddr, int size)
   1490 {
   1491 	SEGUSE *sup;
   1492 	struct buf *bp;
   1493 	struct indir a[ULFS_NIADDR + 2], *ap;
   1494 	struct inode *ip;
   1495 	daddr_t daddr, ooff;
   1496 	int num, error;
   1497 	int bb, osize, obb;
   1498 
   1499 	ASSERT_SEGLOCK(fs);
   1500 	KASSERT(sp == NULL || sp->vp == vp);
   1501 	ip = VTOI(vp);
   1502 
   1503 	error = ulfs_bmaparray(vp, lbn, &daddr, a, &num, NULL, NULL);
   1504 	if (error)
   1505 		panic("lfs_updatemeta: ulfs_bmaparray returned %d", error);
   1506 
   1507 	KASSERT(daddr <= LFS_MAX_DADDR(fs));
   1508 	if (daddr > 0)
   1509 		daddr = LFS_DBTOFSB(fs, daddr);
   1510 
   1511 	bb = lfs_numfrags(fs, size);
   1512 	switch (num) {
   1513 	    case 0:
   1514 		    ooff = ip->i_ffs1_db[lbn];
   1515 		    DEBUG_OOFF(0);
   1516 		    if (ooff == UNWRITTEN)
   1517 			    ip->i_ffs1_blocks += bb;
   1518 		    else {
   1519 			    /* possible fragment truncation or extension */
   1520 			    obb = lfs_btofsb(fs, ip->i_lfs_fragsize[lbn]);
   1521 			    ip->i_ffs1_blocks += (bb - obb);
   1522 		    }
   1523 		    ip->i_ffs1_db[lbn] = ndaddr;
   1524 		    break;
   1525 	    case 1:
   1526 		    ooff = ip->i_ffs1_ib[a[0].in_off];
   1527 		    DEBUG_OOFF(1);
   1528 		    if (ooff == UNWRITTEN)
   1529 			    ip->i_ffs1_blocks += bb;
   1530 		    ip->i_ffs1_ib[a[0].in_off] = ndaddr;
   1531 		    break;
   1532 	    default:
   1533 		    ap = &a[num - 1];
   1534 		    if (bread(vp, ap->in_lbn, lfs_sb_getbsize(fs),
   1535 			B_MODIFY, &bp))
   1536 			    panic("lfs_updatemeta: bread bno %" PRId64,
   1537 				  ap->in_lbn);
   1538 
   1539 		    /* XXX ondisk32 */
   1540 		    ooff = ((int32_t *)bp->b_data)[ap->in_off];
   1541 		    DEBUG_OOFF(num);
   1542 		    if (ooff == UNWRITTEN)
   1543 			    ip->i_ffs1_blocks += bb;
   1544 		    /* XXX ondisk32 */
   1545 		    ((int32_t *)bp->b_data)[ap->in_off] = ndaddr;
   1546 		    (void) VOP_BWRITE(bp->b_vp, bp);
   1547 	}
   1548 
   1549 	KASSERT(ooff == 0 || ooff == UNWRITTEN || ooff == daddr);
   1550 
   1551 	/* Update hiblk when extending the file */
   1552 	if (lbn > ip->i_lfs_hiblk)
   1553 		ip->i_lfs_hiblk = lbn;
   1554 
   1555 	/*
   1556 	 * Though we'd rather it couldn't, this *can* happen right now
   1557 	 * if cleaning blocks and regular blocks coexist.
   1558 	 */
   1559 	/* KASSERT(daddr < fs->lfs_lastpseg || daddr > ndaddr); */
   1560 
   1561 	/*
   1562 	 * Update segment usage information, based on old size
   1563 	 * and location.
   1564 	 */
   1565 	if (daddr > 0) {
   1566 		u_int32_t oldsn = lfs_dtosn(fs, daddr);
   1567 #ifdef DIAGNOSTIC
   1568 		int ndupino;
   1569 
   1570 		if (sp && sp->seg_number == oldsn) {
   1571 			ndupino = sp->ndupino;
   1572 		} else {
   1573 			ndupino = 0;
   1574 		}
   1575 #endif
   1576 		KASSERT(oldsn < lfs_sb_getnseg(fs));
   1577 		if (lbn >= 0 && lbn < ULFS_NDADDR)
   1578 			osize = ip->i_lfs_fragsize[lbn];
   1579 		else
   1580 			osize = lfs_sb_getbsize(fs);
   1581 		LFS_SEGENTRY(sup, fs, oldsn, bp);
   1582 #ifdef DIAGNOSTIC
   1583 		if (sup->su_nbytes + DINOSIZE(fs) * ndupino < osize) {
   1584 			printf("lfs_updatemeta: negative bytes "
   1585 			       "(segment %" PRIu32 " short by %" PRId64
   1586 			       ")\n", lfs_dtosn(fs, daddr),
   1587 			       (int64_t)osize -
   1588 			       (DINOSIZE(fs) * ndupino + sup->su_nbytes));
   1589 			printf("lfs_updatemeta: ino %llu, lbn %" PRId64
   1590 			       ", addr = 0x%" PRIx64 "\n",
   1591 			       (unsigned long long)ip->i_number, lbn, daddr);
   1592 			printf("lfs_updatemeta: ndupino=%d\n", ndupino);
   1593 			panic("lfs_updatemeta: negative bytes");
   1594 			sup->su_nbytes = osize -
   1595 			    DINOSIZE(fs) * ndupino;
   1596 		}
   1597 #endif
   1598 		DLOG((DLOG_SU, "seg %" PRIu32 " -= %d for ino %d lbn %" PRId64
   1599 		      " db 0x%" PRIx64 "\n",
   1600 		      lfs_dtosn(fs, daddr), osize,
   1601 		      ip->i_number, lbn, daddr));
   1602 		sup->su_nbytes -= osize;
   1603 		if (!(bp->b_flags & B_GATHERED)) {
   1604 			mutex_enter(&lfs_lock);
   1605 			fs->lfs_flags |= LFS_IFDIRTY;
   1606 			mutex_exit(&lfs_lock);
   1607 		}
   1608 		LFS_WRITESEGENTRY(sup, fs, oldsn, bp);
   1609 	}
   1610 	/*
   1611 	 * Now that this block has a new address, and its old
   1612 	 * segment no longer owns it, we can forget about its
   1613 	 * old size.
   1614 	 */
   1615 	if (lbn >= 0 && lbn < ULFS_NDADDR)
   1616 		ip->i_lfs_fragsize[lbn] = size;
   1617 }
   1618 
   1619 /*
   1620  * Update the metadata that points to the blocks listed in the FINFO
   1621  * array.
   1622  */
   1623 void
   1624 lfs_updatemeta(struct segment *sp)
   1625 {
   1626 	struct buf *sbp;
   1627 	struct lfs *fs;
   1628 	struct vnode *vp;
   1629 	daddr_t lbn;
   1630 	int i, nblocks, num;
   1631 	int __diagused nblocks_orig;
   1632 	int bb;
   1633 	int bytesleft, size;
   1634 	unsigned lastlength;
   1635 	union lfs_blocks tmpptr;
   1636 
   1637 	fs = sp->fs;
   1638 	vp = sp->vp;
   1639 	ASSERT_SEGLOCK(fs);
   1640 
   1641 	/*
   1642 	 * This used to be:
   1643 	 *
   1644 	 *  nblocks = &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp;
   1645 	 *
   1646 	 * that is, it allowed for the possibility that start_lbp did
   1647 	 * not point to the beginning of the finfo block pointer area.
   1648 	 * This particular formulation is six kinds of painful in the
   1649 	 * lfs64 world where we have two sizes of block pointer, so
   1650 	 * unless/until everything can be cleaned up to not move
   1651 	 * start_lbp around but instead use an offset, we do the
   1652 	 * following:
   1653 	 *    1. Get NEXT_FINFO(sp->fip). This is the same pointer as
   1654 	 * &sp->fip->fi_blocks[sp->fip->fi_nblocks], just the wrong
   1655 	 * type. (Ugh.)
   1656 	 *    2. Cast it to void *, then assign it to a temporary
   1657 	 * union lfs_blocks.
   1658 	 *    3. Subtract start_lbp from that.
   1659 	 *    4. Save the value of nblocks in blocks_orig so we can
   1660 	 * assert below that it hasn't changed without repeating this
   1661 	 * rubbish.
   1662 	 *
   1663 	 * XXX.
   1664 	 */
   1665 	lfs_blocks_fromvoid(fs, &tmpptr, (void *)NEXT_FINFO(fs, sp->fip));
   1666 	nblocks = lfs_blocks_sub(fs, &tmpptr, &sp->start_lbp);
   1667 	nblocks_orig = nblocks;
   1668 
   1669 	KASSERT(nblocks >= 0);
   1670 	KASSERT(vp != NULL);
   1671 	if (nblocks == 0)
   1672 		return;
   1673 
   1674 	/*
   1675 	 * This count may be high due to oversize blocks from lfs_gop_write.
   1676 	 * Correct for this. (XXX we should be able to keep track of these.)
   1677 	 */
   1678 	for (i = 0; i < nblocks; i++) {
   1679 		if (sp->start_bpp[i] == NULL) {
   1680 			DLOG((DLOG_SEG, "lfs_updatemeta: nblocks = %d, not %d\n", i, nblocks));
   1681 			nblocks = i;
   1682 			break;
   1683 		}
   1684 		num = howmany(sp->start_bpp[i]->b_bcount, lfs_sb_getbsize(fs));
   1685 		KASSERT(sp->start_bpp[i]->b_lblkno >= 0 || num == 1);
   1686 		nblocks -= num - 1;
   1687 	}
   1688 
   1689 #if 0
   1690 	/* pre-lfs64 assertion */
   1691 	KASSERT(vp->v_type == VREG ||
   1692 	   nblocks == &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp);
   1693 #else
   1694 	KASSERT(vp->v_type == VREG || nblocks == nblocks_orig);
   1695 #endif
   1696 	KASSERT(nblocks == sp->cbpp - sp->start_bpp);
   1697 
   1698 	/*
   1699 	 * Sort the blocks.
   1700 	 *
   1701 	 * We have to sort even if the blocks come from the
   1702 	 * cleaner, because there might be other pending blocks on the
   1703 	 * same inode...and if we don't sort, and there are fragments
   1704 	 * present, blocks may be written in the wrong place.
   1705 	 */
   1706 	lfs_shellsort(fs, sp->start_bpp, &sp->start_lbp, nblocks, lfs_sb_getbsize(fs));
   1707 
   1708 	/*
   1709 	 * Record the length of the last block in case it's a fragment.
   1710 	 * If there are indirect blocks present, they sort last.  An
   1711 	 * indirect block will be lfs_bsize and its presence indicates
   1712 	 * that you cannot have fragments.
   1713 	 *
   1714 	 * XXX This last is a lie.  A cleaned fragment can coexist with
   1715 	 * XXX a later indirect block.	This will continue to be
   1716 	 * XXX true until lfs_markv is fixed to do everything with
   1717 	 * XXX fake blocks (including fake inodes and fake indirect blocks).
   1718 	 */
   1719 	lastlength = ((sp->start_bpp[nblocks - 1]->b_bcount - 1) &
   1720 		lfs_sb_getbmask(fs)) + 1;
   1721 	lfs_fi_setlastlength(fs, sp->fip, lastlength);
   1722 
   1723 	/*
   1724 	 * Assign disk addresses, and update references to the logical
   1725 	 * block and the segment usage information.
   1726 	 */
   1727 	for (i = nblocks; i--; ++sp->start_bpp) {
   1728 		sbp = *sp->start_bpp;
   1729 		lbn = lfs_blocks_get(fs, &sp->start_lbp, 0);
   1730 		KASSERT(sbp->b_lblkno == lbn);
   1731 
   1732 		sbp->b_blkno = LFS_FSBTODB(fs, lfs_sb_getoffset(fs));
   1733 
   1734 		/*
   1735 		 * If we write a frag in the wrong place, the cleaner won't
   1736 		 * be able to correctly identify its size later, and the
   1737 		 * segment will be uncleanable.	 (Even worse, it will assume
   1738 		 * that the indirect block that actually ends the list
   1739 		 * is of a smaller size!)
   1740 		 */
   1741 		if ((sbp->b_bcount & lfs_sb_getbmask(fs)) && i != 0)
   1742 			panic("lfs_updatemeta: fragment is not last block");
   1743 
   1744 		/*
   1745 		 * For each subblock in this possibly oversized block,
   1746 		 * update its address on disk.
   1747 		 */
   1748 		KASSERT(lbn >= 0 || sbp->b_bcount == lfs_sb_getbsize(fs));
   1749 		KASSERT(vp == sbp->b_vp);
   1750 		for (bytesleft = sbp->b_bcount; bytesleft > 0;
   1751 		     bytesleft -= lfs_sb_getbsize(fs)) {
   1752 			size = MIN(bytesleft, lfs_sb_getbsize(fs));
   1753 			bb = lfs_numfrags(fs, size);
   1754 			lbn = lfs_blocks_get(fs, &sp->start_lbp, 0);
   1755 			lfs_blocks_inc(fs, &sp->start_lbp);
   1756 			lfs_update_single(fs, sp, sp->vp, lbn, lfs_sb_getoffset(fs),
   1757 			    size);
   1758 			lfs_sb_addoffset(fs, bb);
   1759 		}
   1760 
   1761 	}
   1762 
   1763 	/* This inode has been modified */
   1764 	LFS_SET_UINO(VTOI(vp), IN_MODIFIED);
   1765 }
   1766 
   1767 /*
   1768  * Move lfs_offset to a segment earlier than newsn.
   1769  */
   1770 int
   1771 lfs_rewind(struct lfs *fs, int newsn)
   1772 {
   1773 	int sn, osn, isdirty;
   1774 	struct buf *bp;
   1775 	SEGUSE *sup;
   1776 
   1777 	ASSERT_SEGLOCK(fs);
   1778 
   1779 	osn = lfs_dtosn(fs, lfs_sb_getoffset(fs));
   1780 	if (osn < newsn)
   1781 		return 0;
   1782 
   1783 	/* lfs_avail eats the remaining space in this segment */
   1784 	lfs_sb_subavail(fs, lfs_sb_getfsbpseg(fs) - (lfs_sb_getoffset(fs) - lfs_sb_getcurseg(fs)));
   1785 
   1786 	/* Find a low-numbered segment */
   1787 	for (sn = 0; sn < lfs_sb_getnseg(fs); ++sn) {
   1788 		LFS_SEGENTRY(sup, fs, sn, bp);
   1789 		isdirty = sup->su_flags & SEGUSE_DIRTY;
   1790 		brelse(bp, 0);
   1791 
   1792 		if (!isdirty)
   1793 			break;
   1794 	}
   1795 	if (sn == lfs_sb_getnseg(fs))
   1796 		panic("lfs_rewind: no clean segments");
   1797 	if (newsn >= 0 && sn >= newsn)
   1798 		return ENOENT;
   1799 	lfs_sb_setnextseg(fs, lfs_sntod(fs, sn));
   1800 	lfs_newseg(fs);
   1801 	lfs_sb_setoffset(fs, lfs_sb_getcurseg(fs));
   1802 
   1803 	return 0;
   1804 }
   1805 
   1806 /*
   1807  * Start a new partial segment.
   1808  *
   1809  * Return 1 when we entered to a new segment.
   1810  * Otherwise, return 0.
   1811  */
   1812 int
   1813 lfs_initseg(struct lfs *fs)
   1814 {
   1815 	struct segment *sp = fs->lfs_sp;
   1816 	SEGSUM *ssp;
   1817 	struct buf *sbp;	/* buffer for SEGSUM */
   1818 	int repeat = 0;		/* return value */
   1819 
   1820 	ASSERT_SEGLOCK(fs);
   1821 	/* Advance to the next segment. */
   1822 	if (!LFS_PARTIAL_FITS(fs)) {
   1823 		SEGUSE *sup;
   1824 		struct buf *bp;
   1825 
   1826 		/* lfs_avail eats the remaining space */
   1827 		lfs_sb_subavail(fs, lfs_sb_getfsbpseg(fs) - (lfs_sb_getoffset(fs) -
   1828 						   lfs_sb_getcurseg(fs)));
   1829 		/* Wake up any cleaning procs waiting on this file system. */
   1830 		lfs_wakeup_cleaner(fs);
   1831 		lfs_newseg(fs);
   1832 		repeat = 1;
   1833 		lfs_sb_setoffset(fs, lfs_sb_getcurseg(fs));
   1834 
   1835 		sp->seg_number = lfs_dtosn(fs, lfs_sb_getcurseg(fs));
   1836 		sp->seg_bytes_left = lfs_fsbtob(fs, lfs_sb_getfsbpseg(fs));
   1837 
   1838 		/*
   1839 		 * If the segment contains a superblock, update the offset
   1840 		 * and summary address to skip over it.
   1841 		 */
   1842 		LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
   1843 		if (sup->su_flags & SEGUSE_SUPERBLOCK) {
   1844 			lfs_sb_addoffset(fs, lfs_btofsb(fs, LFS_SBPAD));
   1845 			sp->seg_bytes_left -= LFS_SBPAD;
   1846 		}
   1847 		brelse(bp, 0);
   1848 		/* Segment zero could also contain the labelpad */
   1849 		if (lfs_sb_getversion(fs) > 1 && sp->seg_number == 0 &&
   1850 		    lfs_sb_gets0addr(fs) < lfs_btofsb(fs, LFS_LABELPAD)) {
   1851 			lfs_sb_addoffset(fs,
   1852 			    lfs_btofsb(fs, LFS_LABELPAD) - lfs_sb_gets0addr(fs));
   1853 			sp->seg_bytes_left -=
   1854 			    LFS_LABELPAD - lfs_fsbtob(fs, lfs_sb_gets0addr(fs));
   1855 		}
   1856 	} else {
   1857 		sp->seg_number = lfs_dtosn(fs, lfs_sb_getcurseg(fs));
   1858 		sp->seg_bytes_left = lfs_fsbtob(fs, lfs_sb_getfsbpseg(fs) -
   1859 				      (lfs_sb_getoffset(fs) - lfs_sb_getcurseg(fs)));
   1860 	}
   1861 	lfs_sb_setlastpseg(fs, lfs_sb_getoffset(fs));
   1862 
   1863 	/* Record first address of this partial segment */
   1864 	if (sp->seg_flags & SEGM_CLEAN) {
   1865 		fs->lfs_cleanint[fs->lfs_cleanind] = lfs_sb_getoffset(fs);
   1866 		if (++fs->lfs_cleanind >= LFS_MAX_CLEANIND) {
   1867 			/* "1" is the artificial inc in lfs_seglock */
   1868 			mutex_enter(&lfs_lock);
   1869 			while (fs->lfs_iocount > 1) {
   1870 				mtsleep(&fs->lfs_iocount, PRIBIO + 1,
   1871 				    "lfs_initseg", 0, &lfs_lock);
   1872 			}
   1873 			mutex_exit(&lfs_lock);
   1874 			fs->lfs_cleanind = 0;
   1875 		}
   1876 	}
   1877 
   1878 	sp->fs = fs;
   1879 	sp->ibp = NULL;
   1880 	sp->idp = NULL;
   1881 	sp->ninodes = 0;
   1882 	sp->ndupino = 0;
   1883 
   1884 	sp->cbpp = sp->bpp;
   1885 
   1886 	/* Get a new buffer for SEGSUM */
   1887 	sbp = lfs_newbuf(fs, VTOI(fs->lfs_ivnode)->i_devvp,
   1888 	    LFS_FSBTODB(fs, lfs_sb_getoffset(fs)), lfs_sb_getsumsize(fs), LFS_NB_SUMMARY);
   1889 
   1890 	/* ... and enter it into the buffer list. */
   1891 	*sp->cbpp = sbp;
   1892 	sp->cbpp++;
   1893 	lfs_sb_addoffset(fs, lfs_btofsb(fs, lfs_sb_getsumsize(fs)));
   1894 
   1895 	sp->start_bpp = sp->cbpp;
   1896 
   1897 	/* Set point to SEGSUM, initialize it. */
   1898 	ssp = sp->segsum = sbp->b_data;
   1899 	memset(ssp, 0, lfs_sb_getsumsize(fs));
   1900 	lfs_ss_setnext(fs, ssp, lfs_sb_getnextseg(fs));
   1901 	lfs_ss_setnfinfo(fs, ssp, 0);
   1902 	lfs_ss_setninos(fs, ssp, 0);
   1903 	lfs_ss_setmagic(fs, ssp, SS_MAGIC);
   1904 
   1905 	/* Set pointer to first FINFO, initialize it. */
   1906 	sp->fip = SEGSUM_FINFOBASE(fs, sp->segsum);
   1907 	lfs_fi_setnblocks(fs, sp->fip, 0);
   1908 	lfs_fi_setlastlength(fs, sp->fip, 0);
   1909 	lfs_blocks_fromfinfo(fs, &sp->start_lbp, sp->fip);
   1910 
   1911 	sp->seg_bytes_left -= lfs_sb_getsumsize(fs);
   1912 	sp->sum_bytes_left = lfs_sb_getsumsize(fs) - SEGSUM_SIZE(fs);
   1913 
   1914 	return (repeat);
   1915 }
   1916 
   1917 /*
   1918  * Remove SEGUSE_INVAL from all segments.
   1919  */
   1920 void
   1921 lfs_unset_inval_all(struct lfs *fs)
   1922 {
   1923 	SEGUSE *sup;
   1924 	struct buf *bp;
   1925 	int i;
   1926 
   1927 	for (i = 0; i < lfs_sb_getnseg(fs); i++) {
   1928 		LFS_SEGENTRY(sup, fs, i, bp);
   1929 		if (sup->su_flags & SEGUSE_INVAL) {
   1930 			sup->su_flags &= ~SEGUSE_INVAL;
   1931 			LFS_WRITESEGENTRY(sup, fs, i, bp);
   1932 		} else
   1933 			brelse(bp, 0);
   1934 	}
   1935 }
   1936 
   1937 /*
   1938  * Return the next segment to write.
   1939  */
   1940 void
   1941 lfs_newseg(struct lfs *fs)
   1942 {
   1943 	CLEANERINFO *cip;
   1944 	SEGUSE *sup;
   1945 	struct buf *bp;
   1946 	int curseg, isdirty, sn, skip_inval;
   1947 
   1948 	ASSERT_SEGLOCK(fs);
   1949 
   1950 	/* Honor LFCNWRAPSTOP */
   1951 	mutex_enter(&lfs_lock);
   1952 	while (lfs_sb_getnextseg(fs) < lfs_sb_getcurseg(fs) && fs->lfs_nowrap) {
   1953 		if (fs->lfs_wrappass) {
   1954 			log(LOG_NOTICE, "%s: wrappass=%d\n",
   1955 				lfs_sb_getfsmnt(fs), fs->lfs_wrappass);
   1956 			fs->lfs_wrappass = 0;
   1957 			break;
   1958 		}
   1959 		fs->lfs_wrapstatus = LFS_WRAP_WAITING;
   1960 		wakeup(&fs->lfs_nowrap);
   1961 		log(LOG_NOTICE, "%s: waiting at log wrap\n", lfs_sb_getfsmnt(fs));
   1962 		mtsleep(&fs->lfs_wrappass, PVFS, "newseg", 10 * hz,
   1963 			&lfs_lock);
   1964 	}
   1965 	fs->lfs_wrapstatus = LFS_WRAP_GOING;
   1966 	mutex_exit(&lfs_lock);
   1967 
   1968 	LFS_SEGENTRY(sup, fs, lfs_dtosn(fs, lfs_sb_getnextseg(fs)), bp);
   1969 	DLOG((DLOG_SU, "lfs_newseg: seg %d := 0 in newseg\n",
   1970 	      lfs_dtosn(fs, lfs_sb_getnextseg(fs))));
   1971 	sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
   1972 	sup->su_nbytes = 0;
   1973 	sup->su_nsums = 0;
   1974 	sup->su_ninos = 0;
   1975 	LFS_WRITESEGENTRY(sup, fs, lfs_dtosn(fs, lfs_sb_getnextseg(fs)), bp);
   1976 
   1977 	LFS_CLEANERINFO(cip, fs, bp);
   1978 	lfs_ci_shiftcleantodirty(fs, cip, 1);
   1979 	lfs_sb_setnclean(fs, lfs_ci_getclean(fs, cip));
   1980 	LFS_SYNC_CLEANERINFO(cip, fs, bp, 1);
   1981 
   1982 	lfs_sb_setlastseg(fs, lfs_sb_getcurseg(fs));
   1983 	lfs_sb_setcurseg(fs, lfs_sb_getnextseg(fs));
   1984 	skip_inval = 1;
   1985 	for (sn = curseg = lfs_dtosn(fs, lfs_sb_getcurseg(fs)) + lfs_sb_getinterleave(fs);;) {
   1986 		sn = (sn + 1) % lfs_sb_getnseg(fs);
   1987 
   1988 		if (sn == curseg) {
   1989 			if (skip_inval)
   1990 				skip_inval = 0;
   1991 			else
   1992 				panic("lfs_nextseg: no clean segments");
   1993 		}
   1994 		LFS_SEGENTRY(sup, fs, sn, bp);
   1995 		isdirty = sup->su_flags & (SEGUSE_DIRTY | (skip_inval ? SEGUSE_INVAL : 0));
   1996 		/* Check SEGUSE_EMPTY as we go along */
   1997 		if (isdirty && sup->su_nbytes == 0 &&
   1998 		    !(sup->su_flags & SEGUSE_EMPTY))
   1999 			LFS_WRITESEGENTRY(sup, fs, sn, bp);
   2000 		else
   2001 			brelse(bp, 0);
   2002 
   2003 		if (!isdirty)
   2004 			break;
   2005 	}
   2006 	if (skip_inval == 0)
   2007 		lfs_unset_inval_all(fs);
   2008 
   2009 	++fs->lfs_nactive;
   2010 	lfs_sb_setnextseg(fs, lfs_sntod(fs, sn));
   2011 	if (lfs_dostats) {
   2012 		++lfs_stats.segsused;
   2013 	}
   2014 }
   2015 
   2016 static struct buf *
   2017 lfs_newclusterbuf(struct lfs *fs, struct vnode *vp, daddr_t addr,
   2018     int n)
   2019 {
   2020 	struct lfs_cluster *cl;
   2021 	struct buf **bpp, *bp;
   2022 
   2023 	ASSERT_SEGLOCK(fs);
   2024 	cl = (struct lfs_cluster *)pool_get(&fs->lfs_clpool, PR_WAITOK);
   2025 	bpp = (struct buf **)pool_get(&fs->lfs_bpppool, PR_WAITOK);
   2026 	memset(cl, 0, sizeof(*cl));
   2027 	cl->fs = fs;
   2028 	cl->bpp = bpp;
   2029 	cl->bufcount = 0;
   2030 	cl->bufsize = 0;
   2031 
   2032 	/* If this segment is being written synchronously, note that */
   2033 	if (fs->lfs_sp->seg_flags & SEGM_SYNC) {
   2034 		cl->flags |= LFS_CL_SYNC;
   2035 		cl->seg = fs->lfs_sp;
   2036 		++cl->seg->seg_iocount;
   2037 	}
   2038 
   2039 	/* Get an empty buffer header, or maybe one with something on it */
   2040 	bp = getiobuf(vp, true);
   2041 	bp->b_dev = NODEV;
   2042 	bp->b_blkno = bp->b_lblkno = addr;
   2043 	bp->b_iodone = lfs_cluster_callback;
   2044 	bp->b_private = cl;
   2045 
   2046 	return bp;
   2047 }
   2048 
   2049 int
   2050 lfs_writeseg(struct lfs *fs, struct segment *sp)
   2051 {
   2052 	struct buf **bpp, *bp, *cbp, *newbp, *unbusybp;
   2053 	SEGUSE *sup;
   2054 	SEGSUM *ssp;
   2055 	int i;
   2056 	int do_again, nblocks, byteoffset;
   2057 	size_t el_size;
   2058 	struct lfs_cluster *cl;
   2059 	u_short ninos;
   2060 	struct vnode *devvp;
   2061 	char *p = NULL;
   2062 	struct vnode *vp;
   2063 	int32_t *daddrp;	/* XXX ondisk32 */
   2064 	int changed;
   2065 	u_int32_t sum;
   2066 	size_t sumstart;
   2067 #ifdef DEBUG
   2068 	FINFO *fip;
   2069 	int findex;
   2070 #endif
   2071 
   2072 	ASSERT_SEGLOCK(fs);
   2073 
   2074 	ssp = (SEGSUM *)sp->segsum;
   2075 
   2076 	/*
   2077 	 * If there are no buffers other than the segment summary to write,
   2078 	 * don't do anything.  If we are the end of a dirop sequence, however,
   2079 	 * write the empty segment summary anyway, to help out the
   2080 	 * roll-forward agent.
   2081 	 */
   2082 	if ((nblocks = sp->cbpp - sp->bpp) == 1) {
   2083 		if ((lfs_ss_getflags(fs, ssp) & (SS_DIROP | SS_CONT)) != SS_DIROP)
   2084 			return 0;
   2085 	}
   2086 
   2087 	/* Note if partial segment is being written by the cleaner */
   2088 	if (sp->seg_flags & SEGM_CLEAN)
   2089 		lfs_ss_setflags(fs, ssp, lfs_ss_getflags(fs, ssp) | SS_CLEAN);
   2090 
   2091 	/* Note if we are writing to reclaim */
   2092 	if (sp->seg_flags & SEGM_RECLAIM) {
   2093 		lfs_ss_setflags(fs, ssp, lfs_ss_getflags(fs, ssp) | SS_RECLAIM);
   2094 		lfs_ss_setreclino(fs, ssp, fs->lfs_reclino);
   2095 	}
   2096 
   2097 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
   2098 
   2099 	/* Update the segment usage information. */
   2100 	LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
   2101 
   2102 	/* Loop through all blocks, except the segment summary. */
   2103 	for (bpp = sp->bpp; ++bpp < sp->cbpp; ) {
   2104 		if ((*bpp)->b_vp != devvp) {
   2105 			sup->su_nbytes += (*bpp)->b_bcount;
   2106 			DLOG((DLOG_SU, "seg %" PRIu32 " += %ld for ino %d"
   2107 			      " lbn %" PRId64 " db 0x%" PRIx64 "\n",
   2108 			      sp->seg_number, (*bpp)->b_bcount,
   2109 			      VTOI((*bpp)->b_vp)->i_number, (*bpp)->b_lblkno,
   2110 			      (*bpp)->b_blkno));
   2111 		}
   2112 	}
   2113 
   2114 #ifdef DEBUG
   2115 	/* Check for zero-length and zero-version FINFO entries. */
   2116 	fip = SEGSUM_FINFOBASE(fs, ssp);
   2117 	for (findex = 0; findex < lfs_ss_getnfinfo(fs, ssp); findex++) {
   2118 		KDASSERT(lfs_fi_getnblocks(fs, fip) > 0);
   2119 		KDASSERT(lfs_fi_getversion(fs, fip) > 0);
   2120 		fip = NEXT_FINFO(fs, fip);
   2121 	}
   2122 #endif /* DEBUG */
   2123 
   2124 	ninos = (lfs_ss_getninos(fs, ssp) + LFS_INOPB(fs) - 1) / LFS_INOPB(fs);
   2125 	DLOG((DLOG_SU, "seg %d += %d for %d inodes\n",
   2126 	      sp->seg_number,
   2127 	      lfs_ss_getninos(fs, ssp) * DINOSIZE(fs),
   2128 	      lfs_ss_getninos(fs, ssp)));
   2129 	sup->su_nbytes += lfs_ss_getninos(fs, ssp) * DINOSIZE(fs);
   2130 	/* sup->su_nbytes += lfs_sb_getsumsize(fs); */
   2131 	if (lfs_sb_getversion(fs) == 1)
   2132 		sup->su_olastmod = time_second;
   2133 	else
   2134 		sup->su_lastmod = time_second;
   2135 	sup->su_ninos += ninos;
   2136 	++sup->su_nsums;
   2137 	lfs_sb_subavail(fs, lfs_btofsb(fs, lfs_sb_getsumsize(fs)));
   2138 
   2139 	do_again = !(bp->b_flags & B_GATHERED);
   2140 	LFS_WRITESEGENTRY(sup, fs, sp->seg_number, bp); /* Ifile */
   2141 
   2142 	/*
   2143 	 * Mark blocks B_BUSY, to prevent then from being changed between
   2144 	 * the checksum computation and the actual write.
   2145 	 *
   2146 	 * If we are cleaning, check indirect blocks for UNWRITTEN, and if
   2147 	 * there are any, replace them with copies that have UNASSIGNED
   2148 	 * instead.
   2149 	 */
   2150 	mutex_enter(&bufcache_lock);
   2151 	for (bpp = sp->bpp, i = nblocks - 1; i--;) {
   2152 		++bpp;
   2153 		bp = *bpp;
   2154 		if (bp->b_iodone != NULL) {	 /* UBC or malloced buffer */
   2155 			bp->b_cflags |= BC_BUSY;
   2156 			continue;
   2157 		}
   2158 
   2159 		while (bp->b_cflags & BC_BUSY) {
   2160 			DLOG((DLOG_SEG, "lfs_writeseg: avoiding potential"
   2161 			      " data summary corruption for ino %d, lbn %"
   2162 			      PRId64 "\n",
   2163 			      VTOI(bp->b_vp)->i_number, bp->b_lblkno));
   2164 			bp->b_cflags |= BC_WANTED;
   2165 			cv_wait(&bp->b_busy, &bufcache_lock);
   2166 		}
   2167 		bp->b_cflags |= BC_BUSY;
   2168 		mutex_exit(&bufcache_lock);
   2169 		unbusybp = NULL;
   2170 
   2171 		/*
   2172 		 * Check and replace indirect block UNWRITTEN bogosity.
   2173 		 * XXX See comment in lfs_writefile.
   2174 		 */
   2175 		if (bp->b_lblkno < 0 && bp->b_vp != devvp && bp->b_vp &&
   2176 		   VTOI(bp->b_vp)->i_ffs1_blocks !=
   2177 		   VTOI(bp->b_vp)->i_lfs_effnblks) {
   2178 			DLOG((DLOG_VNODE, "lfs_writeseg: cleansing ino %d (%jd != %d)\n",
   2179 			      VTOI(bp->b_vp)->i_number,
   2180 			      (intmax_t)VTOI(bp->b_vp)->i_lfs_effnblks,
   2181 			      VTOI(bp->b_vp)->i_ffs1_blocks));
   2182 			/* Make a copy we'll make changes to */
   2183 			newbp = lfs_newbuf(fs, bp->b_vp, bp->b_lblkno,
   2184 					   bp->b_bcount, LFS_NB_IBLOCK);
   2185 			newbp->b_blkno = bp->b_blkno;
   2186 			memcpy(newbp->b_data, bp->b_data,
   2187 			       newbp->b_bcount);
   2188 
   2189 			changed = 0;
   2190 			/* XXX ondisk32 */
   2191 			for (daddrp = (int32_t *)(newbp->b_data);
   2192 			     daddrp < (int32_t *)((char *)newbp->b_data +
   2193 						  newbp->b_bcount); daddrp++) {
   2194 				if (*daddrp == UNWRITTEN) {
   2195 					++changed;
   2196 					*daddrp = 0;
   2197 				}
   2198 			}
   2199 			/*
   2200 			 * Get rid of the old buffer.  Don't mark it clean,
   2201 			 * though, if it still has dirty data on it.
   2202 			 */
   2203 			if (changed) {
   2204 				DLOG((DLOG_SEG, "lfs_writeseg: replacing UNWRITTEN(%d):"
   2205 				      " bp = %p newbp = %p\n", changed, bp,
   2206 				      newbp));
   2207 				*bpp = newbp;
   2208 				bp->b_flags &= ~B_GATHERED;
   2209 				bp->b_error = 0;
   2210 				if (bp->b_iodone != NULL) {
   2211 					DLOG((DLOG_SEG, "lfs_writeseg: "
   2212 					      "indir bp should not be B_CALL\n"));
   2213 					biodone(bp);
   2214 					bp = NULL;
   2215 				} else {
   2216 					/* Still on free list, leave it there */
   2217 					unbusybp = bp;
   2218 					/*
   2219 					 * We have to re-decrement lfs_avail
   2220 					 * since this block is going to come
   2221 					 * back around to us in the next
   2222 					 * segment.
   2223 					 */
   2224 					lfs_sb_subavail(fs,
   2225 					    lfs_btofsb(fs, bp->b_bcount));
   2226 				}
   2227 			} else {
   2228 				lfs_freebuf(fs, newbp);
   2229 			}
   2230 		}
   2231 		mutex_enter(&bufcache_lock);
   2232 		if (unbusybp != NULL) {
   2233 			unbusybp->b_cflags &= ~BC_BUSY;
   2234 			if (unbusybp->b_cflags & BC_WANTED)
   2235 				cv_broadcast(&bp->b_busy);
   2236 		}
   2237 	}
   2238 	mutex_exit(&bufcache_lock);
   2239 
   2240 	/*
   2241 	 * Compute checksum across data and then across summary; the first
   2242 	 * block (the summary block) is skipped.  Set the create time here
   2243 	 * so that it's guaranteed to be later than the inode mod times.
   2244 	 */
   2245 	sum = 0;
   2246 	if (lfs_sb_getversion(fs) == 1)
   2247 		el_size = sizeof(u_long);
   2248 	else
   2249 		el_size = sizeof(u_int32_t);
   2250 	for (bpp = sp->bpp, i = nblocks - 1; i--; ) {
   2251 		++bpp;
   2252 		/* Loop through gop_write cluster blocks */
   2253 		for (byteoffset = 0; byteoffset < (*bpp)->b_bcount;
   2254 		     byteoffset += lfs_sb_getbsize(fs)) {
   2255 #ifdef LFS_USE_B_INVAL
   2256 			if (((*bpp)->b_cflags & BC_INVAL) != 0 &&
   2257 			    (*bpp)->b_iodone != NULL) {
   2258 				if (copyin((void *)(*bpp)->b_saveaddr +
   2259 					   byteoffset, dp, el_size)) {
   2260 					panic("lfs_writeseg: copyin failed [1]:"
   2261 						" ino %d blk %" PRId64,
   2262 						VTOI((*bpp)->b_vp)->i_number,
   2263 						(*bpp)->b_lblkno);
   2264 				}
   2265 			} else
   2266 #endif /* LFS_USE_B_INVAL */
   2267 			{
   2268 				sum = lfs_cksum_part((char *)
   2269 				    (*bpp)->b_data + byteoffset, el_size, sum);
   2270 			}
   2271 		}
   2272 	}
   2273 	if (lfs_sb_getversion(fs) == 1)
   2274 		lfs_ss_setocreate(fs, ssp, time_second);
   2275 	else {
   2276 		lfs_ss_setcreate(fs, ssp, time_second);
   2277 		lfs_sb_addserial(fs, 1);
   2278 		lfs_ss_setserial(fs, ssp, lfs_sb_getserial(fs));
   2279 		lfs_ss_setident(fs, ssp, lfs_sb_getident(fs));
   2280 	}
   2281 	lfs_ss_setdatasum(fs, ssp, lfs_cksum_fold(sum));
   2282 	sumstart = lfs_ss_getsumstart(fs);
   2283 	lfs_ss_setsumsum(fs, ssp, cksum((char *)ssp + sumstart,
   2284 	    lfs_sb_getsumsize(fs) - sumstart));
   2285 
   2286 	mutex_enter(&lfs_lock);
   2287 	lfs_sb_subbfree(fs, (lfs_btofsb(fs, ninos * lfs_sb_getibsize(fs)) +
   2288 			  lfs_btofsb(fs, lfs_sb_getsumsize(fs))));
   2289 	lfs_sb_adddmeta(fs, (lfs_btofsb(fs, ninos * lfs_sb_getibsize(fs)) +
   2290 			  lfs_btofsb(fs, lfs_sb_getsumsize(fs))));
   2291 	mutex_exit(&lfs_lock);
   2292 
   2293 	/*
   2294 	 * When we simply write the blocks we lose a rotation for every block
   2295 	 * written.  To avoid this problem, we cluster the buffers into a
   2296 	 * chunk and write the chunk.  MAXPHYS is the largest size I/O
   2297 	 * devices can handle, use that for the size of the chunks.
   2298 	 *
   2299 	 * Blocks that are already clusters (from GOP_WRITE), however, we
   2300 	 * don't bother to copy into other clusters.
   2301 	 */
   2302 
   2303 #define CHUNKSIZE MAXPHYS
   2304 
   2305 	if (devvp == NULL)
   2306 		panic("devvp is NULL");
   2307 	for (bpp = sp->bpp, i = nblocks; i;) {
   2308 		cbp = lfs_newclusterbuf(fs, devvp, (*bpp)->b_blkno, i);
   2309 		cl = cbp->b_private;
   2310 
   2311 		cbp->b_flags |= B_ASYNC;
   2312 		cbp->b_cflags |= BC_BUSY;
   2313 		cbp->b_bcount = 0;
   2314 
   2315 #if defined(DEBUG) && defined(DIAGNOSTIC)
   2316 		if (bpp - sp->bpp > (lfs_sb_getsumsize(fs) - SEGSUM_SIZE(fs))
   2317 		    / sizeof(int32_t)) {
   2318 			panic("lfs_writeseg: real bpp overwrite");
   2319 		}
   2320 		if (bpp - sp->bpp > lfs_segsize(fs) / lfs_sb_getfsize(fs)) {
   2321 			panic("lfs_writeseg: theoretical bpp overwrite");
   2322 		}
   2323 #endif
   2324 
   2325 		/*
   2326 		 * Construct the cluster.
   2327 		 */
   2328 		mutex_enter(&lfs_lock);
   2329 		++fs->lfs_iocount;
   2330 		mutex_exit(&lfs_lock);
   2331 		while (i && cbp->b_bcount < CHUNKSIZE) {
   2332 			bp = *bpp;
   2333 
   2334 			if (bp->b_bcount > (CHUNKSIZE - cbp->b_bcount))
   2335 				break;
   2336 			if (cbp->b_bcount > 0 && !(cl->flags & LFS_CL_MALLOC))
   2337 				break;
   2338 
   2339 			/* Clusters from GOP_WRITE are expedited */
   2340 			if (bp->b_bcount > lfs_sb_getbsize(fs)) {
   2341 				if (cbp->b_bcount > 0)
   2342 					/* Put in its own buffer */
   2343 					break;
   2344 				else {
   2345 					cbp->b_data = bp->b_data;
   2346 				}
   2347 			} else if (cbp->b_bcount == 0) {
   2348 				p = cbp->b_data = lfs_malloc(fs, CHUNKSIZE,
   2349 							     LFS_NB_CLUSTER);
   2350 				cl->flags |= LFS_CL_MALLOC;
   2351 			}
   2352 #ifdef DIAGNOSTIC
   2353 			if (lfs_dtosn(fs, LFS_DBTOFSB(fs, bp->b_blkno +
   2354 					      btodb(bp->b_bcount - 1))) !=
   2355 			    sp->seg_number) {
   2356 				printf("blk size %d daddr %" PRIx64
   2357 				    " not in seg %d\n",
   2358 				    bp->b_bcount, bp->b_blkno,
   2359 				    sp->seg_number);
   2360 				panic("segment overwrite");
   2361 			}
   2362 #endif
   2363 
   2364 #ifdef LFS_USE_B_INVAL
   2365 			/*
   2366 			 * Fake buffers from the cleaner are marked as B_INVAL.
   2367 			 * We need to copy the data from user space rather than
   2368 			 * from the buffer indicated.
   2369 			 * XXX == what do I do on an error?
   2370 			 */
   2371 			if ((bp->b_cflags & BC_INVAL) != 0 &&
   2372 			    bp->b_iodone != NULL) {
   2373 				if (copyin(bp->b_saveaddr, p, bp->b_bcount))
   2374 					panic("lfs_writeseg: "
   2375 					    "copyin failed [2]");
   2376 			} else
   2377 #endif /* LFS_USE_B_INVAL */
   2378 			if (cl->flags & LFS_CL_MALLOC) {
   2379 				/* copy data into our cluster. */
   2380 				memcpy(p, bp->b_data, bp->b_bcount);
   2381 				p += bp->b_bcount;
   2382 			}
   2383 
   2384 			cbp->b_bcount += bp->b_bcount;
   2385 			cl->bufsize += bp->b_bcount;
   2386 
   2387 			bp->b_flags &= ~B_READ;
   2388 			bp->b_error = 0;
   2389 			cl->bpp[cl->bufcount++] = bp;
   2390 
   2391 			vp = bp->b_vp;
   2392 			mutex_enter(&bufcache_lock);
   2393 			mutex_enter(vp->v_interlock);
   2394 			bp->b_oflags &= ~(BO_DELWRI | BO_DONE);
   2395 			reassignbuf(bp, vp);
   2396 			vp->v_numoutput++;
   2397 			mutex_exit(vp->v_interlock);
   2398 			mutex_exit(&bufcache_lock);
   2399 
   2400 			bpp++;
   2401 			i--;
   2402 		}
   2403 		if (fs->lfs_sp->seg_flags & SEGM_SYNC)
   2404 			BIO_SETPRIO(cbp, BPRIO_TIMECRITICAL);
   2405 		else
   2406 			BIO_SETPRIO(cbp, BPRIO_TIMELIMITED);
   2407 		mutex_enter(devvp->v_interlock);
   2408 		devvp->v_numoutput++;
   2409 		mutex_exit(devvp->v_interlock);
   2410 		VOP_STRATEGY(devvp, cbp);
   2411 		curlwp->l_ru.ru_oublock++;
   2412 	}
   2413 
   2414 	if (lfs_dostats) {
   2415 		++lfs_stats.psegwrites;
   2416 		lfs_stats.blocktot += nblocks - 1;
   2417 		if (fs->lfs_sp->seg_flags & SEGM_SYNC)
   2418 			++lfs_stats.psyncwrites;
   2419 		if (fs->lfs_sp->seg_flags & SEGM_CLEAN) {
   2420 			++lfs_stats.pcleanwrites;
   2421 			lfs_stats.cleanblocks += nblocks - 1;
   2422 		}
   2423 	}
   2424 
   2425 	return (lfs_initseg(fs) || do_again);
   2426 }
   2427 
   2428 void
   2429 lfs_writesuper(struct lfs *fs, daddr_t daddr)
   2430 {
   2431 	struct buf *bp;
   2432 	struct vnode *devvp = VTOI(fs->lfs_ivnode)->i_devvp;
   2433 	int s;
   2434 
   2435 	ASSERT_MAYBE_SEGLOCK(fs);
   2436 #ifdef DIAGNOSTIC
   2437 	if (fs->lfs_is64) {
   2438 		KASSERT(fs->lfs_dlfs_u.u_64.dlfs_magic == LFS64_MAGIC);
   2439 	} else {
   2440 		KASSERT(fs->lfs_dlfs_u.u_32.dlfs_magic == LFS_MAGIC);
   2441 	}
   2442 #endif
   2443 	/*
   2444 	 * If we can write one superblock while another is in
   2445 	 * progress, we risk not having a complete checkpoint if we crash.
   2446 	 * So, block here if a superblock write is in progress.
   2447 	 */
   2448 	mutex_enter(&lfs_lock);
   2449 	s = splbio();
   2450 	while (fs->lfs_sbactive) {
   2451 		mtsleep(&fs->lfs_sbactive, PRIBIO+1, "lfs sb", 0,
   2452 			&lfs_lock);
   2453 	}
   2454 	fs->lfs_sbactive = daddr;
   2455 	splx(s);
   2456 	mutex_exit(&lfs_lock);
   2457 
   2458 	/* Set timestamp of this version of the superblock */
   2459 	if (lfs_sb_getversion(fs) == 1)
   2460 		lfs_sb_setotstamp(fs, time_second);
   2461 	lfs_sb_settstamp(fs, time_second);
   2462 
   2463 	/* The next chunk of code relies on this assumption */
   2464 	CTASSERT(sizeof(struct dlfs) == sizeof(struct dlfs64));
   2465 
   2466 	/* Checksum the superblock and copy it into a buffer. */
   2467 	lfs_sb_setcksum(fs, lfs_sb_cksum(fs));
   2468 	bp = lfs_newbuf(fs, devvp,
   2469 	    LFS_FSBTODB(fs, daddr), LFS_SBPAD, LFS_NB_SBLOCK);
   2470 	memcpy(bp->b_data, &fs->lfs_dlfs_u, sizeof(struct dlfs));
   2471 	memset((char *)bp->b_data + sizeof(struct dlfs), 0,
   2472 	    LFS_SBPAD - sizeof(struct dlfs));
   2473 
   2474 	bp->b_cflags |= BC_BUSY;
   2475 	bp->b_flags = (bp->b_flags & ~B_READ) | B_ASYNC;
   2476 	bp->b_oflags &= ~(BO_DONE | BO_DELWRI);
   2477 	bp->b_error = 0;
   2478 	bp->b_iodone = lfs_supercallback;
   2479 
   2480 	if (fs->lfs_sp != NULL && fs->lfs_sp->seg_flags & SEGM_SYNC)
   2481 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
   2482 	else
   2483 		BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
   2484 	curlwp->l_ru.ru_oublock++;
   2485 
   2486 	mutex_enter(devvp->v_interlock);
   2487 	devvp->v_numoutput++;
   2488 	mutex_exit(devvp->v_interlock);
   2489 
   2490 	mutex_enter(&lfs_lock);
   2491 	++fs->lfs_iocount;
   2492 	mutex_exit(&lfs_lock);
   2493 	VOP_STRATEGY(devvp, bp);
   2494 }
   2495 
   2496 /*
   2497  * Logical block number match routines used when traversing the dirty block
   2498  * chain.
   2499  */
   2500 int
   2501 lfs_match_fake(struct lfs *fs, struct buf *bp)
   2502 {
   2503 
   2504 	ASSERT_SEGLOCK(fs);
   2505 	return LFS_IS_MALLOC_BUF(bp);
   2506 }
   2507 
   2508 #if 0
   2509 int
   2510 lfs_match_real(struct lfs *fs, struct buf *bp)
   2511 {
   2512 
   2513 	ASSERT_SEGLOCK(fs);
   2514 	return (lfs_match_data(fs, bp) && !lfs_match_fake(fs, bp));
   2515 }
   2516 #endif
   2517 
   2518 int
   2519 lfs_match_data(struct lfs *fs, struct buf *bp)
   2520 {
   2521 
   2522 	ASSERT_SEGLOCK(fs);
   2523 	return (bp->b_lblkno >= 0);
   2524 }
   2525 
   2526 int
   2527 lfs_match_indir(struct lfs *fs, struct buf *bp)
   2528 {
   2529 	daddr_t lbn;
   2530 
   2531 	ASSERT_SEGLOCK(fs);
   2532 	lbn = bp->b_lblkno;
   2533 	return (lbn < 0 && (-lbn - ULFS_NDADDR) % LFS_NINDIR(fs) == 0);
   2534 }
   2535 
   2536 int
   2537 lfs_match_dindir(struct lfs *fs, struct buf *bp)
   2538 {
   2539 	daddr_t lbn;
   2540 
   2541 	ASSERT_SEGLOCK(fs);
   2542 	lbn = bp->b_lblkno;
   2543 	return (lbn < 0 && (-lbn - ULFS_NDADDR) % LFS_NINDIR(fs) == 1);
   2544 }
   2545 
   2546 int
   2547 lfs_match_tindir(struct lfs *fs, struct buf *bp)
   2548 {
   2549 	daddr_t lbn;
   2550 
   2551 	ASSERT_SEGLOCK(fs);
   2552 	lbn = bp->b_lblkno;
   2553 	return (lbn < 0 && (-lbn - ULFS_NDADDR) % LFS_NINDIR(fs) == 2);
   2554 }
   2555 
   2556 static void
   2557 lfs_free_aiodone(struct buf *bp)
   2558 {
   2559 	struct lfs *fs;
   2560 
   2561 	KERNEL_LOCK(1, curlwp);
   2562 	fs = bp->b_private;
   2563 	ASSERT_NO_SEGLOCK(fs);
   2564 	lfs_freebuf(fs, bp);
   2565 	KERNEL_UNLOCK_LAST(curlwp);
   2566 }
   2567 
   2568 static void
   2569 lfs_super_aiodone(struct buf *bp)
   2570 {
   2571 	struct lfs *fs;
   2572 
   2573 	KERNEL_LOCK(1, curlwp);
   2574 	fs = bp->b_private;
   2575 	ASSERT_NO_SEGLOCK(fs);
   2576 	mutex_enter(&lfs_lock);
   2577 	fs->lfs_sbactive = 0;
   2578 	if (--fs->lfs_iocount <= 1)
   2579 		wakeup(&fs->lfs_iocount);
   2580 	wakeup(&fs->lfs_sbactive);
   2581 	mutex_exit(&lfs_lock);
   2582 	lfs_freebuf(fs, bp);
   2583 	KERNEL_UNLOCK_LAST(curlwp);
   2584 }
   2585 
   2586 static void
   2587 lfs_cluster_aiodone(struct buf *bp)
   2588 {
   2589 	struct lfs_cluster *cl;
   2590 	struct lfs *fs;
   2591 	struct buf *tbp, *fbp;
   2592 	struct vnode *vp, *devvp, *ovp;
   2593 	struct inode *ip;
   2594 	int error;
   2595 
   2596 	KERNEL_LOCK(1, curlwp);
   2597 
   2598 	error = bp->b_error;
   2599 	cl = bp->b_private;
   2600 	fs = cl->fs;
   2601 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
   2602 	ASSERT_NO_SEGLOCK(fs);
   2603 
   2604 	/* Put the pages back, and release the buffer */
   2605 	while (cl->bufcount--) {
   2606 		tbp = cl->bpp[cl->bufcount];
   2607 		KASSERT(tbp->b_cflags & BC_BUSY);
   2608 		if (error) {
   2609 			tbp->b_error = error;
   2610 		}
   2611 
   2612 		/*
   2613 		 * We're done with tbp.	 If it has not been re-dirtied since
   2614 		 * the cluster was written, free it.  Otherwise, keep it on
   2615 		 * the locked list to be written again.
   2616 		 */
   2617 		vp = tbp->b_vp;
   2618 
   2619 		tbp->b_flags &= ~B_GATHERED;
   2620 
   2621 		LFS_BCLEAN_LOG(fs, tbp);
   2622 
   2623 		mutex_enter(&bufcache_lock);
   2624 		if (tbp->b_iodone == NULL) {
   2625 			KASSERT(tbp->b_flags & B_LOCKED);
   2626 			bremfree(tbp);
   2627 			if (vp) {
   2628 				mutex_enter(vp->v_interlock);
   2629 				reassignbuf(tbp, vp);
   2630 				mutex_exit(vp->v_interlock);
   2631 			}
   2632 			tbp->b_flags |= B_ASYNC; /* for biodone */
   2633 		}
   2634 
   2635 		if (((tbp->b_flags | tbp->b_oflags) &
   2636 		    (B_LOCKED | BO_DELWRI)) == B_LOCKED)
   2637 			LFS_UNLOCK_BUF(tbp);
   2638 
   2639 		if (tbp->b_oflags & BO_DONE) {
   2640 			DLOG((DLOG_SEG, "blk %d biodone already (flags %lx)\n",
   2641 				cl->bufcount, (long)tbp->b_flags));
   2642 		}
   2643 
   2644 		if (tbp->b_iodone != NULL && !LFS_IS_MALLOC_BUF(tbp)) {
   2645 			/*
   2646 			 * A buffer from the page daemon.
   2647 			 * We use the same iodone as it does,
   2648 			 * so we must manually disassociate its
   2649 			 * buffers from the vp.
   2650 			 */
   2651 			if ((ovp = tbp->b_vp) != NULL) {
   2652 				/* This is just silly */
   2653 				mutex_enter(ovp->v_interlock);
   2654 				brelvp(tbp);
   2655 				mutex_exit(ovp->v_interlock);
   2656 				tbp->b_vp = vp;
   2657 				tbp->b_objlock = vp->v_interlock;
   2658 			}
   2659 			/* Put it back the way it was */
   2660 			tbp->b_flags |= B_ASYNC;
   2661 			/* Master buffers have BC_AGE */
   2662 			if (tbp->b_private == tbp)
   2663 				tbp->b_cflags |= BC_AGE;
   2664 		}
   2665 		mutex_exit(&bufcache_lock);
   2666 
   2667 		biodone(tbp);
   2668 
   2669 		/*
   2670 		 * If this is the last block for this vnode, but
   2671 		 * there are other blocks on its dirty list,
   2672 		 * set IN_MODIFIED/IN_CLEANING depending on what
   2673 		 * sort of block.  Only do this for our mount point,
   2674 		 * not for, e.g., inode blocks that are attached to
   2675 		 * the devvp.
   2676 		 * XXX KS - Shouldn't we set *both* if both types
   2677 		 * of blocks are present (traverse the dirty list?)
   2678 		 */
   2679 		mutex_enter(vp->v_interlock);
   2680 		mutex_enter(&lfs_lock);
   2681 		if (vp != devvp && vp->v_numoutput == 0 &&
   2682 		    (fbp = LIST_FIRST(&vp->v_dirtyblkhd)) != NULL) {
   2683 			ip = VTOI(vp);
   2684 			DLOG((DLOG_SEG, "lfs_cluster_aiodone: mark ino %d\n",
   2685 			       ip->i_number));
   2686 			if (LFS_IS_MALLOC_BUF(fbp))
   2687 				LFS_SET_UINO(ip, IN_CLEANING);
   2688 			else
   2689 				LFS_SET_UINO(ip, IN_MODIFIED);
   2690 		}
   2691 		cv_broadcast(&vp->v_cv);
   2692 		mutex_exit(&lfs_lock);
   2693 		mutex_exit(vp->v_interlock);
   2694 	}
   2695 
   2696 	/* Fix up the cluster buffer, and release it */
   2697 	if (cl->flags & LFS_CL_MALLOC)
   2698 		lfs_free(fs, bp->b_data, LFS_NB_CLUSTER);
   2699 	putiobuf(bp);
   2700 
   2701 	/* Note i/o done */
   2702 	if (cl->flags & LFS_CL_SYNC) {
   2703 		if (--cl->seg->seg_iocount == 0)
   2704 			wakeup(&cl->seg->seg_iocount);
   2705 	}
   2706 	mutex_enter(&lfs_lock);
   2707 #ifdef DIAGNOSTIC
   2708 	if (fs->lfs_iocount == 0)
   2709 		panic("lfs_cluster_aiodone: zero iocount");
   2710 #endif
   2711 	if (--fs->lfs_iocount <= 1)
   2712 		wakeup(&fs->lfs_iocount);
   2713 	mutex_exit(&lfs_lock);
   2714 
   2715 	KERNEL_UNLOCK_LAST(curlwp);
   2716 
   2717 	pool_put(&fs->lfs_bpppool, cl->bpp);
   2718 	cl->bpp = NULL;
   2719 	pool_put(&fs->lfs_clpool, cl);
   2720 }
   2721 
   2722 static void
   2723 lfs_generic_callback(struct buf *bp, void (*aiodone)(struct buf *))
   2724 {
   2725 	/* reset b_iodone for when this is a single-buf i/o. */
   2726 	bp->b_iodone = aiodone;
   2727 
   2728 	workqueue_enqueue(uvm.aiodone_queue, &bp->b_work, NULL);
   2729 }
   2730 
   2731 static void
   2732 lfs_cluster_callback(struct buf *bp)
   2733 {
   2734 
   2735 	lfs_generic_callback(bp, lfs_cluster_aiodone);
   2736 }
   2737 
   2738 void
   2739 lfs_supercallback(struct buf *bp)
   2740 {
   2741 
   2742 	lfs_generic_callback(bp, lfs_super_aiodone);
   2743 }
   2744 
   2745 /*
   2746  * The only buffers that are going to hit these functions are the
   2747  * segment write blocks, or the segment summaries, or the superblocks.
   2748  *
   2749  * All of the above are created by lfs_newbuf, and so do not need to be
   2750  * released via brelse.
   2751  */
   2752 void
   2753 lfs_callback(struct buf *bp)
   2754 {
   2755 
   2756 	lfs_generic_callback(bp, lfs_free_aiodone);
   2757 }
   2758 
   2759 /*
   2760  * Shellsort (diminishing increment sort) from Data Structures and
   2761  * Algorithms, Aho, Hopcraft and Ullman, 1983 Edition, page 290;
   2762  * see also Knuth Vol. 3, page 84.  The increments are selected from
   2763  * formula (8), page 95.  Roughly O(N^3/2).
   2764  */
   2765 /*
   2766  * This is our own private copy of shellsort because we want to sort
   2767  * two parallel arrays (the array of buffer pointers and the array of
   2768  * logical block numbers) simultaneously.  Note that we cast the array
   2769  * of logical block numbers to a unsigned in this routine so that the
   2770  * negative block numbers (meta data blocks) sort AFTER the data blocks.
   2771  */
   2772 
   2773 static void
   2774 lfs_shellsort(struct lfs *fs,
   2775 	      struct buf **bp_array, union lfs_blocks *lb_array,
   2776 	      int nmemb, int size)
   2777 {
   2778 	static int __rsshell_increments[] = { 4, 1, 0 };
   2779 	int incr, *incrp, t1, t2;
   2780 	struct buf *bp_temp;
   2781 
   2782 #ifdef DEBUG
   2783 	incr = 0;
   2784 	for (t1 = 0; t1 < nmemb; t1++) {
   2785 		for (t2 = 0; t2 * size < bp_array[t1]->b_bcount; t2++) {
   2786 			if (lfs_blocks_get(fs, lb_array, incr++) != bp_array[t1]->b_lblkno + t2) {
   2787 				/* dump before panic */
   2788 				printf("lfs_shellsort: nmemb=%d, size=%d\n",
   2789 				    nmemb, size);
   2790 				incr = 0;
   2791 				for (t1 = 0; t1 < nmemb; t1++) {
   2792 					const struct buf *bp = bp_array[t1];
   2793 
   2794 					printf("bp[%d]: lbn=%" PRIu64 ", size=%"
   2795 					    PRIu64 "\n", t1,
   2796 					    (uint64_t)bp->b_bcount,
   2797 					    (uint64_t)bp->b_lblkno);
   2798 					printf("lbns:");
   2799 					for (t2 = 0; t2 * size < bp->b_bcount;
   2800 					    t2++) {
   2801 						printf(" %jd",
   2802 						    (intmax_t)lfs_blocks_get(fs, lb_array, incr++));
   2803 					}
   2804 					printf("\n");
   2805 				}
   2806 				panic("lfs_shellsort: inconsistent input");
   2807 			}
   2808 		}
   2809 	}
   2810 #endif
   2811 
   2812 	for (incrp = __rsshell_increments; (incr = *incrp++) != 0;)
   2813 		for (t1 = incr; t1 < nmemb; ++t1)
   2814 			for (t2 = t1 - incr; t2 >= 0;)
   2815 				if ((u_int64_t)bp_array[t2]->b_lblkno >
   2816 				    (u_int64_t)bp_array[t2 + incr]->b_lblkno) {
   2817 					bp_temp = bp_array[t2];
   2818 					bp_array[t2] = bp_array[t2 + incr];
   2819 					bp_array[t2 + incr] = bp_temp;
   2820 					t2 -= incr;
   2821 				} else
   2822 					break;
   2823 
   2824 	/* Reform the list of logical blocks */
   2825 	incr = 0;
   2826 	for (t1 = 0; t1 < nmemb; t1++) {
   2827 		for (t2 = 0; t2 * size < bp_array[t1]->b_bcount; t2++) {
   2828 			lfs_blocks_set(fs, lb_array, incr++,
   2829 				       bp_array[t1]->b_lblkno + t2);
   2830 		}
   2831 	}
   2832 }
   2833 
   2834 /*
   2835  * Set up an FINFO entry for a new file.  The fip pointer is assumed to
   2836  * point at uninitialized space.
   2837  */
   2838 void
   2839 lfs_acquire_finfo(struct lfs *fs, ino_t ino, int vers)
   2840 {
   2841 	struct segment *sp = fs->lfs_sp;
   2842 	SEGSUM *ssp;
   2843 
   2844 	KASSERT(vers > 0);
   2845 
   2846 	if (sp->seg_bytes_left < lfs_sb_getbsize(fs) ||
   2847 	    sp->sum_bytes_left < FINFOSIZE(fs) + LFS_BLKPTRSIZE(fs))
   2848 		(void) lfs_writeseg(fs, fs->lfs_sp);
   2849 
   2850 	sp->sum_bytes_left -= FINFOSIZE(fs);
   2851 	ssp = (SEGSUM *)sp->segsum;
   2852 	lfs_ss_setnfinfo(fs, ssp, lfs_ss_getnfinfo(fs, ssp) + 1);
   2853 	lfs_fi_setnblocks(fs, sp->fip, 0);
   2854 	lfs_fi_setino(fs, sp->fip, ino);
   2855 	lfs_fi_setversion(fs, sp->fip, vers);
   2856 }
   2857 
   2858 /*
   2859  * Release the FINFO entry, either clearing out an unused entry or
   2860  * advancing us to the next available entry.
   2861  */
   2862 void
   2863 lfs_release_finfo(struct lfs *fs)
   2864 {
   2865 	struct segment *sp = fs->lfs_sp;
   2866 	SEGSUM *ssp;
   2867 
   2868 	if (lfs_fi_getnblocks(fs, sp->fip) != 0) {
   2869 		sp->fip = NEXT_FINFO(fs, sp->fip);
   2870 		lfs_blocks_fromfinfo(fs, &sp->start_lbp, sp->fip);
   2871 	} else {
   2872 		/* XXX shouldn't this update sp->fip? */
   2873 		sp->sum_bytes_left += FINFOSIZE(fs);
   2874 		ssp = (SEGSUM *)sp->segsum;
   2875 		lfs_ss_setnfinfo(fs, ssp, lfs_ss_getnfinfo(fs, ssp) - 1);
   2876 	}
   2877 }
   2878