Home | History | Annotate | Line # | Download | only in lfs
lfs_segment.c revision 1.62
      1 /*	$NetBSD: lfs_segment.c,v 1.62 2000/11/17 19:14:41 perseant Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1999, 2000 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 #define ivndebug(vp,str) printf("ino %d: %s\n",VTOI(vp)->i_number,(str))
     74 
     75 #include "opt_ddb.h"
     76 #include <sys/param.h>
     77 #include <sys/systm.h>
     78 #include <sys/namei.h>
     79 #include <sys/kernel.h>
     80 #include <sys/resourcevar.h>
     81 #include <sys/file.h>
     82 #include <sys/stat.h>
     83 #include <sys/buf.h>
     84 #include <sys/proc.h>
     85 #include <sys/conf.h>
     86 #include <sys/vnode.h>
     87 #include <sys/malloc.h>
     88 #include <sys/mount.h>
     89 
     90 #include <miscfs/specfs/specdev.h>
     91 #include <miscfs/fifofs/fifo.h>
     92 
     93 #include <ufs/ufs/quota.h>
     94 #include <ufs/ufs/inode.h>
     95 #include <ufs/ufs/dir.h>
     96 #include <ufs/ufs/ufsmount.h>
     97 #include <ufs/ufs/ufs_extern.h>
     98 
     99 #include <ufs/lfs/lfs.h>
    100 #include <ufs/lfs/lfs_extern.h>
    101 
    102 extern int count_lock_queue __P((void));
    103 extern struct simplelock vnode_free_list_slock;		/* XXX */
    104 
    105 /*
    106  * Determine if it's OK to start a partial in this segment, or if we need
    107  * to go on to a new segment.
    108  */
    109 #define	LFS_PARTIAL_FITS(fs) \
    110 	((fs)->lfs_dbpseg - ((fs)->lfs_offset - (fs)->lfs_curseg) > \
    111 	1 << (fs)->lfs_fsbtodb)
    112 
    113 void	 lfs_callback __P((struct buf *));
    114 int	 lfs_gather __P((struct lfs *, struct segment *,
    115 	     struct vnode *, int (*) __P((struct lfs *, struct buf *))));
    116 int	 lfs_gatherblock __P((struct segment *, struct buf *, int *));
    117 void	 lfs_iset __P((struct inode *, ufs_daddr_t, time_t));
    118 int	 lfs_match_fake __P((struct lfs *, struct buf *));
    119 int	 lfs_match_data __P((struct lfs *, struct buf *));
    120 int	 lfs_match_dindir __P((struct lfs *, struct buf *));
    121 int	 lfs_match_indir __P((struct lfs *, struct buf *));
    122 int	 lfs_match_tindir __P((struct lfs *, struct buf *));
    123 void	 lfs_newseg __P((struct lfs *));
    124 void	 lfs_shellsort __P((struct buf **, ufs_daddr_t *, int));
    125 void	 lfs_supercallback __P((struct buf *));
    126 void	 lfs_updatemeta __P((struct segment *));
    127 int	 lfs_vref __P((struct vnode *));
    128 void	 lfs_vunref __P((struct vnode *));
    129 void	 lfs_writefile __P((struct lfs *, struct segment *, struct vnode *));
    130 int	 lfs_writeinode __P((struct lfs *, struct segment *, struct inode *));
    131 int	 lfs_writeseg __P((struct lfs *, struct segment *));
    132 void	 lfs_writesuper __P((struct lfs *, daddr_t));
    133 int	 lfs_writevnodes __P((struct lfs *fs, struct mount *mp,
    134 	    struct segment *sp, int dirops));
    135 
    136 int	lfs_allclean_wakeup;		/* Cleaner wakeup address. */
    137 int	lfs_writeindir = 1;             /* whether to flush indir on non-ckp */
    138 int	lfs_clean_vnhead = 0;		/* Allow freeing to head of vn list */
    139 int	lfs_dirvcount = 0;		/* # active dirops */
    140 
    141 /* Statistics Counters */
    142 int lfs_dostats = 1;
    143 struct lfs_stats lfs_stats;
    144 
    145 extern int locked_queue_count;
    146 extern long locked_queue_bytes;
    147 
    148 /* op values to lfs_writevnodes */
    149 #define	VN_REG	        0
    150 #define	VN_DIROP	1
    151 #define	VN_EMPTY	2
    152 #define VN_CLEAN        3
    153 
    154 #define LFS_MAX_ACTIVE          10
    155 
    156 /*
    157  * XXX KS - Set modification time on the Ifile, so the cleaner can
    158  * read the fs mod time off of it.  We don't set IN_UPDATE here,
    159  * since we don't really need this to be flushed to disk (and in any
    160  * case that wouldn't happen to the Ifile until we checkpoint).
    161  */
    162 void
    163 lfs_imtime(fs)
    164 	struct lfs *fs;
    165 {
    166 	struct timespec ts;
    167 	struct inode *ip;
    168 
    169 	TIMEVAL_TO_TIMESPEC(&time, &ts);
    170 	ip = VTOI(fs->lfs_ivnode);
    171 	ip->i_ffs_mtime = ts.tv_sec;
    172 	ip->i_ffs_mtimensec = ts.tv_nsec;
    173 }
    174 
    175 /*
    176  * Ifile and meta data blocks are not marked busy, so segment writes MUST be
    177  * single threaded.  Currently, there are two paths into lfs_segwrite, sync()
    178  * and getnewbuf().  They both mark the file system busy.  Lfs_vflush()
    179  * explicitly marks the file system busy.  So lfs_segwrite is safe.  I think.
    180  */
    181 
    182 #define SET_FLUSHING(fs,vp) (fs)->lfs_flushvp = (vp)
    183 #define IS_FLUSHING(fs,vp)  ((fs)->lfs_flushvp == (vp))
    184 #define CLR_FLUSHING(fs,vp) (fs)->lfs_flushvp = NULL
    185 
    186 int
    187 lfs_vflush(vp)
    188 	struct vnode *vp;
    189 {
    190 	struct inode *ip;
    191 	struct lfs *fs;
    192 	struct segment *sp;
    193 	struct buf *bp, *nbp, *tbp, *tnbp;
    194 	int error, s;
    195 
    196 	ip = VTOI(vp);
    197 	fs = VFSTOUFS(vp->v_mount)->um_lfs;
    198 
    199 	if(ip->i_flag & IN_CLEANING) {
    200 #ifdef DEBUG_LFS
    201 		ivndebug(vp,"vflush/in_cleaning");
    202 #endif
    203 		LFS_CLR_UINO(ip, IN_CLEANING);
    204 		LFS_SET_UINO(ip, IN_MODIFIED);
    205 
    206 		/*
    207 		 * Toss any cleaning buffers that have real counterparts
    208 		 * to avoid losing new data
    209 		 */
    210 		s = splbio();
    211 		for(bp=vp->v_dirtyblkhd.lh_first; bp; bp=nbp) {
    212 			nbp = bp->b_vnbufs.le_next;
    213 			if(bp->b_flags & B_CALL) {
    214 				for(tbp=vp->v_dirtyblkhd.lh_first; tbp;
    215 				    tbp=tnbp)
    216 				{
    217 					tnbp = tbp->b_vnbufs.le_next;
    218 					if(tbp->b_vp == bp->b_vp
    219 					   && tbp->b_lblkno == bp->b_lblkno
    220 					   && tbp != bp)
    221 					{
    222 						fs->lfs_avail += btodb(bp->b_bcount);
    223 						wakeup(&fs->lfs_avail);
    224 						lfs_freebuf(bp);
    225 					}
    226 				}
    227 			}
    228 		}
    229 		splx(s);
    230 	}
    231 
    232 	/* If the node is being written, wait until that is done */
    233 	if(WRITEINPROG(vp)) {
    234 #ifdef DEBUG_LFS
    235 		ivndebug(vp,"vflush/writeinprog");
    236 #endif
    237 		tsleep(vp, PRIBIO+1, "lfs_vw", 0);
    238 	}
    239 
    240 	/* Protect against VXLOCK deadlock in vinvalbuf() */
    241 	lfs_seglock(fs, SEGM_SYNC);
    242 
    243 	/* If we're supposed to flush a freed inode, just toss it */
    244 	/* XXX - seglock, so these buffers can't be gathered, right? */
    245 	if(ip->i_ffs_mode == 0) {
    246 		printf("lfs_vflush: ino %d is freed, not flushing\n",
    247 			ip->i_number);
    248 		s = splbio();
    249 		for(bp=vp->v_dirtyblkhd.lh_first; bp; bp=nbp) {
    250 			nbp = bp->b_vnbufs.le_next;
    251 			if (bp->b_flags & B_DELWRI) { /* XXX always true? */
    252 				fs->lfs_avail += btodb(bp->b_bcount);
    253 				wakeup(&fs->lfs_avail);
    254 			}
    255 			/* Copied from lfs_writeseg */
    256 			if (bp->b_flags & B_CALL) {
    257 				/* if B_CALL, it was created with newbuf */
    258 				lfs_freebuf(bp);
    259 			} else {
    260 				bremfree(bp);
    261 				LFS_UNLOCK_BUF(bp);
    262 				bp->b_flags &= ~(B_ERROR | B_READ | B_DELWRI |
    263                                          B_GATHERED);
    264 				bp->b_flags |= B_DONE;
    265 				reassignbuf(bp, vp);
    266 				brelse(bp);
    267 			}
    268 		}
    269 		splx(s);
    270 		LFS_CLR_UINO(ip, IN_CLEANING);
    271 		LFS_CLR_UINO(ip, IN_MODIFIED | IN_ACCESSED);
    272 		ip->i_flag &= ~IN_ALLMOD;
    273 		printf("lfs_vflush: done not flushing ino %d\n",
    274 			ip->i_number);
    275 		lfs_segunlock(fs);
    276 		return 0;
    277 	}
    278 
    279 	SET_FLUSHING(fs,vp);
    280 	if (fs->lfs_nactive > LFS_MAX_ACTIVE) {
    281 		error = lfs_segwrite(vp->v_mount, SEGM_SYNC|SEGM_CKP);
    282 		CLR_FLUSHING(fs,vp);
    283 		lfs_segunlock(fs);
    284 		return error;
    285 	}
    286 	sp = fs->lfs_sp;
    287 
    288 	if (vp->v_dirtyblkhd.lh_first == NULL) {
    289 		lfs_writevnodes(fs, vp->v_mount, sp, VN_EMPTY);
    290 	} else if((ip->i_flag & IN_CLEANING) &&
    291 		  (fs->lfs_sp->seg_flags & SEGM_CLEAN)) {
    292 #ifdef DEBUG_LFS
    293 		ivndebug(vp,"vflush/clean");
    294 #endif
    295 		lfs_writevnodes(fs, vp->v_mount, sp, VN_CLEAN);
    296 	}
    297 	else if(lfs_dostats) {
    298 		if(vp->v_dirtyblkhd.lh_first || (VTOI(vp)->i_flag & IN_ALLMOD))
    299 			++lfs_stats.vflush_invoked;
    300 #ifdef DEBUG_LFS
    301 		ivndebug(vp,"vflush");
    302 #endif
    303 	}
    304 
    305 #ifdef DIAGNOSTIC
    306 	/* XXX KS This actually can happen right now, though it shouldn't(?) */
    307 	if(vp->v_flag & VDIROP) {
    308 		printf("lfs_vflush: flushing VDIROP, this shouldn\'t be\n");
    309 		/* panic("VDIROP being flushed...this can\'t happen"); */
    310 	}
    311 	if(vp->v_usecount<0) {
    312 		printf("usecount=%ld\n",vp->v_usecount);
    313 		panic("lfs_vflush: usecount<0");
    314 	}
    315 #endif
    316 
    317 	do {
    318 		do {
    319 			if (vp->v_dirtyblkhd.lh_first != NULL)
    320 				lfs_writefile(fs, sp, vp);
    321 		} while (lfs_writeinode(fs, sp, ip));
    322 	} while (lfs_writeseg(fs, sp) && ip->i_number == LFS_IFILE_INUM);
    323 
    324 	if(lfs_dostats) {
    325 		++lfs_stats.nwrites;
    326 		if (sp->seg_flags & SEGM_SYNC)
    327 			++lfs_stats.nsync_writes;
    328 		if (sp->seg_flags & SEGM_CKP)
    329 			++lfs_stats.ncheckpoints;
    330 	}
    331 	lfs_segunlock(fs);
    332 
    333 	CLR_FLUSHING(fs,vp);
    334 	return (0);
    335 }
    336 
    337 #ifdef DEBUG_LFS_VERBOSE
    338 # 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)
    339 #else
    340 # define vndebug(vp,str)
    341 #endif
    342 
    343 int
    344 lfs_writevnodes(fs, mp, sp, op)
    345 	struct lfs *fs;
    346 	struct mount *mp;
    347 	struct segment *sp;
    348 	int op;
    349 {
    350 	struct inode *ip;
    351 	struct vnode *vp;
    352 	int inodes_written=0, only_cleaning;
    353 	int needs_unlock;
    354 
    355 #ifndef LFS_NO_BACKVP_HACK
    356 	/* BEGIN HACK */
    357 #define	VN_OFFSET	(((caddr_t)&vp->v_mntvnodes.le_next) - (caddr_t)vp)
    358 #define	BACK_VP(VP)	((struct vnode *)(((caddr_t)VP->v_mntvnodes.le_prev) - VN_OFFSET))
    359 #define	BEG_OF_VLIST	((struct vnode *)(((caddr_t)&mp->mnt_vnodelist.lh_first) - VN_OFFSET))
    360 
    361 	/* Find last vnode. */
    362  loop:	for (vp = mp->mnt_vnodelist.lh_first;
    363 	     vp && vp->v_mntvnodes.le_next != NULL;
    364 	     vp = vp->v_mntvnodes.le_next);
    365 	for (; vp && vp != BEG_OF_VLIST; vp = BACK_VP(vp)) {
    366 #else
    367 	loop:
    368 	for (vp = mp->mnt_vnodelist.lh_first;
    369 	     vp != NULL;
    370 	     vp = vp->v_mntvnodes.le_next) {
    371 #endif
    372 		/*
    373 		 * If the vnode that we are about to sync is no longer
    374 		 * associated with this mount point, start over.
    375 		 */
    376 		if (vp->v_mount != mp) {
    377 			printf("lfs_writevnodes: starting over\n");
    378 			goto loop;
    379 		}
    380 
    381 		ip = VTOI(vp);
    382 		if ((op == VN_DIROP && !(vp->v_flag & VDIROP)) ||
    383 		    (op != VN_DIROP && op != VN_CLEAN && (vp->v_flag & VDIROP))) {
    384 			vndebug(vp,"dirop");
    385 			continue;
    386 		}
    387 
    388 		if (op == VN_EMPTY && vp->v_dirtyblkhd.lh_first) {
    389 			vndebug(vp,"empty");
    390 			continue;
    391 		}
    392 
    393 		if (vp->v_type == VNON) {
    394 			continue;
    395 		}
    396 
    397 		if(op == VN_CLEAN && ip->i_number != LFS_IFILE_INUM
    398 		   && vp != fs->lfs_flushvp
    399 		   && !(ip->i_flag & IN_CLEANING)) {
    400 			vndebug(vp,"cleaning");
    401 			continue;
    402 		}
    403 
    404 		if (lfs_vref(vp)) {
    405 			vndebug(vp,"vref");
    406 			continue;
    407 		}
    408 
    409 		needs_unlock = 0;
    410 		if (VOP_ISLOCKED(vp)) {
    411 			if (vp != fs->lfs_ivnode &&
    412 			    vp->v_lock.lk_lockholder != curproc->p_pid) {
    413 #ifdef DEBUG_LFS
    414 				printf("lfs_writevnodes: not writing ino %d,"
    415 				       " locked by pid %d\n",
    416 				       VTOI(vp)->i_number,
    417 				       vp->v_lock.lk_lockholder);
    418 #endif
    419 				lfs_vunref(vp);
    420 				continue;
    421 			}
    422 		} else if (vp != fs->lfs_ivnode) {
    423 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    424 			needs_unlock = 1;
    425 		}
    426 
    427 		only_cleaning = 0;
    428 		/*
    429 		 * Write the inode/file if dirty and it's not the IFILE.
    430 		 */
    431 		if ((ip->i_flag & IN_ALLMOD) ||
    432 		     (vp->v_dirtyblkhd.lh_first != NULL))
    433 		{
    434 			only_cleaning = ((ip->i_flag & IN_ALLMOD)==IN_CLEANING);
    435 
    436 			if(ip->i_number != LFS_IFILE_INUM
    437 			   && vp->v_dirtyblkhd.lh_first != NULL)
    438 			{
    439 				lfs_writefile(fs, sp, vp);
    440 			}
    441 			if(vp->v_dirtyblkhd.lh_first != NULL) {
    442 				if(WRITEINPROG(vp)) {
    443 #ifdef DEBUG_LFS
    444 					ivndebug(vp,"writevnodes/write2");
    445 #endif
    446 				} else if(!(ip->i_flag & IN_ALLMOD)) {
    447 #ifdef DEBUG_LFS
    448 					printf("<%d>",ip->i_number);
    449 #endif
    450 					LFS_SET_UINO(ip, IN_MODIFIED);
    451 				}
    452 			}
    453 			(void) lfs_writeinode(fs, sp, ip);
    454 			inodes_written++;
    455 		}
    456 
    457 		if (needs_unlock)
    458 			VOP_UNLOCK(vp, 0);
    459 
    460 		if (lfs_clean_vnhead && only_cleaning)
    461 			lfs_vunref_head(vp);
    462 		else
    463 			lfs_vunref(vp);
    464 	}
    465 	return inodes_written;
    466 }
    467 
    468 int
    469 lfs_segwrite(mp, flags)
    470 	struct mount *mp;
    471 	int flags;			/* Do a checkpoint. */
    472 {
    473 	struct buf *bp;
    474 	struct inode *ip;
    475 	struct lfs *fs;
    476 	struct segment *sp;
    477 	struct vnode *vp;
    478 	SEGUSE *segusep;
    479 	ufs_daddr_t ibno;
    480 	int do_ckp, did_ckp, error, i;
    481 	int writer_set = 0;
    482 	int dirty;
    483 
    484 	fs = VFSTOUFS(mp)->um_lfs;
    485 
    486 	if (fs->lfs_ronly)
    487 		return EROFS;
    488 
    489 	lfs_imtime(fs);
    490 
    491 	/* printf("lfs_segwrite: ifile flags are 0x%lx\n",
    492 	       (long)(VTOI(fs->lfs_ivnode)->i_flag)); */
    493 
    494 #if 0
    495 	/*
    496 	 * If we are not the cleaner, and there is no space available,
    497 	 * wait until cleaner writes.
    498 	 */
    499 	if(!(flags & SEGM_CLEAN) && !(fs->lfs_seglock && fs->lfs_sp &&
    500 				      (fs->lfs_sp->seg_flags & SEGM_CLEAN)))
    501 	{
    502 		while (fs->lfs_avail <= 0) {
    503 			LFS_CLEANERINFO(cip, fs, bp);
    504 			LFS_SYNC_CLEANERINFO(cip, fs, bp, 0);
    505 
    506 			wakeup(&lfs_allclean_wakeup);
    507 			wakeup(&fs->lfs_nextseg);
    508 			error = tsleep(&fs->lfs_avail, PRIBIO + 1, "lfs_av2",
    509 				       0);
    510 			if (error) {
    511 				return (error);
    512 			}
    513 		}
    514 	}
    515 #endif
    516 	/*
    517 	 * Allocate a segment structure and enough space to hold pointers to
    518 	 * the maximum possible number of buffers which can be described in a
    519 	 * single summary block.
    520 	 */
    521 	do_ckp = (flags & SEGM_CKP) || fs->lfs_nactive > LFS_MAX_ACTIVE;
    522 	lfs_seglock(fs, flags | (do_ckp ? SEGM_CKP : 0));
    523 	sp = fs->lfs_sp;
    524 
    525 	/*
    526 	 * If lfs_flushvp is non-NULL, we are called from lfs_vflush,
    527 	 * in which case we have to flush *all* buffers off of this vnode.
    528 	 * We don't care about other nodes, but write any non-dirop nodes
    529 	 * anyway in anticipation of another getnewvnode().
    530 	 *
    531 	 * If we're cleaning we only write cleaning and ifile blocks, and
    532 	 * no dirops, since otherwise we'd risk corruption in a crash.
    533 	 */
    534 	if(sp->seg_flags & SEGM_CLEAN)
    535 		lfs_writevnodes(fs, mp, sp, VN_CLEAN);
    536 	else {
    537 		lfs_writevnodes(fs, mp, sp, VN_REG);
    538 		if(!fs->lfs_dirops || !fs->lfs_flushvp) {
    539 			while(fs->lfs_dirops)
    540 				if((error = tsleep(&fs->lfs_writer, PRIBIO + 1,
    541 						"lfs writer", 0)))
    542 				{
    543 					free(sp->bpp, M_SEGMENT);
    544 					free(sp, M_SEGMENT);
    545 					return (error);
    546 				}
    547 			fs->lfs_writer++;
    548 			writer_set=1;
    549 			lfs_writevnodes(fs, mp, sp, VN_DIROP);
    550 			((SEGSUM *)(sp->segsum))->ss_flags &= ~(SS_CONT);
    551 		}
    552 	}
    553 
    554 	/*
    555 	 * If we are doing a checkpoint, mark everything since the
    556 	 * last checkpoint as no longer ACTIVE.
    557 	 */
    558 	if (do_ckp) {
    559 		for (ibno = fs->lfs_cleansz + fs->lfs_segtabsz;
    560 		     --ibno >= fs->lfs_cleansz; ) {
    561 			dirty = 0;
    562 			if (bread(fs->lfs_ivnode, ibno, fs->lfs_bsize, NOCRED, &bp))
    563 
    564 				panic("lfs_segwrite: ifile read");
    565 			segusep = (SEGUSE *)bp->b_data;
    566 			for (i = fs->lfs_sepb; i--; segusep++) {
    567 				if (segusep->su_flags & SEGUSE_ACTIVE) {
    568 					segusep->su_flags &= ~SEGUSE_ACTIVE;
    569 					++dirty;
    570 				}
    571 			}
    572 
    573 			/* But the current segment is still ACTIVE */
    574 			segusep = (SEGUSE *)bp->b_data;
    575 			if (datosn(fs, fs->lfs_curseg) / fs->lfs_sepb ==
    576 			    (ibno-fs->lfs_cleansz)) {
    577 				segusep[datosn(fs, fs->lfs_curseg) %
    578 					fs->lfs_sepb].su_flags |= SEGUSE_ACTIVE;
    579 				--dirty;
    580 			}
    581 			if (dirty)
    582 				error = VOP_BWRITE(bp); /* Ifile */
    583 			else
    584 				brelse(bp);
    585 		}
    586 	}
    587 
    588 	did_ckp = 0;
    589 	if (do_ckp || fs->lfs_doifile) {
    590 	redo:
    591 		vp = fs->lfs_ivnode;
    592 
    593 		vget(vp, LK_EXCLUSIVE | LK_CANRECURSE | LK_RETRY);
    594 
    595 		ip = VTOI(vp);
    596 		if (vp->v_dirtyblkhd.lh_first != NULL)
    597 			lfs_writefile(fs, sp, vp);
    598 		if (ip->i_flag & IN_ALLMOD)
    599 			++did_ckp;
    600 		(void) lfs_writeinode(fs, sp, ip);
    601 
    602 		vput(vp);
    603 
    604 		if (lfs_writeseg(fs, sp) && do_ckp)
    605 			goto redo;
    606 		/* The ifile should now be all clear */
    607 		LFS_CLR_UINO(ip, IN_ALLMOD);
    608 	} else {
    609 		(void) lfs_writeseg(fs, sp);
    610 	}
    611 
    612 	/*
    613 	 * If the I/O count is non-zero, sleep until it reaches zero.
    614 	 * At the moment, the user's process hangs around so we can
    615 	 * sleep.
    616 	 */
    617 	fs->lfs_doifile = 0;
    618 	if(writer_set && --fs->lfs_writer==0)
    619 		wakeup(&fs->lfs_dirops);
    620 
    621 	/*
    622 	 * If we didn't write the Ifile, we didn't really do anything.
    623 	 * That means that (1) there is a checkpoint on disk and (2)
    624 	 * nothing has changed since it was written.
    625 	 *
    626 	 * Take the flags off of the segment so that lfs_segunlock
    627 	 * doesn't have to write the superblock either.
    628 	 */
    629 	if (did_ckp == 0) {
    630 		sp->seg_flags &= ~(SEGM_SYNC|SEGM_CKP);
    631 		/* if(do_ckp) printf("lfs_segwrite: no checkpoint\n"); */
    632 	}
    633 
    634 	if(lfs_dostats) {
    635 		++lfs_stats.nwrites;
    636 		if (sp->seg_flags & SEGM_SYNC)
    637 			++lfs_stats.nsync_writes;
    638 		if (sp->seg_flags & SEGM_CKP)
    639 			++lfs_stats.ncheckpoints;
    640 	}
    641 	lfs_segunlock(fs);
    642 	return (0);
    643 }
    644 
    645 /*
    646  * Write the dirty blocks associated with a vnode.
    647  */
    648 void
    649 lfs_writefile(fs, sp, vp)
    650 	struct lfs *fs;
    651 	struct segment *sp;
    652 	struct vnode *vp;
    653 {
    654 	struct buf *bp;
    655 	struct finfo *fip;
    656 	IFILE *ifp;
    657 
    658 
    659 	if (sp->seg_bytes_left < fs->lfs_bsize ||
    660 	    sp->sum_bytes_left < sizeof(struct finfo))
    661 		(void) lfs_writeseg(fs, sp);
    662 
    663 	sp->sum_bytes_left -= sizeof(struct finfo) - sizeof(ufs_daddr_t);
    664 	++((SEGSUM *)(sp->segsum))->ss_nfinfo;
    665 
    666 	if(vp->v_flag & VDIROP)
    667 		((SEGSUM *)(sp->segsum))->ss_flags |= (SS_DIROP|SS_CONT);
    668 
    669 	fip = sp->fip;
    670 	fip->fi_nblocks = 0;
    671 	fip->fi_ino = VTOI(vp)->i_number;
    672 	LFS_IENTRY(ifp, fs, fip->fi_ino, bp);
    673 	fip->fi_version = ifp->if_version;
    674 	brelse(bp);
    675 
    676 	if(sp->seg_flags & SEGM_CLEAN)
    677 	{
    678 		lfs_gather(fs, sp, vp, lfs_match_fake);
    679 		/*
    680 		 * For a file being flushed, we need to write *all* blocks.
    681 		 * This means writing the cleaning blocks first, and then
    682 		 * immediately following with any non-cleaning blocks.
    683 		 * The same is true of the Ifile since checkpoints assume
    684 		 * that all valid Ifile blocks are written.
    685 		 */
    686 	   	if(IS_FLUSHING(fs,vp) || VTOI(vp)->i_number == LFS_IFILE_INUM)
    687 			lfs_gather(fs, sp, vp, lfs_match_data);
    688 	} else
    689 		lfs_gather(fs, sp, vp, lfs_match_data);
    690 
    691 	/*
    692 	 * It may not be necessary to write the meta-data blocks at this point,
    693 	 * as the roll-forward recovery code should be able to reconstruct the
    694 	 * list.
    695 	 *
    696 	 * We have to write them anyway, though, under two conditions: (1) the
    697 	 * vnode is being flushed (for reuse by vinvalbuf); or (2) we are
    698 	 * checkpointing.
    699 	 */
    700 	if(lfs_writeindir
    701 	   || IS_FLUSHING(fs,vp)
    702 	   || (sp->seg_flags & SEGM_CKP))
    703 	{
    704 		lfs_gather(fs, sp, vp, lfs_match_indir);
    705 		lfs_gather(fs, sp, vp, lfs_match_dindir);
    706 		lfs_gather(fs, sp, vp, lfs_match_tindir);
    707 	}
    708 	fip = sp->fip;
    709 	if (fip->fi_nblocks != 0) {
    710 		sp->fip = (FINFO*)((caddr_t)fip + sizeof(struct finfo) +
    711 				   sizeof(ufs_daddr_t) * (fip->fi_nblocks-1));
    712 		sp->start_lbp = &sp->fip->fi_blocks[0];
    713 	} else {
    714 		sp->sum_bytes_left += sizeof(FINFO) - sizeof(ufs_daddr_t);
    715 		--((SEGSUM *)(sp->segsum))->ss_nfinfo;
    716 	}
    717 }
    718 
    719 int
    720 lfs_writeinode(fs, sp, ip)
    721 	struct lfs *fs;
    722 	struct segment *sp;
    723 	struct inode *ip;
    724 {
    725 	struct buf *bp, *ibp;
    726 	struct dinode *cdp;
    727 	IFILE *ifp;
    728 	SEGUSE *sup;
    729 	ufs_daddr_t daddr;
    730 	daddr_t *daddrp;
    731 	ino_t ino;
    732 	int error, i, ndx;
    733 	int redo_ifile = 0;
    734 	struct timespec ts;
    735 	int gotblk=0;
    736 
    737 	if (!(ip->i_flag & IN_ALLMOD))
    738 		return(0);
    739 
    740 	/* Allocate a new inode block if necessary. */
    741 	if ((ip->i_number != LFS_IFILE_INUM || sp->idp==NULL) && sp->ibp == NULL) {
    742 		/* Allocate a new segment if necessary. */
    743 		if (sp->seg_bytes_left < fs->lfs_bsize ||
    744 		    sp->sum_bytes_left < sizeof(ufs_daddr_t))
    745 			(void) lfs_writeseg(fs, sp);
    746 
    747 		/* Get next inode block. */
    748 		daddr = fs->lfs_offset;
    749 		fs->lfs_offset += fsbtodb(fs, 1);
    750 		sp->ibp = *sp->cbpp++ =
    751 			getblk(VTOI(fs->lfs_ivnode)->i_devvp, daddr, fs->lfs_bsize, 0, 0);
    752 		gotblk++;
    753 
    754 		/* Zero out inode numbers */
    755 		for (i = 0; i < INOPB(fs); ++i)
    756 			((struct dinode *)sp->ibp->b_data)[i].di_inumber = 0;
    757 
    758 		++sp->start_bpp;
    759 		fs->lfs_avail -= fsbtodb(fs, 1);
    760 		/* Set remaining space counters. */
    761 		sp->seg_bytes_left -= fs->lfs_bsize;
    762 		sp->sum_bytes_left -= sizeof(ufs_daddr_t);
    763 		ndx = LFS_SUMMARY_SIZE / sizeof(ufs_daddr_t) -
    764 			sp->ninodes / INOPB(fs) - 1;
    765 		((ufs_daddr_t *)(sp->segsum))[ndx] = daddr;
    766 	}
    767 
    768 	/* Update the inode times and copy the inode onto the inode page. */
    769 	TIMEVAL_TO_TIMESPEC(&time, &ts);
    770 	LFS_ITIMES(ip, &ts, &ts, &ts);
    771 
    772 	/*
    773 	 * If this is the Ifile, and we've already written the Ifile in this
    774 	 * partial segment, just overwrite it (it's not on disk yet) and
    775 	 * continue.
    776 	 *
    777 	 * XXX we know that the bp that we get the second time around has
    778 	 * already been gathered.
    779 	 */
    780 	if(ip->i_number == LFS_IFILE_INUM && sp->idp) {
    781 		*(sp->idp) = ip->i_din.ffs_din;
    782 		return 0;
    783 	}
    784 
    785 	bp = sp->ibp;
    786 	cdp = ((struct dinode *)bp->b_data) + (sp->ninodes % INOPB(fs));
    787 	*cdp = ip->i_din.ffs_din;
    788 
    789 	/*
    790 	 * If we are cleaning, ensure that we don't write UNWRITTEN disk
    791 	 * addresses to disk.
    792 	 */
    793 	if (ip->i_lfs_effnblks != ip->i_ffs_blocks) {
    794 #ifdef DEBUG_LFS
    795 		printf("lfs_writeinode: cleansing ino %d (%d != %d)\n",
    796 		       ip->i_number, ip->i_lfs_effnblks, ip->i_ffs_blocks);
    797 #endif
    798 		for (daddrp = cdp->di_db; daddrp < cdp->di_ib + NIADDR;
    799 		     daddrp++) {
    800 			if (*daddrp == UNWRITTEN) {
    801 #ifdef DEBUG_LFS
    802 				printf("lfs_writeinode: wiping UNWRITTEN\n");
    803 #endif
    804 				*daddrp = 0;
    805 			}
    806 		}
    807 	}
    808 
    809 	if(ip->i_flag & IN_CLEANING)
    810 		LFS_CLR_UINO(ip, IN_CLEANING);
    811 	else {
    812 		/* XXX IN_ALLMOD */
    813 		LFS_CLR_UINO(ip, IN_ACCESSED | IN_ACCESS | IN_CHANGE |
    814 			     IN_UPDATE);
    815 		if (ip->i_lfs_effnblks == ip->i_ffs_blocks)
    816 			LFS_CLR_UINO(ip, IN_MODIFIED);
    817 	}
    818 
    819 	if(ip->i_number == LFS_IFILE_INUM) /* We know sp->idp == NULL */
    820 		sp->idp = ((struct dinode *)bp->b_data) +
    821 			(sp->ninodes % INOPB(fs));
    822 	if(gotblk) {
    823 		LFS_LOCK_BUF(bp);
    824 		brelse(bp);
    825 	}
    826 
    827 	/* Increment inode count in segment summary block. */
    828 	++((SEGSUM *)(sp->segsum))->ss_ninos;
    829 
    830 	/* If this page is full, set flag to allocate a new page. */
    831 	if (++sp->ninodes % INOPB(fs) == 0)
    832 		sp->ibp = NULL;
    833 
    834 	/*
    835 	 * If updating the ifile, update the super-block.  Update the disk
    836 	 * address and access times for this inode in the ifile.
    837 	 */
    838 	ino = ip->i_number;
    839 	if (ino == LFS_IFILE_INUM) {
    840 		daddr = fs->lfs_idaddr;
    841 		fs->lfs_idaddr = bp->b_blkno;
    842 	} else {
    843 		LFS_IENTRY(ifp, fs, ino, ibp);
    844 		daddr = ifp->if_daddr;
    845 		ifp->if_daddr = bp->b_blkno;
    846 #ifdef LFS_DEBUG_NEXTFREE
    847 		if(ino > 3 && ifp->if_nextfree) {
    848 			vprint("lfs_writeinode",ITOV(ip));
    849 			printf("lfs_writeinode: updating free ino %d\n",
    850 				ip->i_number);
    851 		}
    852 #endif
    853 		error = VOP_BWRITE(ibp); /* Ifile */
    854 	}
    855 
    856 	/*
    857 	 * Account the inode: it no longer belongs to its former segment,
    858 	 * though it will not belong to the new segment until that segment
    859 	 * is actually written.
    860 	 */
    861 #ifdef DEBUG
    862 	/*
    863 	 * The inode's last address should not be in the current partial
    864 	 * segment, except under exceptional circumstances (lfs_writevnodes
    865 	 * had to start over, and in the meantime more blocks were written
    866 	 * to a vnode).  Although the previous inode won't be accounted in
    867 	 * su_nbytes until lfs_writeseg, this shouldn't be a problem as we
    868 	 * have more data blocks in the current partial segment.
    869 	 */
    870 	if (daddr >= fs->lfs_lastpseg && daddr <= bp->b_blkno)
    871 		printf("lfs_writeinode: last inode addr in current pseg "
    872 		       "(ino %d daddr 0x%x)\n", ino, daddr);
    873 #endif
    874 	if (daddr != LFS_UNUSED_DADDR) {
    875 		LFS_SEGENTRY(sup, fs, datosn(fs, daddr), bp);
    876 #ifdef DIAGNOSTIC
    877 		if (sup->su_nbytes < DINODE_SIZE) {
    878 			printf("lfs_writeinode: negative bytes "
    879 			       "(segment %d short by %d)\n",
    880 			       datosn(fs, daddr),
    881 			       (int)DINODE_SIZE - sup->su_nbytes);
    882 			panic("lfs_writeinode: negative bytes");
    883 			sup->su_nbytes = DINODE_SIZE;
    884 		}
    885 #endif
    886 		sup->su_nbytes -= DINODE_SIZE;
    887 		redo_ifile =
    888 			(ino == LFS_IFILE_INUM && !(bp->b_flags & B_GATHERED));
    889 		error = VOP_BWRITE(bp); /* Ifile */
    890 	}
    891 	return (redo_ifile);
    892 }
    893 
    894 int
    895 lfs_gatherblock(sp, bp, sptr)
    896 	struct segment *sp;
    897 	struct buf *bp;
    898 	int *sptr;
    899 {
    900 	struct lfs *fs;
    901 	int version;
    902 
    903 	/*
    904 	 * If full, finish this segment.  We may be doing I/O, so
    905 	 * release and reacquire the splbio().
    906 	 */
    907 #ifdef DIAGNOSTIC
    908 	if (sp->vp == NULL)
    909 		panic ("lfs_gatherblock: Null vp in segment");
    910 #endif
    911 	fs = sp->fs;
    912 	if (sp->sum_bytes_left < sizeof(ufs_daddr_t) ||
    913 	    sp->seg_bytes_left < bp->b_bcount) {
    914 		if (sptr)
    915 			splx(*sptr);
    916 		lfs_updatemeta(sp);
    917 
    918 		version = sp->fip->fi_version;
    919 		(void) lfs_writeseg(fs, sp);
    920 
    921 		sp->fip->fi_version = version;
    922 		sp->fip->fi_ino = VTOI(sp->vp)->i_number;
    923 		/* Add the current file to the segment summary. */
    924 		++((SEGSUM *)(sp->segsum))->ss_nfinfo;
    925 		sp->sum_bytes_left -=
    926 			sizeof(struct finfo) - sizeof(ufs_daddr_t);
    927 
    928 		if (sptr)
    929 			*sptr = splbio();
    930 		return(1);
    931 	}
    932 
    933 #ifdef DEBUG
    934 	if(bp->b_flags & B_GATHERED) {
    935 		printf("lfs_gatherblock: already gathered! Ino %d, lbn %d\n",
    936 		       sp->fip->fi_ino, bp->b_lblkno);
    937 		return(0);
    938 	}
    939 #endif
    940 	/* Insert into the buffer list, update the FINFO block. */
    941 	bp->b_flags |= B_GATHERED;
    942 	*sp->cbpp++ = bp;
    943 	sp->fip->fi_blocks[sp->fip->fi_nblocks++] = bp->b_lblkno;
    944 
    945 	sp->sum_bytes_left -= sizeof(ufs_daddr_t);
    946 	sp->seg_bytes_left -= bp->b_bcount;
    947 	return(0);
    948 }
    949 
    950 int
    951 lfs_gather(fs, sp, vp, match)
    952 	struct lfs *fs;
    953 	struct segment *sp;
    954 	struct vnode *vp;
    955 	int (*match) __P((struct lfs *, struct buf *));
    956 {
    957 	struct buf *bp;
    958 	int s, count=0;
    959 
    960 	sp->vp = vp;
    961 	s = splbio();
    962 
    963 #ifndef LFS_NO_BACKBUF_HACK
    964 loop:	for (bp = vp->v_dirtyblkhd.lh_first; bp; bp = bp->b_vnbufs.le_next) {
    965 #else /* LFS_NO_BACKBUF_HACK */
    966 /* This is a hack to see if ordering the blocks in LFS makes a difference. */
    967 # define	BUF_OFFSET	(((void *)&bp->b_vnbufs.le_next) - (void *)bp)
    968 # define	BACK_BUF(BP)	((struct buf *)(((void *)BP->b_vnbufs.le_prev) - BUF_OFFSET))
    969 # define	BEG_OF_LIST	((struct buf *)(((void *)&vp->v_dirtyblkhd.lh_first) - BUF_OFFSET))
    970 /* Find last buffer. */
    971 loop:	for (bp = vp->v_dirtyblkhd.lh_first; bp && bp->b_vnbufs.le_next != NULL;
    972 	    bp = bp->b_vnbufs.le_next);
    973 	for (; bp && bp != BEG_OF_LIST; bp = BACK_BUF(bp)) {
    974 #endif /* LFS_NO_BACKBUF_HACK */
    975 		if ((bp->b_flags & (B_BUSY|B_GATHERED)) || !match(fs, bp))
    976 			continue;
    977 		if(vp->v_type == VBLK) {
    978 			/* For block devices, just write the blocks. */
    979 			/* XXX Do we really need to even do this? */
    980 #ifdef DEBUG_LFS
    981 			if(count==0)
    982 				printf("BLK(");
    983 			printf(".");
    984 #endif
    985 			/* Get the block before bwrite, so we don't corrupt the free list */
    986 			bp->b_flags |= B_BUSY;
    987 			bremfree(bp);
    988 			bwrite(bp);
    989 		} else {
    990 #ifdef DIAGNOSTIC
    991 			if ((bp->b_flags & (B_CALL|B_INVAL))==B_INVAL) {
    992 				printf("lfs_gather: lbn %d is B_INVAL\n",
    993 					bp->b_lblkno);
    994 				VOP_PRINT(bp->b_vp);
    995 			}
    996 			if (!(bp->b_flags & B_DELWRI))
    997 				panic("lfs_gather: bp not B_DELWRI");
    998 			if (!(bp->b_flags & B_LOCKED)) {
    999 				printf("lfs_gather: lbn %d blk %d"
   1000 				       " not B_LOCKED\n", bp->b_lblkno,
   1001 				       bp->b_blkno);
   1002 				VOP_PRINT(bp->b_vp);
   1003 				panic("lfs_gather: bp not B_LOCKED");
   1004 			}
   1005 #endif
   1006 			if (lfs_gatherblock(sp, bp, &s)) {
   1007 				goto loop;
   1008 			}
   1009 		}
   1010 		count++;
   1011 	}
   1012 	splx(s);
   1013 #ifdef DEBUG_LFS
   1014 	if(vp->v_type == VBLK && count)
   1015 		printf(")\n");
   1016 #endif
   1017 	lfs_updatemeta(sp);
   1018 	sp->vp = NULL;
   1019 	return count;
   1020 }
   1021 
   1022 /*
   1023  * Update the metadata that points to the blocks listed in the FINFO
   1024  * array.
   1025  */
   1026 void
   1027 lfs_updatemeta(sp)
   1028 	struct segment *sp;
   1029 {
   1030 	SEGUSE *sup;
   1031 	struct buf *bp;
   1032 	struct lfs *fs;
   1033 	struct vnode *vp;
   1034 	struct indir a[NIADDR + 2], *ap;
   1035 	struct inode *ip;
   1036 	ufs_daddr_t daddr, lbn, off;
   1037 	daddr_t ooff;
   1038 	int error, i, nblocks, num;
   1039 	int bb;
   1040 
   1041 	vp = sp->vp;
   1042 	nblocks = &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp;
   1043 	if (nblocks < 0)
   1044 		panic("This is a bad thing\n");
   1045 	if (vp == NULL || nblocks == 0)
   1046 		return;
   1047 
   1048 	/* Sort the blocks. */
   1049 	/*
   1050 	 * XXX KS - We have to sort even if the blocks come from the
   1051 	 * cleaner, because there might be other pending blocks on the
   1052 	 * same inode...and if we don't sort, and there are fragments
   1053 	 * present, blocks may be written in the wrong place.
   1054 	 */
   1055 	/* if (!(sp->seg_flags & SEGM_CLEAN)) */
   1056 	lfs_shellsort(sp->start_bpp, sp->start_lbp, nblocks);
   1057 
   1058 	/*
   1059 	 * Record the length of the last block in case it's a fragment.
   1060 	 * If there are indirect blocks present, they sort last.  An
   1061 	 * indirect block will be lfs_bsize and its presence indicates
   1062 	 * that you cannot have fragments.
   1063 	 */
   1064 	sp->fip->fi_lastlength = sp->start_bpp[nblocks - 1]->b_bcount;
   1065 
   1066 	/*
   1067 	 * Assign disk addresses, and update references to the logical
   1068 	 * block and the segment usage information.
   1069 	 */
   1070 	fs = sp->fs;
   1071 	for (i = nblocks; i--; ++sp->start_bpp) {
   1072 		lbn = *sp->start_lbp++;
   1073 
   1074 		(*sp->start_bpp)->b_blkno = off = fs->lfs_offset;
   1075 		if((*sp->start_bpp)->b_blkno == (*sp->start_bpp)->b_lblkno) {
   1076 			printf("lfs_updatemeta: ino %d blk %d"
   1077 			       " has same lbn and daddr\n",
   1078 			       VTOI(vp)->i_number, off);
   1079 		}
   1080 		bb = fragstodb(fs, numfrags(fs, (*sp->start_bpp)->b_bcount));
   1081 		fs->lfs_offset += bb;
   1082 		error = ufs_bmaparray(vp, lbn, &daddr, a, &num, NULL);
   1083 		if (error)
   1084 			panic("lfs_updatemeta: ufs_bmaparray %d", error);
   1085 		ip = VTOI(vp);
   1086 		switch (num) {
   1087 		case 0:
   1088 			ooff = ip->i_ffs_db[lbn];
   1089 #ifdef DEBUG
   1090 			if (ooff == 0) {
   1091 				printf("lfs_updatemeta[1]: warning: writing "
   1092 				       "ino %d lbn %d at 0x%x, was 0x0\n",
   1093 				       ip->i_number, lbn, off);
   1094 			}
   1095 #endif
   1096 			if (ooff == UNWRITTEN)
   1097 				ip->i_ffs_blocks += bb;
   1098 			ip->i_ffs_db[lbn] = off;
   1099 			break;
   1100 		case 1:
   1101 			ooff = ip->i_ffs_ib[a[0].in_off];
   1102 #ifdef DEBUG
   1103 			if (ooff == 0) {
   1104 				printf("lfs_updatemeta[2]: warning: writing "
   1105 				       "ino %d lbn %d at 0x%x, was 0x0\n",
   1106 				       ip->i_number, lbn, off);
   1107 			}
   1108 #endif
   1109 			if (ooff == UNWRITTEN)
   1110 				ip->i_ffs_blocks += bb;
   1111 			ip->i_ffs_ib[a[0].in_off] = off;
   1112 			break;
   1113 		default:
   1114 			ap = &a[num - 1];
   1115 			if (bread(vp, ap->in_lbn, fs->lfs_bsize, NOCRED, &bp))
   1116 				panic("lfs_updatemeta: bread bno %d",
   1117 				      ap->in_lbn);
   1118 
   1119 			ooff = ((ufs_daddr_t *)bp->b_data)[ap->in_off];
   1120 #if DEBUG
   1121 			if (ooff == 0) {
   1122 				printf("lfs_updatemeta[3]: warning: writing "
   1123 				       "ino %d lbn %d at 0x%x, was 0x0\n",
   1124 				       ip->i_number, lbn, off);
   1125 			}
   1126 #endif
   1127 			if (ooff == UNWRITTEN)
   1128 				ip->i_ffs_blocks += bb;
   1129 			((ufs_daddr_t *)bp->b_data)[ap->in_off] = off;
   1130 			(void) VOP_BWRITE(bp);
   1131 		}
   1132 #ifdef DEBUG
   1133 		if (daddr >= fs->lfs_lastpseg && daddr <= off) {
   1134 			printf("lfs_updatemeta: ino %d, lbn %d, addr = %x "
   1135 			       "in same pseg\n", VTOI(sp->vp)->i_number,
   1136 			       (*sp->start_bpp)->b_lblkno, daddr);
   1137 		}
   1138 #endif
   1139 		/* Update segment usage information. */
   1140 		if (daddr > 0) {
   1141 			LFS_SEGENTRY(sup, fs, datosn(fs, daddr), bp);
   1142 #ifdef DIAGNOSTIC
   1143 			if (sup->su_nbytes < (*sp->start_bpp)->b_bcount) {
   1144 				/* XXX -- Change to a panic. */
   1145 				printf("lfs_updatemeta: negative bytes "
   1146 				       "(segment %d short by %ld)\n",
   1147 				       datosn(fs, daddr),
   1148 				       (*sp->start_bpp)->b_bcount -
   1149 				       sup->su_nbytes);
   1150 				printf("lfs_updatemeta: ino %d, lbn %d, "
   1151 				       "addr = %x\n", VTOI(sp->vp)->i_number,
   1152 				       (*sp->start_bpp)->b_lblkno, daddr);
   1153 				panic("lfs_updatemeta: negative bytes");
   1154 				sup->su_nbytes = (*sp->start_bpp)->b_bcount;
   1155 			}
   1156 #endif
   1157 			sup->su_nbytes -= (*sp->start_bpp)->b_bcount;
   1158 			error = VOP_BWRITE(bp); /* Ifile */
   1159 		}
   1160 	}
   1161 }
   1162 
   1163 /*
   1164  * Start a new segment.
   1165  */
   1166 int
   1167 lfs_initseg(fs)
   1168 	struct lfs *fs;
   1169 {
   1170 	struct segment *sp;
   1171 	SEGUSE *sup;
   1172 	SEGSUM *ssp;
   1173 	struct buf *bp;
   1174 	int repeat;
   1175 
   1176 	sp = fs->lfs_sp;
   1177 
   1178 	repeat = 0;
   1179 	/* Advance to the next segment. */
   1180 	if (!LFS_PARTIAL_FITS(fs)) {
   1181 		/* lfs_avail eats the remaining space */
   1182 		fs->lfs_avail -= fs->lfs_dbpseg - (fs->lfs_offset -
   1183 						   fs->lfs_curseg);
   1184 		/* Wake up any cleaning procs waiting on this file system. */
   1185 		wakeup(&lfs_allclean_wakeup);
   1186 		wakeup(&fs->lfs_nextseg);
   1187 		lfs_newseg(fs);
   1188 		repeat = 1;
   1189 		fs->lfs_offset = fs->lfs_curseg;
   1190 		sp->seg_number = datosn(fs, fs->lfs_curseg);
   1191 		sp->seg_bytes_left = dbtob(fs->lfs_dbpseg);
   1192 		/*
   1193 		 * If the segment contains a superblock, update the offset
   1194 		 * and summary address to skip over it.
   1195 		 */
   1196 		LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
   1197 		if (sup->su_flags & SEGUSE_SUPERBLOCK) {
   1198 			fs->lfs_offset += btodb(LFS_SBPAD);
   1199 			sp->seg_bytes_left -= LFS_SBPAD;
   1200 		}
   1201 		brelse(bp);
   1202 	} else {
   1203 		sp->seg_number = datosn(fs, fs->lfs_curseg);
   1204 		sp->seg_bytes_left = dbtob(fs->lfs_dbpseg -
   1205 				      (fs->lfs_offset - fs->lfs_curseg));
   1206 	}
   1207 	fs->lfs_lastpseg = fs->lfs_offset;
   1208 
   1209 	sp->fs = fs;
   1210 	sp->ibp = NULL;
   1211 	sp->idp = NULL;
   1212 	sp->ninodes = 0;
   1213 
   1214 	/* Get a new buffer for SEGSUM and enter it into the buffer list. */
   1215 	sp->cbpp = sp->bpp;
   1216 	*sp->cbpp = lfs_newbuf(VTOI(fs->lfs_ivnode)->i_devvp,
   1217 			       fs->lfs_offset, LFS_SUMMARY_SIZE);
   1218 	sp->segsum = (*sp->cbpp)->b_data;
   1219 	bzero(sp->segsum, LFS_SUMMARY_SIZE);
   1220 	sp->start_bpp = ++sp->cbpp;
   1221 	fs->lfs_offset += btodb(LFS_SUMMARY_SIZE);
   1222 
   1223 	/* Set point to SEGSUM, initialize it. */
   1224 	ssp = sp->segsum;
   1225 	ssp->ss_next = fs->lfs_nextseg;
   1226 	ssp->ss_nfinfo = ssp->ss_ninos = 0;
   1227 	ssp->ss_magic = SS_MAGIC;
   1228 
   1229 	/* Set pointer to first FINFO, initialize it. */
   1230 	sp->fip = (struct finfo *)((caddr_t)sp->segsum + sizeof(SEGSUM));
   1231 	sp->fip->fi_nblocks = 0;
   1232 	sp->start_lbp = &sp->fip->fi_blocks[0];
   1233 	sp->fip->fi_lastlength = 0;
   1234 
   1235 	sp->seg_bytes_left -= LFS_SUMMARY_SIZE;
   1236 	sp->sum_bytes_left = LFS_SUMMARY_SIZE - sizeof(SEGSUM);
   1237 
   1238 	return(repeat);
   1239 }
   1240 
   1241 /*
   1242  * Return the next segment to write.
   1243  */
   1244 void
   1245 lfs_newseg(fs)
   1246 	struct lfs *fs;
   1247 {
   1248 	CLEANERINFO *cip;
   1249 	SEGUSE *sup;
   1250 	struct buf *bp;
   1251 	int curseg, isdirty, sn;
   1252 
   1253 	LFS_SEGENTRY(sup, fs, datosn(fs, fs->lfs_nextseg), bp);
   1254 	sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
   1255 	sup->su_nbytes = 0;
   1256 	sup->su_nsums = 0;
   1257 	sup->su_ninos = 0;
   1258 	(void) VOP_BWRITE(bp); /* Ifile */
   1259 
   1260 	LFS_CLEANERINFO(cip, fs, bp);
   1261 	--cip->clean;
   1262 	++cip->dirty;
   1263 	fs->lfs_nclean = cip->clean;
   1264 	LFS_SYNC_CLEANERINFO(cip, fs, bp, 1);
   1265 
   1266 	fs->lfs_lastseg = fs->lfs_curseg;
   1267 	fs->lfs_curseg = fs->lfs_nextseg;
   1268 	for (sn = curseg = datosn(fs, fs->lfs_curseg);;) {
   1269 		sn = (sn + 1) % fs->lfs_nseg;
   1270 		if (sn == curseg)
   1271 			panic("lfs_nextseg: no clean segments");
   1272 		LFS_SEGENTRY(sup, fs, sn, bp);
   1273 		isdirty = sup->su_flags & SEGUSE_DIRTY;
   1274 		brelse(bp);
   1275 		if (!isdirty)
   1276 			break;
   1277 	}
   1278 
   1279 	++fs->lfs_nactive;
   1280 	fs->lfs_nextseg = sntoda(fs, sn);
   1281 	if(lfs_dostats) {
   1282 		++lfs_stats.segsused;
   1283 	}
   1284 }
   1285 
   1286 int
   1287 lfs_writeseg(fs, sp)
   1288 	struct lfs *fs;
   1289 	struct segment *sp;
   1290 {
   1291 	struct buf **bpp, *bp, *cbp, *newbp;
   1292 	SEGUSE *sup;
   1293 	SEGSUM *ssp;
   1294 	dev_t i_dev;
   1295 	u_long *datap, *dp;
   1296 	int do_again, i, nblocks, s;
   1297 #ifdef LFS_TRACK_IOS
   1298 	int j;
   1299 #endif
   1300 	int (*strategy)__P((void *));
   1301 	struct vop_strategy_args vop_strategy_a;
   1302 	u_short ninos;
   1303 	struct vnode *devvp;
   1304 	char *p;
   1305 	struct vnode *vn;
   1306 	struct inode *ip;
   1307 	daddr_t *daddrp;
   1308 	int changed;
   1309 #if defined(DEBUG) && defined(LFS_PROPELLER)
   1310 	static int propeller;
   1311 	char propstring[4] = "-\\|/";
   1312 
   1313 	printf("%c\b",propstring[propeller++]);
   1314 	if(propeller==4)
   1315 		propeller = 0;
   1316 #endif
   1317 
   1318 	/*
   1319 	 * If there are no buffers other than the segment summary to write
   1320 	 * and it is not a checkpoint, don't do anything.  On a checkpoint,
   1321 	 * even if there aren't any buffers, you need to write the superblock.
   1322 	 */
   1323 	if ((nblocks = sp->cbpp - sp->bpp) == 1)
   1324 		return (0);
   1325 
   1326 	i_dev = VTOI(fs->lfs_ivnode)->i_dev;
   1327 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
   1328 
   1329 	/* Update the segment usage information. */
   1330 	LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
   1331 
   1332 	/* Loop through all blocks, except the segment summary. */
   1333 	for (bpp = sp->bpp; ++bpp < sp->cbpp; ) {
   1334 		if((*bpp)->b_vp != devvp)
   1335 			sup->su_nbytes += (*bpp)->b_bcount;
   1336 	}
   1337 
   1338 	ssp = (SEGSUM *)sp->segsum;
   1339 
   1340 	ninos = (ssp->ss_ninos + INOPB(fs) - 1) / INOPB(fs);
   1341 	sup->su_nbytes += ssp->ss_ninos * DINODE_SIZE;
   1342 	/* sup->su_nbytes += LFS_SUMMARY_SIZE; */
   1343 	sup->su_lastmod = time.tv_sec;
   1344 	sup->su_ninos += ninos;
   1345 	++sup->su_nsums;
   1346 	fs->lfs_dmeta += (btodb(LFS_SUMMARY_SIZE) + fsbtodb(fs, ninos));
   1347 	fs->lfs_avail -= btodb(LFS_SUMMARY_SIZE);
   1348 
   1349 	do_again = !(bp->b_flags & B_GATHERED);
   1350 	(void)VOP_BWRITE(bp); /* Ifile */
   1351 	/*
   1352 	 * Mark blocks B_BUSY, to prevent then from being changed between
   1353 	 * the checksum computation and the actual write.
   1354 	 *
   1355 	 * If we are cleaning, check indirect blocks for UNWRITTEN, and if
   1356 	 * there are any, replace them with copies that have UNASSIGNED
   1357 	 * instead.
   1358 	 */
   1359 	for (bpp = sp->bpp, i = nblocks - 1; i--;) {
   1360 		++bpp;
   1361 		if((*bpp)->b_flags & B_CALL)
   1362 			continue;
   1363 		bp = *bpp;
   1364 	    again:
   1365 		s = splbio();
   1366 		if(bp->b_flags & B_BUSY) {
   1367 #ifdef DEBUG
   1368 			printf("lfs_writeseg: avoiding potential data "
   1369 			       "summary corruption for ino %d, lbn %d\n",
   1370 			       VTOI(bp->b_vp)->i_number, bp->b_lblkno);
   1371 #endif
   1372 			bp->b_flags |= B_WANTED;
   1373 			tsleep(bp, (PRIBIO + 1), "lfs_writeseg", 0);
   1374 			splx(s);
   1375 			goto again;
   1376 		}
   1377 		bp->b_flags |= B_BUSY;
   1378 		splx(s);
   1379 		/* Check and replace indirect block UNWRITTEN bogosity */
   1380 		if(bp->b_lblkno < 0 && bp->b_vp != devvp && bp->b_vp &&
   1381 		   VTOI(bp->b_vp)->i_ffs_blocks !=
   1382 		   VTOI(bp->b_vp)->i_lfs_effnblks) {
   1383 #ifdef DEBUG_LFS
   1384 			printf("lfs_writeseg: cleansing ino %d (%d != %d)\n",
   1385 			       VTOI(bp->b_vp)->i_number,
   1386 			       VTOI(bp->b_vp)->i_lfs_effnblks,
   1387 			       VTOI(bp->b_vp)->i_ffs_blocks);
   1388 #endif
   1389 			/* Make a copy we'll make changes to */
   1390 			newbp = lfs_newbuf(bp->b_vp, bp->b_lblkno,
   1391 					   bp->b_bcount);
   1392 			newbp->b_blkno = bp->b_blkno;
   1393 			memcpy(newbp->b_data, bp->b_data,
   1394 			       newbp->b_bcount);
   1395 			*bpp = newbp;
   1396 
   1397 			changed = 0;
   1398 			for (daddrp = (daddr_t *)(newbp->b_data);
   1399 			     daddrp < (daddr_t *)(newbp->b_data +
   1400 						  newbp->b_bcount); daddrp++) {
   1401 				if (*daddrp == UNWRITTEN) {
   1402 					++changed;
   1403 #ifdef DEBUG_LFS
   1404 					printf("lfs_writeseg: replacing UNWRITTEN\n");
   1405 #endif
   1406 					*daddrp = 0;
   1407 				}
   1408 			}
   1409 			/*
   1410 			 * Get rid of the old buffer.  Don't mark it clean,
   1411 			 * though, if it still has dirty data on it.
   1412 			 */
   1413 			if (changed) {
   1414 				bp->b_flags &= ~(B_ERROR | B_GATHERED);
   1415 				if (bp->b_flags & B_CALL)
   1416 					lfs_freebuf(bp);
   1417 				else {
   1418 					/* Still on free list, leave it there */
   1419 					s = splbio();
   1420 					bp->b_flags &= ~B_BUSY;
   1421 					if (bp->b_flags & B_WANTED)
   1422 						wakeup(bp);
   1423 				 	splx(s);
   1424 					/*
   1425 					 * We have to re-decrement lfs_avail
   1426 					 * since this block is going to come
   1427 					 * back around to us in the next
   1428 					 * segment.
   1429 					 */
   1430 					fs->lfs_avail -= btodb(bp->b_bcount);
   1431 				}
   1432 			} else {
   1433 				bp->b_flags &= ~(B_ERROR | B_READ | B_DELWRI |
   1434 						 B_GATHERED);
   1435 				LFS_UNLOCK_BUF(bp);
   1436 				if (bp->b_flags & B_CALL)
   1437 					lfs_freebuf(bp);
   1438 				else {
   1439 					bremfree(bp);
   1440 					bp->b_flags |= B_DONE;
   1441 					reassignbuf(bp, bp->b_vp);
   1442 					brelse(bp);
   1443 				}
   1444 			}
   1445 
   1446 		}
   1447 	}
   1448 	/*
   1449 	 * Compute checksum across data and then across summary; the first
   1450 	 * block (the summary block) is skipped.  Set the create time here
   1451 	 * so that it's guaranteed to be later than the inode mod times.
   1452 	 *
   1453 	 * XXX
   1454 	 * Fix this to do it inline, instead of malloc/copy.
   1455 	 */
   1456 	datap = dp = malloc(nblocks * sizeof(u_long), M_SEGMENT, M_WAITOK);
   1457 	for (bpp = sp->bpp, i = nblocks - 1; i--;) {
   1458 		if (((*++bpp)->b_flags & (B_CALL|B_INVAL)) == (B_CALL|B_INVAL)) {
   1459 			if (copyin((*bpp)->b_saveaddr, dp++, sizeof(u_long)))
   1460 				panic("lfs_writeseg: copyin failed [1]: "
   1461 				      "ino %d blk %d",
   1462 				      VTOI((*bpp)->b_vp)->i_number,
   1463 				      (*bpp)->b_lblkno);
   1464 		} else
   1465 			*dp++ = ((u_long *)(*bpp)->b_data)[0];
   1466 	}
   1467 	ssp->ss_create = time.tv_sec;
   1468 	ssp->ss_datasum = cksum(datap, (nblocks - 1) * sizeof(u_long));
   1469 	ssp->ss_sumsum =
   1470 	    cksum(&ssp->ss_datasum, LFS_SUMMARY_SIZE - sizeof(ssp->ss_sumsum));
   1471 	free(datap, M_SEGMENT);
   1472 
   1473 	fs->lfs_bfree -= (fsbtodb(fs, ninos) + btodb(LFS_SUMMARY_SIZE));
   1474 
   1475 	strategy = devvp->v_op[VOFFSET(vop_strategy)];
   1476 
   1477 	/*
   1478 	 * When we simply write the blocks we lose a rotation for every block
   1479 	 * written.  To avoid this problem, we allocate memory in chunks, copy
   1480 	 * the buffers into the chunk and write the chunk.  CHUNKSIZE is the
   1481 	 * largest size I/O devices can handle.
   1482 	 * When the data is copied to the chunk, turn off the B_LOCKED bit
   1483 	 * and brelse the buffer (which will move them to the LRU list).  Add
   1484 	 * the B_CALL flag to the buffer header so we can count I/O's for the
   1485 	 * checkpoints and so we can release the allocated memory.
   1486 	 *
   1487 	 * XXX
   1488 	 * This should be removed if the new virtual memory system allows us to
   1489 	 * easily make the buffers contiguous in kernel memory and if that's
   1490 	 * fast enough.
   1491 	 */
   1492 
   1493 #define CHUNKSIZE MAXPHYS
   1494 
   1495 	if(devvp==NULL)
   1496 		panic("devvp is NULL");
   1497 	for (bpp = sp->bpp,i = nblocks; i;) {
   1498 		cbp = lfs_newbuf(devvp, (*bpp)->b_blkno, CHUNKSIZE);
   1499 		cbp->b_dev = i_dev;
   1500 		cbp->b_flags |= B_ASYNC | B_BUSY;
   1501 		cbp->b_bcount = 0;
   1502 
   1503 #ifdef DIAGNOSTIC
   1504 		if(datosn(fs, (*bpp)->b_blkno + btodb((*bpp)->b_bcount) - 1) !=
   1505 		   datosn(fs, cbp->b_blkno)) {
   1506 			panic("lfs_writeseg: Segment overwrite");
   1507 		}
   1508 #endif
   1509 
   1510 		s = splbio();
   1511 		if(fs->lfs_iocount >= LFS_THROTTLE) {
   1512 			tsleep(&fs->lfs_iocount, PRIBIO+1, "lfs throttle", 0);
   1513 		}
   1514 		++fs->lfs_iocount;
   1515 #ifdef LFS_TRACK_IOS
   1516 		for(j=0;j<LFS_THROTTLE;j++) {
   1517 			if(fs->lfs_pending[j]==LFS_UNUSED_DADDR) {
   1518 				fs->lfs_pending[j] = cbp->b_blkno;
   1519 				break;
   1520 			}
   1521 		}
   1522 #endif /* LFS_TRACK_IOS */
   1523 		for (p = cbp->b_data; i && cbp->b_bcount < CHUNKSIZE; i--) {
   1524 			bp = *bpp;
   1525 
   1526 			if (bp->b_bcount > (CHUNKSIZE - cbp->b_bcount))
   1527 				break;
   1528 
   1529 			/*
   1530 			 * Fake buffers from the cleaner are marked as B_INVAL.
   1531 			 * We need to copy the data from user space rather than
   1532 			 * from the buffer indicated.
   1533 			 * XXX == what do I do on an error?
   1534 			 */
   1535 			if ((bp->b_flags & (B_CALL|B_INVAL)) == (B_CALL|B_INVAL)) {
   1536 				if (copyin(bp->b_saveaddr, p, bp->b_bcount))
   1537 					panic("lfs_writeseg: copyin failed [2]");
   1538 			} else
   1539 				bcopy(bp->b_data, p, bp->b_bcount);
   1540 			p += bp->b_bcount;
   1541 			cbp->b_bcount += bp->b_bcount;
   1542 			LFS_UNLOCK_BUF(bp);
   1543 			bp->b_flags &= ~(B_ERROR | B_READ | B_DELWRI |
   1544 					 B_GATHERED);
   1545 			vn = bp->b_vp;
   1546 			if (bp->b_flags & B_CALL) {
   1547 				/* if B_CALL, it was created with newbuf */
   1548 				lfs_freebuf(bp);
   1549 			} else {
   1550 				bremfree(bp);
   1551 				bp->b_flags |= B_DONE;
   1552 				if(vn)
   1553 					reassignbuf(bp, vn);
   1554 				brelse(bp);
   1555 			}
   1556 			if(bp->b_flags & B_NEEDCOMMIT) { /* XXX */
   1557 				bp->b_flags &= ~B_NEEDCOMMIT;
   1558 				wakeup(bp);
   1559 			}
   1560 
   1561 			bpp++;
   1562 
   1563 			/*
   1564 			 * If this is the last block for this vnode, but
   1565 			 * there are other blocks on its dirty list,
   1566 			 * set IN_MODIFIED/IN_CLEANING depending on what
   1567 			 * sort of block.  Only do this for our mount point,
   1568 			 * not for, e.g., inode blocks that are attached to
   1569 			 * the devvp.
   1570 			 */
   1571 			if(i>1 && vn && *bpp && (*bpp)->b_vp != vn
   1572 			   && (*bpp)->b_vp && (bp=vn->v_dirtyblkhd.lh_first)!=NULL &&
   1573 			   vn->v_mount == fs->lfs_ivnode->v_mount)
   1574 			{
   1575 				ip = VTOI(vn);
   1576 #ifdef DEBUG_LFS
   1577 				printf("lfs_writeseg: marking ino %d\n",ip->i_number);
   1578 #endif
   1579 				if(bp->b_flags & B_CALL)
   1580 					LFS_SET_UINO(ip, IN_CLEANING);
   1581 				else
   1582 					LFS_SET_UINO(ip, IN_MODIFIED);
   1583 			}
   1584 			/* if(vn->v_dirtyblkhd.lh_first == NULL) */
   1585 				wakeup(vn);
   1586 		}
   1587 		++cbp->b_vp->v_numoutput;
   1588 		splx(s);
   1589 		/*
   1590 		 * XXXX This is a gross and disgusting hack.  Since these
   1591 		 * buffers are physically addressed, they hang off the
   1592 		 * device vnode (devvp).  As a result, they have no way
   1593 		 * of getting to the LFS superblock or lfs structure to
   1594 		 * keep track of the number of I/O's pending.  So, I am
   1595 		 * going to stuff the fs into the saveaddr field of
   1596 		 * the buffer (yuk).
   1597 		 */
   1598 		cbp->b_saveaddr = (caddr_t)fs;
   1599 		vop_strategy_a.a_desc = VDESC(vop_strategy);
   1600 		vop_strategy_a.a_bp = cbp;
   1601 		(strategy)(&vop_strategy_a);
   1602 	}
   1603 #if 1 || defined(DEBUG)
   1604 	/*
   1605 	 * After doing a big write, we recalculate how many buffers are
   1606 	 * really still left on the locked queue.
   1607 	 */
   1608 	s = splbio();
   1609 	lfs_countlocked(&locked_queue_count, &locked_queue_bytes);
   1610 	splx(s);
   1611 	wakeup(&locked_queue_count);
   1612 #endif /* 1 || DEBUG */
   1613 	if(lfs_dostats) {
   1614 		++lfs_stats.psegwrites;
   1615 		lfs_stats.blocktot += nblocks - 1;
   1616 		if (fs->lfs_sp->seg_flags & SEGM_SYNC)
   1617 			++lfs_stats.psyncwrites;
   1618 		if (fs->lfs_sp->seg_flags & SEGM_CLEAN) {
   1619 			++lfs_stats.pcleanwrites;
   1620 			lfs_stats.cleanblocks += nblocks - 1;
   1621 		}
   1622 	}
   1623 	return (lfs_initseg(fs) || do_again);
   1624 }
   1625 
   1626 void
   1627 lfs_writesuper(fs, daddr)
   1628 	struct lfs *fs;
   1629 	daddr_t daddr;
   1630 {
   1631 	struct buf *bp;
   1632 	dev_t i_dev;
   1633 	int (*strategy) __P((void *));
   1634 	int s;
   1635 	struct vop_strategy_args vop_strategy_a;
   1636 
   1637 #ifdef LFS_CANNOT_ROLLFW
   1638 	/*
   1639 	 * If we can write one superblock while another is in
   1640 	 * progress, we risk not having a complete checkpoint if we crash.
   1641 	 * So, block here if a superblock write is in progress.
   1642 	 */
   1643 	s = splbio();
   1644 	while(fs->lfs_sbactive) {
   1645 		tsleep(&fs->lfs_sbactive, PRIBIO+1, "lfs sb", 0);
   1646 	}
   1647 	fs->lfs_sbactive = daddr;
   1648 	splx(s);
   1649 #endif
   1650 	i_dev = VTOI(fs->lfs_ivnode)->i_dev;
   1651 	strategy = VTOI(fs->lfs_ivnode)->i_devvp->v_op[VOFFSET(vop_strategy)];
   1652 
   1653 	/* Set timestamp of this version of the superblock */
   1654 	fs->lfs_tstamp = time.tv_sec;
   1655 
   1656 	/* Checksum the superblock and copy it into a buffer. */
   1657 	fs->lfs_cksum = lfs_sb_cksum(&(fs->lfs_dlfs));
   1658 	bp = lfs_newbuf(VTOI(fs->lfs_ivnode)->i_devvp, daddr, LFS_SBPAD);
   1659 	*(struct dlfs *)bp->b_data = fs->lfs_dlfs;
   1660 
   1661 	bp->b_dev = i_dev;
   1662 	bp->b_flags |= B_BUSY | B_CALL | B_ASYNC;
   1663 	bp->b_flags &= ~(B_DONE | B_ERROR | B_READ | B_DELWRI);
   1664 	bp->b_iodone = lfs_supercallback;
   1665 	/* XXX KS - same nasty hack as above */
   1666 	bp->b_saveaddr = (caddr_t)fs;
   1667 
   1668 	vop_strategy_a.a_desc = VDESC(vop_strategy);
   1669 	vop_strategy_a.a_bp = bp;
   1670 	s = splbio();
   1671 	++bp->b_vp->v_numoutput;
   1672 	++fs->lfs_iocount;
   1673 	splx(s);
   1674 	(strategy)(&vop_strategy_a);
   1675 }
   1676 
   1677 /*
   1678  * Logical block number match routines used when traversing the dirty block
   1679  * chain.
   1680  */
   1681 int
   1682 lfs_match_fake(fs, bp)
   1683 	struct lfs *fs;
   1684 	struct buf *bp;
   1685 {
   1686 	return (bp->b_flags & B_CALL);
   1687 }
   1688 
   1689 int
   1690 lfs_match_data(fs, bp)
   1691 	struct lfs *fs;
   1692 	struct buf *bp;
   1693 {
   1694 	return (bp->b_lblkno >= 0);
   1695 }
   1696 
   1697 int
   1698 lfs_match_indir(fs, bp)
   1699 	struct lfs *fs;
   1700 	struct buf *bp;
   1701 {
   1702 	int lbn;
   1703 
   1704 	lbn = bp->b_lblkno;
   1705 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 0);
   1706 }
   1707 
   1708 int
   1709 lfs_match_dindir(fs, bp)
   1710 	struct lfs *fs;
   1711 	struct buf *bp;
   1712 {
   1713 	int lbn;
   1714 
   1715 	lbn = bp->b_lblkno;
   1716 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 1);
   1717 }
   1718 
   1719 int
   1720 lfs_match_tindir(fs, bp)
   1721 	struct lfs *fs;
   1722 	struct buf *bp;
   1723 {
   1724 	int lbn;
   1725 
   1726 	lbn = bp->b_lblkno;
   1727 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 2);
   1728 }
   1729 
   1730 /*
   1731  * XXX - The only buffers that are going to hit these functions are the
   1732  * segment write blocks, or the segment summaries, or the superblocks.
   1733  *
   1734  * All of the above are created by lfs_newbuf, and so do not need to be
   1735  * released via brelse.
   1736  */
   1737 void
   1738 lfs_callback(bp)
   1739 	struct buf *bp;
   1740 {
   1741 	struct lfs *fs;
   1742 #ifdef LFS_TRACK_IOS
   1743 	int j;
   1744 #endif
   1745 
   1746 	fs = (struct lfs *)bp->b_saveaddr;
   1747 #ifdef DIAGNOSTIC
   1748 	if (fs->lfs_iocount == 0)
   1749 		panic("lfs_callback: zero iocount\n");
   1750 #endif
   1751 	if (--fs->lfs_iocount < LFS_THROTTLE)
   1752 		wakeup(&fs->lfs_iocount);
   1753 #ifdef LFS_TRACK_IOS
   1754 	for(j=0;j<LFS_THROTTLE;j++) {
   1755 		if(fs->lfs_pending[j]==bp->b_blkno) {
   1756 			fs->lfs_pending[j] = LFS_UNUSED_DADDR;
   1757 			wakeup(&(fs->lfs_pending[j]));
   1758 			break;
   1759 		}
   1760 	}
   1761 #endif /* LFS_TRACK_IOS */
   1762 
   1763 	lfs_freebuf(bp);
   1764 }
   1765 
   1766 void
   1767 lfs_supercallback(bp)
   1768 	struct buf *bp;
   1769 {
   1770 	struct lfs *fs;
   1771 
   1772 	fs = (struct lfs *)bp->b_saveaddr;
   1773 #ifdef LFS_CANNOT_ROLLFW
   1774 	fs->lfs_sbactive = 0;
   1775 	wakeup(&fs->lfs_sbactive);
   1776 #endif
   1777 	if (--fs->lfs_iocount < LFS_THROTTLE)
   1778 		wakeup(&fs->lfs_iocount);
   1779 	lfs_freebuf(bp);
   1780 }
   1781 
   1782 /*
   1783  * Shellsort (diminishing increment sort) from Data Structures and
   1784  * Algorithms, Aho, Hopcraft and Ullman, 1983 Edition, page 290;
   1785  * see also Knuth Vol. 3, page 84.  The increments are selected from
   1786  * formula (8), page 95.  Roughly O(N^3/2).
   1787  */
   1788 /*
   1789  * This is our own private copy of shellsort because we want to sort
   1790  * two parallel arrays (the array of buffer pointers and the array of
   1791  * logical block numbers) simultaneously.  Note that we cast the array
   1792  * of logical block numbers to a unsigned in this routine so that the
   1793  * negative block numbers (meta data blocks) sort AFTER the data blocks.
   1794  */
   1795 
   1796 void
   1797 lfs_shellsort(bp_array, lb_array, nmemb)
   1798 	struct buf **bp_array;
   1799 	ufs_daddr_t *lb_array;
   1800 	int nmemb;
   1801 {
   1802 	static int __rsshell_increments[] = { 4, 1, 0 };
   1803 	int incr, *incrp, t1, t2;
   1804 	struct buf *bp_temp;
   1805 	u_long lb_temp;
   1806 
   1807 	for (incrp = __rsshell_increments; (incr = *incrp++) != 0;)
   1808 		for (t1 = incr; t1 < nmemb; ++t1)
   1809 			for (t2 = t1 - incr; t2 >= 0;)
   1810 				if (lb_array[t2] > lb_array[t2 + incr]) {
   1811 					lb_temp = lb_array[t2];
   1812 					lb_array[t2] = lb_array[t2 + incr];
   1813 					lb_array[t2 + incr] = lb_temp;
   1814 					bp_temp = bp_array[t2];
   1815 					bp_array[t2] = bp_array[t2 + incr];
   1816 					bp_array[t2 + incr] = bp_temp;
   1817 					t2 -= incr;
   1818 				} else
   1819 					break;
   1820 }
   1821 
   1822 /*
   1823  * Check VXLOCK.  Return 1 if the vnode is locked.  Otherwise, vget it.
   1824  */
   1825 int
   1826 lfs_vref(vp)
   1827 	struct vnode *vp;
   1828 {
   1829 	/*
   1830 	 * If we return 1 here during a flush, we risk vinvalbuf() not
   1831 	 * being able to flush all of the pages from this vnode, which
   1832 	 * will cause it to panic.  So, return 0 if a flush is in progress.
   1833 	 */
   1834 	if (vp->v_flag & VXLOCK) {
   1835 		if(IS_FLUSHING(VTOI(vp)->i_lfs,vp)) {
   1836 			return 0;
   1837 		}
   1838 		return(1);
   1839 	}
   1840 	return (vget(vp, 0));
   1841 }
   1842 
   1843 /*
   1844  * This is vrele except that we do not want to VOP_INACTIVE this vnode. We
   1845  * inline vrele here to avoid the vn_lock and VOP_INACTIVE call at the end.
   1846  */
   1847 void
   1848 lfs_vunref(vp)
   1849 	struct vnode *vp;
   1850 {
   1851 	/*
   1852 	 * Analogous to lfs_vref, if the node is flushing, fake it.
   1853 	 */
   1854 	if((vp->v_flag & VXLOCK) && IS_FLUSHING(VTOI(vp)->i_lfs,vp)) {
   1855 		return;
   1856 	}
   1857 
   1858 	simple_lock(&vp->v_interlock);
   1859 #ifdef DIAGNOSTIC
   1860 	if(vp->v_usecount<=0) {
   1861 		printf("lfs_vunref: inum is %d\n", VTOI(vp)->i_number);
   1862 		printf("lfs_vunref: flags are 0x%lx\n", vp->v_flag);
   1863 		printf("lfs_vunref: usecount = %ld\n", vp->v_usecount);
   1864 		panic("lfs_vunref: v_usecount<0");
   1865 	}
   1866 #endif
   1867 	vp->v_usecount--;
   1868 	if (vp->v_usecount > 0) {
   1869 		simple_unlock(&vp->v_interlock);
   1870 		return;
   1871 	}
   1872 	/*
   1873 	 * insert at tail of LRU list
   1874 	 */
   1875 	simple_lock(&vnode_free_list_slock);
   1876 	if (vp->v_holdcnt > 0)
   1877 		TAILQ_INSERT_TAIL(&vnode_hold_list, vp, v_freelist);
   1878 	else
   1879 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
   1880 	simple_unlock(&vnode_free_list_slock);
   1881 	simple_unlock(&vp->v_interlock);
   1882 }
   1883 
   1884 /*
   1885  * We use this when we have vnodes that were loaded in solely for cleaning.
   1886  * There is no reason to believe that these vnodes will be referenced again
   1887  * soon, since the cleaning process is unrelated to normal filesystem
   1888  * activity.  Putting cleaned vnodes at the tail of the list has the effect
   1889  * of flushing the vnode LRU.  So, put vnodes that were loaded only for
   1890  * cleaning at the head of the list, instead.
   1891  */
   1892 void
   1893 lfs_vunref_head(vp)
   1894 	struct vnode *vp;
   1895 {
   1896 	simple_lock(&vp->v_interlock);
   1897 #ifdef DIAGNOSTIC
   1898 	if(vp->v_usecount==0) {
   1899 		panic("lfs_vunref: v_usecount<0");
   1900 	}
   1901 #endif
   1902 	vp->v_usecount--;
   1903 	if (vp->v_usecount > 0) {
   1904 		simple_unlock(&vp->v_interlock);
   1905 		return;
   1906 	}
   1907 	/*
   1908 	 * insert at head of LRU list
   1909 	 */
   1910 	simple_lock(&vnode_free_list_slock);
   1911 	TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
   1912 	simple_unlock(&vnode_free_list_slock);
   1913 	simple_unlock(&vp->v_interlock);
   1914 }
   1915 
   1916