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