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