xref: /netbsd-src/sys/ufs/lfs/lfs_segment.c (revision e5548b402ae4c44fb816de42c7bba9581ce23ef5)
1 /*	$NetBSD: lfs_segment.c,v 1.168 2005/12/11 12:25:26 christos 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.168 2005/12/11 12:25:26 christos 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 	nanotime(&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 	int gotblk = 0;
837 
838 	ASSERT_SEGLOCK(fs);
839 	if (!(ip->i_flag & IN_ALLMOD))
840 		return (0);
841 
842 	/* Allocate a new inode block if necessary. */
843 	if ((ip->i_number != LFS_IFILE_INUM || sp->idp == NULL) &&
844 	    sp->ibp == NULL) {
845 		/* Allocate a new segment if necessary. */
846 		if (sp->seg_bytes_left < fs->lfs_ibsize ||
847 		    sp->sum_bytes_left < sizeof(int32_t))
848 			(void) lfs_writeseg(fs, sp);
849 
850 		/* Get next inode block. */
851 		daddr = fs->lfs_offset;
852 		fs->lfs_offset += btofsb(fs, fs->lfs_ibsize);
853 		sp->ibp = *sp->cbpp++ =
854 			getblk(VTOI(fs->lfs_ivnode)->i_devvp,
855 			    fsbtodb(fs, daddr), fs->lfs_ibsize, 0, 0);
856 		gotblk++;
857 
858 		/* Zero out inode numbers */
859 		for (i = 0; i < INOPB(fs); ++i)
860 			((struct ufs1_dinode *)sp->ibp->b_data)[i].di_inumber =
861 			    0;
862 
863 		++sp->start_bpp;
864 		fs->lfs_avail -= btofsb(fs, fs->lfs_ibsize);
865 		/* Set remaining space counters. */
866 		sp->seg_bytes_left -= fs->lfs_ibsize;
867 		sp->sum_bytes_left -= sizeof(int32_t);
868 		ndx = fs->lfs_sumsize / sizeof(int32_t) -
869 			sp->ninodes / INOPB(fs) - 1;
870 		((int32_t *)(sp->segsum))[ndx] = daddr;
871 	}
872 
873 	/* Update the inode times and copy the inode onto the inode page. */
874 	/* XXX kludge --- don't redirty the ifile just to put times on it */
875 	if (ip->i_number != LFS_IFILE_INUM)
876 		LFS_ITIMES(ip, NULL, NULL, NULL);
877 
878 	/*
879 	 * If this is the Ifile, and we've already written the Ifile in this
880 	 * partial segment, just overwrite it (it's not on disk yet) and
881 	 * continue.
882 	 *
883 	 * XXX we know that the bp that we get the second time around has
884 	 * already been gathered.
885 	 */
886 	if (ip->i_number == LFS_IFILE_INUM && sp->idp) {
887 		*(sp->idp) = *ip->i_din.ffs1_din;
888 		ip->i_lfs_osize = ip->i_size;
889 		return 0;
890 	}
891 
892 	bp = sp->ibp;
893 	cdp = ((struct ufs1_dinode *)bp->b_data) + (sp->ninodes % INOPB(fs));
894 	*cdp = *ip->i_din.ffs1_din;
895 
896 	/*
897 	 * If we are cleaning, ensure that we don't write UNWRITTEN disk
898 	 * addresses to disk; possibly change the on-disk record of
899 	 * the inode size, either by reverting to the previous size
900 	 * (in the case of cleaning) or by verifying the inode's block
901 	 * holdings (in the case of files being allocated as they are being
902 	 * written).
903 	 * XXX By not writing UNWRITTEN blocks, we are making the lfs_avail
904 	 * XXX count on disk wrong by the same amount.	We should be
905 	 * XXX able to "borrow" from lfs_avail and return it after the
906 	 * XXX Ifile is written.  See also in lfs_writeseg.
907 	 */
908 
909 	/* Check file size based on highest allocated block */
910 	if (((ip->i_ffs1_mode & IFMT) == IFREG ||
911 	     (ip->i_ffs1_mode & IFMT) == IFDIR) &&
912 	    ip->i_size > ((ip->i_lfs_hiblk + 1) << fs->lfs_bshift)) {
913 		cdp->di_size = (ip->i_lfs_hiblk + 1) << fs->lfs_bshift;
914 		DLOG((DLOG_SEG, "lfs_writeinode: ino %d size %" PRId64 " -> %"
915 		      PRId64 "\n", (int)ip->i_number, ip->i_size, cdp->di_size));
916 	}
917 	if (ip->i_lfs_effnblks != ip->i_ffs1_blocks) {
918 		if (ip->i_flags & IN_CLEANING)
919 			cdp->di_size = ip->i_lfs_osize;
920 		DLOG((DLOG_SEG, "lfs_writeinode: cleansing ino %d eff %d != nblk %d)"
921 		      " at %x\n", ip->i_number, ip->i_lfs_effnblks,
922 		      ip->i_ffs1_blocks, fs->lfs_offset));
923 		for (daddrp = cdp->di_db; daddrp < cdp->di_ib + NIADDR;
924 		     daddrp++) {
925 			if (*daddrp == UNWRITTEN) {
926 				DLOG((DLOG_SEG, "lfs_writeinode: wiping UNWRITTEN\n"));
927 				*daddrp = 0;
928 			}
929 		}
930 	} else {
931 		/* If all blocks are going to disk, update "size on disk" */
932 		ip->i_lfs_osize = ip->i_size;
933 	}
934 
935 #ifdef DIAGNOSTIC
936 	/*
937 	 * Check dinode held blocks against dinode size.
938 	 * This should be identical to the check in lfs_vget().
939 	 */
940 	for (i = (cdp->di_size + fs->lfs_bsize - 1) >> fs->lfs_bshift;
941 	     i < NDADDR; i++) {
942 		KASSERT(i >= 0);
943 		if ((cdp->di_mode & IFMT) == IFLNK)
944 			continue;
945 		if (((cdp->di_mode & IFMT) == IFBLK ||
946 		     (cdp->di_mode & IFMT) == IFCHR) && i == 0)
947 			continue;
948 		if (cdp->di_db[i] != 0) {
949 # ifdef DEBUG
950 			lfs_dump_dinode(cdp);
951 # endif
952 			panic("writing inconsistent inode");
953 		}
954 	}
955 #endif /* DIAGNOSTIC */
956 
957 	if (ip->i_flag & IN_CLEANING)
958 		LFS_CLR_UINO(ip, IN_CLEANING);
959 	else {
960 		/* XXX IN_ALLMOD */
961 		LFS_CLR_UINO(ip, IN_ACCESSED | IN_ACCESS | IN_CHANGE |
962 			     IN_UPDATE | IN_MODIFY);
963 		if (ip->i_lfs_effnblks == ip->i_ffs1_blocks)
964 			LFS_CLR_UINO(ip, IN_MODIFIED);
965 		else
966 			DLOG((DLOG_VNODE, "lfs_writeinode: ino %d: real blks=%d, "
967 			      "eff=%d\n", ip->i_number, ip->i_ffs1_blocks,
968 			      ip->i_lfs_effnblks));
969 	}
970 
971 	if (ip->i_number == LFS_IFILE_INUM) /* We know sp->idp == NULL */
972 		sp->idp = ((struct ufs1_dinode *)bp->b_data) +
973 			(sp->ninodes % INOPB(fs));
974 	if (gotblk) {
975 		LFS_LOCK_BUF(bp);
976 		brelse(bp);
977 	}
978 
979 	/* Increment inode count in segment summary block. */
980 	++((SEGSUM *)(sp->segsum))->ss_ninos;
981 
982 	/* If this page is full, set flag to allocate a new page. */
983 	if (++sp->ninodes % INOPB(fs) == 0)
984 		sp->ibp = NULL;
985 
986 	/*
987 	 * If updating the ifile, update the super-block.  Update the disk
988 	 * address and access times for this inode in the ifile.
989 	 */
990 	ino = ip->i_number;
991 	if (ino == LFS_IFILE_INUM) {
992 		daddr = fs->lfs_idaddr;
993 		fs->lfs_idaddr = dbtofsb(fs, bp->b_blkno);
994 	} else {
995 		LFS_IENTRY(ifp, fs, ino, ibp);
996 		daddr = ifp->if_daddr;
997 		ifp->if_daddr = dbtofsb(fs, bp->b_blkno) + fsb;
998 		error = LFS_BWRITE_LOG(ibp); /* Ifile */
999 	}
1000 
1001 	/*
1002 	 * The inode's last address should not be in the current partial
1003 	 * segment, except under exceptional circumstances (lfs_writevnodes
1004 	 * had to start over, and in the meantime more blocks were written
1005 	 * to a vnode).	 Both inodes will be accounted to this segment
1006 	 * in lfs_writeseg so we need to subtract the earlier version
1007 	 * here anyway.	 The segment count can temporarily dip below
1008 	 * zero here; keep track of how many duplicates we have in
1009 	 * "dupino" so we don't panic below.
1010 	 */
1011 	if (daddr >= fs->lfs_lastpseg && daddr <= dbtofsb(fs, bp->b_blkno)) {
1012 		++sp->ndupino;
1013 		DLOG((DLOG_SEG, "lfs_writeinode: last inode addr in current pseg "
1014 		      "(ino %d daddr 0x%llx) ndupino=%d\n", ino,
1015 		      (long long)daddr, sp->ndupino));
1016 	}
1017 	/*
1018 	 * Account the inode: it no longer belongs to its former segment,
1019 	 * though it will not belong to the new segment until that segment
1020 	 * is actually written.
1021 	 */
1022 	if (daddr != LFS_UNUSED_DADDR) {
1023 		u_int32_t oldsn = dtosn(fs, daddr);
1024 #ifdef DIAGNOSTIC
1025 		int ndupino = (sp->seg_number == oldsn) ? sp->ndupino : 0;
1026 #endif
1027 		LFS_SEGENTRY(sup, fs, oldsn, bp);
1028 #ifdef DIAGNOSTIC
1029 		if (sup->su_nbytes +
1030 		    sizeof (struct ufs1_dinode) * ndupino
1031 		      < sizeof (struct ufs1_dinode)) {
1032 			printf("lfs_writeinode: negative bytes "
1033 			       "(segment %" PRIu32 " short by %d, "
1034 			       "oldsn=%" PRIu32 ", cursn=%" PRIu32
1035 			       ", daddr=%" PRId64 ", su_nbytes=%u, "
1036 			       "ndupino=%d)\n",
1037 			       dtosn(fs, daddr),
1038 			       (int)sizeof (struct ufs1_dinode) *
1039 				   (1 - sp->ndupino) - sup->su_nbytes,
1040 			       oldsn, sp->seg_number, daddr,
1041 			       (unsigned int)sup->su_nbytes,
1042 			       sp->ndupino);
1043 			panic("lfs_writeinode: negative bytes");
1044 			sup->su_nbytes = sizeof (struct ufs1_dinode);
1045 		}
1046 #endif
1047 		DLOG((DLOG_SU, "seg %d -= %d for ino %d inode\n",
1048 		      dtosn(fs, daddr), sizeof (struct ufs1_dinode), ino));
1049 		sup->su_nbytes -= sizeof (struct ufs1_dinode);
1050 		redo_ifile =
1051 			(ino == LFS_IFILE_INUM && !(bp->b_flags & B_GATHERED));
1052 		if (redo_ifile) {
1053 			simple_lock(&fs->lfs_interlock);
1054 			fs->lfs_flags |= LFS_IFDIRTY;
1055 			simple_unlock(&fs->lfs_interlock);
1056 		}
1057 		LFS_WRITESEGENTRY(sup, fs, oldsn, bp); /* Ifile */
1058 	}
1059 	return (redo_ifile);
1060 }
1061 
1062 int
1063 lfs_gatherblock(struct segment *sp, struct buf *bp, int *sptr)
1064 {
1065 	struct lfs *fs;
1066 	int vers;
1067 	int j, blksinblk;
1068 
1069 	ASSERT_SEGLOCK(sp->fs);
1070 	/*
1071 	 * If full, finish this segment.  We may be doing I/O, so
1072 	 * release and reacquire the splbio().
1073 	 */
1074 #ifdef DIAGNOSTIC
1075 	if (sp->vp == NULL)
1076 		panic ("lfs_gatherblock: Null vp in segment");
1077 #endif
1078 	fs = sp->fs;
1079 	blksinblk = howmany(bp->b_bcount, fs->lfs_bsize);
1080 	if (sp->sum_bytes_left < sizeof(int32_t) * blksinblk ||
1081 	    sp->seg_bytes_left < bp->b_bcount) {
1082 		if (sptr)
1083 			splx(*sptr);
1084 		lfs_updatemeta(sp);
1085 
1086 		vers = sp->fip->fi_version;
1087 		(void) lfs_writeseg(fs, sp);
1088 
1089 		sp->fip->fi_version = vers;
1090 		sp->fip->fi_ino = VTOI(sp->vp)->i_number;
1091 		/* Add the current file to the segment summary. */
1092 		++((SEGSUM *)(sp->segsum))->ss_nfinfo;
1093 		sp->sum_bytes_left -= FINFOSIZE;
1094 
1095 		if (sptr)
1096 			*sptr = splbio();
1097 		return (1);
1098 	}
1099 
1100 	if (bp->b_flags & B_GATHERED) {
1101 		DLOG((DLOG_SEG, "lfs_gatherblock: already gathered! Ino %d,"
1102 		      " lbn %" PRId64 "\n",
1103 		      sp->fip->fi_ino, bp->b_lblkno));
1104 		return (0);
1105 	}
1106 
1107 	/* Insert into the buffer list, update the FINFO block. */
1108 	bp->b_flags |= B_GATHERED;
1109 
1110 	*sp->cbpp++ = bp;
1111 	for (j = 0; j < blksinblk; j++) {
1112 		sp->fip->fi_blocks[sp->fip->fi_nblocks++] = bp->b_lblkno + j;
1113 		/* This block's accounting moves from lfs_favail to lfs_avail */
1114 		lfs_deregister_block(sp->vp, bp->b_lblkno + j);
1115 	}
1116 
1117 	sp->sum_bytes_left -= sizeof(int32_t) * blksinblk;
1118 	sp->seg_bytes_left -= bp->b_bcount;
1119 	return (0);
1120 }
1121 
1122 int
1123 lfs_gather(struct lfs *fs, struct segment *sp, struct vnode *vp,
1124     int (*match)(struct lfs *, struct buf *))
1125 {
1126 	struct buf *bp, *nbp;
1127 	int s, count = 0;
1128 
1129 	ASSERT_SEGLOCK(fs);
1130 	KASSERT(sp->vp == NULL);
1131 	sp->vp = vp;
1132 	s = splbio();
1133 
1134 #ifndef LFS_NO_BACKBUF_HACK
1135 /* This is a hack to see if ordering the blocks in LFS makes a difference. */
1136 # define	BUF_OFFSET	\
1137 	(((caddr_t)&LIST_NEXT(bp, b_vnbufs)) - (caddr_t)bp)
1138 # define	BACK_BUF(BP)	\
1139 	((struct buf *)(((caddr_t)(BP)->b_vnbufs.le_prev) - BUF_OFFSET))
1140 # define	BEG_OF_LIST	\
1141 	((struct buf *)(((caddr_t)&LIST_FIRST(&vp->v_dirtyblkhd)) - BUF_OFFSET))
1142 
1143 loop:
1144 	/* Find last buffer. */
1145 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd);
1146 	     bp && LIST_NEXT(bp, b_vnbufs) != NULL;
1147 	     bp = LIST_NEXT(bp, b_vnbufs))
1148 		/* nothing */;
1149 	for (; bp && bp != BEG_OF_LIST; bp = nbp) {
1150 		nbp = BACK_BUF(bp);
1151 #else /* LFS_NO_BACKBUF_HACK */
1152 loop:
1153 	for (bp = LIST_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
1154 		nbp = LIST_NEXT(bp, b_vnbufs);
1155 #endif /* LFS_NO_BACKBUF_HACK */
1156 		if ((bp->b_flags & (B_BUSY|B_GATHERED)) || !match(fs, bp)) {
1157 #ifdef DEBUG
1158 			if (vp == fs->lfs_ivnode &&
1159 			    (bp->b_flags & (B_BUSY|B_GATHERED)) == B_BUSY)
1160 				DLOG((DLOG_SEG, "lfs_gather: ifile lbn %"
1161 				      PRId64 " busy (%x)",
1162 				      bp->b_lblkno, bp->b_flags));
1163 #endif
1164 			continue;
1165 		}
1166 		if (vp->v_type == VBLK) {
1167 			/* For block devices, just write the blocks. */
1168 			/* XXX Do we even need to do this? */
1169 			/*
1170 			 * Get the block before bwrite,
1171 			 * so we don't corrupt the free list
1172 			 */
1173 			bp->b_flags |= B_BUSY;
1174 			bremfree(bp);
1175 			bwrite(bp);
1176 		} else {
1177 #ifdef DIAGNOSTIC
1178 # ifdef LFS_USE_B_INVAL
1179 			if ((bp->b_flags & (B_CALL|B_INVAL)) == B_INVAL) {
1180 				DLOG((DLOG_SEG, "lfs_gather: lbn %" PRId64
1181 				      " is B_INVAL\n", bp->b_lblkno));
1182 				VOP_PRINT(bp->b_vp);
1183 			}
1184 # endif /* LFS_USE_B_INVAL */
1185 			if (!(bp->b_flags & B_DELWRI))
1186 				panic("lfs_gather: bp not B_DELWRI");
1187 			if (!(bp->b_flags & B_LOCKED)) {
1188 				DLOG((DLOG_SEG, "lfs_gather: lbn %" PRId64
1189 				      " blk %" PRId64 " not B_LOCKED\n",
1190 				      bp->b_lblkno,
1191 				      dbtofsb(fs, bp->b_blkno)));
1192 				VOP_PRINT(bp->b_vp);
1193 				panic("lfs_gather: bp not B_LOCKED");
1194 			}
1195 #endif
1196 			if (lfs_gatherblock(sp, bp, &s)) {
1197 				goto loop;
1198 			}
1199 		}
1200 		count++;
1201 	}
1202 	splx(s);
1203 	lfs_updatemeta(sp);
1204 	KASSERT(sp->vp == vp);
1205 	sp->vp = NULL;
1206 	return count;
1207 }
1208 
1209 #if DEBUG
1210 # define DEBUG_OOFF(n) do {						\
1211 	if (ooff == 0) {						\
1212 		DLOG((DLOG_SEG, "lfs_updatemeta[%d]: warning: writing " \
1213 			"ino %d lbn %" PRId64 " at 0x%" PRIx32		\
1214 			", was 0x0 (or %" PRId64 ")\n",			\
1215 			(n), ip->i_number, lbn, ndaddr, daddr));	\
1216 	}								\
1217 } while (0)
1218 #else
1219 # define DEBUG_OOFF(n)
1220 #endif
1221 
1222 /*
1223  * Change the given block's address to ndaddr, finding its previous
1224  * location using ufs_bmaparray().
1225  *
1226  * Account for this change in the segment table.
1227  *
1228  * called with sp == NULL by roll-forwarding code.
1229  */
1230 void
1231 lfs_update_single(struct lfs *fs, struct segment *sp, struct vnode *vp,
1232     daddr_t lbn, int32_t ndaddr, int size)
1233 {
1234 	SEGUSE *sup;
1235 	struct buf *bp;
1236 	struct indir a[NIADDR + 2], *ap;
1237 	struct inode *ip;
1238 	daddr_t daddr, ooff;
1239 	int num, error;
1240 	int bb, osize, obb;
1241 
1242 	ASSERT_SEGLOCK(fs);
1243 	KASSERT(sp == NULL || sp->vp == vp);
1244 	ip = VTOI(vp);
1245 
1246 	error = ufs_bmaparray(vp, lbn, &daddr, a, &num, NULL, NULL);
1247 	if (error)
1248 		panic("lfs_updatemeta: ufs_bmaparray returned %d", error);
1249 
1250 	daddr = (daddr_t)((int32_t)daddr); /* XXX ondisk32 */
1251 	KASSERT(daddr <= LFS_MAX_DADDR);
1252 	if (daddr > 0)
1253 		daddr = dbtofsb(fs, daddr);
1254 
1255 	bb = fragstofsb(fs, numfrags(fs, size));
1256 	switch (num) {
1257 	    case 0:
1258 		    ooff = ip->i_ffs1_db[lbn];
1259 		    DEBUG_OOFF(0);
1260 		    if (ooff == UNWRITTEN)
1261 			    ip->i_ffs1_blocks += bb;
1262 		    else {
1263 			    /* possible fragment truncation or extension */
1264 			    obb = btofsb(fs, ip->i_lfs_fragsize[lbn]);
1265 			    ip->i_ffs1_blocks += (bb - obb);
1266 		    }
1267 		    ip->i_ffs1_db[lbn] = ndaddr;
1268 		    break;
1269 	    case 1:
1270 		    ooff = ip->i_ffs1_ib[a[0].in_off];
1271 		    DEBUG_OOFF(1);
1272 		    if (ooff == UNWRITTEN)
1273 			    ip->i_ffs1_blocks += bb;
1274 		    ip->i_ffs1_ib[a[0].in_off] = ndaddr;
1275 		    break;
1276 	    default:
1277 		    ap = &a[num - 1];
1278 		    if (bread(vp, ap->in_lbn, fs->lfs_bsize, NOCRED, &bp))
1279 			    panic("lfs_updatemeta: bread bno %" PRId64,
1280 				  ap->in_lbn);
1281 
1282 		    /* XXX ondisk32 */
1283 		    ooff = ((int32_t *)bp->b_data)[ap->in_off];
1284 		    DEBUG_OOFF(num);
1285 		    if (ooff == UNWRITTEN)
1286 			    ip->i_ffs1_blocks += bb;
1287 		    /* XXX ondisk32 */
1288 		    ((int32_t *)bp->b_data)[ap->in_off] = ndaddr;
1289 		    (void) VOP_BWRITE(bp);
1290 	}
1291 
1292 	KASSERT(ooff == 0 || ooff == UNWRITTEN || ooff == daddr);
1293 
1294 	/* Update hiblk when extending the file */
1295 	if (lbn > ip->i_lfs_hiblk)
1296 		ip->i_lfs_hiblk = lbn;
1297 
1298 	/*
1299 	 * Though we'd rather it couldn't, this *can* happen right now
1300 	 * if cleaning blocks and regular blocks coexist.
1301 	 */
1302 	/* KASSERT(daddr < fs->lfs_lastpseg || daddr > ndaddr); */
1303 
1304 	/*
1305 	 * Update segment usage information, based on old size
1306 	 * and location.
1307 	 */
1308 	if (daddr > 0) {
1309 		u_int32_t oldsn = dtosn(fs, daddr);
1310 #ifdef DIAGNOSTIC
1311 		int ndupino;
1312 
1313 		if (sp && sp->seg_number == oldsn) {
1314 			ndupino = sp->ndupino;
1315 		} else {
1316 			ndupino = 0;
1317 		}
1318 #endif
1319 		KASSERT(oldsn >= 0 && oldsn < fs->lfs_nseg);
1320 		if (lbn >= 0 && lbn < NDADDR)
1321 			osize = ip->i_lfs_fragsize[lbn];
1322 		else
1323 			osize = fs->lfs_bsize;
1324 		LFS_SEGENTRY(sup, fs, oldsn, bp);
1325 #ifdef DIAGNOSTIC
1326 		if (sup->su_nbytes + sizeof (struct ufs1_dinode) * ndupino
1327 		    < osize) {
1328 			printf("lfs_updatemeta: negative bytes "
1329 			       "(segment %" PRIu32 " short by %" PRId64
1330 			       ")\n", dtosn(fs, daddr),
1331 			       (int64_t)osize -
1332 			       (sizeof (struct ufs1_dinode) * ndupino +
1333 				sup->su_nbytes));
1334 			printf("lfs_updatemeta: ino %llu, lbn %" PRId64
1335 			       ", addr = 0x%" PRIx64 "\n",
1336 			       (unsigned long long)ip->i_number, lbn, daddr);
1337 			printf("lfs_updatemeta: ndupino=%d\n", ndupino);
1338 			panic("lfs_updatemeta: negative bytes");
1339 			sup->su_nbytes = osize -
1340 			    sizeof (struct ufs1_dinode) * ndupino;
1341 		}
1342 #endif
1343 		DLOG((DLOG_SU, "seg %" PRIu32 " -= %d for ino %d lbn %" PRId64
1344 		      " db 0x%" PRIx64 "\n",
1345 		      dtosn(fs, daddr), osize,
1346 		      ip->i_number, lbn, daddr));
1347 		sup->su_nbytes -= osize;
1348 		if (!(bp->b_flags & B_GATHERED)) {
1349 			simple_lock(&fs->lfs_interlock);
1350 			fs->lfs_flags |= LFS_IFDIRTY;
1351 			simple_unlock(&fs->lfs_interlock);
1352 		}
1353 		LFS_WRITESEGENTRY(sup, fs, oldsn, bp);
1354 	}
1355 	/*
1356 	 * Now that this block has a new address, and its old
1357 	 * segment no longer owns it, we can forget about its
1358 	 * old size.
1359 	 */
1360 	if (lbn >= 0 && lbn < NDADDR)
1361 		ip->i_lfs_fragsize[lbn] = size;
1362 }
1363 
1364 /*
1365  * Update the metadata that points to the blocks listed in the FINFO
1366  * array.
1367  */
1368 void
1369 lfs_updatemeta(struct segment *sp)
1370 {
1371 	struct buf *sbp;
1372 	struct lfs *fs;
1373 	struct vnode *vp;
1374 	daddr_t lbn;
1375 	int i, nblocks, num;
1376 	int bb;
1377 	int bytesleft, size;
1378 
1379 	ASSERT_SEGLOCK(sp->fs);
1380 	vp = sp->vp;
1381 	nblocks = &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp;
1382 	KASSERT(nblocks >= 0);
1383 	KASSERT(vp != NULL);
1384 	if (nblocks == 0)
1385 		return;
1386 
1387 	/*
1388 	 * This count may be high due to oversize blocks from lfs_gop_write.
1389 	 * Correct for this. (XXX we should be able to keep track of these.)
1390 	 */
1391 	fs = sp->fs;
1392 	for (i = 0; i < nblocks; i++) {
1393 		if (sp->start_bpp[i] == NULL) {
1394 			DLOG((DLOG_SEG, "lfs_updatemeta: nblocks = %d, not %d\n", i, nblocks));
1395 			nblocks = i;
1396 			break;
1397 		}
1398 		num = howmany(sp->start_bpp[i]->b_bcount, fs->lfs_bsize);
1399 		KASSERT(sp->start_bpp[i]->b_lblkno >= 0 || num == 1);
1400 		nblocks -= num - 1;
1401 	}
1402 
1403 	KASSERT(vp->v_type == VREG ||
1404 	   nblocks == &sp->fip->fi_blocks[sp->fip->fi_nblocks] - sp->start_lbp);
1405 	KASSERT(nblocks == sp->cbpp - sp->start_bpp);
1406 
1407 	/*
1408 	 * Sort the blocks.
1409 	 *
1410 	 * We have to sort even if the blocks come from the
1411 	 * cleaner, because there might be other pending blocks on the
1412 	 * same inode...and if we don't sort, and there are fragments
1413 	 * present, blocks may be written in the wrong place.
1414 	 */
1415 	lfs_shellsort(sp->start_bpp, sp->start_lbp, nblocks, fs->lfs_bsize);
1416 
1417 	/*
1418 	 * Record the length of the last block in case it's a fragment.
1419 	 * If there are indirect blocks present, they sort last.  An
1420 	 * indirect block will be lfs_bsize and its presence indicates
1421 	 * that you cannot have fragments.
1422 	 *
1423 	 * XXX This last is a lie.  A cleaned fragment can coexist with
1424 	 * XXX a later indirect block.	This will continue to be
1425 	 * XXX true until lfs_markv is fixed to do everything with
1426 	 * XXX fake blocks (including fake inodes and fake indirect blocks).
1427 	 */
1428 	sp->fip->fi_lastlength = ((sp->start_bpp[nblocks - 1]->b_bcount - 1) &
1429 		fs->lfs_bmask) + 1;
1430 
1431 	/*
1432 	 * Assign disk addresses, and update references to the logical
1433 	 * block and the segment usage information.
1434 	 */
1435 	for (i = nblocks; i--; ++sp->start_bpp) {
1436 		sbp = *sp->start_bpp;
1437 		lbn = *sp->start_lbp;
1438 		KASSERT(sbp->b_lblkno == lbn);
1439 
1440 		sbp->b_blkno = fsbtodb(fs, fs->lfs_offset);
1441 
1442 		/*
1443 		 * If we write a frag in the wrong place, the cleaner won't
1444 		 * be able to correctly identify its size later, and the
1445 		 * segment will be uncleanable.	 (Even worse, it will assume
1446 		 * that the indirect block that actually ends the list
1447 		 * is of a smaller size!)
1448 		 */
1449 		if ((sbp->b_bcount & fs->lfs_bmask) && i != 0)
1450 			panic("lfs_updatemeta: fragment is not last block");
1451 
1452 		/*
1453 		 * For each subblock in this possibly oversized block,
1454 		 * update its address on disk.
1455 		 */
1456 		KASSERT(lbn >= 0 || sbp->b_bcount == fs->lfs_bsize);
1457 		KASSERT(vp == sbp->b_vp);
1458 		for (bytesleft = sbp->b_bcount; bytesleft > 0;
1459 		     bytesleft -= fs->lfs_bsize) {
1460 			size = MIN(bytesleft, fs->lfs_bsize);
1461 			bb = fragstofsb(fs, numfrags(fs, size));
1462 			lbn = *sp->start_lbp++;
1463 			lfs_update_single(fs, sp, sp->vp, lbn, fs->lfs_offset,
1464 			    size);
1465 			fs->lfs_offset += bb;
1466 		}
1467 
1468 	}
1469 }
1470 
1471 /*
1472  * Move lfs_offset to a segment earlier than sn.
1473  */
1474 int
1475 lfs_rewind(struct lfs *fs, int newsn)
1476 {
1477 	int sn, osn, isdirty;
1478 	struct buf *bp;
1479 	SEGUSE *sup;
1480 
1481 	ASSERT_SEGLOCK(fs);
1482 
1483 	osn = dtosn(fs, fs->lfs_offset);
1484 	if (osn < newsn)
1485 		return 0;
1486 
1487 	/* lfs_avail eats the remaining space in this segment */
1488 	fs->lfs_avail -= fs->lfs_fsbpseg - (fs->lfs_offset - fs->lfs_curseg);
1489 
1490 	/* Find a low-numbered segment */
1491 	for (sn = 0; sn < fs->lfs_nseg; ++sn) {
1492 		LFS_SEGENTRY(sup, fs, sn, bp);
1493 		isdirty = sup->su_flags & SEGUSE_DIRTY;
1494 		brelse(bp);
1495 
1496 		if (!isdirty)
1497 			break;
1498 	}
1499 	if (sn == fs->lfs_nseg)
1500 		panic("lfs_rewind: no clean segments");
1501 	if (sn >= newsn)
1502 		return ENOENT;
1503 	fs->lfs_nextseg = sn;
1504 	lfs_newseg(fs);
1505 	fs->lfs_offset = fs->lfs_curseg;
1506 
1507 	return 0;
1508 }
1509 
1510 /*
1511  * Start a new partial segment.
1512  *
1513  * Return 1 when we entered to a new segment.
1514  * Otherwise, return 0.
1515  */
1516 int
1517 lfs_initseg(struct lfs *fs)
1518 {
1519 	struct segment *sp = fs->lfs_sp;
1520 	SEGSUM *ssp;
1521 	struct buf *sbp;	/* buffer for SEGSUM */
1522 	int repeat = 0;		/* return value */
1523 
1524 	ASSERT_SEGLOCK(fs);
1525 	/* Advance to the next segment. */
1526 	if (!LFS_PARTIAL_FITS(fs)) {
1527 		SEGUSE *sup;
1528 		struct buf *bp;
1529 
1530 		/* lfs_avail eats the remaining space */
1531 		fs->lfs_avail -= fs->lfs_fsbpseg - (fs->lfs_offset -
1532 						   fs->lfs_curseg);
1533 		/* Wake up any cleaning procs waiting on this file system. */
1534 		wakeup(&lfs_allclean_wakeup);
1535 		wakeup(&fs->lfs_nextseg);
1536 		lfs_newseg(fs);
1537 		repeat = 1;
1538 		fs->lfs_offset = fs->lfs_curseg;
1539 
1540 		sp->seg_number = dtosn(fs, fs->lfs_curseg);
1541 		sp->seg_bytes_left = fsbtob(fs, fs->lfs_fsbpseg);
1542 
1543 		/*
1544 		 * If the segment contains a superblock, update the offset
1545 		 * and summary address to skip over it.
1546 		 */
1547 		LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
1548 		if (sup->su_flags & SEGUSE_SUPERBLOCK) {
1549 			fs->lfs_offset += btofsb(fs, LFS_SBPAD);
1550 			sp->seg_bytes_left -= LFS_SBPAD;
1551 		}
1552 		brelse(bp);
1553 		/* Segment zero could also contain the labelpad */
1554 		if (fs->lfs_version > 1 && sp->seg_number == 0 &&
1555 		    fs->lfs_start < btofsb(fs, LFS_LABELPAD)) {
1556 			fs->lfs_offset +=
1557 			    btofsb(fs, LFS_LABELPAD) - fs->lfs_start;
1558 			sp->seg_bytes_left -=
1559 			    LFS_LABELPAD - fsbtob(fs, fs->lfs_start);
1560 		}
1561 	} else {
1562 		sp->seg_number = dtosn(fs, fs->lfs_curseg);
1563 		sp->seg_bytes_left = fsbtob(fs, fs->lfs_fsbpseg -
1564 				      (fs->lfs_offset - fs->lfs_curseg));
1565 	}
1566 	fs->lfs_lastpseg = fs->lfs_offset;
1567 
1568 	/* Record first address of this partial segment */
1569 	if (sp->seg_flags & SEGM_CLEAN) {
1570 		fs->lfs_cleanint[fs->lfs_cleanind] = fs->lfs_offset;
1571 		if (++fs->lfs_cleanind >= LFS_MAX_CLEANIND) {
1572 			/* "1" is the artificial inc in lfs_seglock */
1573 			simple_lock(&fs->lfs_interlock);
1574 			while (fs->lfs_iocount > 1) {
1575 				ltsleep(&fs->lfs_iocount, PRIBIO + 1,
1576 				    "lfs_initseg", 0, &fs->lfs_interlock);
1577 			}
1578 			simple_unlock(&fs->lfs_interlock);
1579 			fs->lfs_cleanind = 0;
1580 		}
1581 	}
1582 
1583 	sp->fs = fs;
1584 	sp->ibp = NULL;
1585 	sp->idp = NULL;
1586 	sp->ninodes = 0;
1587 	sp->ndupino = 0;
1588 
1589 	sp->cbpp = sp->bpp;
1590 
1591 	/* Get a new buffer for SEGSUM */
1592 	sbp = lfs_newbuf(fs, VTOI(fs->lfs_ivnode)->i_devvp,
1593 	    fsbtodb(fs, fs->lfs_offset), fs->lfs_sumsize, LFS_NB_SUMMARY);
1594 
1595 	/* ... and enter it into the buffer list. */
1596 	*sp->cbpp = sbp;
1597 	sp->cbpp++;
1598 	fs->lfs_offset += btofsb(fs, fs->lfs_sumsize);
1599 
1600 	sp->start_bpp = sp->cbpp;
1601 
1602 	/* Set point to SEGSUM, initialize it. */
1603 	ssp = sp->segsum = sbp->b_data;
1604 	memset(ssp, 0, fs->lfs_sumsize);
1605 	ssp->ss_next = fs->lfs_nextseg;
1606 	ssp->ss_nfinfo = ssp->ss_ninos = 0;
1607 	ssp->ss_magic = SS_MAGIC;
1608 
1609 	/* Set pointer to first FINFO, initialize it. */
1610 	sp->fip = (struct finfo *)((caddr_t)sp->segsum + SEGSUM_SIZE(fs));
1611 	sp->fip->fi_nblocks = 0;
1612 	sp->start_lbp = &sp->fip->fi_blocks[0];
1613 	sp->fip->fi_lastlength = 0;
1614 
1615 	sp->seg_bytes_left -= fs->lfs_sumsize;
1616 	sp->sum_bytes_left = fs->lfs_sumsize - SEGSUM_SIZE(fs);
1617 
1618 	return (repeat);
1619 }
1620 
1621 /*
1622  * Remove SEGUSE_INVAL from all segments.
1623  */
1624 void
1625 lfs_unset_inval_all(struct lfs *fs)
1626 {
1627 	SEGUSE *sup;
1628 	struct buf *bp;
1629 	int i;
1630 
1631 	for (i = 0; i < fs->lfs_nseg; i++) {
1632 		LFS_SEGENTRY(sup, fs, i, bp);
1633 		if (sup->su_flags & SEGUSE_INVAL) {
1634 			sup->su_flags &= ~SEGUSE_INVAL;
1635 			VOP_BWRITE(bp);
1636 		} else
1637 			brelse(bp);
1638 	}
1639 }
1640 
1641 /*
1642  * Return the next segment to write.
1643  */
1644 void
1645 lfs_newseg(struct lfs *fs)
1646 {
1647 	CLEANERINFO *cip;
1648 	SEGUSE *sup;
1649 	struct buf *bp;
1650 	int curseg, isdirty, sn, skip_inval;
1651 
1652 	ASSERT_SEGLOCK(fs);
1653 	LFS_SEGENTRY(sup, fs, dtosn(fs, fs->lfs_nextseg), bp);
1654 	DLOG((DLOG_SU, "lfs_newseg: seg %d := 0 in newseg\n",
1655 	      dtosn(fs, fs->lfs_nextseg)));
1656 	sup->su_flags |= SEGUSE_DIRTY | SEGUSE_ACTIVE;
1657 	sup->su_nbytes = 0;
1658 	sup->su_nsums = 0;
1659 	sup->su_ninos = 0;
1660 	LFS_WRITESEGENTRY(sup, fs, dtosn(fs, fs->lfs_nextseg), bp);
1661 
1662 	LFS_CLEANERINFO(cip, fs, bp);
1663 	--cip->clean;
1664 	++cip->dirty;
1665 	fs->lfs_nclean = cip->clean;
1666 	LFS_SYNC_CLEANERINFO(cip, fs, bp, 1);
1667 
1668 	fs->lfs_lastseg = fs->lfs_curseg;
1669 	fs->lfs_curseg = fs->lfs_nextseg;
1670 	skip_inval = 1;
1671 	for (sn = curseg = dtosn(fs, fs->lfs_curseg) + fs->lfs_interleave;;) {
1672 		sn = (sn + 1) % fs->lfs_nseg;
1673 		if (sn == curseg) {
1674 			if (skip_inval)
1675 				skip_inval = 0;
1676 			else
1677 				panic("lfs_nextseg: no clean segments");
1678 		}
1679 		LFS_SEGENTRY(sup, fs, sn, bp);
1680 		isdirty = sup->su_flags & (SEGUSE_DIRTY | (skip_inval ? SEGUSE_INVAL : 0));
1681 		/* Check SEGUSE_EMPTY as we go along */
1682 		if (isdirty && sup->su_nbytes == 0 &&
1683 		    !(sup->su_flags & SEGUSE_EMPTY))
1684 			LFS_WRITESEGENTRY(sup, fs, sn, bp);
1685 		else
1686 			brelse(bp);
1687 
1688 		if (!isdirty)
1689 			break;
1690 	}
1691 	if (skip_inval == 0)
1692 		lfs_unset_inval_all(fs);
1693 
1694 	++fs->lfs_nactive;
1695 	fs->lfs_nextseg = sntod(fs, sn);
1696 	if (lfs_dostats) {
1697 		++lfs_stats.segsused;
1698 	}
1699 }
1700 
1701 static struct buf *
1702 lfs_newclusterbuf(struct lfs *fs, struct vnode *vp, daddr_t addr, int n)
1703 {
1704 	struct lfs_cluster *cl;
1705 	struct buf **bpp, *bp;
1706 	int s;
1707 
1708 	ASSERT_SEGLOCK(fs);
1709 	cl = (struct lfs_cluster *)pool_get(&fs->lfs_clpool, PR_WAITOK);
1710 	bpp = (struct buf **)pool_get(&fs->lfs_bpppool, PR_WAITOK);
1711 	memset(cl, 0, sizeof(*cl));
1712 	cl->fs = fs;
1713 	cl->bpp = bpp;
1714 	cl->bufcount = 0;
1715 	cl->bufsize = 0;
1716 
1717 	/* If this segment is being written synchronously, note that */
1718 	if (fs->lfs_sp->seg_flags & SEGM_SYNC) {
1719 		cl->flags |= LFS_CL_SYNC;
1720 		cl->seg = fs->lfs_sp;
1721 		++cl->seg->seg_iocount;
1722 	}
1723 
1724 	/* Get an empty buffer header, or maybe one with something on it */
1725 	s = splbio();
1726 	bp = pool_get(&bufpool, PR_WAITOK); /* XXX should use lfs_malloc? */
1727 	splx(s);
1728 	memset(bp, 0, sizeof(*bp));
1729 	BUF_INIT(bp);
1730 
1731 	bp->b_flags = B_BUSY | B_CALL;
1732 	bp->b_dev = NODEV;
1733 	bp->b_blkno = bp->b_lblkno = addr;
1734 	bp->b_iodone = lfs_cluster_callback;
1735 	bp->b_private = cl;
1736 	bp->b_vp = vp;
1737 
1738 	return bp;
1739 }
1740 
1741 int
1742 lfs_writeseg(struct lfs *fs, struct segment *sp)
1743 {
1744 	struct buf **bpp, *bp, *cbp, *newbp;
1745 	SEGUSE *sup;
1746 	SEGSUM *ssp;
1747 	int i, s;
1748 	int do_again, nblocks, byteoffset;
1749 	size_t el_size;
1750 	struct lfs_cluster *cl;
1751 	u_short ninos;
1752 	struct vnode *devvp;
1753 	char *p = NULL;
1754 	struct vnode *vp;
1755 	int32_t *daddrp;	/* XXX ondisk32 */
1756 	int changed;
1757 	u_int32_t sum;
1758 
1759 	ASSERT_SEGLOCK(fs);
1760 	/*
1761 	 * If there are no buffers other than the segment summary to write
1762 	 * and it is not a checkpoint, don't do anything.  On a checkpoint,
1763 	 * even if there aren't any buffers, you need to write the superblock.
1764 	 */
1765 	if ((nblocks = sp->cbpp - sp->bpp) == 1)
1766 		return (0);
1767 
1768 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
1769 
1770 	/* Update the segment usage information. */
1771 	LFS_SEGENTRY(sup, fs, sp->seg_number, bp);
1772 
1773 	/* Loop through all blocks, except the segment summary. */
1774 	for (bpp = sp->bpp; ++bpp < sp->cbpp; ) {
1775 		if ((*bpp)->b_vp != devvp) {
1776 			sup->su_nbytes += (*bpp)->b_bcount;
1777 			DLOG((DLOG_SU, "seg %" PRIu32 " += %ld for ino %d"
1778 			      " lbn %" PRId64 " db 0x%" PRIx64 "\n",
1779 			      sp->seg_number, (*bpp)->b_bcount,
1780 			      VTOI((*bpp)->b_vp)->i_number, (*bpp)->b_lblkno,
1781 			      (*bpp)->b_blkno));
1782 		}
1783 	}
1784 
1785 	ssp = (SEGSUM *)sp->segsum;
1786 
1787 	ninos = (ssp->ss_ninos + INOPB(fs) - 1) / INOPB(fs);
1788 	DLOG((DLOG_SU, "seg %d += %d for %d inodes\n",
1789 	      sp->seg_number, ssp->ss_ninos * sizeof (struct ufs1_dinode),
1790 	      ssp->ss_ninos));
1791 	sup->su_nbytes += ssp->ss_ninos * sizeof (struct ufs1_dinode);
1792 	/* sup->su_nbytes += fs->lfs_sumsize; */
1793 	if (fs->lfs_version == 1)
1794 		sup->su_olastmod = time.tv_sec;
1795 	else
1796 		sup->su_lastmod = time.tv_sec;
1797 	sup->su_ninos += ninos;
1798 	++sup->su_nsums;
1799 	fs->lfs_dmeta += (btofsb(fs, fs->lfs_sumsize) + btofsb(fs, ninos *
1800 							 fs->lfs_ibsize));
1801 	fs->lfs_avail -= btofsb(fs, fs->lfs_sumsize);
1802 
1803 	do_again = !(bp->b_flags & B_GATHERED);
1804 	LFS_WRITESEGENTRY(sup, fs, sp->seg_number, bp); /* Ifile */
1805 
1806 	/*
1807 	 * Mark blocks B_BUSY, to prevent then from being changed between
1808 	 * the checksum computation and the actual write.
1809 	 *
1810 	 * If we are cleaning, check indirect blocks for UNWRITTEN, and if
1811 	 * there are any, replace them with copies that have UNASSIGNED
1812 	 * instead.
1813 	 */
1814 	for (bpp = sp->bpp, i = nblocks - 1; i--;) {
1815 		++bpp;
1816 		bp = *bpp;
1817 		if (bp->b_flags & B_CALL) { /* UBC or malloced buffer */
1818 			bp->b_flags |= B_BUSY;
1819 			continue;
1820 		}
1821 
1822 		simple_lock(&bp->b_interlock);
1823 		s = splbio();
1824 		while (bp->b_flags & B_BUSY) {
1825 			DLOG((DLOG_SEG, "lfs_writeseg: avoiding potential"
1826 			      " data summary corruption for ino %d, lbn %"
1827 			      PRId64 "\n",
1828 			      VTOI(bp->b_vp)->i_number, bp->b_lblkno));
1829 			bp->b_flags |= B_WANTED;
1830 			ltsleep(bp, (PRIBIO + 1), "lfs_writeseg", 0,
1831 				&bp->b_interlock);
1832 			splx(s);
1833 			s = splbio();
1834 		}
1835 		bp->b_flags |= B_BUSY;
1836 		splx(s);
1837 		simple_unlock(&bp->b_interlock);
1838 
1839 		/*
1840 		 * Check and replace indirect block UNWRITTEN bogosity.
1841 		 * XXX See comment in lfs_writefile.
1842 		 */
1843 		if (bp->b_lblkno < 0 && bp->b_vp != devvp && bp->b_vp &&
1844 		   VTOI(bp->b_vp)->i_ffs1_blocks !=
1845 		   VTOI(bp->b_vp)->i_lfs_effnblks) {
1846 			DLOG((DLOG_VNODE, "lfs_writeseg: cleansing ino %d (%d != %d)\n",
1847 			      VTOI(bp->b_vp)->i_number,
1848 			      VTOI(bp->b_vp)->i_lfs_effnblks,
1849 			      VTOI(bp->b_vp)->i_ffs1_blocks));
1850 			/* Make a copy we'll make changes to */
1851 			newbp = lfs_newbuf(fs, bp->b_vp, bp->b_lblkno,
1852 					   bp->b_bcount, LFS_NB_IBLOCK);
1853 			newbp->b_blkno = bp->b_blkno;
1854 			memcpy(newbp->b_data, bp->b_data,
1855 			       newbp->b_bcount);
1856 
1857 			changed = 0;
1858 			/* XXX ondisk32 */
1859 			for (daddrp = (int32_t *)(newbp->b_data);
1860 			     daddrp < (int32_t *)(newbp->b_data +
1861 						  newbp->b_bcount); daddrp++) {
1862 				if (*daddrp == UNWRITTEN) {
1863 					++changed;
1864 					*daddrp = 0;
1865 				}
1866 			}
1867 			/*
1868 			 * Get rid of the old buffer.  Don't mark it clean,
1869 			 * though, if it still has dirty data on it.
1870 			 */
1871 			if (changed) {
1872 				DLOG((DLOG_SEG, "lfs_writeseg: replacing UNWRITTEN(%d):"
1873 				      " bp = %p newbp = %p\n", changed, bp,
1874 				      newbp));
1875 				*bpp = newbp;
1876 				bp->b_flags &= ~(B_ERROR | B_GATHERED);
1877 				if (bp->b_flags & B_CALL) {
1878 					DLOG((DLOG_SEG, "lfs_writeseg: "
1879 					      "indir bp should not be B_CALL\n"));
1880 					s = splbio();
1881 					biodone(bp);
1882 					splx(s);
1883 					bp = NULL;
1884 				} else {
1885 					/* Still on free list, leave it there */
1886 					s = splbio();
1887 					bp->b_flags &= ~B_BUSY;
1888 					if (bp->b_flags & B_WANTED)
1889 						wakeup(bp);
1890 					splx(s);
1891 					/*
1892 					 * We have to re-decrement lfs_avail
1893 					 * since this block is going to come
1894 					 * back around to us in the next
1895 					 * segment.
1896 					 */
1897 					fs->lfs_avail -=
1898 					    btofsb(fs, bp->b_bcount);
1899 				}
1900 			} else {
1901 				lfs_freebuf(fs, newbp);
1902 			}
1903 		}
1904 	}
1905 	/*
1906 	 * Compute checksum across data and then across summary; the first
1907 	 * block (the summary block) is skipped.  Set the create time here
1908 	 * so that it's guaranteed to be later than the inode mod times.
1909 	 */
1910 	sum = 0;
1911 	if (fs->lfs_version == 1)
1912 		el_size = sizeof(u_long);
1913 	else
1914 		el_size = sizeof(u_int32_t);
1915 	for (bpp = sp->bpp, i = nblocks - 1; i--; ) {
1916 		++bpp;
1917 		/* Loop through gop_write cluster blocks */
1918 		for (byteoffset = 0; byteoffset < (*bpp)->b_bcount;
1919 		     byteoffset += fs->lfs_bsize) {
1920 #ifdef LFS_USE_B_INVAL
1921 			if (((*bpp)->b_flags & (B_CALL | B_INVAL)) ==
1922 			    (B_CALL | B_INVAL)) {
1923 				if (copyin((caddr_t)(*bpp)->b_saveaddr +
1924 					   byteoffset, dp, el_size)) {
1925 					panic("lfs_writeseg: copyin failed [1]:"
1926 						" ino %d blk %" PRId64,
1927 						VTOI((*bpp)->b_vp)->i_number,
1928 						(*bpp)->b_lblkno);
1929 				}
1930 			} else
1931 #endif /* LFS_USE_B_INVAL */
1932 			{
1933 				sum = lfs_cksum_part(
1934 				    (*bpp)->b_data + byteoffset, el_size, sum);
1935 			}
1936 		}
1937 	}
1938 	if (fs->lfs_version == 1)
1939 		ssp->ss_ocreate = time.tv_sec;
1940 	else {
1941 		ssp->ss_create = time.tv_sec;
1942 		ssp->ss_serial = ++fs->lfs_serial;
1943 		ssp->ss_ident  = fs->lfs_ident;
1944 	}
1945 	ssp->ss_datasum = lfs_cksum_fold(sum);
1946 	ssp->ss_sumsum = cksum(&ssp->ss_datasum,
1947 	    fs->lfs_sumsize - sizeof(ssp->ss_sumsum));
1948 
1949 	simple_lock(&fs->lfs_interlock);
1950 	fs->lfs_bfree -= (btofsb(fs, ninos * fs->lfs_ibsize) +
1951 			  btofsb(fs, fs->lfs_sumsize));
1952 	simple_unlock(&fs->lfs_interlock);
1953 
1954 	/*
1955 	 * When we simply write the blocks we lose a rotation for every block
1956 	 * written.  To avoid this problem, we cluster the buffers into a
1957 	 * chunk and write the chunk.  MAXPHYS is the largest size I/O
1958 	 * devices can handle, use that for the size of the chunks.
1959 	 *
1960 	 * Blocks that are already clusters (from GOP_WRITE), however, we
1961 	 * don't bother to copy into other clusters.
1962 	 */
1963 
1964 #define CHUNKSIZE MAXPHYS
1965 
1966 	if (devvp == NULL)
1967 		panic("devvp is NULL");
1968 	for (bpp = sp->bpp, i = nblocks; i;) {
1969 		cbp = lfs_newclusterbuf(fs, devvp, (*bpp)->b_blkno, i);
1970 		cl = cbp->b_private;
1971 
1972 		cbp->b_flags |= B_ASYNC | B_BUSY;
1973 		cbp->b_bcount = 0;
1974 
1975 #if defined(DEBUG) && defined(DIAGNOSTIC)
1976 		if (bpp - sp->bpp > (fs->lfs_sumsize - SEGSUM_SIZE(fs))
1977 		    / sizeof(int32_t)) {
1978 			panic("lfs_writeseg: real bpp overwrite");
1979 		}
1980 		if (bpp - sp->bpp > segsize(fs) / fs->lfs_fsize) {
1981 			panic("lfs_writeseg: theoretical bpp overwrite");
1982 		}
1983 #endif
1984 
1985 		/*
1986 		 * Construct the cluster.
1987 		 */
1988 		simple_lock(&fs->lfs_interlock);
1989 		++fs->lfs_iocount;
1990 		simple_unlock(&fs->lfs_interlock);
1991 		while (i && cbp->b_bcount < CHUNKSIZE) {
1992 			bp = *bpp;
1993 
1994 			if (bp->b_bcount > (CHUNKSIZE - cbp->b_bcount))
1995 				break;
1996 			if (cbp->b_bcount > 0 && !(cl->flags & LFS_CL_MALLOC))
1997 				break;
1998 
1999 			/* Clusters from GOP_WRITE are expedited */
2000 			if (bp->b_bcount > fs->lfs_bsize) {
2001 				if (cbp->b_bcount > 0)
2002 					/* Put in its own buffer */
2003 					break;
2004 				else {
2005 					cbp->b_data = bp->b_data;
2006 				}
2007 			} else if (cbp->b_bcount == 0) {
2008 				p = cbp->b_data = lfs_malloc(fs, CHUNKSIZE,
2009 							     LFS_NB_CLUSTER);
2010 				cl->flags |= LFS_CL_MALLOC;
2011 			}
2012 #ifdef DIAGNOSTIC
2013 			if (dtosn(fs, dbtofsb(fs, bp->b_blkno +
2014 					      btodb(bp->b_bcount - 1))) !=
2015 			    sp->seg_number) {
2016 				printf("blk size %d daddr %" PRIx64
2017 				    " not in seg %d\n",
2018 				    bp->b_bcount, bp->b_blkno,
2019 				    sp->seg_number);
2020 				panic("segment overwrite");
2021 			}
2022 #endif
2023 
2024 #ifdef LFS_USE_B_INVAL
2025 			/*
2026 			 * Fake buffers from the cleaner are marked as B_INVAL.
2027 			 * We need to copy the data from user space rather than
2028 			 * from the buffer indicated.
2029 			 * XXX == what do I do on an error?
2030 			 */
2031 			if ((bp->b_flags & (B_CALL|B_INVAL)) ==
2032 			    (B_CALL|B_INVAL)) {
2033 				if (copyin(bp->b_saveaddr, p, bp->b_bcount))
2034 					panic("lfs_writeseg: "
2035 					    "copyin failed [2]");
2036 			} else
2037 #endif /* LFS_USE_B_INVAL */
2038 			if (cl->flags & LFS_CL_MALLOC) {
2039 				/* copy data into our cluster. */
2040 				memcpy(p, bp->b_data, bp->b_bcount);
2041 				p += bp->b_bcount;
2042 			}
2043 
2044 			cbp->b_bcount += bp->b_bcount;
2045 			cl->bufsize += bp->b_bcount;
2046 
2047 			bp->b_flags &= ~(B_ERROR | B_READ | B_DELWRI | B_DONE);
2048 			cl->bpp[cl->bufcount++] = bp;
2049 			vp = bp->b_vp;
2050 			s = splbio();
2051 			reassignbuf(bp, vp);
2052 			V_INCR_NUMOUTPUT(vp);
2053 			splx(s);
2054 
2055 			bpp++;
2056 			i--;
2057 		}
2058 		if (fs->lfs_sp->seg_flags & SEGM_SYNC)
2059 			BIO_SETPRIO(cbp, BPRIO_TIMECRITICAL);
2060 		else
2061 			BIO_SETPRIO(cbp, BPRIO_TIMELIMITED);
2062 		s = splbio();
2063 		V_INCR_NUMOUTPUT(devvp);
2064 		splx(s);
2065 		VOP_STRATEGY(devvp, cbp);
2066 		curproc->p_stats->p_ru.ru_oublock++;
2067 	}
2068 
2069 	if (lfs_dostats) {
2070 		++lfs_stats.psegwrites;
2071 		lfs_stats.blocktot += nblocks - 1;
2072 		if (fs->lfs_sp->seg_flags & SEGM_SYNC)
2073 			++lfs_stats.psyncwrites;
2074 		if (fs->lfs_sp->seg_flags & SEGM_CLEAN) {
2075 			++lfs_stats.pcleanwrites;
2076 			lfs_stats.cleanblocks += nblocks - 1;
2077 		}
2078 	}
2079 	return (lfs_initseg(fs) || do_again);
2080 }
2081 
2082 void
2083 lfs_writesuper(struct lfs *fs, daddr_t daddr)
2084 {
2085 	struct buf *bp;
2086 	int s;
2087 	struct vnode *devvp = VTOI(fs->lfs_ivnode)->i_devvp;
2088 
2089 	ASSERT_MAYBE_SEGLOCK(fs);
2090 #ifdef DIAGNOSTIC
2091 	KASSERT(fs->lfs_magic == LFS_MAGIC);
2092 #endif
2093 	/*
2094 	 * If we can write one superblock while another is in
2095 	 * progress, we risk not having a complete checkpoint if we crash.
2096 	 * So, block here if a superblock write is in progress.
2097 	 */
2098 	simple_lock(&fs->lfs_interlock);
2099 	s = splbio();
2100 	while (fs->lfs_sbactive) {
2101 		ltsleep(&fs->lfs_sbactive, PRIBIO+1, "lfs sb", 0,
2102 			&fs->lfs_interlock);
2103 	}
2104 	fs->lfs_sbactive = daddr;
2105 	splx(s);
2106 	simple_unlock(&fs->lfs_interlock);
2107 
2108 	/* Set timestamp of this version of the superblock */
2109 	if (fs->lfs_version == 1)
2110 		fs->lfs_otstamp = time.tv_sec;
2111 	fs->lfs_tstamp = time.tv_sec;
2112 
2113 	/* Checksum the superblock and copy it into a buffer. */
2114 	fs->lfs_cksum = lfs_sb_cksum(&(fs->lfs_dlfs));
2115 	bp = lfs_newbuf(fs, devvp,
2116 	    fsbtodb(fs, daddr), LFS_SBPAD, LFS_NB_SBLOCK);
2117 	memset(bp->b_data + sizeof(struct dlfs), 0,
2118 	    LFS_SBPAD - sizeof(struct dlfs));
2119 	*(struct dlfs *)bp->b_data = fs->lfs_dlfs;
2120 
2121 	bp->b_flags |= B_BUSY | B_CALL | B_ASYNC;
2122 	bp->b_flags &= ~(B_DONE | B_ERROR | B_READ | B_DELWRI);
2123 	bp->b_iodone = lfs_supercallback;
2124 
2125 	if (fs->lfs_sp != NULL && fs->lfs_sp->seg_flags & SEGM_SYNC)
2126 		BIO_SETPRIO(bp, BPRIO_TIMECRITICAL);
2127 	else
2128 		BIO_SETPRIO(bp, BPRIO_TIMELIMITED);
2129 	curproc->p_stats->p_ru.ru_oublock++;
2130 	s = splbio();
2131 	V_INCR_NUMOUTPUT(bp->b_vp);
2132 	splx(s);
2133 	simple_lock(&fs->lfs_interlock);
2134 	++fs->lfs_iocount;
2135 	simple_unlock(&fs->lfs_interlock);
2136 	VOP_STRATEGY(devvp, bp);
2137 }
2138 
2139 /*
2140  * Logical block number match routines used when traversing the dirty block
2141  * chain.
2142  */
2143 int
2144 lfs_match_fake(struct lfs *fs, struct buf *bp)
2145 {
2146 
2147 	ASSERT_SEGLOCK(fs);
2148 	return LFS_IS_MALLOC_BUF(bp);
2149 }
2150 
2151 #if 0
2152 int
2153 lfs_match_real(struct lfs *fs, struct buf *bp)
2154 {
2155 
2156 	ASSERT_SEGLOCK(fs);
2157 	return (lfs_match_data(fs, bp) && !lfs_match_fake(fs, bp));
2158 }
2159 #endif
2160 
2161 int
2162 lfs_match_data(struct lfs *fs, struct buf *bp)
2163 {
2164 
2165 	ASSERT_SEGLOCK(fs);
2166 	return (bp->b_lblkno >= 0);
2167 }
2168 
2169 int
2170 lfs_match_indir(struct lfs *fs, struct buf *bp)
2171 {
2172 	daddr_t lbn;
2173 
2174 	ASSERT_SEGLOCK(fs);
2175 	lbn = bp->b_lblkno;
2176 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 0);
2177 }
2178 
2179 int
2180 lfs_match_dindir(struct lfs *fs, struct buf *bp)
2181 {
2182 	daddr_t lbn;
2183 
2184 	ASSERT_SEGLOCK(fs);
2185 	lbn = bp->b_lblkno;
2186 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 1);
2187 }
2188 
2189 int
2190 lfs_match_tindir(struct lfs *fs, struct buf *bp)
2191 {
2192 	daddr_t lbn;
2193 
2194 	ASSERT_SEGLOCK(fs);
2195 	lbn = bp->b_lblkno;
2196 	return (lbn < 0 && (-lbn - NDADDR) % NINDIR(fs) == 2);
2197 }
2198 
2199 /*
2200  * XXX - The only buffers that are going to hit these functions are the
2201  * segment write blocks, or the segment summaries, or the superblocks.
2202  *
2203  * All of the above are created by lfs_newbuf, and so do not need to be
2204  * released via brelse.
2205  */
2206 void
2207 lfs_callback(struct buf *bp)
2208 {
2209 	struct lfs *fs;
2210 
2211 	fs = bp->b_private;
2212 	ASSERT_NO_SEGLOCK(fs);
2213 	lfs_freebuf(fs, bp);
2214 }
2215 
2216 static void
2217 lfs_super_aiodone(struct buf *bp)
2218 {
2219 	struct lfs *fs;
2220 
2221 	fs = bp->b_private;
2222 	ASSERT_NO_SEGLOCK(fs);
2223 	simple_lock(&fs->lfs_interlock);
2224 	fs->lfs_sbactive = 0;
2225 	if (--fs->lfs_iocount <= 1)
2226 		wakeup(&fs->lfs_iocount);
2227 	simple_unlock(&fs->lfs_interlock);
2228 	wakeup(&fs->lfs_sbactive);
2229 	lfs_freebuf(fs, bp);
2230 }
2231 
2232 static void
2233 lfs_cluster_aiodone(struct buf *bp)
2234 {
2235 	struct lfs_cluster *cl;
2236 	struct lfs *fs;
2237 	struct buf *tbp, *fbp;
2238 	struct vnode *vp, *devvp;
2239 	struct inode *ip;
2240 	int s, error=0;
2241 
2242 	if (bp->b_flags & B_ERROR)
2243 		error = bp->b_error;
2244 
2245 	cl = bp->b_private;
2246 	fs = cl->fs;
2247 	devvp = VTOI(fs->lfs_ivnode)->i_devvp;
2248 	ASSERT_NO_SEGLOCK(fs);
2249 
2250 	/* Put the pages back, and release the buffer */
2251 	while (cl->bufcount--) {
2252 		tbp = cl->bpp[cl->bufcount];
2253 		KASSERT(tbp->b_flags & B_BUSY);
2254 		if (error) {
2255 			tbp->b_flags |= B_ERROR;
2256 			tbp->b_error = error;
2257 		}
2258 
2259 		/*
2260 		 * We're done with tbp.	 If it has not been re-dirtied since
2261 		 * the cluster was written, free it.  Otherwise, keep it on
2262 		 * the locked list to be written again.
2263 		 */
2264 		vp = tbp->b_vp;
2265 
2266 		tbp->b_flags &= ~B_GATHERED;
2267 
2268 		LFS_BCLEAN_LOG(fs, tbp);
2269 
2270 		if (!(tbp->b_flags & B_CALL)) {
2271 			KASSERT(tbp->b_flags & B_LOCKED);
2272 			s = splbio();
2273 			simple_lock(&bqueue_slock);
2274 			bremfree(tbp);
2275 			simple_unlock(&bqueue_slock);
2276 			if (vp)
2277 				reassignbuf(tbp, vp);
2278 			splx(s);
2279 			tbp->b_flags |= B_ASYNC; /* for biodone */
2280 		}
2281 
2282 		if ((tbp->b_flags & (B_LOCKED | B_DELWRI)) == B_LOCKED)
2283 			LFS_UNLOCK_BUF(tbp);
2284 
2285 		if (tbp->b_flags & B_DONE) {
2286 			DLOG((DLOG_SEG, "blk %d biodone already (flags %lx)\n",
2287 				cl->bufcount, (long)tbp->b_flags));
2288 		}
2289 
2290 		if ((tbp->b_flags & B_CALL) && !LFS_IS_MALLOC_BUF(tbp)) {
2291 			/*
2292 			 * A buffer from the page daemon.
2293 			 * We use the same iodone as it does,
2294 			 * so we must manually disassociate its
2295 			 * buffers from the vp.
2296 			 */
2297 			if (tbp->b_vp) {
2298 				/* This is just silly */
2299 				s = splbio();
2300 				brelvp(tbp);
2301 				tbp->b_vp = vp;
2302 				splx(s);
2303 			}
2304 			/* Put it back the way it was */
2305 			tbp->b_flags |= B_ASYNC;
2306 			/* Master buffers have B_AGE */
2307 			if (tbp->b_private == tbp)
2308 				tbp->b_flags |= B_AGE;
2309 		}
2310 		s = splbio();
2311 		biodone(tbp);
2312 
2313 		/*
2314 		 * If this is the last block for this vnode, but
2315 		 * there are other blocks on its dirty list,
2316 		 * set IN_MODIFIED/IN_CLEANING depending on what
2317 		 * sort of block.  Only do this for our mount point,
2318 		 * not for, e.g., inode blocks that are attached to
2319 		 * the devvp.
2320 		 * XXX KS - Shouldn't we set *both* if both types
2321 		 * of blocks are present (traverse the dirty list?)
2322 		 */
2323 		simple_lock(&global_v_numoutput_slock);
2324 		if (vp != devvp && vp->v_numoutput == 0 &&
2325 		    (fbp = LIST_FIRST(&vp->v_dirtyblkhd)) != NULL) {
2326 			ip = VTOI(vp);
2327 			DLOG((DLOG_SEG, "lfs_cluster_aiodone: mark ino %d\n",
2328 			       ip->i_number));
2329 			if (LFS_IS_MALLOC_BUF(fbp))
2330 				LFS_SET_UINO(ip, IN_CLEANING);
2331 			else
2332 				LFS_SET_UINO(ip, IN_MODIFIED);
2333 		}
2334 		simple_unlock(&global_v_numoutput_slock);
2335 		splx(s);
2336 		wakeup(vp);
2337 	}
2338 
2339 	/* Fix up the cluster buffer, and release it */
2340 	if (cl->flags & LFS_CL_MALLOC)
2341 		lfs_free(fs, bp->b_data, LFS_NB_CLUSTER);
2342 	s = splbio();
2343 	pool_put(&bufpool, bp); /* XXX should use lfs_free? */
2344 	splx(s);
2345 
2346 	/* Note i/o done */
2347 	if (cl->flags & LFS_CL_SYNC) {
2348 		if (--cl->seg->seg_iocount == 0)
2349 			wakeup(&cl->seg->seg_iocount);
2350 	}
2351 	simple_lock(&fs->lfs_interlock);
2352 #ifdef DIAGNOSTIC
2353 	if (fs->lfs_iocount == 0)
2354 		panic("lfs_cluster_aiodone: zero iocount");
2355 #endif
2356 	if (--fs->lfs_iocount <= 1)
2357 		wakeup(&fs->lfs_iocount);
2358 	simple_unlock(&fs->lfs_interlock);
2359 
2360 	pool_put(&fs->lfs_bpppool, cl->bpp);
2361 	cl->bpp = NULL;
2362 	pool_put(&fs->lfs_clpool, cl);
2363 }
2364 
2365 static void
2366 lfs_generic_callback(struct buf *bp, void (*aiodone)(struct buf *))
2367 {
2368 	/* reset b_iodone for when this is a single-buf i/o. */
2369 	bp->b_iodone = aiodone;
2370 
2371 	simple_lock(&uvm.aiodoned_lock);	/* locks uvm.aio_done */
2372 	TAILQ_INSERT_TAIL(&uvm.aio_done, bp, b_freelist);
2373 	wakeup(&uvm.aiodoned);
2374 	simple_unlock(&uvm.aiodoned_lock);
2375 }
2376 
2377 static void
2378 lfs_cluster_callback(struct buf *bp)
2379 {
2380 
2381 	lfs_generic_callback(bp, lfs_cluster_aiodone);
2382 }
2383 
2384 void
2385 lfs_supercallback(struct buf *bp)
2386 {
2387 
2388 	lfs_generic_callback(bp, lfs_super_aiodone);
2389 }
2390 
2391 /*
2392  * Shellsort (diminishing increment sort) from Data Structures and
2393  * Algorithms, Aho, Hopcraft and Ullman, 1983 Edition, page 290;
2394  * see also Knuth Vol. 3, page 84.  The increments are selected from
2395  * formula (8), page 95.  Roughly O(N^3/2).
2396  */
2397 /*
2398  * This is our own private copy of shellsort because we want to sort
2399  * two parallel arrays (the array of buffer pointers and the array of
2400  * logical block numbers) simultaneously.  Note that we cast the array
2401  * of logical block numbers to a unsigned in this routine so that the
2402  * negative block numbers (meta data blocks) sort AFTER the data blocks.
2403  */
2404 
2405 void
2406 lfs_shellsort(struct buf **bp_array, int32_t *lb_array, int nmemb, int size)
2407 {
2408 	static int __rsshell_increments[] = { 4, 1, 0 };
2409 	int incr, *incrp, t1, t2;
2410 	struct buf *bp_temp;
2411 
2412 #ifdef DEBUG
2413 	incr = 0;
2414 	for (t1 = 0; t1 < nmemb; t1++) {
2415 		for (t2 = 0; t2 * size < bp_array[t1]->b_bcount; t2++) {
2416 			if (lb_array[incr++] != bp_array[t1]->b_lblkno + t2) {
2417 				/* dump before panic */
2418 				printf("lfs_shellsort: nmemb=%d, size=%d\n",
2419 				    nmemb, size);
2420 				incr = 0;
2421 				for (t1 = 0; t1 < nmemb; t1++) {
2422 					const struct buf *bp = bp_array[t1];
2423 
2424 					printf("bp[%d]: lbn=%" PRIu64 ", size=%"
2425 					    PRIu64 "\n", t1,
2426 					    (uint64_t)bp->b_bcount,
2427 					    (uint64_t)bp->b_lblkno);
2428 					printf("lbns:");
2429 					for (t2 = 0; t2 * size < bp->b_bcount;
2430 					    t2++) {
2431 						printf(" %" PRId32,
2432 						    lb_array[incr++]);
2433 					}
2434 					printf("\n");
2435 				}
2436 				panic("lfs_shellsort: inconsistent input");
2437 			}
2438 		}
2439 	}
2440 #endif
2441 
2442 	for (incrp = __rsshell_increments; (incr = *incrp++) != 0;)
2443 		for (t1 = incr; t1 < nmemb; ++t1)
2444 			for (t2 = t1 - incr; t2 >= 0;)
2445 				if ((u_int32_t)bp_array[t2]->b_lblkno >
2446 				    (u_int32_t)bp_array[t2 + incr]->b_lblkno) {
2447 					bp_temp = bp_array[t2];
2448 					bp_array[t2] = bp_array[t2 + incr];
2449 					bp_array[t2 + incr] = bp_temp;
2450 					t2 -= incr;
2451 				} else
2452 					break;
2453 
2454 	/* Reform the list of logical blocks */
2455 	incr = 0;
2456 	for (t1 = 0; t1 < nmemb; t1++) {
2457 		for (t2 = 0; t2 * size < bp_array[t1]->b_bcount; t2++) {
2458 			lb_array[incr++] = bp_array[t1]->b_lblkno + t2;
2459 		}
2460 	}
2461 }
2462 
2463 /*
2464  * Check VXLOCK.  Return 1 if the vnode is locked.  Otherwise, vget it.
2465  */
2466 int
2467 lfs_vref(struct vnode *vp)
2468 {
2469 	ASSERT_MAYBE_SEGLOCK(VTOI(vp)->i_lfs);
2470 	/*
2471 	 * If we return 1 here during a flush, we risk vinvalbuf() not
2472 	 * being able to flush all of the pages from this vnode, which
2473 	 * will cause it to panic.  So, return 0 if a flush is in progress.
2474 	 */
2475 	if (vp->v_flag & VXLOCK) {
2476 		if (IS_FLUSHING(VTOI(vp)->i_lfs, vp)) {
2477 			return 0;
2478 		}
2479 		return (1);
2480 	}
2481 	return (vget(vp, 0));
2482 }
2483 
2484 /*
2485  * This is vrele except that we do not want to VOP_INACTIVE this vnode. We
2486  * inline vrele here to avoid the vn_lock and VOP_INACTIVE call at the end.
2487  */
2488 void
2489 lfs_vunref(struct vnode *vp)
2490 {
2491 	ASSERT_MAYBE_SEGLOCK(VTOI(vp)->i_lfs);
2492 	/*
2493 	 * Analogous to lfs_vref, if the node is flushing, fake it.
2494 	 */
2495 	if ((vp->v_flag & VXLOCK) && IS_FLUSHING(VTOI(vp)->i_lfs, vp)) {
2496 		return;
2497 	}
2498 
2499 	simple_lock(&vp->v_interlock);
2500 #ifdef DIAGNOSTIC
2501 	if (vp->v_usecount <= 0) {
2502 		printf("lfs_vunref: inum is %llu\n", (unsigned long long)
2503 		    VTOI(vp)->i_number);
2504 		printf("lfs_vunref: flags are 0x%lx\n", (u_long)vp->v_flag);
2505 		printf("lfs_vunref: usecount = %ld\n", (long)vp->v_usecount);
2506 		panic("lfs_vunref: v_usecount < 0");
2507 	}
2508 #endif
2509 	vp->v_usecount--;
2510 	if (vp->v_usecount > 0) {
2511 		simple_unlock(&vp->v_interlock);
2512 		return;
2513 	}
2514 	/*
2515 	 * insert at tail of LRU list
2516 	 */
2517 	simple_lock(&vnode_free_list_slock);
2518 	if (vp->v_holdcnt > 0)
2519 		TAILQ_INSERT_TAIL(&vnode_hold_list, vp, v_freelist);
2520 	else
2521 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2522 	simple_unlock(&vnode_free_list_slock);
2523 	simple_unlock(&vp->v_interlock);
2524 }
2525 
2526 /*
2527  * We use this when we have vnodes that were loaded in solely for cleaning.
2528  * There is no reason to believe that these vnodes will be referenced again
2529  * soon, since the cleaning process is unrelated to normal filesystem
2530  * activity.  Putting cleaned vnodes at the tail of the list has the effect
2531  * of flushing the vnode LRU.  So, put vnodes that were loaded only for
2532  * cleaning at the head of the list, instead.
2533  */
2534 void
2535 lfs_vunref_head(struct vnode *vp)
2536 {
2537 
2538 	ASSERT_SEGLOCK(VTOI(vp)->i_lfs);
2539 	simple_lock(&vp->v_interlock);
2540 #ifdef DIAGNOSTIC
2541 	if (vp->v_usecount == 0) {
2542 		panic("lfs_vunref: v_usecount<0");
2543 	}
2544 #endif
2545 	vp->v_usecount--;
2546 	if (vp->v_usecount > 0) {
2547 		simple_unlock(&vp->v_interlock);
2548 		return;
2549 	}
2550 	/*
2551 	 * insert at head of LRU list
2552 	 */
2553 	simple_lock(&vnode_free_list_slock);
2554 	if (vp->v_holdcnt > 0)
2555 		TAILQ_INSERT_TAIL(&vnode_hold_list, vp, v_freelist);
2556 	else
2557 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2558 	simple_unlock(&vnode_free_list_slock);
2559 	simple_unlock(&vp->v_interlock);
2560 }
2561 
2562