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